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->hasZeroInits() || IList->hasOneInit())
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 // Count in 64 bits so that the index cannot wrap with a narrow size_t.
2212 if (elementIndex.getBitWidth() < 64)
2213 elementIndex = elementIndex.extend(64);
2214
2215 // We might know the maximum number of elements in advance.
2216 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2217 elementIndex.isUnsigned());
2218 bool maxElementsKnown = false;
2219 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
2220 maxElements = CAT->getSize();
2221 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
2222 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2223 maxElementsKnown = true;
2224 }
2225
2226 QualType elementType = arrayType->getElementType();
2227 while (Index < IList->getNumInits()) {
2228 Expr *Init = IList->getInit(Index);
2229 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2230 // If we're not the subobject that matches up with the '{' for
2231 // the designator, we shouldn't be handling the
2232 // designator. Return immediately.
2233 if (!SubobjectIsDesignatorContext)
2234 return;
2235
2236 // Handle this designated initializer. elementIndex will be
2237 // updated to be the next array element we'll initialize.
2238 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2239 DeclType, nullptr, &elementIndex, Index,
2240 StructuredList, StructuredIndex, true,
2241 false)) {
2242 hadError = true;
2243 continue;
2244 }
2245
2246 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2247 maxElements = maxElements.extend(elementIndex.getBitWidth());
2248 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2249 elementIndex = elementIndex.extend(maxElements.getBitWidth());
2250 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2251
2252 // If the array is of incomplete type, keep track of the number of
2253 // elements in the initializer.
2254 if (!maxElementsKnown && elementIndex > maxElements)
2255 maxElements = elementIndex;
2256
2257 continue;
2258 }
2259
2260 // If we know the maximum number of elements, and we've already
2261 // hit it, stop consuming elements in the initializer list.
2262 if (maxElementsKnown && elementIndex == maxElements)
2263 break;
2264
2265 InitializedEntity ElementEntity = InitializedEntity::InitializeElement(
2266 SemaRef.Context, StructuredIndex, Entity);
2267 ElementEntity.setElementIndex(elementIndex.getExtValue());
2268
2269 unsigned EmbedElementIndexBeforeInit = CurEmbedIndex;
2270 // Check this element.
2271 CheckSubElementType(ElementEntity, IList, elementType, Index,
2272 StructuredList, StructuredIndex);
2273 ++elementIndex;
2274 if ((CurEmbed || isa<EmbedExpr>(Init)) && elementType->isScalarType()) {
2275 if (CurEmbed) {
2276 elementIndex =
2277 elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1;
2278 } else {
2279 auto Embed = cast<EmbedExpr>(Init);
2280 elementIndex = elementIndex + Embed->getDataElementCount() -
2281 EmbedElementIndexBeforeInit - 1;
2282 }
2283 }
2284
2285 // If the array is of incomplete type, keep track of the number of
2286 // elements in the initializer.
2287 if (!maxElementsKnown && elementIndex > maxElements)
2288 maxElements = elementIndex;
2289 }
2290 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2291 // If this is an incomplete array type, the actual type needs to
2292 // be calculated here.
2293 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2294 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2295 // Sizing an array implicitly to zero is not allowed by ISO C,
2296 // but is supported by GNU.
2297 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2298 }
2299
2300 if (SemaRef.checkArrayTooLarge(elementType, maxElements,
2301 IList->getBeginLoc())) {
2302 hadError = true;
2303 return;
2304 }
2305
2306 DeclType = SemaRef.Context.getConstantArrayType(
2307 elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2308 }
2309 if (!hadError) {
2310 // If there are any members of the array that get value-initialized, check
2311 // that is possible. That happens if we know the bound and don't have
2312 // enough elements, or if we're performing an array new with an unknown
2313 // bound.
2314 if ((maxElementsKnown && elementIndex < maxElements) ||
2315 Entity.isVariableLengthArrayNew())
2316 CheckEmptyInitializable(
2318 IList->getEndLoc());
2319 }
2320}
2321
2322bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2323 Expr *InitExpr,
2324 FieldDecl *Field,
2325 bool TopLevelObject) {
2326 // Handle GNU flexible array initializers.
2327 unsigned FlexArrayDiag;
2328 if (isa<InitListExpr>(InitExpr) &&
2329 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2330 // Empty flexible array init always allowed as an extension
2331 FlexArrayDiag = diag::ext_flexible_array_init;
2332 } else if (!TopLevelObject) {
2333 // Disallow flexible array init on non-top-level object
2334 FlexArrayDiag = diag::err_flexible_array_init;
2335 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2336 // Disallow flexible array init on anything which is not a variable.
2337 FlexArrayDiag = diag::err_flexible_array_init;
2338 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2339 // Disallow flexible array init on local variables.
2340 FlexArrayDiag = diag::err_flexible_array_init;
2341 } else {
2342 // Allow other cases.
2343 FlexArrayDiag = diag::ext_flexible_array_init;
2344 }
2345
2346 if (!VerifyOnly) {
2347 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2348 << InitExpr->getBeginLoc();
2349 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2350 << Field;
2351 }
2352
2353 return FlexArrayDiag != diag::ext_flexible_array_init;
2354}
2355
2356static bool isInitializedStructuredList(const InitListExpr *StructuredList) {
2357 return StructuredList && StructuredList->getNumInits() == 1U;
2358}
2359
2360void InitListChecker::CheckStructUnionTypes(
2361 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2363 bool SubobjectIsDesignatorContext, unsigned &Index,
2364 InitListExpr *StructuredList, unsigned &StructuredIndex,
2365 bool TopLevelObject) {
2366 const RecordDecl *RD = DeclType->getAsRecordDecl();
2367
2368 // If the record is invalid, some of it's members are invalid. To avoid
2369 // confusion, we forgo checking the initializer for the entire record.
2370 if (RD->isInvalidDecl()) {
2371 // Assume it was supposed to consume a single initializer.
2372 ++Index;
2373 hadError = true;
2374 return;
2375 }
2376
2377 if (RD->isUnion() && IList->getNumInits() == 0) {
2378 if (!VerifyOnly)
2379 for (FieldDecl *FD : RD->fields()) {
2380 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2381 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2382 hadError = true;
2383 return;
2384 }
2385 }
2386
2387 // If there's a default initializer, use it.
2388 if (isa<CXXRecordDecl>(RD) &&
2389 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2390 if (!StructuredList)
2391 return;
2392 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2393 Field != FieldEnd; ++Field) {
2394 if (Field->hasInClassInitializer() ||
2395 (Field->isAnonymousStructOrUnion() &&
2396 Field->getType()
2397 ->castAsCXXRecordDecl()
2398 ->hasInClassInitializer())) {
2399 StructuredList->setInitializedFieldInUnion(*Field);
2400 // FIXME: Actually build a CXXDefaultInitExpr?
2401 return;
2402 }
2403 }
2404 llvm_unreachable("Couldn't find in-class initializer");
2405 }
2406
2407 // Value-initialize the first member of the union that isn't an unnamed
2408 // bitfield.
2409 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2410 Field != FieldEnd; ++Field) {
2411 if (!Field->isUnnamedBitField()) {
2412 CheckEmptyInitializable(
2413 InitializedEntity::InitializeMember(*Field, &Entity),
2414 IList->getEndLoc());
2415 if (StructuredList)
2416 StructuredList->setInitializedFieldInUnion(*Field);
2417 break;
2418 }
2419 }
2420 return;
2421 }
2422
2423 bool InitializedSomething = false;
2424
2425 // If we have any base classes, they are initialized prior to the fields.
2426 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2427 auto &Base = *I;
2428 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2429
2430 // Designated inits always initialize fields, so if we see one, all
2431 // remaining base classes have no explicit initializer.
2432 if (isa_and_nonnull<DesignatedInitExpr>(Init))
2433 Init = nullptr;
2434
2435 // C++ [over.match.class.deduct]p1.6:
2436 // each non-trailing aggregate element that is a pack expansion is assumed
2437 // to correspond to no elements of the initializer list, and (1.7) a
2438 // trailing aggregate element that is a pack expansion is assumed to
2439 // correspond to all remaining elements of the initializer list (if any).
2440
2441 // C++ [over.match.class.deduct]p1.9:
2442 // ... except that additional parameter packs of the form P_j... are
2443 // inserted into the parameter list in their original aggregate element
2444 // position corresponding to each non-trailing aggregate element of
2445 // type P_j that was skipped because it was a parameter pack, and the
2446 // trailing sequence of parameters corresponding to a trailing
2447 // aggregate element that is a pack expansion (if any) is replaced
2448 // by a single parameter of the form T_n....
2449 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2450 AggrDeductionCandidateParamTypes->push_back(
2451 SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2452
2453 // Trailing pack expansion
2454 if (I + 1 == E && RD->field_empty()) {
2455 if (Index < IList->getNumInits())
2456 Index = IList->getNumInits();
2457 return;
2458 }
2459
2460 continue;
2461 }
2462
2463 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2464 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2465 SemaRef.Context, &Base, false, &Entity);
2466 if (Init) {
2467 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2468 StructuredList, StructuredIndex);
2469 InitializedSomething = true;
2470 } else {
2471 CheckEmptyInitializable(BaseEntity, InitLoc);
2472 }
2473
2474 if (!VerifyOnly)
2475 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2476 hadError = true;
2477 return;
2478 }
2479 }
2480
2481 // If structDecl is a forward declaration, this loop won't do
2482 // anything except look at designated initializers; That's okay,
2483 // because an error should get printed out elsewhere. It might be
2484 // worthwhile to skip over the rest of the initializer, though.
2485 RecordDecl::field_iterator FieldEnd = RD->field_end();
2486 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2487 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2488 });
2489 bool HasDesignatedInit = false;
2490
2491 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2492
2493 while (Index < IList->getNumInits()) {
2494 Expr *Init = IList->getInit(Index);
2495 SourceLocation InitLoc = Init->getBeginLoc();
2496
2497 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2498 // If we're not the subobject that matches up with the '{' for
2499 // the designator, we shouldn't be handling the
2500 // designator. Return immediately.
2501 if (!SubobjectIsDesignatorContext)
2502 return;
2503
2504 HasDesignatedInit = true;
2505
2506 // Handle this designated initializer. Field will be updated to
2507 // the next field that we'll be initializing.
2508 bool DesignatedInitFailed = CheckDesignatedInitializer(
2509 Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2510 StructuredList, StructuredIndex, true, TopLevelObject);
2511 if (DesignatedInitFailed)
2512 hadError = true;
2513
2514 // Find the field named by the designated initializer.
2515 DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2516 if (!VerifyOnly && D->isFieldDesignator()) {
2517 FieldDecl *F = D->getFieldDecl();
2518 InitializedFields.insert(F);
2519 if (!DesignatedInitFailed) {
2520 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2521 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2522 hadError = true;
2523 return;
2524 }
2525 }
2526 }
2527
2528 InitializedSomething = true;
2529 continue;
2530 }
2531
2532 // Check if this is an initializer of forms:
2533 //
2534 // struct foo f = {};
2535 // struct foo g = {0};
2536 //
2537 // These are okay for randomized structures. [C99 6.7.8p19]
2538 //
2539 // Also, if there is only one element in the structure, we allow something
2540 // like this, because it's really not randomized in the traditional sense.
2541 //
2542 // struct foo h = {bar};
2543 auto IsZeroInitializer = [&](const Expr *I) {
2544 if (IList->getNumInits() == 1) {
2545 if (NumRecordDecls == 1)
2546 return true;
2547 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2548 return IL->getValue().isZero();
2549 }
2550 return false;
2551 };
2552
2553 // Don't allow non-designated initializers on randomized structures.
2554 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2555 if (!VerifyOnly)
2556 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2557 hadError = true;
2558 break;
2559 }
2560
2561 if (Field == FieldEnd) {
2562 // We've run out of fields. We're done.
2563 break;
2564 }
2565
2566 // We've already initialized a member of a union. We can stop entirely.
2567 if (InitializedSomething && RD->isUnion())
2568 return;
2569
2570 // Stop if we've hit a flexible array member.
2571 if (Field->getType()->isIncompleteArrayType())
2572 break;
2573
2574 if (Field->isUnnamedBitField()) {
2575 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2576 ++Field;
2577 continue;
2578 }
2579
2580 // Make sure we can use this declaration.
2581 bool InvalidUse;
2582 if (VerifyOnly)
2583 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2584 else
2585 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2586 *Field, IList->getInit(Index)->getBeginLoc());
2587 if (InvalidUse) {
2588 ++Index;
2589 ++Field;
2590 hadError = true;
2591 continue;
2592 }
2593
2594 if (!VerifyOnly) {
2595 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2596 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2597 hadError = true;
2598 return;
2599 }
2600 }
2601
2602 InitializedEntity MemberEntity =
2603 InitializedEntity::InitializeMember(*Field, &Entity);
2604 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2605 StructuredList, StructuredIndex);
2606 InitializedSomething = true;
2607 InitializedFields.insert(*Field);
2608 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2609 // Initialize the first field within the union.
2610 StructuredList->setInitializedFieldInUnion(*Field);
2611 }
2612
2613 ++Field;
2614 }
2615
2616 // Emit warnings for missing struct field initializers.
2617 // This check is disabled for designated initializers in C.
2618 // This matches gcc behaviour.
2619 bool IsCDesignatedInitializer =
2620 HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2621 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2622 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
2623 !IsCDesignatedInitializer) {
2624 // It is possible we have one or more unnamed bitfields remaining.
2625 // Find first (if any) named field and emit warning.
2626 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2627 : Field,
2628 end = RD->field_end();
2629 it != end; ++it) {
2630 if (HasDesignatedInit && InitializedFields.count(*it))
2631 continue;
2632
2633 if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2634 !it->getType()->isIncompleteArrayType()) {
2635 auto Diag = HasDesignatedInit
2636 ? diag::warn_missing_designated_field_initializers
2637 : diag::warn_missing_field_initializers;
2638 SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;
2639 break;
2640 }
2641 }
2642 }
2643
2644 // Check that any remaining fields can be value-initialized if we're not
2645 // building a structured list. (If we are, we'll check this later.)
2646 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2647 !Field->getType()->isIncompleteArrayType()) {
2648 for (; Field != FieldEnd && !hadError; ++Field) {
2649 if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())
2650 CheckEmptyInitializable(
2651 InitializedEntity::InitializeMember(*Field, &Entity),
2652 IList->getEndLoc());
2653 }
2654 }
2655
2656 // Check that the types of the remaining fields have accessible destructors.
2657 if (!VerifyOnly) {
2658 // If the initializer expression has a designated initializer, check the
2659 // elements for which a designated initializer is not provided too.
2660 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2661 : Field;
2662 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2663 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2664 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2665 hadError = true;
2666 return;
2667 }
2668 }
2669 }
2670
2671 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2672 Index >= IList->getNumInits())
2673 return;
2674
2675 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2676 TopLevelObject)) {
2677 hadError = true;
2678 ++Index;
2679 return;
2680 }
2681
2682 InitializedEntity MemberEntity =
2683 InitializedEntity::InitializeMember(*Field, &Entity);
2684
2685 if (isa<InitListExpr>(IList->getInit(Index)) ||
2686 AggrDeductionCandidateParamTypes)
2687 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2688 StructuredList, StructuredIndex);
2689 else
2690 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2691 StructuredList, StructuredIndex);
2692
2693 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2694 // Initialize the first field within the union.
2695 StructuredList->setInitializedFieldInUnion(*Field);
2696 }
2697}
2698
2699/// Expand a field designator that refers to a member of an
2700/// anonymous struct or union into a series of field designators that
2701/// refers to the field within the appropriate subobject.
2702///
2704 DesignatedInitExpr *DIE,
2705 unsigned DesigIdx,
2706 IndirectFieldDecl *IndirectField) {
2708
2709 // Build the replacement designators.
2710 SmallVector<Designator, 4> Replacements;
2711 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2712 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2713 if (PI + 1 == PE)
2714 Replacements.push_back(Designator::CreateFieldDesignator(
2715 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2716 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2717 else
2718 Replacements.push_back(Designator::CreateFieldDesignator(
2719 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2720 assert(isa<FieldDecl>(*PI));
2721 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2722 }
2723
2724 // Expand the current designator into the set of replacement
2725 // designators, so we have a full subobject path down to where the
2726 // member of the anonymous struct/union is actually stored.
2727 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2728 &Replacements[0] + Replacements.size());
2729}
2730
2732 DesignatedInitExpr *DIE) {
2733 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2734 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2735 for (unsigned I = 0; I < NumIndexExprs; ++I)
2736 IndexExprs[I] = DIE->getSubExpr(I + 1);
2737 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2738 IndexExprs,
2739 DIE->getEqualOrColonLoc(),
2740 DIE->usesGNUSyntax(), DIE->getInit());
2741}
2742
2743namespace {
2744
2745// Callback to only accept typo corrections that are for field members of
2746// the given struct or union.
2747class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2748 public:
2749 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2750 : Record(RD) {}
2751
2752 bool ValidateCandidate(const TypoCorrection &candidate) override {
2753 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2754 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2755 }
2756
2757 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2758 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2759 }
2760
2761 private:
2762 const RecordDecl *Record;
2763};
2764
2765} // end anonymous namespace
2766
2767/// Check the well-formedness of a C99 designated initializer.
2768///
2769/// Determines whether the designated initializer @p DIE, which
2770/// resides at the given @p Index within the initializer list @p
2771/// IList, is well-formed for a current object of type @p DeclType
2772/// (C99 6.7.8). The actual subobject that this designator refers to
2773/// within the current subobject is returned in either
2774/// @p NextField or @p NextElementIndex (whichever is appropriate).
2775///
2776/// @param IList The initializer list in which this designated
2777/// initializer occurs.
2778///
2779/// @param DIE The designated initializer expression.
2780///
2781/// @param DesigIdx The index of the current designator.
2782///
2783/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2784/// into which the designation in @p DIE should refer.
2785///
2786/// @param NextField If non-NULL and the first designator in @p DIE is
2787/// a field, this will be set to the field declaration corresponding
2788/// to the field named by the designator. On input, this is expected to be
2789/// the next field that would be initialized in the absence of designation,
2790/// if the complete object being initialized is a struct.
2791///
2792/// @param NextElementIndex If non-NULL and the first designator in @p
2793/// DIE is an array designator or GNU array-range designator, this
2794/// will be set to the last index initialized by this designator.
2795///
2796/// @param Index Index into @p IList where the designated initializer
2797/// @p DIE occurs.
2798///
2799/// @param StructuredList The initializer list expression that
2800/// describes all of the subobject initializers in the order they'll
2801/// actually be initialized.
2802///
2803/// @returns true if there was an error, false otherwise.
2804bool
2805InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2806 InitListExpr *IList,
2807 DesignatedInitExpr *DIE,
2808 unsigned DesigIdx,
2809 QualType &CurrentObjectType,
2810 RecordDecl::field_iterator *NextField,
2811 llvm::APSInt *NextElementIndex,
2812 unsigned &Index,
2813 InitListExpr *StructuredList,
2814 unsigned &StructuredIndex,
2815 bool FinishSubobjectInit,
2816 bool TopLevelObject) {
2817 if (DesigIdx == DIE->size()) {
2818 // C++20 designated initialization can result in direct-list-initialization
2819 // of the designated subobject. This is the only way that we can end up
2820 // performing direct initialization as part of aggregate initialization, so
2821 // it needs special handling.
2822 if (DIE->isDirectInit()) {
2823 Expr *Init = DIE->getInit();
2824 assert(isa<InitListExpr>(Init) &&
2825 "designator result in direct non-list initialization?");
2826 InitializationKind Kind = InitializationKind::CreateDirectList(
2827 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2828 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2829 /*TopLevelOfInitList*/ true);
2830 if (StructuredList) {
2831 ExprResult Result = VerifyOnly
2832 ? getDummyInit()
2833 : Seq.Perform(SemaRef, Entity, Kind, Init);
2834 UpdateStructuredListElement(StructuredList, StructuredIndex,
2835 Result.get());
2836 }
2837 ++Index;
2838 if (AggrDeductionCandidateParamTypes)
2839 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2840 return !Seq;
2841 }
2842
2843 // Check the actual initialization for the designated object type.
2844 bool prevHadError = hadError;
2845
2846 // Temporarily remove the designator expression from the
2847 // initializer list that the child calls see, so that we don't try
2848 // to re-process the designator.
2849 unsigned OldIndex = Index;
2850 auto *OldDIE =
2851 dyn_cast_if_present<DesignatedInitExpr>(IList->getInit(OldIndex));
2852 if (!OldDIE)
2853 OldDIE = DIE;
2854 IList->setInit(OldIndex, OldDIE->getInit());
2855
2856 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2857 StructuredIndex, /*DirectlyDesignated=*/true);
2858
2859 // Restore the designated initializer expression in the syntactic
2860 // form of the initializer list.
2861 if (IList->getInit(OldIndex) != OldDIE->getInit())
2862 OldDIE->setInit(IList->getInit(OldIndex));
2863 IList->setInit(OldIndex, OldDIE);
2864
2865 return hadError && !prevHadError;
2866 }
2867
2868 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2869 bool IsFirstDesignator = (DesigIdx == 0);
2870 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2871 // Determine the structural initializer list that corresponds to the
2872 // current subobject.
2873 if (IsFirstDesignator)
2874 StructuredList = FullyStructuredList;
2875 else {
2876 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2877 StructuredList->getInit(StructuredIndex) : nullptr;
2878 if (!ExistingInit && StructuredList->hasArrayFiller())
2879 ExistingInit = StructuredList->getArrayFiller();
2880
2881 if (!ExistingInit)
2882 StructuredList = getStructuredSubobjectInit(
2883 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2884 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2885 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2886 StructuredList = Result;
2887 else {
2888 // We are creating an initializer list that initializes the
2889 // subobjects of the current object, but there was already an
2890 // initialization that completely initialized the current
2891 // subobject, e.g., by a compound literal:
2892 //
2893 // struct X { int a, b; };
2894 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2895 //
2896 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2897 // designated initializer re-initializes only its current object
2898 // subobject [0].b.
2899 diagnoseInitOverride(ExistingInit,
2900 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2901 /*UnionOverride=*/false,
2902 /*FullyOverwritten=*/false);
2903
2904 if (!VerifyOnly) {
2905 if (DesignatedInitUpdateExpr *E =
2906 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2907 StructuredList = E->getUpdater();
2908 else {
2909 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2910 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2911 ExistingInit, DIE->getEndLoc());
2912 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2913 StructuredList = DIUE->getUpdater();
2914 }
2915 } else {
2916 // We don't need to track the structured representation of a
2917 // designated init update of an already-fully-initialized object in
2918 // verify-only mode. The only reason we would need the structure is
2919 // to determine where the uninitialized "holes" are, and in this
2920 // case, we know there aren't any and we can't introduce any.
2921 StructuredList = nullptr;
2922 }
2923 }
2924 }
2925 }
2926
2927 if (D->isFieldDesignator()) {
2928 // C99 6.7.8p7:
2929 //
2930 // If a designator has the form
2931 //
2932 // . identifier
2933 //
2934 // then the current object (defined below) shall have
2935 // structure or union type and the identifier shall be the
2936 // name of a member of that type.
2937 RecordDecl *RD = CurrentObjectType->getAsRecordDecl();
2938 if (!RD) {
2939 SourceLocation Loc = D->getDotLoc();
2940 if (Loc.isInvalid())
2941 Loc = D->getFieldLoc();
2942 if (!VerifyOnly)
2943 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2944 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2945 ++Index;
2946 return true;
2947 }
2948
2949 FieldDecl *KnownField = D->getFieldDecl();
2950 if (!KnownField) {
2951 const IdentifierInfo *FieldName = D->getFieldName();
2952 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2953 if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2954 KnownField = FD;
2955 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2956 // In verify mode, don't modify the original.
2957 if (VerifyOnly)
2958 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2959 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2960 D = DIE->getDesignator(DesigIdx);
2961 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2962 }
2963 if (!KnownField) {
2964 if (VerifyOnly) {
2965 ++Index;
2966 return true; // No typo correction when just trying this out.
2967 }
2968
2969 // We found a placeholder variable
2970 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2971 FieldName)) {
2972 ++Index;
2973 return true;
2974 }
2975 // Name lookup found something, but it wasn't a field.
2976 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2977 !Lookup.empty()) {
2978 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2979 << FieldName;
2980 SemaRef.Diag(Lookup.front()->getLocation(),
2981 diag::note_field_designator_found);
2982 ++Index;
2983 return true;
2984 }
2985
2986 // Name lookup didn't find anything.
2987 // Determine whether this was a typo for another field name.
2988 FieldInitializerValidatorCCC CCC(RD);
2989 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2990 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2991 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2992 CorrectTypoKind::ErrorRecovery, RD)) {
2993 SemaRef.diagnoseTypo(
2994 Corrected,
2995 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2996 << FieldName << CurrentObjectType);
2997 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2998 hadError = true;
2999 } else {
3000 // Typo correction didn't find anything.
3001 SourceLocation Loc = D->getFieldLoc();
3002
3003 // The loc can be invalid with a "null" designator (i.e. an anonymous
3004 // union/struct). Do our best to approximate the location.
3005 if (Loc.isInvalid())
3006 Loc = IList->getBeginLoc();
3007
3008 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
3009 << FieldName << CurrentObjectType << DIE->getSourceRange();
3010 ++Index;
3011 return true;
3012 }
3013 }
3014 }
3015
3016 unsigned NumBases = 0;
3017 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3018 NumBases = CXXRD->getNumBases();
3019
3020 unsigned FieldIndex = NumBases;
3021
3022 for (auto *FI : RD->fields()) {
3023 if (FI->isUnnamedBitField())
3024 continue;
3025 if (declaresSameEntity(KnownField, FI)) {
3026 KnownField = FI;
3027 break;
3028 }
3029 ++FieldIndex;
3030 }
3031
3033 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
3034
3035 // All of the fields of a union are located at the same place in
3036 // the initializer list.
3037 if (RD->isUnion()) {
3038 FieldIndex = 0;
3039 if (StructuredList) {
3040 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
3041 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
3042 assert(StructuredList->getNumInits() == 1
3043 && "A union should never have more than one initializer!");
3044
3045 Expr *ExistingInit = StructuredList->getInit(0);
3046 if (ExistingInit) {
3047 // We're about to throw away an initializer, emit warning.
3048 diagnoseInitOverride(
3049 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
3050 /*UnionOverride=*/true,
3051 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
3052 : true);
3053 }
3054
3055 // remove existing initializer
3056 StructuredList->resizeInits(SemaRef.Context, 0);
3057 StructuredList->setInitializedFieldInUnion(nullptr);
3058 }
3059
3060 StructuredList->setInitializedFieldInUnion(*Field);
3061 }
3062 }
3063
3064 // Make sure we can use this declaration.
3065 bool InvalidUse;
3066 if (VerifyOnly)
3067 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
3068 else
3069 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
3070 if (InvalidUse) {
3071 ++Index;
3072 return true;
3073 }
3074
3075 // C++20 [dcl.init.list]p3:
3076 // The ordered identifiers in the designators of the designated-
3077 // initializer-list shall form a subsequence of the ordered identifiers
3078 // in the direct non-static data members of T.
3079 //
3080 // Note that this is not a condition on forming the aggregate
3081 // initialization, only on actually performing initialization,
3082 // so it is not checked in VerifyOnly mode.
3083 //
3084 // FIXME: This is the only reordering diagnostic we produce, and it only
3085 // catches cases where we have a top-level field designator that jumps
3086 // backwards. This is the only such case that is reachable in an
3087 // otherwise-valid C++20 program, so is the only case that's required for
3088 // conformance, but for consistency, we should diagnose all the other
3089 // cases where a designator takes us backwards too.
3090 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
3091 NextField &&
3092 (*NextField == RD->field_end() ||
3093 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
3094 // Find the field that we just initialized.
3095 FieldDecl *PrevField = nullptr;
3096 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
3097 if (FI->isUnnamedBitField())
3098 continue;
3099 if (*NextField != RD->field_end() &&
3100 declaresSameEntity(*FI, **NextField))
3101 break;
3102 PrevField = *FI;
3103 }
3104
3105 const auto GenerateDesignatedInitReorderingFixit =
3106 [&](SemaBase::SemaDiagnosticBuilder &Diag) {
3107 struct ReorderInfo {
3108 int Pos{};
3109 const Expr *InitExpr{};
3110 };
3111
3112 llvm::SmallDenseMap<IdentifierInfo *, int> MemberNameInx{};
3113 llvm::SmallVector<ReorderInfo, 16> ReorderedInitExprs{};
3114
3115 const auto *CxxRecord =
3117
3118 for (const FieldDecl *Field : CxxRecord->fields())
3119 MemberNameInx[Field->getIdentifier()] = Field->getFieldIndex();
3120
3121 for (const Expr *Init : IList->inits()) {
3122 if (const auto *DI =
3123 dyn_cast_if_present<DesignatedInitExpr>(Init)) {
3124 // We expect only one Designator
3125 if (DI->size() != 1)
3126 return;
3127
3128 const IdentifierInfo *const FieldName =
3129 DI->getDesignator(0)->getFieldName();
3130 // In case we have an unknown initializer in the source, not in
3131 // the record
3132 if (MemberNameInx.contains(FieldName))
3133 ReorderedInitExprs.emplace_back(
3134 ReorderInfo{MemberNameInx.at(FieldName), Init});
3135 }
3136 }
3137
3138 llvm::sort(ReorderedInitExprs,
3139 [](const ReorderInfo &A, const ReorderInfo &B) {
3140 return A.Pos < B.Pos;
3141 });
3142
3143 SourceManager &SM = SemaRef.getSourceManager();
3144 const LangOptions &LangOpts = SemaRef.getLangOpts();
3145
3146 // In a derived Record, first n base-classes are initialized first.
3147 // They do not use designated init, so skip them
3148 const ArrayRef<clang::Expr *> IListInits =
3149 IList->inits().drop_front(CxxRecord->getNumBases());
3150 // loop over each existing expressions and apply replacement
3151 for (const auto &[OrigExpr, Repl] :
3152 llvm::zip(IListInits, ReorderedInitExprs)) {
3153 CharSourceRange CharRange = CharSourceRange::getTokenRange(
3154 Repl.InitExpr->getSourceRange());
3155 const StringRef InitText =
3156 Lexer::getSourceText(CharRange, SM, LangOpts);
3157
3158 Diag << FixItHint::CreateReplacement(OrigExpr->getSourceRange(),
3159 InitText.str());
3160 }
3161 };
3162
3163 if (PrevField &&
3164 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
3165 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3166 diag::ext_designated_init_reordered)
3167 << KnownField << PrevField << DIE->getSourceRange();
3168
3169 unsigned OldIndex = StructuredIndex - 1;
3170 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
3171 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
3172 auto Diag = SemaRef.Diag(PrevInit->getBeginLoc(),
3173 diag::note_previous_field_init)
3174 << PrevField << PrevInit->getSourceRange();
3175 GenerateDesignatedInitReorderingFixit(Diag);
3176 }
3177 }
3178 }
3179 }
3180
3181
3182 // Update the designator with the field declaration.
3183 if (!VerifyOnly)
3184 D->setFieldDecl(*Field);
3185
3186 // Make sure that our non-designated initializer list has space
3187 // for a subobject corresponding to this field.
3188 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
3189 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
3190
3191 // This designator names a flexible array member.
3192 if (Field->getType()->isIncompleteArrayType()) {
3193 bool Invalid = false;
3194 if ((DesigIdx + 1) != DIE->size()) {
3195 // We can't designate an object within the flexible array
3196 // member (because GCC doesn't allow it).
3197 if (!VerifyOnly) {
3198 DesignatedInitExpr::Designator *NextD
3199 = DIE->getDesignator(DesigIdx + 1);
3200 SemaRef.Diag(NextD->getBeginLoc(),
3201 diag::err_designator_into_flexible_array_member)
3202 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
3203 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3204 << *Field;
3205 }
3206 Invalid = true;
3207 }
3208
3209 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
3210 !isa<StringLiteral>(DIE->getInit())) {
3211 // The initializer is not an initializer list.
3212 if (!VerifyOnly) {
3213 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3214 diag::err_flexible_array_init_needs_braces)
3215 << DIE->getInit()->getSourceRange();
3216 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3217 << *Field;
3218 }
3219 Invalid = true;
3220 }
3221
3222 // Check GNU flexible array initializer.
3223 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
3224 TopLevelObject))
3225 Invalid = true;
3226
3227 if (Invalid) {
3228 ++Index;
3229 return true;
3230 }
3231
3232 // Initialize the array.
3233 bool prevHadError = hadError;
3234 unsigned newStructuredIndex = FieldIndex;
3235 unsigned OldIndex = Index;
3236 IList->setInit(Index, DIE->getInit());
3237
3238 InitializedEntity MemberEntity =
3239 InitializedEntity::InitializeMember(*Field, &Entity);
3240 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
3241 StructuredList, newStructuredIndex);
3242
3243 IList->setInit(OldIndex, DIE);
3244 if (hadError && !prevHadError) {
3245 ++Field;
3246 ++FieldIndex;
3247 if (NextField)
3248 *NextField = Field;
3249 StructuredIndex = FieldIndex;
3250 return true;
3251 }
3252 } else {
3253 // Recurse to check later designated subobjects.
3254 QualType FieldType = Field->getType();
3255 unsigned newStructuredIndex = FieldIndex;
3256
3257 InitializedEntity MemberEntity =
3258 InitializedEntity::InitializeMember(*Field, &Entity);
3259 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
3260 FieldType, nullptr, nullptr, Index,
3261 StructuredList, newStructuredIndex,
3262 FinishSubobjectInit, false))
3263 return true;
3264 }
3265
3266 // Find the position of the next field to be initialized in this
3267 // subobject.
3268 ++Field;
3269 ++FieldIndex;
3270
3271 // If this the first designator, our caller will continue checking
3272 // the rest of this struct/class/union subobject.
3273 if (IsFirstDesignator) {
3274 if (Field != RD->field_end() && Field->isUnnamedBitField())
3275 ++Field;
3276
3277 if (NextField)
3278 *NextField = Field;
3279
3280 StructuredIndex = FieldIndex;
3281 return false;
3282 }
3283
3284 if (!FinishSubobjectInit)
3285 return false;
3286
3287 // We've already initialized something in the union; we're done.
3288 if (RD->isUnion())
3289 return hadError;
3290
3291 // Check the remaining fields within this class/struct/union subobject.
3292 bool prevHadError = hadError;
3293
3294 auto NoBases =
3297 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
3298 false, Index, StructuredList, FieldIndex);
3299 return hadError && !prevHadError;
3300 }
3301
3302 // C99 6.7.8p6:
3303 //
3304 // If a designator has the form
3305 //
3306 // [ constant-expression ]
3307 //
3308 // then the current object (defined below) shall have array
3309 // type and the expression shall be an integer constant
3310 // expression. If the array is of unknown size, any
3311 // nonnegative value is valid.
3312 //
3313 // Additionally, cope with the GNU extension that permits
3314 // designators of the form
3315 //
3316 // [ constant-expression ... constant-expression ]
3317 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
3318 if (!AT) {
3319 if (!VerifyOnly)
3320 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3321 << CurrentObjectType;
3322 ++Index;
3323 return true;
3324 }
3325
3326 Expr *IndexExpr = nullptr;
3327 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3328 if (D->isArrayDesignator()) {
3329 IndexExpr = DIE->getArrayIndex(*D);
3330 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3331 DesignatedEndIndex = DesignatedStartIndex;
3332 } else {
3333 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3334
3335 DesignatedStartIndex =
3337 DesignatedEndIndex =
3339 IndexExpr = DIE->getArrayRangeEnd(*D);
3340
3341 // Codegen can't handle evaluating array range designators that have side
3342 // effects, because we replicate the AST value for each initialized element.
3343 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3344 // elements with something that has a side effect, so codegen can emit an
3345 // "error unsupported" error instead of miscompiling the app.
3346 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3347 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3348 FullyStructuredList->sawArrayRangeDesignator();
3349 }
3350
3351 if (isa<ConstantArrayType>(AT)) {
3352 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3353 DesignatedStartIndex
3354 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3355 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3356 DesignatedEndIndex
3357 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3358 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3359 if (DesignatedEndIndex >= MaxElements) {
3360 if (!VerifyOnly)
3361 SemaRef.Diag(IndexExpr->getBeginLoc(),
3362 diag::err_array_designator_too_large)
3363 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3364 << IndexExpr->getSourceRange();
3365 ++Index;
3366 return true;
3367 }
3368 } else {
3369 unsigned DesignatedIndexBitWidth =
3371 DesignatedStartIndex =
3372 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3373 DesignatedEndIndex =
3374 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3375 DesignatedStartIndex.setIsUnsigned(true);
3376 DesignatedEndIndex.setIsUnsigned(true);
3377 }
3378
3379 bool IsStringLiteralInitUpdate =
3380 StructuredList && StructuredList->isStringLiteralInit();
3381 if (IsStringLiteralInitUpdate && VerifyOnly) {
3382 // We're just verifying an update to a string literal init. We don't need
3383 // to split the string up into individual characters to do that.
3384 StructuredList = nullptr;
3385 } else if (IsStringLiteralInitUpdate) {
3386 // We're modifying a string literal init; we have to decompose the string
3387 // so we can modify the individual characters.
3388 ASTContext &Context = SemaRef.Context;
3389 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3390
3391 // Compute the character type
3392 QualType CharTy = AT->getElementType();
3393
3394 // Compute the type of the integer literals.
3395 QualType PromotedCharTy = CharTy;
3396 if (Context.isPromotableIntegerType(CharTy))
3397 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3398 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3399
3400 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3401 // Get the length of the string.
3402 uint64_t StrLen = SL->getLength();
3403 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3404 CAT && CAT->getSize().ult(StrLen))
3405 StrLen = CAT->getZExtSize();
3406 StructuredList->resizeInits(Context, StrLen);
3407
3408 // Build a literal for each character in the string, and put them into
3409 // the init list.
3410 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3411 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3412 Expr *Init = new (Context) IntegerLiteral(
3413 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3414 if (CharTy != PromotedCharTy)
3415 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3416 Init, nullptr, VK_PRValue,
3417 FPOptionsOverride());
3418 StructuredList->updateInit(Context, i, Init);
3419 }
3420 } else {
3421 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3422 std::string Str;
3423 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3424
3425 // Get the length of the string.
3426 uint64_t StrLen = Str.size();
3427 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3428 CAT && CAT->getSize().ult(StrLen))
3429 StrLen = CAT->getZExtSize();
3430 StructuredList->resizeInits(Context, StrLen);
3431
3432 // Build a literal for each character in the string, and put them into
3433 // the init list.
3434 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3435 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3436 Expr *Init = new (Context) IntegerLiteral(
3437 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3438 if (CharTy != PromotedCharTy)
3439 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3440 Init, nullptr, VK_PRValue,
3441 FPOptionsOverride());
3442 StructuredList->updateInit(Context, i, Init);
3443 }
3444 }
3445 }
3446
3447 // Make sure that our non-designated initializer list has space
3448 // for a subobject corresponding to this array element.
3449 if (StructuredList &&
3450 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3451 StructuredList->resizeInits(SemaRef.Context,
3452 DesignatedEndIndex.getZExtValue() + 1);
3453
3454 // Repeatedly perform subobject initializations in the range
3455 // [DesignatedStartIndex, DesignatedEndIndex].
3456
3457 // Move to the next designator
3458 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3459 unsigned OldIndex = Index;
3460
3461 InitializedEntity ElementEntity =
3463
3464 while (DesignatedStartIndex <= DesignatedEndIndex) {
3465 // Recurse to check later designated subobjects.
3466 QualType ElementType = AT->getElementType();
3467 Index = OldIndex;
3468
3469 ElementEntity.setElementIndex(ElementIndex);
3470 if (CheckDesignatedInitializer(
3471 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3472 nullptr, Index, StructuredList, ElementIndex,
3473 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3474 false))
3475 return true;
3476
3477 // Move to the next index in the array that we'll be initializing.
3478 ++DesignatedStartIndex;
3479 ElementIndex = DesignatedStartIndex.getZExtValue();
3480 }
3481
3482 // If this the first designator, our caller will continue checking
3483 // the rest of this array subobject.
3484 if (IsFirstDesignator) {
3485 if (NextElementIndex)
3486 *NextElementIndex = std::move(DesignatedStartIndex);
3487 StructuredIndex = ElementIndex;
3488 return false;
3489 }
3490
3491 if (!FinishSubobjectInit)
3492 return false;
3493
3494 // Check the remaining elements within this array subobject.
3495 bool prevHadError = hadError;
3496 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3497 /*SubobjectIsDesignatorContext=*/false, Index,
3498 StructuredList, ElementIndex);
3499 return hadError && !prevHadError;
3500}
3501
3502// Get the structured initializer list for a subobject of type
3503// @p CurrentObjectType.
3504InitListExpr *
3505InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3506 QualType CurrentObjectType,
3507 InitListExpr *StructuredList,
3508 unsigned StructuredIndex,
3509 SourceRange InitRange,
3510 bool IsFullyOverwritten) {
3511 if (!StructuredList)
3512 return nullptr;
3513
3514 Expr *ExistingInit = nullptr;
3515 if (StructuredIndex < StructuredList->getNumInits())
3516 ExistingInit = StructuredList->getInit(StructuredIndex);
3517
3518 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3519 // There might have already been initializers for subobjects of the current
3520 // object, but a subsequent initializer list will overwrite the entirety
3521 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3522 //
3523 // struct P { char x[6]; };
3524 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3525 //
3526 // The first designated initializer is ignored, and l.x is just "f".
3527 if (!IsFullyOverwritten)
3528 return Result;
3529
3530 if (ExistingInit) {
3531 // We are creating an initializer list that initializes the
3532 // subobjects of the current object, but there was already an
3533 // initialization that completely initialized the current
3534 // subobject:
3535 //
3536 // struct X { int a, b; };
3537 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3538 //
3539 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3540 // designated initializer overwrites the [0].b initializer
3541 // from the prior initialization.
3542 //
3543 // When the existing initializer is an expression rather than an
3544 // initializer list, we cannot decompose and update it in this way.
3545 // For example:
3546 //
3547 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3548 //
3549 // This case is handled by CheckDesignatedInitializer.
3550 diagnoseInitOverride(ExistingInit, InitRange);
3551 }
3552
3553 unsigned ExpectedNumInits = 0;
3554 if (Index < IList->getNumInits()) {
3555 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3556 ExpectedNumInits = Init->getNumInits();
3557 else
3558 ExpectedNumInits = IList->getNumInits() - Index;
3559 }
3560
3561 InitListExpr *Result = createInitListExpr(
3562 CurrentObjectType, InitRange, ExpectedNumInits, /*IsExplicit=*/false);
3563
3564 // Link this new initializer list into the structured initializer
3565 // lists.
3566 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3567 return Result;
3568}
3569
3570InitListExpr *InitListChecker::createInitListExpr(QualType CurrentObjectType,
3571 SourceRange InitRange,
3572 unsigned ExpectedNumInits,
3573 bool IsExplicit) {
3574 InitListExpr *Result =
3575 new (SemaRef.Context) InitListExpr(SemaRef.Context, InitRange.getBegin(),
3576 {}, InitRange.getEnd(), IsExplicit);
3577
3578 QualType ResultType = CurrentObjectType;
3579 if (!ResultType->isArrayType())
3580 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3581 Result->setType(ResultType);
3582
3583 // Pre-allocate storage for the structured initializer list.
3584 unsigned NumElements = 0;
3585
3586 if (const ArrayType *AType
3587 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3588 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3589 NumElements = CAType->getZExtSize();
3590 // Simple heuristic so that we don't allocate a very large
3591 // initializer with many empty entries at the end.
3592 if (NumElements > ExpectedNumInits)
3593 NumElements = 0;
3594 }
3595 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3596 NumElements = VType->getNumElements();
3597 } else if (CurrentObjectType->isRecordType()) {
3598 NumElements = numStructUnionElements(CurrentObjectType);
3599 } else if (CurrentObjectType->isDependentType()) {
3600 NumElements = 1;
3601 }
3602
3603 Result->reserveInits(SemaRef.Context, NumElements);
3604
3605 return Result;
3606}
3607
3608/// Update the initializer at index @p StructuredIndex within the
3609/// structured initializer list to the value @p expr.
3610void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3611 unsigned &StructuredIndex,
3612 Expr *expr) {
3613 // No structured initializer list to update
3614 if (!StructuredList)
3615 return;
3616
3617 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3618 StructuredIndex, expr)) {
3619 // This initializer overwrites a previous initializer.
3620 // No need to diagnose when `expr` is nullptr because a more relevant
3621 // diagnostic has already been issued and this diagnostic is potentially
3622 // noise.
3623 if (expr)
3624 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3625 }
3626
3627 ++StructuredIndex;
3628}
3629
3631 const InitializedEntity &Entity, InitListExpr *From) {
3632 QualType Type = Entity.getType();
3633 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3634 /*TreatUnavailableAsInvalid=*/false,
3635 /*InOverloadResolution=*/true);
3636 return !Check.HadError();
3637}
3638
3640 SmallVectorImpl<Expr *> &Storage) {
3641 auto AsMultiElementEmbed = [](Expr *Init) {
3642 auto *Embed = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts());
3643 return Embed && Embed->getDataElementCount() > 1 ? Embed : nullptr;
3644 };
3645 if (llvm::none_of(ILE->inits(), AsMultiElementEmbed))
3646 return MultiExprArg(ILE->getInits(), ILE->getNumInits());
3647
3648 Storage.clear();
3649 Storage.reserve(ILE->getNumInitsWithEmbedExpanded());
3650 for (Expr *Init : ILE->inits()) {
3651 EmbedExpr *Embed = AsMultiElementEmbed(Init);
3652 if (!Embed) {
3653 Storage.push_back(Init);
3654 continue;
3655 }
3656 for (unsigned I = Embed->getStartingElementPos(),
3657 E = I + Embed->getDataElementCount();
3658 I != E; ++I)
3659 Storage.push_back(new (Context) EmbedExpr(Context, Embed->getLocation(),
3660 Embed->getData(), I, 1));
3661 }
3662 return Storage;
3663}
3664
3665/// Check that the given Index expression is a valid array designator
3666/// value. This is essentially just a wrapper around
3667/// VerifyIntegerConstantExpression that also checks for negative values
3668/// and produces a reasonable diagnostic if there is a
3669/// failure. Returns the index expression, possibly with an implicit cast
3670/// added, on success. If everything went okay, Value will receive the
3671/// value of the constant expression.
3672static ExprResult
3673CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3674 SourceLocation Loc = Index->getBeginLoc();
3675
3676 // Make sure this is an integer constant expression.
3679 if (Result.isInvalid())
3680 return Result;
3681
3682 if (Value.isSigned() && Value.isNegative())
3683 return S.Diag(Loc, diag::err_array_designator_negative)
3684 << toString(Value, 10) << Index->getSourceRange();
3685
3686 Value.setIsUnsigned(true);
3687 return Result;
3688}
3689
3691 SourceLocation EqualOrColonLoc,
3692 bool GNUSyntax,
3693 ExprResult Init) {
3694 typedef DesignatedInitExpr::Designator ASTDesignator;
3695
3696 bool Invalid = false;
3698 SmallVector<Expr *, 32> InitExpressions;
3699
3700 // Build designators and check array designator expressions.
3701 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3702 const Designator &D = Desig.getDesignator(Idx);
3703
3704 if (D.isFieldDesignator()) {
3705 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3706 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3707 } else if (D.isArrayDesignator()) {
3708 Expr *Index = D.getArrayIndex();
3709 llvm::APSInt IndexValue;
3710 if (!Index->isTypeDependent() && !Index->isValueDependent())
3711 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3712 if (!Index)
3713 Invalid = true;
3714 else {
3715 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3716 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3717 InitExpressions.push_back(Index);
3718 }
3719 } else if (D.isArrayRangeDesignator()) {
3720 Expr *StartIndex = D.getArrayRangeStart();
3721 Expr *EndIndex = D.getArrayRangeEnd();
3722 llvm::APSInt StartValue;
3723 llvm::APSInt EndValue;
3724 bool StartDependent = StartIndex->isTypeDependent() ||
3725 StartIndex->isValueDependent();
3726 bool EndDependent = EndIndex->isTypeDependent() ||
3727 EndIndex->isValueDependent();
3728 if (!StartDependent)
3729 StartIndex =
3730 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3731 if (!EndDependent)
3732 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3733
3734 if (!StartIndex || !EndIndex)
3735 Invalid = true;
3736 else {
3737 // Make sure we're comparing values with the same bit width.
3738 if (StartDependent || EndDependent) {
3739 // Nothing to compute.
3740 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3741 EndValue = EndValue.extend(StartValue.getBitWidth());
3742 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3743 StartValue = StartValue.extend(EndValue.getBitWidth());
3744
3745 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3746 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3747 << toString(StartValue, 10) << toString(EndValue, 10)
3748 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3749 Invalid = true;
3750 } else {
3751 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3752 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3753 D.getRBracketLoc()));
3754 InitExpressions.push_back(StartIndex);
3755 InitExpressions.push_back(EndIndex);
3756 }
3757 }
3758 }
3759 }
3760
3761 if (Invalid || Init.isInvalid())
3762 return ExprError();
3763
3764 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3765 EqualOrColonLoc, GNUSyntax,
3766 Init.getAs<Expr>());
3767}
3768
3769//===----------------------------------------------------------------------===//
3770// Initialization entity
3771//===----------------------------------------------------------------------===//
3772
3773InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3774 const InitializedEntity &Parent)
3775 : Parent(&Parent), Index(Index)
3776{
3777 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3778 Kind = EK_ArrayElement;
3779 Type = AT->getElementType();
3780 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3781 Kind = EK_VectorElement;
3782 Type = VT->getElementType();
3783 } else if (const MatrixType *MT = Parent.getType()->getAs<MatrixType>()) {
3784 Kind = EK_MatrixElement;
3785 Type = MT->getElementType();
3786 } else {
3787 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3788 assert(CT && "Unexpected type");
3789 Kind = EK_ComplexElement;
3790 Type = CT->getElementType();
3791 }
3792}
3793
3796 const CXXBaseSpecifier *Base,
3797 bool IsInheritedVirtualBase,
3798 const InitializedEntity *Parent) {
3799 InitializedEntity Result;
3800 Result.Kind = EK_Base;
3801 Result.Parent = Parent;
3802 Result.Base = {Base, IsInheritedVirtualBase};
3803 Result.Type = Base->getType();
3804 return Result;
3805}
3806
3808 switch (getKind()) {
3809 case EK_Parameter:
3811 ParmVarDecl *D = Parameter.getPointer();
3812 return (D ? D->getDeclName() : DeclarationName());
3813 }
3814
3815 case EK_Variable:
3816 case EK_Member:
3818 case EK_Binding:
3820 return Variable.VariableOrMember->getDeclName();
3821
3822 case EK_LambdaCapture:
3823 return DeclarationName(Capture.VarID);
3824
3825 case EK_Result:
3826 case EK_StmtExprResult:
3827 case EK_Exception:
3828 case EK_New:
3829 case EK_Temporary:
3830 case EK_Base:
3831 case EK_Delegating:
3832 case EK_ArrayElement:
3833 case EK_VectorElement:
3834 case EK_MatrixElement:
3835 case EK_ComplexElement:
3836 case EK_BlockElement:
3839 case EK_RelatedResult:
3840 return DeclarationName();
3841 }
3842
3843 llvm_unreachable("Invalid EntityKind!");
3844}
3845
3847 switch (getKind()) {
3848 case EK_Variable:
3849 case EK_Member:
3851 case EK_Binding:
3853 return cast<ValueDecl>(Variable.VariableOrMember);
3854
3855 case EK_Parameter:
3857 return Parameter.getPointer();
3858
3859 case EK_Result:
3860 case EK_StmtExprResult:
3861 case EK_Exception:
3862 case EK_New:
3863 case EK_Temporary:
3864 case EK_Base:
3865 case EK_Delegating:
3866 case EK_ArrayElement:
3867 case EK_VectorElement:
3868 case EK_MatrixElement:
3869 case EK_ComplexElement:
3870 case EK_BlockElement:
3872 case EK_LambdaCapture:
3874 case EK_RelatedResult:
3875 return nullptr;
3876 }
3877
3878 llvm_unreachable("Invalid EntityKind!");
3879}
3880
3882 switch (getKind()) {
3883 case EK_Result:
3884 case EK_Exception:
3885 return LocAndNRVO.NRVO == NRVOKind::Allowed;
3886
3887 case EK_StmtExprResult:
3888 case EK_Variable:
3889 case EK_Parameter:
3892 case EK_Member:
3894 case EK_Binding:
3895 case EK_New:
3896 case EK_Temporary:
3898 case EK_Base:
3899 case EK_Delegating:
3900 case EK_ArrayElement:
3901 case EK_VectorElement:
3902 case EK_MatrixElement:
3903 case EK_ComplexElement:
3904 case EK_BlockElement:
3906 case EK_LambdaCapture:
3907 case EK_RelatedResult:
3908 break;
3909 }
3910
3911 return false;
3912}
3913
3914unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3915 assert(getParent() != this);
3916 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3917 for (unsigned I = 0; I != Depth; ++I)
3918 OS << "`-";
3919
3920 switch (getKind()) {
3921 case EK_Variable: OS << "Variable"; break;
3922 case EK_Parameter: OS << "Parameter"; break;
3923 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3924 break;
3925 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3926 case EK_Result: OS << "Result"; break;
3927 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3928 case EK_Exception: OS << "Exception"; break;
3929 case EK_Member:
3931 OS << "Member";
3932 break;
3933 case EK_Binding: OS << "Binding"; break;
3934 case EK_New: OS << "New"; break;
3935 case EK_Temporary: OS << "Temporary"; break;
3936 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3937 case EK_RelatedResult: OS << "RelatedResult"; break;
3938 case EK_Base: OS << "Base"; break;
3939 case EK_Delegating: OS << "Delegating"; break;
3940 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3941 case EK_VectorElement: OS << "VectorElement " << Index; break;
3942 case EK_MatrixElement:
3943 OS << "MatrixElement " << Index;
3944 break;
3945 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3946 case EK_BlockElement: OS << "Block"; break;
3948 OS << "Block (lambda)";
3949 break;
3950 case EK_LambdaCapture:
3951 OS << "LambdaCapture ";
3952 OS << DeclarationName(Capture.VarID);
3953 break;
3954 }
3955
3956 if (auto *D = getDecl()) {
3957 OS << " ";
3958 D->printQualifiedName(OS);
3959 }
3960
3961 OS << " '" << getType() << "'\n";
3962
3963 return Depth + 1;
3964}
3965
3966LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3967 dumpImpl(llvm::errs());
3968}
3969
3970//===----------------------------------------------------------------------===//
3971// Initialization sequence
3972//===----------------------------------------------------------------------===//
3973
4020
4022 // There can be some lvalue adjustments after the SK_BindReference step.
4023 for (const Step &S : llvm::reverse(Steps)) {
4024 if (S.Kind == SK_BindReference)
4025 return true;
4026 if (S.Kind == SK_BindReferenceToTemporary)
4027 return false;
4028 }
4029 return false;
4030}
4031
4033 if (!Failed())
4034 return false;
4035
4036 switch (getFailureKind()) {
4047 case FK_AddressOfOverloadFailed: // FIXME: Could do better
4064 case FK_Incomplete:
4069 case FK_PlaceholderType:
4075 return false;
4076
4081 return FailedOverloadResult == OR_Ambiguous;
4082 }
4083
4084 llvm_unreachable("Invalid EntityKind!");
4085}
4086
4088 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
4089}
4090
4091void
4092InitializationSequence
4093::AddAddressOverloadResolutionStep(FunctionDecl *Function,
4095 bool HadMultipleCandidates) {
4096 Step S;
4098 S.Type = Function->getType();
4099 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4102 Steps.push_back(S);
4103}
4104
4106 ExprValueKind VK) {
4107 Step S;
4108 switch (VK) {
4109 case VK_PRValue:
4111 break;
4112 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
4113 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
4114 }
4115 S.Type = BaseType;
4116 Steps.push_back(S);
4117}
4118
4120 bool BindingTemporary) {
4121 Step S;
4122 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
4123 S.Type = T;
4124 Steps.push_back(S);
4125}
4126
4128 Step S;
4129 S.Kind = SK_FinalCopy;
4130 S.Type = T;
4131 Steps.push_back(S);
4132}
4133
4135 Step S;
4137 S.Type = T;
4138 Steps.push_back(S);
4139}
4140
4141void
4143 DeclAccessPair FoundDecl,
4144 QualType T,
4145 bool HadMultipleCandidates) {
4146 Step S;
4148 S.Type = T;
4149 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4151 S.Function.FoundDecl = FoundDecl;
4152 Steps.push_back(S);
4153}
4154
4156 ExprValueKind VK) {
4157 Step S;
4158 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
4159 switch (VK) {
4160 case VK_PRValue:
4162 break;
4163 case VK_XValue:
4165 break;
4166 case VK_LValue:
4168 break;
4169 }
4170 S.Type = Ty;
4171 Steps.push_back(S);
4172}
4173
4175 Step S;
4177 S.Type = Ty;
4178 Steps.push_back(S);
4179}
4180
4182 Step S;
4184 S.Type = Ty;
4185 Steps.push_back(S);
4186}
4187
4190 bool TopLevelOfInitList) {
4191 Step S;
4192 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
4194 S.Type = T;
4195 S.ICS = new ImplicitConversionSequence(ICS);
4196 Steps.push_back(S);
4197}
4198
4200 Step S;
4202 S.Type = T;
4203 Steps.push_back(S);
4204}
4205
4208 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
4209 Step S;
4210 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
4213 S.Type = T;
4214 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4216 S.Function.FoundDecl = FoundDecl;
4217 Steps.push_back(S);
4218}
4219
4221 Step S;
4223 S.Type = T;
4224 Steps.push_back(S);
4225}
4226
4228 Step S;
4229 S.Kind = SK_CAssignment;
4230 S.Type = T;
4231 Steps.push_back(S);
4232}
4233
4235 Step S;
4236 S.Kind = SK_StringInit;
4237 S.Type = T;
4238 Steps.push_back(S);
4239}
4240
4242 Step S;
4244 S.Type = T;
4245 Steps.push_back(S);
4246}
4247
4249 Step S;
4250 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
4251 S.Type = T;
4252 Steps.push_back(S);
4253}
4254
4256 Step S;
4258 S.Type = EltT;
4259 Steps.insert(Steps.begin(), S);
4260
4262 S.Type = T;
4263 Steps.push_back(S);
4264}
4265
4267 Step S;
4269 S.Type = T;
4270 Steps.push_back(S);
4271}
4272
4274 bool shouldCopy) {
4275 Step s;
4276 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
4278 s.Type = type;
4279 Steps.push_back(s);
4280}
4281
4283 Step S;
4285 S.Type = T;
4286 Steps.push_back(S);
4287}
4288
4290 Step S;
4292 S.Type = T;
4293 Steps.push_back(S);
4294}
4295
4297 Step S;
4299 S.Type = T;
4300 Steps.push_back(S);
4301}
4302
4304 Step S;
4306 S.Type = T;
4307 Steps.push_back(S);
4308}
4309
4311 Step S;
4313 S.Type = T;
4314 Steps.push_back(S);
4315}
4316
4318 InitListExpr *Syntactic) {
4319 assert(Syntactic->getNumInits() == 1 &&
4320 "Can only unwrap trivial init lists.");
4321 Step S;
4323 S.Type = Syntactic->getInit(0)->getType();
4324 Steps.insert(Steps.begin(), S);
4325}
4326
4328 InitListExpr *Syntactic) {
4329 assert(Syntactic->getNumInits() == 1 &&
4330 "Can only rewrap trivial init lists.");
4331 Step S;
4333 S.Type = Syntactic->getInit(0)->getType();
4334 Steps.insert(Steps.begin(), S);
4335
4337 S.Type = T;
4338 S.WrappingSyntacticList = Syntactic;
4339 Steps.push_back(S);
4340}
4341
4343 Step S;
4345 S.Type = T;
4346 Steps.push_back(S);
4347}
4348
4352 this->Failure = Failure;
4353 this->FailedOverloadResult = Result;
4354}
4355
4356//===----------------------------------------------------------------------===//
4357// Attempt initialization
4358//===----------------------------------------------------------------------===//
4359
4360/// Tries to add a zero initializer. Returns true if that worked.
4361static bool
4363 const InitializedEntity &Entity) {
4365 return false;
4366
4367 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
4368 if (VD->getInit() || VD->getEndLoc().isMacroID())
4369 return false;
4370
4371 QualType VariableTy = VD->getType().getCanonicalType();
4373 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
4374 if (!Init.empty()) {
4375 Sequence.AddZeroInitializationStep(Entity.getType());
4376 Sequence.SetZeroInitializationFixit(Init, Loc);
4377 return true;
4378 }
4379 return false;
4380}
4381
4383 InitializationSequence &Sequence,
4384 const InitializedEntity &Entity) {
4385 if (!S.getLangOpts().ObjCAutoRefCount) return;
4386
4387 /// When initializing a parameter, produce the value if it's marked
4388 /// __attribute__((ns_consumed)).
4389 if (Entity.isParameterKind()) {
4390 if (!Entity.isParameterConsumed())
4391 return;
4392
4393 assert(Entity.getType()->isObjCRetainableType() &&
4394 "consuming an object of unretainable type?");
4395 Sequence.AddProduceObjCObjectStep(Entity.getType());
4396
4397 /// When initializing a return value, if the return type is a
4398 /// retainable type, then returns need to immediately retain the
4399 /// object. If an autorelease is required, it will be done at the
4400 /// last instant.
4401 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4403 if (!Entity.getType()->isObjCRetainableType())
4404 return;
4405
4406 Sequence.AddProduceObjCObjectStep(Entity.getType());
4407 }
4408}
4409
4410/// Initialize an array from another array
4411static void TryArrayCopy(Sema &S, const InitializationKind &Kind,
4412 const InitializedEntity &Entity, Expr *Initializer,
4413 QualType DestType, InitializationSequence &Sequence,
4414 bool TreatUnavailableAsInvalid) {
4415 // If source is a prvalue, use it directly.
4416 if (Initializer->isPRValue()) {
4417 Sequence.AddArrayInitStep(DestType, /*IsGNUExtension*/ false);
4418 return;
4419 }
4420
4421 // Emit element-at-a-time copy loop.
4422 InitializedEntity Element =
4424 QualType InitEltT =
4426
4427 // FIXME: Here's a functional memory leak cuz we don't have a temporary
4428 // allocator at the moment
4430 Initializer->getExprLoc(), InitEltT, Initializer->getValueKind(),
4431 Initializer->getObjectKind());
4432 Expr *OVEAsExpr = OVE;
4433 Sequence.InitializeFrom(S, Element, Kind, OVEAsExpr,
4434 /*TopLevelOfInitList*/ false,
4435 TreatUnavailableAsInvalid);
4436 if (Sequence)
4437 Sequence.AddArrayInitLoopStep(Entity.getType(), InitEltT);
4438}
4439
4440static void TryListInitialization(Sema &S,
4441 const InitializedEntity &Entity,
4442 const InitializationKind &Kind,
4443 InitListExpr *InitList,
4444 InitializationSequence &Sequence,
4445 bool TreatUnavailableAsInvalid);
4446
4447/// When initializing from init list via constructor, handle
4448/// initialization of an object of type std::initializer_list<T>.
4449///
4450/// \return true if we have handled initialization of an object of type
4451/// std::initializer_list<T>, false otherwise.
4453 InitListExpr *List,
4454 QualType DestType,
4455 InitializationSequence &Sequence,
4456 bool TreatUnavailableAsInvalid) {
4457 QualType E;
4458 if (!S.isStdInitializerList(DestType, &E))
4459 return false;
4460
4461 if (!S.isCompleteType(List->getExprLoc(), E)) {
4462 Sequence.setIncompleteTypeFailure(E);
4463 return true;
4464 }
4465
4466 // Try initializing a temporary array from the init list.
4468 E.withConst(),
4469 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4472 InitializedEntity HiddenArray =
4475 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4476 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4477 TreatUnavailableAsInvalid);
4478 if (Sequence)
4479 Sequence.AddStdInitializerListConstructionStep(DestType);
4480 return true;
4481}
4482
4483/// Determine if the constructor has the signature of a copy or move
4484/// constructor for the type T of the class in which it was found. That is,
4485/// determine if its first parameter is of type T or reference to (possibly
4486/// cv-qualified) T.
4488 const ConstructorInfo &Info) {
4489 if (Info.Constructor->getNumParams() == 0)
4490 return false;
4491
4492 QualType ParmT =
4494 CanQualType ClassT = Ctx.getCanonicalTagType(
4496
4497 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4498}
4499
4501 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4502 OverloadCandidateSet &CandidateSet, QualType DestType,
4504 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4505 bool IsListInit, bool RequireActualConstructor,
4506 bool SecondStepOfCopyInit = false) {
4508 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4509
4510 for (NamedDecl *D : Ctors) {
4511 auto Info = getConstructorInfo(D);
4512 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4513 continue;
4514
4515 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4516 continue;
4517
4518 // C++11 [over.best.ics]p4:
4519 // ... and the constructor or user-defined conversion function is a
4520 // candidate by
4521 // - 13.3.1.3, when the argument is the temporary in the second step
4522 // of a class copy-initialization, or
4523 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4524 // - the second phase of 13.3.1.7 when the initializer list has exactly
4525 // one element that is itself an initializer list, and the target is
4526 // the first parameter of a constructor of class X, and the conversion
4527 // is to X or reference to (possibly cv-qualified X),
4528 // user-defined conversion sequences are not considered.
4529 bool SuppressUserConversions =
4530 SecondStepOfCopyInit ||
4531 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4533
4534 if (Info.ConstructorTmpl)
4536 Info.ConstructorTmpl, Info.FoundDecl,
4537 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4538 /*PartialOverloading=*/false, AllowExplicit);
4539 else {
4540 // C++ [over.match.copy]p1:
4541 // - When initializing a temporary to be bound to the first parameter
4542 // of a constructor [for type T] that takes a reference to possibly
4543 // cv-qualified T as its first argument, called with a single
4544 // argument in the context of direct-initialization, explicit
4545 // conversion functions are also considered.
4546 // FIXME: What if a constructor template instantiates to such a signature?
4547 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4548 Args.size() == 1 &&
4550 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4551 CandidateSet, SuppressUserConversions,
4552 /*PartialOverloading=*/false, AllowExplicit,
4553 AllowExplicitConv);
4554 }
4555 }
4556
4557 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4558 //
4559 // When initializing an object of class type T by constructor
4560 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4561 // from a single expression of class type U, conversion functions of
4562 // U that convert to the non-reference type cv T are candidates.
4563 // Explicit conversion functions are only candidates during
4564 // direct-initialization.
4565 //
4566 // Note: SecondStepOfCopyInit is only ever true in this case when
4567 // evaluating whether to produce a C++98 compatibility warning.
4568 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4569 !RequireActualConstructor && !SecondStepOfCopyInit) {
4570 Expr *Initializer = Args[0];
4571 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4572 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4573 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4574 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4575 NamedDecl *D = *I;
4577 D = D->getUnderlyingDecl();
4578
4579 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4580 CXXConversionDecl *Conv;
4581 if (ConvTemplate)
4582 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4583 else
4584 Conv = cast<CXXConversionDecl>(D);
4585
4586 if (ConvTemplate)
4588 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4589 CandidateSet, AllowExplicit, AllowExplicit,
4590 /*AllowResultConversion*/ false);
4591 else
4592 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4593 DestType, CandidateSet, AllowExplicit,
4594 AllowExplicit,
4595 /*AllowResultConversion*/ false);
4596 }
4597 }
4598 }
4599
4600 // Perform overload resolution and return the result.
4601 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4602}
4603
4604/// Attempt initialization by constructor (C++ [dcl.init]), which
4605/// enumerates the constructors of the initialized entity and performs overload
4606/// resolution to select the best.
4607/// \param DestType The destination class type.
4608/// \param DestArrayType The destination type, which is either DestType or
4609/// a (possibly multidimensional) array of DestType.
4610/// \param IsListInit Is this list-initialization?
4611/// \param IsInitListCopy Is this non-list-initialization resulting from a
4612/// list-initialization from {x} where x is the same
4613/// aggregate type as the entity?
4615 const InitializedEntity &Entity,
4616 const InitializationKind &Kind,
4617 MultiExprArg Args, QualType DestType,
4618 QualType DestArrayType,
4619 InitializationSequence &Sequence,
4620 bool IsListInit = false,
4621 bool IsInitListCopy = false) {
4622 assert(((!IsListInit && !IsInitListCopy) ||
4623 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4624 "IsListInit/IsInitListCopy must come with a single initializer list "
4625 "argument.");
4626 InitListExpr *ILE =
4627 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4628 SmallVector<Expr *, 8> ExpandedInits;
4629 MultiExprArg UnwrappedArgs =
4630 ILE ? S.getInitsWithEmbedExpanded(ILE, ExpandedInits) : Args;
4631
4632 // The type we're constructing needs to be complete.
4633 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4634 Sequence.setIncompleteTypeFailure(DestType);
4635 return;
4636 }
4637
4638 bool RequireActualConstructor =
4639 !(Entity.getKind() != InitializedEntity::EK_Base &&
4641 Entity.getKind() !=
4643
4644 bool CopyElisionPossible = false;
4645 auto ElideConstructor = [&] {
4646 // Convert qualifications if necessary.
4647 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4648 if (ILE)
4649 Sequence.RewrapReferenceInitList(DestType, ILE);
4650 };
4651
4652 // C++17 [dcl.init]p17:
4653 // - If the initializer expression is a prvalue and the cv-unqualified
4654 // version of the source type is the same class as the class of the
4655 // destination, the initializer expression is used to initialize the
4656 // destination object.
4657 // Per DR (no number yet), this does not apply when initializing a base
4658 // class or delegating to another constructor from a mem-initializer.
4659 // ObjC++: Lambda captured by the block in the lambda to block conversion
4660 // should avoid copy elision.
4661 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4662 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4663 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4664 if (ILE && !DestType->isAggregateType()) {
4665 // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision
4666 // Make this an elision if this won't call an initializer-list
4667 // constructor. (Always on an aggregate type or check constructors first.)
4668
4669 // This effectively makes our resolution as follows. The parts in angle
4670 // brackets are additions.
4671 // C++17 [over.match.list]p(1.2):
4672 // - If no viable initializer-list constructor is found <and the
4673 // initializer list does not consist of exactly a single element with
4674 // the same cv-unqualified class type as T>, [...]
4675 // C++17 [dcl.init.list]p(3.6):
4676 // - Otherwise, if T is a class type, constructors are considered. The
4677 // applicable constructors are enumerated and the best one is chosen
4678 // through overload resolution. <If no constructor is found and the
4679 // initializer list consists of exactly a single element with the same
4680 // cv-unqualified class type as T, the object is initialized from that
4681 // element (by copy-initialization for copy-list-initialization, or by
4682 // direct-initialization for direct-list-initialization). Otherwise, >
4683 // if a narrowing conversion [...]
4684 assert(!IsInitListCopy &&
4685 "IsInitListCopy only possible with aggregate types");
4686 CopyElisionPossible = true;
4687 } else {
4688 ElideConstructor();
4689 return;
4690 }
4691 }
4692
4693 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
4694 // Build the candidate set directly in the initialization sequence
4695 // structure, so that it will persist if we fail.
4696 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4697
4698 // Determine whether we are allowed to call explicit constructors or
4699 // explicit conversion operators.
4700 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4701 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4702
4703 // - Otherwise, if T is a class type, constructors are considered. The
4704 // applicable constructors are enumerated, and the best one is chosen
4705 // through overload resolution.
4706 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4707
4710 bool AsInitializerList = false;
4711
4712 // C++11 [over.match.list]p1, per DR1467:
4713 // When objects of non-aggregate type T are list-initialized, such that
4714 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4715 // according to the rules in this section, overload resolution selects
4716 // the constructor in two phases:
4717 //
4718 // - Initially, the candidate functions are the initializer-list
4719 // constructors of the class T and the argument list consists of the
4720 // initializer list as a single argument.
4721 if (IsListInit) {
4722 AsInitializerList = true;
4723
4724 // If the initializer list has no elements and T has a default constructor,
4725 // the first phase is omitted.
4726 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4728 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4729 CopyInitialization, AllowExplicit,
4730 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4731
4732 if (CopyElisionPossible && Result == OR_No_Viable_Function) {
4733 // No initializer list candidate
4734 ElideConstructor();
4735 return;
4736 }
4737 }
4738
4739 // if the initialization is direct-initialization, or if it is
4740 // copy-initialization where the cv-unqualified version of the source type is
4741 // the same as or is derived from the class of the destination type,
4742 // constructors are considered.
4743 if ((Kind.getKind() == InitializationKind::IK_Direct ||
4744 Kind.getKind() == InitializationKind::IK_Copy) &&
4745 Args.size() == 1 &&
4747 Args[0]->getType().getNonReferenceType(),
4748 DestType.getNonReferenceType()))
4749 RequireActualConstructor = true;
4750
4751 // C++11 [over.match.list]p1:
4752 // - If no viable initializer-list constructor is found, overload resolution
4753 // is performed again, where the candidate functions are all the
4754 // constructors of the class T and the argument list consists of the
4755 // elements of the initializer list.
4757 AsInitializerList = false;
4759 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4760 Best, CopyInitialization, AllowExplicit,
4761 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4762 }
4763 if (Result) {
4764 Sequence.SetOverloadFailure(
4767 Result);
4768
4769 if (Result != OR_Deleted)
4770 return;
4771 }
4772
4773 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4774
4775 // In C++17, ResolveConstructorOverload can select a conversion function
4776 // instead of a constructor.
4777 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4778 // Add the user-defined conversion step that calls the conversion function.
4779 QualType ConvType = CD->getConversionType();
4780 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4781 "should not have selected this conversion function");
4782 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4783 HadMultipleCandidates);
4784 if (!S.Context.hasSameType(ConvType, DestType))
4785 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4786 if (IsListInit)
4787 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4788 return;
4789 }
4790
4791 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4792 if (Result != OR_Deleted) {
4793 if (!IsListInit &&
4794 (Kind.getKind() == InitializationKind::IK_Default ||
4795 Kind.getKind() == InitializationKind::IK_Direct) &&
4796 !(CtorDecl->isCopyOrMoveConstructor() && CtorDecl->isImplicit()) &&
4797 DestRecordDecl->isAggregate() &&
4798 DestRecordDecl->hasUninitializedExplicitInitFields() &&
4799 !S.isUnevaluatedContext()) {
4800 S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
4801 << /* Var-in-Record */ 1 << DestRecordDecl;
4802 emitUninitializedExplicitInitFields(S, DestRecordDecl);
4803 }
4804
4805 // C++11 [dcl.init]p6:
4806 // If a program calls for the default initialization of an object
4807 // of a const-qualified type T, T shall be a class type with a
4808 // user-provided default constructor.
4809 // C++ core issue 253 proposal:
4810 // If the implicit default constructor initializes all subobjects, no
4811 // initializer should be required.
4812 // The 253 proposal is for example needed to process libstdc++ headers
4813 // in 5.x.
4814 if (Kind.getKind() == InitializationKind::IK_Default &&
4815 Entity.getType().isConstQualified()) {
4816 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4817 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4819 return;
4820 }
4821 }
4822
4823 // C++11 [over.match.list]p1:
4824 // In copy-list-initialization, if an explicit constructor is chosen, the
4825 // initializer is ill-formed.
4826 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4828 return;
4829 }
4830 }
4831
4832 // [class.copy.elision]p3:
4833 // In some copy-initialization contexts, a two-stage overload resolution
4834 // is performed.
4835 // If the first overload resolution selects a deleted function, we also
4836 // need the initialization sequence to decide whether to perform the second
4837 // overload resolution.
4838 // For deleted functions in other contexts, there is no need to get the
4839 // initialization sequence.
4840 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4841 return;
4842
4843 // Add the constructor initialization step. Any cv-qualification conversion is
4844 // subsumed by the initialization.
4846 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4847 IsListInit | IsInitListCopy, AsInitializerList);
4848}
4849
4851 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4852 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
4853 ExprResult *Result = nullptr);
4854
4855/// Attempt to initialize an object of a class type either by
4856/// direct-initialization, or by copy-initialization from an
4857/// expression of the same or derived class type. This corresponds
4858/// to the first two sub-bullets of C++2c [dcl.init.general] p16.6.
4859///
4860/// \param IsAggrListInit Is this non-list-initialization being done as
4861/// part of a list-initialization of an aggregate
4862/// from a single expression of the same or
4863/// derived class type (C++2c [dcl.init.list] p3.2)?
4865 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4866 MultiExprArg Args, QualType DestType, InitializationSequence &Sequence,
4867 bool IsAggrListInit) {
4868 // C++2c [dcl.init.general] p16.6:
4869 // * Otherwise, if the destination type is a class type:
4870 // * If the initializer expression is a prvalue and
4871 // the cv-unqualified version of the source type is the same
4872 // as the destination type, the initializer expression is used
4873 // to initialize the destination object.
4874 // * Otherwise, if the initialization is direct-initialization,
4875 // or if it is copy-initialization where the cv-unqualified
4876 // version of the source type is the same as or is derived from
4877 // the class of the destination type, constructors are considered.
4878 // The applicable constructors are enumerated, and the best one
4879 // is chosen through overload resolution. Then:
4880 // * If overload resolution is successful, the selected
4881 // constructor is called to initialize the object, with
4882 // the initializer expression or expression-list as its
4883 // argument(s).
4884 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
4885 Sequence, /*IsListInit=*/false, IsAggrListInit);
4886
4887 // * Otherwise, if no constructor is viable, the destination type
4888 // is an aggregate class, and the initializer is a parenthesized
4889 // expression-list, the object is initialized as follows. [...]
4890 // Parenthesized initialization of aggregates is a C++20 feature.
4891 if (S.getLangOpts().CPlusPlus20 &&
4892 Kind.getKind() == InitializationKind::IK_Direct && Sequence.Failed() &&
4893 Sequence.getFailureKind() ==
4896 (IsAggrListInit || DestType->isAggregateType()))
4897 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence,
4898 /*VerifyOnly=*/true);
4899
4900 // * Otherwise, the initialization is ill-formed.
4901}
4902
4903static bool
4906 QualType &SourceType,
4907 QualType &UnqualifiedSourceType,
4908 QualType UnqualifiedTargetType,
4909 InitializationSequence &Sequence) {
4910 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4911 S.Context.OverloadTy) {
4913 bool HadMultipleCandidates = false;
4914 if (FunctionDecl *Fn
4916 UnqualifiedTargetType,
4917 false, Found,
4918 &HadMultipleCandidates)) {
4920 HadMultipleCandidates);
4921 SourceType = Fn->getType();
4922 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4923 } else if (!UnqualifiedTargetType->isRecordType()) {
4925 return true;
4926 }
4927 }
4928 return false;
4929}
4930
4931static void TryReferenceInitializationCore(Sema &S,
4932 const InitializedEntity &Entity,
4933 const InitializationKind &Kind,
4934 Expr *Initializer,
4935 QualType cv1T1, QualType T1,
4936 Qualifiers T1Quals,
4937 QualType cv2T2, QualType T2,
4938 Qualifiers T2Quals,
4939 InitializationSequence &Sequence,
4940 bool TopLevelOfInitList);
4941
4942static void TryValueInitialization(Sema &S,
4943 const InitializedEntity &Entity,
4944 const InitializationKind &Kind,
4945 InitializationSequence &Sequence,
4946 InitListExpr *InitList = nullptr);
4947
4948/// Attempt list initialization of a reference.
4950 const InitializedEntity &Entity,
4951 const InitializationKind &Kind,
4952 InitListExpr *InitList,
4953 InitializationSequence &Sequence,
4954 bool TreatUnavailableAsInvalid) {
4955 // First, catch C++03 where this isn't possible.
4956 if (!S.getLangOpts().CPlusPlus11) {
4958 return;
4959 }
4960 // Can't reference initialize a compound literal.
4963 return;
4964 }
4965
4966 QualType DestType = Entity.getType();
4967 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4968 Qualifiers T1Quals;
4969 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4970
4971 // Reference initialization via an initializer list works thus:
4972 // If the initializer list consists of a single element that is
4973 // reference-related to the referenced type, bind directly to that element
4974 // (possibly creating temporaries).
4975 // Otherwise, initialize a temporary with the initializer list and
4976 // bind to that.
4977 if (InitList->hasOneInit()) {
4978 Expr *Initializer = InitList->getInit(0);
4980 Qualifiers T2Quals;
4981 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4982
4983 // If this fails, creating a temporary wouldn't work either.
4985 T1, Sequence))
4986 return;
4987
4988 SourceLocation DeclLoc = Initializer->getBeginLoc();
4989 Sema::ReferenceCompareResult RefRelationship
4990 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4991 if (RefRelationship >= Sema::Ref_Related) {
4992 // Try to bind the reference here.
4993 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4994 T1Quals, cv2T2, T2, T2Quals, Sequence,
4995 /*TopLevelOfInitList=*/true);
4996 if (Sequence)
4997 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4998 return;
4999 }
5000
5001 // Update the initializer if we've resolved an overloaded function.
5002 if (!Sequence.steps().empty())
5003 Sequence.RewrapReferenceInitList(cv1T1, InitList);
5004 }
5005 // Perform address space compatibility check.
5006 QualType cv1T1IgnoreAS = cv1T1;
5007 if (T1Quals.hasAddressSpace()) {
5008 Qualifiers T2Quals;
5009 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
5010 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())) {
5011 Sequence.SetFailed(
5013 return;
5014 }
5015 // Ignore address space of reference type at this point and perform address
5016 // space conversion after the reference binding step.
5017 cv1T1IgnoreAS =
5019 }
5020 // Not reference-related. Create a temporary and bind to that.
5021 InitializedEntity TempEntity =
5023
5024 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
5025 TreatUnavailableAsInvalid);
5026 if (Sequence) {
5027 if (DestType->isRValueReferenceType() ||
5028 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
5029 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
5030 /*BindingTemporary=*/true);
5031 if (S.getLangOpts().CPlusPlus20 &&
5033 DestType->isRValueReferenceType()) {
5034 // C++20 [dcl.init.list]p3.10:
5035 // List-initialization of an object or reference of type T is defined as
5036 // follows:
5037 // ..., unless T is “reference to array of unknown bound of U”, in which
5038 // case the type of the prvalue is the type of x in the declaration U
5039 // x[] H, where H is the initializer list.
5040
5041 // The call to AddReferenceBindingStep above converts the rvalue to an
5042 // xvalue. Convert that xvalue to the incomplete array type.
5044 }
5045 if (T1Quals.hasAddressSpace())
5047 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
5048 } else
5049 Sequence.SetFailed(
5051 }
5052}
5053
5054/// Attempt list initialization (C++0x [dcl.init.list])
5056 const InitializedEntity &Entity,
5057 const InitializationKind &Kind,
5058 InitListExpr *InitList,
5059 InitializationSequence &Sequence,
5060 bool TreatUnavailableAsInvalid) {
5061 QualType DestType = Entity.getType();
5062
5063 if (S.getLangOpts().HLSL && !S.HLSL().transformInitList(Entity, InitList)) {
5065 return;
5066 }
5067
5068 // C++ doesn't allow scalar initialization with more than one argument.
5069 // But C99 complex numbers are scalars and it makes sense there.
5070 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
5071 !DestType->isAnyComplexType() && !InitList->hasZeroInits() &&
5072 !InitList->hasOneInit()) {
5074 return;
5075 }
5076 if (DestType->isReferenceType()) {
5077 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
5078 TreatUnavailableAsInvalid);
5079 return;
5080 }
5081
5082 if (DestType->isRecordType() &&
5083 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
5084 Sequence.setIncompleteTypeFailure(DestType);
5085 return;
5086 }
5087
5088 // C++20 [dcl.init.list]p3:
5089 // - If the braced-init-list contains a designated-initializer-list, T shall
5090 // be an aggregate class. [...] Aggregate initialization is performed.
5091 //
5092 // We allow arrays here too in order to support array designators.
5093 //
5094 // FIXME: This check should precede the handling of reference initialization.
5095 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
5096 // as a tentative DR resolution.
5097 bool IsDesignatedInit = InitList->hasDesignatedInit();
5098 if (!DestType->isAggregateType() && IsDesignatedInit) {
5099 Sequence.SetFailed(
5101 return;
5102 }
5103
5104 // C++11 [dcl.init.list]p3, per DR1467 and DR2137:
5105 // - If T is an aggregate class and the initializer list has a single element
5106 // of type cv U, where U is T or a class derived from T, the object is
5107 // initialized from that element (by copy-initialization for
5108 // copy-list-initialization, or by direct-initialization for
5109 // direct-list-initialization).
5110 // - Otherwise, if T is a character array and the initializer list has a
5111 // single element that is an appropriately-typed string literal
5112 // (8.5.2 [dcl.init.string]), initialization is performed as described
5113 // in that section.
5114 // - Otherwise, if T is an aggregate, [...] (continue below).
5115 if (S.getLangOpts().CPlusPlus11 && InitList->hasOneInit() &&
5116 !IsDesignatedInit) {
5117 if (DestType->isRecordType() && DestType->isAggregateType()) {
5118 QualType InitType = InitList->getInit(0)->getType();
5119 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
5120 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
5121 InitializationKind SubKind =
5123 ? InitializationKind::CreateDirect(Kind.getLocation(),
5124 InitList->getLBraceLoc(),
5125 InitList->getRBraceLoc())
5126 : Kind;
5127 Expr *InitListAsExpr = InitList;
5129 S, Entity, SubKind, InitListAsExpr, DestType, Sequence,
5130 /*IsAggrListInit=*/true);
5131 return;
5132 }
5133 }
5134 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
5135 Expr *SubInit[1] = {InitList->getInit(0)};
5136
5137 // C++17 [dcl.struct.bind]p1:
5138 // ... If the assignment-expression in the initializer has array type A
5139 // and no ref-qualifier is present, e has type cv A and each element is
5140 // copy-initialized or direct-initialized from the corresponding element
5141 // of the assignment-expression as specified by the form of the
5142 // initializer. ...
5143 //
5144 // This is a special case not following list-initialization.
5145 if (isa<ConstantArrayType>(DestAT) &&
5147 isa<DecompositionDecl>(Entity.getDecl())) {
5148 assert(
5149 S.Context.hasSameUnqualifiedType(SubInit[0]->getType(), DestType) &&
5150 "Deduced to other type?");
5151 assert(Kind.getKind() == clang::InitializationKind::IK_DirectList &&
5152 "List-initialize structured bindings but not "
5153 "direct-list-initialization?");
5154 TryArrayCopy(S,
5155 InitializationKind::CreateDirect(Kind.getLocation(),
5156 InitList->getLBraceLoc(),
5157 InitList->getRBraceLoc()),
5158 Entity, SubInit[0], DestType, Sequence,
5159 TreatUnavailableAsInvalid);
5160 if (Sequence)
5161 Sequence.AddUnwrapInitListInitStep(InitList);
5162 return;
5163 }
5164
5165 if (!isa<VariableArrayType>(DestAT) &&
5166 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
5167 InitializationKind SubKind =
5169 ? InitializationKind::CreateDirect(Kind.getLocation(),
5170 InitList->getLBraceLoc(),
5171 InitList->getRBraceLoc())
5172 : Kind;
5173 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
5174 /*TopLevelOfInitList*/ true,
5175 TreatUnavailableAsInvalid);
5176
5177 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
5178 // the element is not an appropriately-typed string literal, in which
5179 // case we should proceed as in C++11 (below).
5180 if (Sequence) {
5181 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5182 return;
5183 }
5184 }
5185 }
5186 }
5187
5188 // C++11 [dcl.init.list]p3:
5189 // - If T is an aggregate, aggregate initialization is performed.
5190 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
5191 (S.getLangOpts().CPlusPlus11 &&
5192 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
5193 if (S.getLangOpts().CPlusPlus11) {
5194 // - Otherwise, if the initializer list has no elements and T is a
5195 // class type with a default constructor, the object is
5196 // value-initialized.
5197 if (InitList->hasZeroInits()) {
5198 CXXRecordDecl *RD = DestType->castAsCXXRecordDecl();
5199 if (S.LookupDefaultConstructor(RD)) {
5200 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
5201 return;
5202 }
5203 }
5204
5205 // - Otherwise, if T is a specialization of std::initializer_list<E>,
5206 // an initializer_list object constructed [...]
5207 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
5208 TreatUnavailableAsInvalid))
5209 return;
5210
5211 // - Otherwise, if T is a class type, constructors are considered.
5212 Expr *InitListAsExpr = InitList;
5213 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
5214 DestType, Sequence, /*InitListSyntax*/true);
5215 } else
5217 return;
5218 }
5219
5220 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
5221 InitList->hasOneInit()) {
5222 Expr *E = InitList->getInit(0);
5223
5224 // - Otherwise, if T is an enumeration with a fixed underlying type,
5225 // the initializer-list has a single element v, and the initialization
5226 // is direct-list-initialization, the object is initialized with the
5227 // value T(v); if a narrowing conversion is required to convert v to
5228 // the underlying type of T, the program is ill-formed.
5229 if (S.getLangOpts().CPlusPlus17 &&
5230 Kind.getKind() == InitializationKind::IK_DirectList &&
5231 DestType->isEnumeralType() && DestType->castAsEnumDecl()->isFixed() &&
5232 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
5234 E->getType()->isFloatingType())) {
5235 // There are two ways that T(v) can work when T is an enumeration type.
5236 // If there is either an implicit conversion sequence from v to T or
5237 // a conversion function that can convert from v to T, then we use that.
5238 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
5239 // type, it is converted to the enumeration type via its underlying type.
5240 // There is no overlap possible between these two cases (except when the
5241 // source value is already of the destination type), and the first
5242 // case is handled by the general case for single-element lists below.
5244 ICS.setStandard();
5246 if (!E->isPRValue())
5248 // If E is of a floating-point type, then the conversion is ill-formed
5249 // due to narrowing, but go through the motions in order to produce the
5250 // right diagnostic.
5254 ICS.Standard.setFromType(E->getType());
5255 ICS.Standard.setToType(0, E->getType());
5256 ICS.Standard.setToType(1, DestType);
5257 ICS.Standard.setToType(2, DestType);
5258 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
5259 /*TopLevelOfInitList*/true);
5260 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5261 return;
5262 }
5263
5264 // - Otherwise, if the initializer list has a single element of type E
5265 // [...references are handled above...], the object or reference is
5266 // initialized from that element (by copy-initialization for
5267 // copy-list-initialization, or by direct-initialization for
5268 // direct-list-initialization); if a narrowing conversion is required
5269 // to convert the element to T, the program is ill-formed.
5270 //
5271 // Per core-24034, this is direct-initialization if we were performing
5272 // direct-list-initialization and copy-initialization otherwise.
5273 // We can't use InitListChecker for this, because it always performs
5274 // copy-initialization. This only matters if we might use an 'explicit'
5275 // conversion operator, or for the special case conversion of nullptr_t to
5276 // bool, so we only need to handle those cases.
5277 //
5278 // FIXME: Why not do this in all cases?
5279 Expr *Init = InitList->getInit(0);
5280 if (Init->getType()->isRecordType() ||
5281 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
5282 InitializationKind SubKind =
5284 ? InitializationKind::CreateDirect(Kind.getLocation(),
5285 InitList->getLBraceLoc(),
5286 InitList->getRBraceLoc())
5287 : Kind;
5288 Expr *SubInit[1] = { Init };
5289 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
5290 /*TopLevelOfInitList*/true,
5291 TreatUnavailableAsInvalid);
5292 if (Sequence)
5293 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5294 return;
5295 }
5296 }
5297
5298 InitListChecker CheckInitList(S, Entity, InitList,
5299 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
5300 if (CheckInitList.HadError()) {
5302 return;
5303 }
5304
5305 // Add the list initialization step with the built init list.
5306 Sequence.AddListInitializationStep(DestType);
5307}
5308
5309/// Try a reference initialization that involves calling a conversion
5310/// function.
5312 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5313 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
5314 InitializationSequence &Sequence) {
5315 QualType DestType = Entity.getType();
5316 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5317 QualType T1 = cv1T1.getUnqualifiedType();
5318 QualType cv2T2 = Initializer->getType();
5319 QualType T2 = cv2T2.getUnqualifiedType();
5320
5321 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
5322 "Must have incompatible references when binding via conversion");
5323
5324 // Build the candidate set directly in the initialization sequence
5325 // structure, so that it will persist if we fail.
5326 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5328
5329 // Determine whether we are allowed to call explicit conversion operators.
5330 // Note that none of [over.match.copy], [over.match.conv], nor
5331 // [over.match.ref] permit an explicit constructor to be chosen when
5332 // initializing a reference, not even for direct-initialization.
5333 bool AllowExplicitCtors = false;
5334 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
5335
5336 if (AllowRValues && T1->isRecordType() &&
5337 S.isCompleteType(Kind.getLocation(), T1)) {
5338 auto *T1RecordDecl = T1->castAsCXXRecordDecl();
5339 if (T1RecordDecl->isInvalidDecl())
5340 return OR_No_Viable_Function;
5341 // The type we're converting to is a class type. Enumerate its constructors
5342 // to see if there is a suitable conversion.
5343 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
5344 auto Info = getConstructorInfo(D);
5345 if (!Info.Constructor)
5346 continue;
5347
5348 if (!Info.Constructor->isInvalidDecl() &&
5349 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5350 if (Info.ConstructorTmpl)
5352 Info.ConstructorTmpl, Info.FoundDecl,
5353 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5354 /*SuppressUserConversions=*/true,
5355 /*PartialOverloading*/ false, AllowExplicitCtors);
5356 else
5358 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
5359 /*SuppressUserConversions=*/true,
5360 /*PartialOverloading*/ false, AllowExplicitCtors);
5361 }
5362 }
5363 }
5364
5365 if (T2->isRecordType() && S.isCompleteType(Kind.getLocation(), T2)) {
5366 const auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5367 if (T2RecordDecl->isInvalidDecl())
5368 return OR_No_Viable_Function;
5369 // The type we're converting from is a class type, enumerate its conversion
5370 // functions.
5371 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5372 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5373 NamedDecl *D = *I;
5375 if (isa<UsingShadowDecl>(D))
5376 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5377
5378 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5379 CXXConversionDecl *Conv;
5380 if (ConvTemplate)
5381 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5382 else
5383 Conv = cast<CXXConversionDecl>(D);
5384
5385 // If the conversion function doesn't return a reference type,
5386 // it can't be considered for this conversion unless we're allowed to
5387 // consider rvalues.
5388 // FIXME: Do we need to make sure that we only consider conversion
5389 // candidates with reference-compatible results? That might be needed to
5390 // break recursion.
5391 if ((AllowRValues ||
5393 if (ConvTemplate)
5395 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5396 CandidateSet,
5397 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5398 else
5400 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
5401 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5402 }
5403 }
5404 }
5405
5406 SourceLocation DeclLoc = Initializer->getBeginLoc();
5407
5408 // Perform overload resolution. If it fails, return the failed result.
5411 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
5412 return Result;
5413
5414 FunctionDecl *Function = Best->Function;
5415 // This is the overload that will be used for this initialization step if we
5416 // use this initialization. Mark it as referenced.
5417 Function->setReferenced();
5418
5419 // Compute the returned type and value kind of the conversion.
5420 QualType cv3T3;
5421 if (isa<CXXConversionDecl>(Function))
5422 cv3T3 = Function->getReturnType();
5423 else
5424 cv3T3 = T1;
5425
5427 if (cv3T3->isLValueReferenceType())
5428 VK = VK_LValue;
5429 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
5430 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
5431 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
5432
5433 // Add the user-defined conversion step.
5434 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5435 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
5436 HadMultipleCandidates);
5437
5438 // Determine whether we'll need to perform derived-to-base adjustments or
5439 // other conversions.
5441 Sema::ReferenceCompareResult NewRefRelationship =
5442 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
5443
5444 // Add the final conversion sequence, if necessary.
5445 if (NewRefRelationship == Sema::Ref_Incompatible) {
5446 assert(Best->HasFinalConversion && !isa<CXXConstructorDecl>(Function) &&
5447 "should not have conversion after constructor");
5448
5450 ICS.setStandard();
5451 ICS.Standard = Best->FinalConversion;
5452 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
5453
5454 // Every implicit conversion results in a prvalue, except for a glvalue
5455 // derived-to-base conversion, which we handle below.
5456 cv3T3 = ICS.Standard.getToType(2);
5457 VK = VK_PRValue;
5458 }
5459
5460 // If the converted initializer is a prvalue, its type T4 is adjusted to
5461 // type "cv1 T4" and the temporary materialization conversion is applied.
5462 //
5463 // We adjust the cv-qualifications to match the reference regardless of
5464 // whether we have a prvalue so that the AST records the change. In this
5465 // case, T4 is "cv3 T3".
5466 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
5467 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
5468 Sequence.AddQualificationConversionStep(cv1T4, VK);
5469 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
5470 VK = IsLValueRef ? VK_LValue : VK_XValue;
5471
5472 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5473 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
5474 else if (RefConv & Sema::ReferenceConversions::ObjC)
5475 Sequence.AddObjCObjectConversionStep(cv1T1);
5476 else if (RefConv & Sema::ReferenceConversions::Function)
5477 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5478 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5479 if (!S.Context.hasSameType(cv1T4, cv1T1))
5480 Sequence.AddQualificationConversionStep(cv1T1, VK);
5481 }
5482
5483 return OR_Success;
5484}
5485
5486static void CheckCXX98CompatAccessibleCopy(Sema &S,
5487 const InitializedEntity &Entity,
5488 Expr *CurInitExpr);
5489
5490/// Attempt reference initialization (C++0x [dcl.init.ref])
5492 const InitializationKind &Kind,
5494 InitializationSequence &Sequence,
5495 bool TopLevelOfInitList) {
5496 QualType DestType = Entity.getType();
5497 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5498 Qualifiers T1Quals;
5499 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
5501 Qualifiers T2Quals;
5502 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
5503
5504 // If the initializer is the address of an overloaded function, try
5505 // to resolve the overloaded function. If all goes well, T2 is the
5506 // type of the resulting function.
5508 T1, Sequence))
5509 return;
5510
5511 // Delegate everything else to a subfunction.
5512 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
5513 T1Quals, cv2T2, T2, T2Quals, Sequence,
5514 TopLevelOfInitList);
5515}
5516
5517/// Determine whether an expression is a non-referenceable glvalue (one to
5518/// which a reference can never bind). Attempting to bind a reference to
5519/// such a glvalue will always create a temporary.
5521 return E->refersToBitField() || E->refersToVectorElement() ||
5523}
5524
5525/// Reference initialization without resolving overloaded functions.
5526///
5527/// We also can get here in C if we call a builtin which is declared as
5528/// a function with a parameter of reference type (such as __builtin_va_end()).
5530 const InitializedEntity &Entity,
5531 const InitializationKind &Kind,
5533 QualType cv1T1, QualType T1,
5534 Qualifiers T1Quals,
5535 QualType cv2T2, QualType T2,
5536 Qualifiers T2Quals,
5537 InitializationSequence &Sequence,
5538 bool TopLevelOfInitList) {
5539 QualType DestType = Entity.getType();
5540 SourceLocation DeclLoc = Initializer->getBeginLoc();
5541
5542 // Compute some basic properties of the types and the initializer.
5543 bool isLValueRef = DestType->isLValueReferenceType();
5544 bool isRValueRef = !isLValueRef;
5545 Expr::Classification InitCategory = Initializer->Classify(S.Context);
5546
5548 Sema::ReferenceCompareResult RefRelationship =
5549 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
5550
5551 // C++0x [dcl.init.ref]p5:
5552 // A reference to type "cv1 T1" is initialized by an expression of type
5553 // "cv2 T2" as follows:
5554 //
5555 // - If the reference is an lvalue reference and the initializer
5556 // expression
5557 // Note the analogous bullet points for rvalue refs to functions. Because
5558 // there are no function rvalues in C++, rvalue refs to functions are treated
5559 // like lvalue refs.
5560 OverloadingResult ConvOvlResult = OR_Success;
5561 bool T1Function = T1->isFunctionType();
5562 if (isLValueRef || T1Function) {
5563 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
5564 (RefRelationship == Sema::Ref_Compatible ||
5565 (Kind.isCStyleOrFunctionalCast() &&
5566 RefRelationship == Sema::Ref_Related))) {
5567 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5568 // reference-compatible with "cv2 T2," or
5569 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5570 Sema::ReferenceConversions::ObjC)) {
5571 // If we're converting the pointee, add any qualifiers first;
5572 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5573 if (RefConv & (Sema::ReferenceConversions::Qualification))
5575 S.Context.getQualifiedType(T2, T1Quals),
5576 Initializer->getValueKind());
5577 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5578 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
5579 else
5580 Sequence.AddObjCObjectConversionStep(cv1T1);
5581 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5582 // Perform a (possibly multi-level) qualification conversion.
5583 Sequence.AddQualificationConversionStep(cv1T1,
5584 Initializer->getValueKind());
5585 } else if (RefConv & Sema::ReferenceConversions::Function) {
5586 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5587 }
5588
5589 // We only create a temporary here when binding a reference to a
5590 // bit-field or vector element. Those cases are't supposed to be
5591 // handled by this bullet, but the outcome is the same either way.
5592 Sequence.AddReferenceBindingStep(cv1T1, false);
5593 return;
5594 }
5595
5596 // - has a class type (i.e., T2 is a class type), where T1 is not
5597 // reference-related to T2, and can be implicitly converted to an
5598 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5599 // with "cv3 T3" (this conversion is selected by enumerating the
5600 // applicable conversion functions (13.3.1.6) and choosing the best
5601 // one through overload resolution (13.3)),
5602 // If we have an rvalue ref to function type here, the rhs must be
5603 // an rvalue. DR1287 removed the "implicitly" here.
5604 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5605 (isLValueRef || InitCategory.isRValue())) {
5606 if (S.getLangOpts().CPlusPlus) {
5607 // Try conversion functions only for C++.
5608 ConvOvlResult = TryRefInitWithConversionFunction(
5609 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5610 /*IsLValueRef*/ isLValueRef, Sequence);
5611 if (ConvOvlResult == OR_Success)
5612 return;
5613 if (ConvOvlResult != OR_No_Viable_Function)
5614 Sequence.SetOverloadFailure(
5616 ConvOvlResult);
5617 } else {
5618 ConvOvlResult = OR_No_Viable_Function;
5619 }
5620 }
5621 }
5622
5623 // - Otherwise, the reference shall be an lvalue reference to a
5624 // non-volatile const type (i.e., cv1 shall be const), or the reference
5625 // shall be an rvalue reference.
5626 // For address spaces, we interpret this to mean that an addr space
5627 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5628 if (isLValueRef &&
5629 !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5630 T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext()))) {
5633 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5634 Sequence.SetOverloadFailure(
5636 ConvOvlResult);
5637 else if (!InitCategory.isLValue())
5638 Sequence.SetFailed(
5639 T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())
5643 else {
5645 switch (RefRelationship) {
5647 if (Initializer->refersToBitField())
5648 FK = InitializationSequence::
5649 FK_NonConstLValueReferenceBindingToBitfield;
5650 else if (Initializer->refersToVectorElement())
5651 FK = InitializationSequence::
5652 FK_NonConstLValueReferenceBindingToVectorElement;
5653 else if (Initializer->refersToMatrixElement())
5654 FK = InitializationSequence::
5655 FK_NonConstLValueReferenceBindingToMatrixElement;
5656 else
5657 llvm_unreachable("unexpected kind of compatible initializer");
5658 break;
5659 case Sema::Ref_Related:
5661 break;
5663 FK = InitializationSequence::
5664 FK_NonConstLValueReferenceBindingToUnrelated;
5665 break;
5666 }
5667 Sequence.SetFailed(FK);
5668 }
5669 return;
5670 }
5671
5672 // - If the initializer expression
5673 // - is an
5674 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5675 // [1z] rvalue (but not a bit-field) or
5676 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5677 //
5678 // Note: functions are handled above and below rather than here...
5679 if (!T1Function &&
5680 (RefRelationship == Sema::Ref_Compatible ||
5681 (Kind.isCStyleOrFunctionalCast() &&
5682 RefRelationship == Sema::Ref_Related)) &&
5683 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5684 (InitCategory.isPRValue() &&
5685 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5686 T2->isArrayType())))) {
5687 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5688 if (InitCategory.isPRValue() && T2->isRecordType()) {
5689 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5690 // compiler the freedom to perform a copy here or bind to the
5691 // object, while C++0x requires that we bind directly to the
5692 // object. Hence, we always bind to the object without making an
5693 // extra copy. However, in C++03 requires that we check for the
5694 // presence of a suitable copy constructor:
5695 //
5696 // The constructor that would be used to make the copy shall
5697 // be callable whether or not the copy is actually done.
5698 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5699 Sequence.AddExtraneousCopyToTemporary(cv2T2);
5700 else if (S.getLangOpts().CPlusPlus11)
5702 }
5703
5704 // C++1z [dcl.init.ref]/5.2.1.2:
5705 // If the converted initializer is a prvalue, its type T4 is adjusted
5706 // to type "cv1 T4" and the temporary materialization conversion is
5707 // applied.
5708 // Postpone address space conversions to after the temporary materialization
5709 // conversion to allow creating temporaries in the alloca address space.
5710 auto T1QualsIgnoreAS = T1Quals;
5711 auto T2QualsIgnoreAS = T2Quals;
5712 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5713 T1QualsIgnoreAS.removeAddressSpace();
5714 T2QualsIgnoreAS.removeAddressSpace();
5715 }
5716 // Strip the existing ObjC lifetime qualifier from cv2T2 before combining
5717 // with T1's qualifiers.
5718 QualType T2ForQualConv = cv2T2;
5719 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime()) {
5720 Qualifiers T2BaseQuals =
5721 T2ForQualConv.getQualifiers().withoutObjCLifetime();
5722 T2ForQualConv = S.Context.getQualifiedType(
5723 T2ForQualConv.getUnqualifiedType(), T2BaseQuals);
5724 }
5725 QualType cv1T4 = S.Context.getQualifiedType(T2ForQualConv, T1QualsIgnoreAS);
5726 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5727 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5728 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5729 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5730 // Add addr space conversion if required.
5731 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5732 auto T4Quals = cv1T4.getQualifiers();
5733 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5734 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5735 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5736 cv1T4 = cv1T4WithAS;
5737 }
5738
5739 // In any case, the reference is bound to the resulting glvalue (or to
5740 // an appropriate base class subobject).
5741 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5742 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5743 else if (RefConv & Sema::ReferenceConversions::ObjC)
5744 Sequence.AddObjCObjectConversionStep(cv1T1);
5745 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5746 if (!S.Context.hasSameType(cv1T4, cv1T1))
5747 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5748 }
5749 return;
5750 }
5751
5752 // - has a class type (i.e., T2 is a class type), where T1 is not
5753 // reference-related to T2, and can be implicitly converted to an
5754 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5755 // where "cv1 T1" is reference-compatible with "cv3 T3",
5756 //
5757 // DR1287 removes the "implicitly" here.
5758 if (T2->isRecordType()) {
5759 if (RefRelationship == Sema::Ref_Incompatible) {
5760 ConvOvlResult = TryRefInitWithConversionFunction(
5761 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5762 /*IsLValueRef*/ isLValueRef, Sequence);
5763 if (ConvOvlResult)
5764 Sequence.SetOverloadFailure(
5766 ConvOvlResult);
5767
5768 return;
5769 }
5770
5771 if (RefRelationship == Sema::Ref_Compatible &&
5772 isRValueRef && InitCategory.isLValue()) {
5773 Sequence.SetFailed(
5775 return;
5776 }
5777
5779 return;
5780 }
5781
5782 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5783 // from the initializer expression using the rules for a non-reference
5784 // copy-initialization (8.5). The reference is then bound to the
5785 // temporary. [...]
5786
5787 // Ignore address space of reference type at this point and perform address
5788 // space conversion after the reference binding step.
5789 QualType cv1T1IgnoreAS =
5790 T1Quals.hasAddressSpace()
5792 : cv1T1;
5793
5794 InitializedEntity TempEntity =
5796
5797 // FIXME: Why do we use an implicit conversion here rather than trying
5798 // copy-initialization?
5800 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5801 /*SuppressUserConversions=*/false,
5802 Sema::AllowedExplicit::None,
5803 /*FIXME:InOverloadResolution=*/false,
5804 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5805 /*AllowObjCWritebackConversion=*/false);
5806
5807 if (ICS.isBad()) {
5808 // FIXME: Use the conversion function set stored in ICS to turn
5809 // this into an overloading ambiguity diagnostic. However, we need
5810 // to keep that set as an OverloadCandidateSet rather than as some
5811 // other kind of set.
5812 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5813 Sequence.SetOverloadFailure(
5815 ConvOvlResult);
5816 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5818 else
5820 return;
5821 } else {
5822 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType(),
5823 TopLevelOfInitList);
5824 }
5825
5826 // [...] If T1 is reference-related to T2, cv1 must be the
5827 // same cv-qualification as, or greater cv-qualification
5828 // than, cv2; otherwise, the program is ill-formed.
5829 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5830 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5831 if (RefRelationship == Sema::Ref_Related &&
5832 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5833 !T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext()))) {
5835 return;
5836 }
5837
5838 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5839 // reference, the initializer expression shall not be an lvalue.
5840 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5841 InitCategory.isLValue()) {
5842 Sequence.SetFailed(
5844 return;
5845 }
5846
5847 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5848
5849 if (T1Quals.hasAddressSpace()) {
5852 Sequence.SetFailed(
5854 return;
5855 }
5856 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5857 : VK_XValue);
5858 }
5859}
5860
5861/// Attempt character array initialization from a string literal
5862/// (C++ [dcl.init.string], C99 6.7.8).
5864 const InitializedEntity &Entity,
5865 const InitializationKind &Kind,
5867 InitializationSequence &Sequence) {
5868 Sequence.AddStringInitStep(Entity.getType());
5869}
5870
5871/// Attempt value initialization (C++ [dcl.init]p7).
5873 const InitializedEntity &Entity,
5874 const InitializationKind &Kind,
5875 InitializationSequence &Sequence,
5876 InitListExpr *InitList) {
5877 assert((!InitList || InitList->getNumInits() == 0) &&
5878 "Shouldn't use value-init for non-empty init lists");
5879
5880 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5881 //
5882 // To value-initialize an object of type T means:
5883 QualType T = Entity.getType();
5884 assert(!T->isVoidType() && "Cannot value-init void");
5885
5886 // -- if T is an array type, then each element is value-initialized;
5888
5889 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
5890 bool NeedZeroInitialization = true;
5891 // C++98:
5892 // -- if T is a class type (clause 9) with a user-declared constructor
5893 // (12.1), then the default constructor for T is called (and the
5894 // initialization is ill-formed if T has no accessible default
5895 // constructor);
5896 // C++11:
5897 // -- if T is a class type (clause 9) with either no default constructor
5898 // (12.1 [class.ctor]) or a default constructor that is user-provided
5899 // or deleted, then the object is default-initialized;
5900 //
5901 // Note that the C++11 rule is the same as the C++98 rule if there are no
5902 // defaulted or deleted constructors, so we just use it unconditionally.
5904 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5905 NeedZeroInitialization = false;
5906
5907 // -- if T is a (possibly cv-qualified) non-union class type without a
5908 // user-provided or deleted default constructor, then the object is
5909 // zero-initialized and, if T has a non-trivial default constructor,
5910 // default-initialized;
5911 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5912 // constructor' part was removed by DR1507.
5913 if (NeedZeroInitialization)
5914 Sequence.AddZeroInitializationStep(Entity.getType());
5915
5916 // C++03:
5917 // -- if T is a non-union class type without a user-declared constructor,
5918 // then every non-static data member and base class component of T is
5919 // value-initialized;
5920 // [...] A program that calls for [...] value-initialization of an
5921 // entity of reference type is ill-formed.
5922 //
5923 // C++11 doesn't need this handling, because value-initialization does not
5924 // occur recursively there, and the implicit default constructor is
5925 // defined as deleted in the problematic cases.
5926 if (!S.getLangOpts().CPlusPlus11 &&
5927 ClassDecl->hasUninitializedReferenceMember()) {
5929 return;
5930 }
5931
5932 // If this is list-value-initialization, pass the empty init list on when
5933 // building the constructor call. This affects the semantics of a few
5934 // things (such as whether an explicit default constructor can be called).
5935 Expr *InitListAsExpr = InitList;
5936 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5937 bool InitListSyntax = InitList;
5938
5939 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5940 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5942 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5943 }
5944
5945 Sequence.AddZeroInitializationStep(Entity.getType());
5946}
5947
5948/// Attempt default initialization (C++ [dcl.init]p6).
5950 const InitializedEntity &Entity,
5951 const InitializationKind &Kind,
5952 InitializationSequence &Sequence) {
5953 assert(Kind.getKind() == InitializationKind::IK_Default);
5954
5955 // C++ [dcl.init]p6:
5956 // To default-initialize an object of type T means:
5957 // - if T is an array type, each element is default-initialized;
5958 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5959
5960 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5961 // constructor for T is called (and the initialization is ill-formed if
5962 // T has no accessible default constructor);
5963 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5964 TryConstructorInitialization(S, Entity, Kind, {}, DestType,
5965 Entity.getType(), Sequence);
5966 return;
5967 }
5968
5969 // - otherwise, no initialization is performed.
5970
5971 // If a program calls for the default initialization of an object of
5972 // a const-qualified type T, T shall be a class type with a user-provided
5973 // default constructor.
5974 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5975 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5977 return;
5978 }
5979
5980 // If the destination type has a lifetime property, zero-initialize it.
5981 if (DestType.getQualifiers().hasObjCLifetime()) {
5982 Sequence.AddZeroInitializationStep(Entity.getType());
5983 return;
5984 }
5985}
5986
5988 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5989 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5990 ExprResult *Result) {
5991 unsigned EntityIndexToProcess = 0;
5992 SmallVector<Expr *, 4> InitExprs;
5993 QualType ResultType;
5994 Expr *ArrayFiller = nullptr;
5995 FieldDecl *InitializedFieldInUnion = nullptr;
5996
5997 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5998 const InitializationKind &SubKind,
5999 Expr *Arg, Expr **InitExpr = nullptr) {
6001 S, SubEntity, SubKind,
6002 Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
6003
6004 if (IS.Failed()) {
6005 if (!VerifyOnly) {
6006 IS.Diagnose(S, SubEntity, SubKind,
6007 Arg ? ArrayRef(Arg) : ArrayRef<Expr *>());
6008 } else {
6009 Sequence.SetFailed(
6011 }
6012
6013 return false;
6014 }
6015 if (!VerifyOnly) {
6016 ExprResult ER;
6017 ER = IS.Perform(S, SubEntity, SubKind,
6018 Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
6019
6020 if (ER.isInvalid())
6021 return false;
6022
6023 if (InitExpr)
6024 *InitExpr = ER.get();
6025 else
6026 InitExprs.push_back(ER.get());
6027 }
6028 return true;
6029 };
6030
6031 if (const ArrayType *AT =
6032 S.getASTContext().getAsArrayType(Entity.getType())) {
6033 uint64_t ArrayLength;
6034 // C++ [dcl.init]p16.5
6035 // if the destination type is an array, the object is initialized as
6036 // follows. Let x1, . . . , xk be the elements of the expression-list. If
6037 // the destination type is an array of unknown bound, it is defined as
6038 // having k elements.
6039 if (const ConstantArrayType *CAT =
6041 ArrayLength = CAT->getZExtSize();
6042 ResultType = Entity.getType();
6043 } else if (const VariableArrayType *VAT =
6045 // Braced-initialization of variable array types is not allowed, even if
6046 // the size is greater than or equal to the number of args, so we don't
6047 // allow them to be initialized via parenthesized aggregate initialization
6048 // either.
6049 const Expr *SE = VAT->getSizeExpr();
6050 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
6051 << SE->getSourceRange();
6052 return;
6053 } else {
6054 assert(Entity.getType()->isIncompleteArrayType());
6055 ArrayLength = Args.size();
6056 }
6057 EntityIndexToProcess = ArrayLength;
6058
6059 // ...the ith array element is copy-initialized with xi for each
6060 // 1 <= i <= k
6061 for (Expr *E : Args) {
6063 S.getASTContext(), EntityIndexToProcess, Entity);
6065 E->getExprLoc(), /*isDirectInit=*/false, E);
6066 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6067 return;
6068 }
6069 // ...and value-initialized for each k < i <= n;
6070 if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {
6072 S.getASTContext(), Args.size(), Entity);
6074 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
6075 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
6076 return;
6077 }
6078
6079 if (ResultType.isNull()) {
6080 ResultType = S.Context.getConstantArrayType(
6081 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
6082 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 0);
6083 }
6084 } else if (auto *RD = Entity.getType()->getAsCXXRecordDecl()) {
6085 bool IsUnion = RD->isUnion();
6086 if (RD->isInvalidDecl()) {
6087 // Exit early to avoid confusion when processing members.
6088 // We do the same for braced list initialization in
6089 // `CheckStructUnionTypes`.
6090 Sequence.SetFailed(
6092 return;
6093 }
6094
6095 if (!IsUnion) {
6096 for (const CXXBaseSpecifier &Base : RD->bases()) {
6098 S.getASTContext(), &Base, false, &Entity);
6099 if (EntityIndexToProcess < Args.size()) {
6100 // C++ [dcl.init]p16.6.2.2.
6101 // ...the object is initialized is follows. Let e1, ..., en be the
6102 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
6103 // the elements of the expression-list...The element ei is
6104 // copy-initialized with xi for 1 <= i <= k.
6105 Expr *E = Args[EntityIndexToProcess];
6107 E->getExprLoc(), /*isDirectInit=*/false, E);
6108 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6109 return;
6110 } else {
6111 // We've processed all of the args, but there are still base classes
6112 // that have to be initialized.
6113 // C++ [dcl.init]p17.6.2.2
6114 // The remaining elements...otherwise are value initialzed
6116 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
6117 /*IsImplicit=*/true);
6118 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6119 return;
6120 }
6121 EntityIndexToProcess++;
6122 }
6123 }
6124
6125 for (FieldDecl *FD : RD->fields()) {
6126 // Unnamed bitfields should not be initialized at all, either with an arg
6127 // or by default.
6128 if (FD->isUnnamedBitField())
6129 continue;
6130
6131 InitializedEntity SubEntity =
6133
6134 if (EntityIndexToProcess < Args.size()) {
6135 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
6136 Expr *E = Args[EntityIndexToProcess];
6137
6138 // Incomplete array types indicate flexible array members. Do not allow
6139 // paren list initializations of structs with these members, as GCC
6140 // doesn't either.
6141 if (FD->getType()->isIncompleteArrayType()) {
6142 if (!VerifyOnly) {
6143 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
6144 << SourceRange(E->getBeginLoc(), E->getEndLoc());
6145 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
6146 }
6147 Sequence.SetFailed(
6149 return;
6150 }
6151
6153 E->getExprLoc(), /*isDirectInit=*/false, E);
6154 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6155 return;
6156
6157 // Unions should have only one initializer expression, so we bail out
6158 // after processing the first field. If there are more initializers then
6159 // it will be caught when we later check whether EntityIndexToProcess is
6160 // less than Args.size();
6161 if (IsUnion) {
6162 InitializedFieldInUnion = FD;
6163 EntityIndexToProcess = 1;
6164 break;
6165 }
6166 } else {
6167 // We've processed all of the args, but there are still members that
6168 // have to be initialized.
6169 if (!VerifyOnly && FD->hasAttr<ExplicitInitAttr>() &&
6170 !S.isUnevaluatedContext()) {
6171 S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
6172 << /* Var-in-Record */ 0 << FD;
6173 S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
6174 }
6175
6176 if (FD->hasInClassInitializer()) {
6177 if (!VerifyOnly) {
6178 // C++ [dcl.init]p16.6.2.2
6179 // The remaining elements are initialized with their default
6180 // member initializers, if any
6182 Kind.getParenOrBraceRange().getEnd(), FD, SubEntity);
6183 if (DIE.isInvalid())
6184 return;
6185 InitExprs.push_back(DIE.get());
6186 }
6187 } else {
6188 // C++ [dcl.init]p17.6.2.2
6189 // The remaining elements...otherwise are value initialzed
6190 if (FD->getType()->isReferenceType()) {
6191 Sequence.SetFailed(
6193 if (!VerifyOnly) {
6194 SourceRange SR = Kind.getParenOrBraceRange();
6195 S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
6196 << FD->getType() << SR;
6197 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
6198 }
6199 return;
6200 }
6202 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
6203 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6204 return;
6205 }
6206 }
6207 EntityIndexToProcess++;
6208 }
6209 ResultType = Entity.getType();
6210 }
6211
6212 // Not all of the args have been processed, so there must've been more args
6213 // than were required to initialize the element.
6214 if (EntityIndexToProcess < Args.size()) {
6216 if (!VerifyOnly) {
6217 QualType T = Entity.getType();
6218 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 4 : 5;
6219 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
6220 Args.back()->getEndLoc());
6221 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6222 << InitKind << ExcessInitSR;
6223 }
6224 return;
6225 }
6226
6227 if (VerifyOnly) {
6229 Sequence.AddParenthesizedListInitStep(Entity.getType());
6230 } else if (Result) {
6231 SourceRange SR = Kind.getParenOrBraceRange();
6232 auto *CPLIE = CXXParenListInitExpr::Create(
6233 S.getASTContext(), InitExprs, ResultType, Args.size(),
6234 Kind.getLocation(), SR.getBegin(), SR.getEnd());
6235 if (ArrayFiller)
6236 CPLIE->setArrayFiller(ArrayFiller);
6237 if (InitializedFieldInUnion)
6238 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
6239 *Result = CPLIE;
6240 S.Diag(Kind.getLocation(),
6241 diag::warn_cxx17_compat_aggregate_init_paren_list)
6242 << Kind.getLocation() << SR << ResultType;
6243 }
6244}
6245
6246/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
6247/// which enumerates all conversion functions and performs overload resolution
6248/// to select the best.
6250 QualType DestType,
6251 const InitializationKind &Kind,
6253 InitializationSequence &Sequence,
6254 bool TopLevelOfInitList) {
6255 assert(!DestType->isReferenceType() && "References are handled elsewhere");
6256 QualType SourceType = Initializer->getType();
6257 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
6258 "Must have a class type to perform a user-defined conversion");
6259
6260 // Build the candidate set directly in the initialization sequence
6261 // structure, so that it will persist if we fail.
6262 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
6264 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
6265
6266 // Determine whether we are allowed to call explicit constructors or
6267 // explicit conversion operators.
6268 bool AllowExplicit = Kind.AllowExplicit();
6269
6270 if (DestType->isRecordType()) {
6271 // The type we're converting to is a class type. Enumerate its constructors
6272 // to see if there is a suitable conversion.
6273 // Try to complete the type we're converting to.
6274 if (S.isCompleteType(Kind.getLocation(), DestType)) {
6275 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
6276 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
6277 auto Info = getConstructorInfo(D);
6278 if (!Info.Constructor)
6279 continue;
6280
6281 if (!Info.Constructor->isInvalidDecl() &&
6282 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
6283 if (Info.ConstructorTmpl)
6285 Info.ConstructorTmpl, Info.FoundDecl,
6286 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
6287 /*SuppressUserConversions=*/true,
6288 /*PartialOverloading*/ false, AllowExplicit);
6289 else
6290 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
6291 Initializer, CandidateSet,
6292 /*SuppressUserConversions=*/true,
6293 /*PartialOverloading*/ false, AllowExplicit);
6294 }
6295 }
6296 }
6297 }
6298
6299 SourceLocation DeclLoc = Initializer->getBeginLoc();
6300
6301 if (SourceType->isRecordType()) {
6302 // The type we're converting from is a class type, enumerate its conversion
6303 // functions.
6304
6305 // We can only enumerate the conversion functions for a complete type; if
6306 // the type isn't complete, simply skip this step.
6307 if (S.isCompleteType(DeclLoc, SourceType)) {
6308 auto *SourceRecordDecl = SourceType->castAsCXXRecordDecl();
6309 const auto &Conversions =
6310 SourceRecordDecl->getVisibleConversionFunctions();
6311 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6312 NamedDecl *D = *I;
6314 if (isa<UsingShadowDecl>(D))
6315 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6316
6317 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6318 CXXConversionDecl *Conv;
6319 if (ConvTemplate)
6320 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6321 else
6322 Conv = cast<CXXConversionDecl>(D);
6323
6324 if (ConvTemplate)
6326 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
6327 CandidateSet, AllowExplicit, AllowExplicit);
6328 else
6329 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
6330 DestType, CandidateSet, AllowExplicit,
6331 AllowExplicit);
6332 }
6333 }
6334 }
6335
6336 // Perform overload resolution. If it fails, return the failed result.
6339 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
6340 Sequence.SetOverloadFailure(
6342
6343 // [class.copy.elision]p3:
6344 // In some copy-initialization contexts, a two-stage overload resolution
6345 // is performed.
6346 // If the first overload resolution selects a deleted function, we also
6347 // need the initialization sequence to decide whether to perform the second
6348 // overload resolution.
6349 if (!(Result == OR_Deleted &&
6350 Kind.getKind() == InitializationKind::IK_Copy))
6351 return;
6352 }
6353
6354 FunctionDecl *Function = Best->Function;
6355 Function->setReferenced();
6356 bool HadMultipleCandidates = (CandidateSet.size() > 1);
6357
6358 if (isa<CXXConstructorDecl>(Function)) {
6359 // Add the user-defined conversion step. Any cv-qualification conversion is
6360 // subsumed by the initialization. Per DR5, the created temporary is of the
6361 // cv-unqualified type of the destination.
6362 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
6363 DestType.getUnqualifiedType(),
6364 HadMultipleCandidates);
6365
6366 // C++14 and before:
6367 // - if the function is a constructor, the call initializes a temporary
6368 // of the cv-unqualified version of the destination type. The [...]
6369 // temporary [...] is then used to direct-initialize, according to the
6370 // rules above, the object that is the destination of the
6371 // copy-initialization.
6372 // Note that this just performs a simple object copy from the temporary.
6373 //
6374 // C++17:
6375 // - if the function is a constructor, the call is a prvalue of the
6376 // cv-unqualified version of the destination type whose return object
6377 // is initialized by the constructor. The call is used to
6378 // direct-initialize, according to the rules above, the object that
6379 // is the destination of the copy-initialization.
6380 // Therefore we need to do nothing further.
6381 //
6382 // FIXME: Mark this copy as extraneous.
6383 if (!S.getLangOpts().CPlusPlus17)
6384 Sequence.AddFinalCopy(DestType);
6385 else if (DestType.hasQualifiers())
6386 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6387 return;
6388 }
6389
6390 // Add the user-defined conversion step that calls the conversion function.
6391 QualType ConvType = Function->getCallResultType();
6392 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
6393 HadMultipleCandidates);
6394
6395 if (ConvType->isRecordType()) {
6396 if (S.getLangOpts().HLSL &&
6397 ConvType.getAddressSpace() == LangAS::hlsl_constant &&
6398 S.Context.hasSameUnqualifiedType(ConvType, DestType)) {
6399 Sequence.AddHLSLBufferConversionStep(ConvType);
6400 return;
6401 }
6402
6403 // The call is used to direct-initialize [...] the object that is the
6404 // destination of the copy-initialization.
6405 //
6406 // In C++17, this does not call a constructor if we enter /17.6.1:
6407 // - If the initializer expression is a prvalue and the cv-unqualified
6408 // version of the source type is the same as the class of the
6409 // destination [... do not make an extra copy]
6410 //
6411 // FIXME: Mark this copy as extraneous.
6412 if (!S.getLangOpts().CPlusPlus17 ||
6413 Function->getReturnType()->isReferenceType() ||
6414 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
6415 Sequence.AddFinalCopy(DestType);
6416 else if (!S.Context.hasSameType(ConvType, DestType))
6417 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6418 return;
6419 }
6420
6421 // If the conversion following the call to the conversion function
6422 // is interesting, add it as a separate step.
6423 assert(Best->HasFinalConversion);
6424 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
6425 Best->FinalConversion.Third) {
6427 ICS.setStandard();
6428 ICS.Standard = Best->FinalConversion;
6429 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6430 }
6431}
6432
6433/// The non-zero enum values here are indexes into diagnostic alternatives.
6435
6436/// Determines whether this expression is an acceptable ICR source.
6438 bool isAddressOf, bool &isWeakAccess) {
6439 // Skip parens.
6440 e = e->IgnoreParens();
6441
6442 // Skip address-of nodes.
6443 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
6444 if (op->getOpcode() == UO_AddrOf)
6445 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
6446 isWeakAccess);
6447
6448 // Skip certain casts.
6449 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
6450 switch (ce->getCastKind()) {
6451 case CK_Dependent:
6452 case CK_BitCast:
6453 case CK_LValueBitCast:
6454 case CK_NoOp:
6455 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
6456
6457 case CK_ArrayToPointerDecay:
6458 return IIK_nonscalar;
6459
6460 case CK_NullToPointer:
6461 return IIK_okay;
6462
6463 default:
6464 break;
6465 }
6466
6467 // If we have a declaration reference, it had better be a local variable.
6468 } else if (isa<DeclRefExpr>(e)) {
6469 // set isWeakAccess to true, to mean that there will be an implicit
6470 // load which requires a cleanup.
6472 isWeakAccess = true;
6473
6474 if (!isAddressOf) return IIK_nonlocal;
6475
6476 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
6477 if (!var) return IIK_nonlocal;
6478
6479 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
6480
6481 // If we have a conditional operator, check both sides.
6482 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
6483 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
6484 isWeakAccess))
6485 return iik;
6486
6487 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
6488
6489 // These are never scalar.
6490 } else if (isa<ArraySubscriptExpr>(e)) {
6491 return IIK_nonscalar;
6492
6493 // Otherwise, it needs to be a null pointer constant.
6494 } else {
6497 }
6498
6499 return IIK_nonlocal;
6500}
6501
6502/// Check whether the given expression is a valid operand for an
6503/// indirect copy/restore.
6505 assert(src->isPRValue());
6506 bool isWeakAccess = false;
6507 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
6508 // If isWeakAccess to true, there will be an implicit
6509 // load which requires a cleanup.
6510 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
6512
6513 if (iik == IIK_okay) return;
6514
6515 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
6516 << ((unsigned) iik - 1) // shift index into diagnostic explanations
6517 << src->getSourceRange();
6518}
6519
6520/// Determine whether we have compatible array types for the
6521/// purposes of GNU by-copy array initialization.
6522static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
6523 const ArrayType *Source) {
6524 // If the source and destination array types are equivalent, we're
6525 // done.
6526 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
6527 return true;
6528
6529 // Make sure that the element types are the same.
6530 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
6531 return false;
6532
6533 // The only mismatch we allow is when the destination is an
6534 // incomplete array type and the source is a constant array type.
6535 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
6536}
6537
6539 InitializationSequence &Sequence,
6540 const InitializedEntity &Entity,
6541 Expr *Initializer) {
6542 bool ArrayDecay = false;
6543 QualType ArgType = Initializer->getType();
6544 QualType ArgPointee;
6545 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
6546 ArrayDecay = true;
6547 ArgPointee = ArgArrayType->getElementType();
6548 ArgType = S.Context.getPointerType(ArgPointee);
6549 }
6550
6551 // Handle write-back conversion.
6552 QualType ConvertedArgType;
6553 if (!S.ObjC().isObjCWritebackConversion(ArgType, Entity.getType(),
6554 ConvertedArgType))
6555 return false;
6556
6557 // We should copy unless we're passing to an argument explicitly
6558 // marked 'out'.
6559 bool ShouldCopy = true;
6560 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6561 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6562
6563 // Do we need an lvalue conversion?
6564 if (ArrayDecay || Initializer->isGLValue()) {
6566 ICS.setStandard();
6568
6569 QualType ResultType;
6570 if (ArrayDecay) {
6572 ResultType = S.Context.getPointerType(ArgPointee);
6573 } else {
6575 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
6576 }
6577
6578 Sequence.AddConversionSequenceStep(ICS, ResultType);
6579 }
6580
6581 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
6582 return true;
6583}
6584
6586 InitializationSequence &Sequence,
6587 QualType DestType,
6588 Expr *Initializer) {
6589 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6590 (!Initializer->isIntegerConstantExpr(S.Context) &&
6591 !Initializer->getType()->isSamplerT()))
6592 return false;
6593
6594 Sequence.AddOCLSamplerInitStep(DestType);
6595 return true;
6596}
6597
6598static bool IsZeroInitializer(const Expr *Init, ASTContext &Ctx) {
6599 std::optional<llvm::APSInt> Value = Init->getIntegerConstantExpr(Ctx);
6600 return Value && Value->isZero();
6601}
6602
6604 InitializationSequence &Sequence,
6605 QualType DestType,
6606 Expr *Initializer) {
6607 if (!S.getLangOpts().OpenCL)
6608 return false;
6609
6610 //
6611 // OpenCL 1.2 spec, s6.12.10
6612 //
6613 // The event argument can also be used to associate the
6614 // async_work_group_copy with a previous async copy allowing
6615 // an event to be shared by multiple async copies; otherwise
6616 // event should be zero.
6617 //
6618 if (DestType->isEventT() || DestType->isQueueT()) {
6620 return false;
6621
6622 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6623 return true;
6624 }
6625
6626 // We should allow zero initialization for all types defined in the
6627 // cl_intel_device_side_avc_motion_estimation extension, except
6628 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6630 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
6631 DestType->isOCLIntelSubgroupAVCType()) {
6632 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6633 DestType->isOCLIntelSubgroupAVCMceResultType())
6634 return false;
6636 return false;
6637
6638 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6639 return true;
6640 }
6641
6642 return false;
6643}
6644
6646 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6647 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6648 : FailedOverloadResult(OR_Success),
6649 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6650 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6651 TreatUnavailableAsInvalid);
6652}
6653
6654/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6655/// address of that function, this returns true. Otherwise, it returns false.
6656static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6657 auto *DRE = dyn_cast<DeclRefExpr>(E);
6658 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6659 return false;
6660
6662 cast<FunctionDecl>(DRE->getDecl()));
6663}
6664
6665/// Determine whether we can perform an elementwise array copy for this kind
6666/// of entity.
6667static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6668 switch (Entity.getKind()) {
6670 // C++ [expr.prim.lambda]p24:
6671 // For array members, the array elements are direct-initialized in
6672 // increasing subscript order.
6673 return true;
6674
6676 // C++ [dcl.decomp]p1:
6677 // [...] each element is copy-initialized or direct-initialized from the
6678 // corresponding element of the assignment-expression [...]
6679 return isa<DecompositionDecl>(Entity.getDecl());
6680
6682 // C++ [class.copy.ctor]p14:
6683 // - if the member is an array, each element is direct-initialized with
6684 // the corresponding subobject of x
6685 return Entity.isImplicitMemberInitializer();
6686
6688 // All the above cases are intended to apply recursively, even though none
6689 // of them actually say that.
6690 if (auto *E = Entity.getParent())
6691 return canPerformArrayCopy(*E);
6692 break;
6693
6694 default:
6695 break;
6696 }
6697
6698 return false;
6699}
6700
6701static const FieldDecl *getConstField(const RecordDecl *RD) {
6702 assert(!isa<CXXRecordDecl>(RD) && "Only expect to call this in C mode");
6703 for (const FieldDecl *FD : RD->fields()) {
6704 // If the field is a flexible array member, we don't want to consider it
6705 // as a const field because there's no way to initialize the FAM anyway.
6706 const ASTContext &Ctx = FD->getASTContext();
6708 Ctx, FD, FD->getType(),
6709 Ctx.getLangOpts().getStrictFlexArraysLevel(),
6710 /*IgnoreTemplateOrMacroSubstitution=*/true))
6711 continue;
6712
6713 QualType QT = FD->getType();
6714 if (QT.isConstQualified())
6715 return FD;
6716 if (const auto *RD = QT->getAsRecordDecl()) {
6717 if (const FieldDecl *FD = getConstField(RD))
6718 return FD;
6719 }
6720 }
6721 return nullptr;
6722}
6723
6725 const InitializedEntity &Entity,
6726 const InitializationKind &Kind,
6727 MultiExprArg Args,
6728 bool TopLevelOfInitList,
6729 bool TreatUnavailableAsInvalid) {
6730 ASTContext &Context = S.Context;
6731
6732 // Eliminate non-overload placeholder types in the arguments. We
6733 // need to do this before checking whether types are dependent
6734 // because lowering a pseudo-object expression might well give us
6735 // something of dependent type.
6736 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6737 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6738 // FIXME: should we be doing this here?
6739 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
6740 if (result.isInvalid()) {
6742 return;
6743 }
6744 Args[I] = result.get();
6745 }
6746
6747 // C++0x [dcl.init]p16:
6748 // The semantics of initializers are as follows. The destination type is
6749 // the type of the object or reference being initialized and the source
6750 // type is the type of the initializer expression. The source type is not
6751 // defined when the initializer is a braced-init-list or when it is a
6752 // parenthesized list of expressions.
6753 QualType DestType = Entity.getType();
6754
6755 if (DestType->isDependentType() ||
6758 return;
6759 }
6760
6761 // Almost everything is a normal sequence.
6763
6764 QualType SourceType;
6765 Expr *Initializer = nullptr;
6766 if (Args.size() == 1) {
6767 Initializer = Args[0];
6768 if (S.getLangOpts().ObjC) {
6770 Initializer->getBeginLoc(), DestType, Initializer->getType(),
6771 Initializer) ||
6773 Args[0] = Initializer;
6774 }
6776 SourceType = Initializer->getType();
6777 }
6778
6779 // - If the initializer is a (non-parenthesized) braced-init-list, the
6780 // object is list-initialized (8.5.4).
6781 if (Kind.getKind() != InitializationKind::IK_Direct) {
6782 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
6783 TryListInitialization(S, Entity, Kind, InitList, *this,
6784 TreatUnavailableAsInvalid);
6785 return;
6786 }
6787 }
6788
6789 if (!S.getLangOpts().CPlusPlus &&
6790 Kind.getKind() == InitializationKind::IK_Default) {
6791 if (RecordDecl *Rec = DestType->getAsRecordDecl()) {
6792 VarDecl *Var = dyn_cast_or_null<VarDecl>(Entity.getDecl());
6793 if (Rec->hasUninitializedExplicitInitFields()) {
6794 if (Var && !Initializer && !S.isUnevaluatedContext()) {
6795 S.Diag(Var->getLocation(), diag::warn_field_requires_explicit_init)
6796 << /* Var-in-Record */ 1 << Rec;
6798 }
6799 }
6800 // If the record has any members which are const (recursively checked),
6801 // then we want to diagnose those as being uninitialized if there is no
6802 // initializer present. However, we only do this for structure types, not
6803 // union types, because an unitialized field in a union is generally
6804 // reasonable, especially in C where unions can be used for type punning.
6805 if (Var && !Initializer && !Rec->isUnion() && !Rec->isInvalidDecl()) {
6806 if (const FieldDecl *FD = getConstField(Rec)) {
6807 unsigned DiagID = diag::warn_default_init_const_field_unsafe;
6808 if (Var->getStorageDuration() == SD_Static ||
6809 Var->getStorageDuration() == SD_Thread)
6810 DiagID = diag::warn_default_init_const_field;
6811
6812 bool EmitCppCompat = !S.Diags.isIgnored(
6813 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
6814 Var->getLocation());
6815
6816 S.Diag(Var->getLocation(), DiagID) << Var->getType() << EmitCppCompat;
6817 S.Diag(FD->getLocation(), diag::note_default_init_const_member) << FD;
6818 }
6819 }
6820 }
6821 }
6822
6823 // - If the destination type is a reference type, see 8.5.3.
6824 if (DestType->isReferenceType()) {
6825 // C++0x [dcl.init.ref]p1:
6826 // A variable declared to be a T& or T&&, that is, "reference to type T"
6827 // (8.3.2), shall be initialized by an object, or function, of type T or
6828 // by an object that can be converted into a T.
6829 // (Therefore, multiple arguments are not permitted.)
6830 if (Args.size() != 1)
6832 // C++17 [dcl.init.ref]p5:
6833 // A reference [...] is initialized by an expression [...] as follows:
6834 // If the initializer is not an expression, presumably we should reject,
6835 // but the standard fails to actually say so.
6836 else if (isa<InitListExpr>(Args[0]))
6838 else
6839 TryReferenceInitialization(S, Entity, Kind, Args[0], *this,
6840 TopLevelOfInitList);
6841 return;
6842 }
6843
6844 // - If the initializer is (), the object is value-initialized.
6845 if (Kind.getKind() == InitializationKind::IK_Value ||
6846 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6847 TryValueInitialization(S, Entity, Kind, *this);
6848 return;
6849 }
6850
6851 // Handle default initialization.
6852 if (Kind.getKind() == InitializationKind::IK_Default) {
6853 TryDefaultInitialization(S, Entity, Kind, *this);
6854 return;
6855 }
6856
6857 // - If the destination type is an array of characters, an array of
6858 // char16_t, an array of char32_t, or an array of wchar_t, and the
6859 // initializer is a string literal, see 8.5.2.
6860 // - Otherwise, if the destination type is an array, the program is
6861 // ill-formed.
6862 // - Except in HLSL, where non-decaying array parameters behave like
6863 // non-array types for initialization.
6864 if (DestType->isArrayType() && !DestType->isArrayParameterType()) {
6865 const ArrayType *DestAT = Context.getAsArrayType(DestType);
6866 if (Initializer && isa<VariableArrayType>(DestAT)) {
6868 return;
6869 }
6870
6871 if (Initializer) {
6872 switch (IsStringInit(Initializer, DestAT, Context)) {
6873 case SIF_None:
6874 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
6875 return;
6878 return;
6881 return;
6884 return;
6887 return;
6890 return;
6891 case SIF_Other:
6892 break;
6893 }
6894 }
6895
6896 if (S.getLangOpts().HLSL && Initializer && isa<ConstantArrayType>(DestAT)) {
6897 QualType SrcType = Entity.getType();
6898 if (SrcType->isArrayParameterType())
6899 SrcType =
6900 cast<ArrayParameterType>(SrcType)->getConstantArrayType(Context);
6901 if (S.Context.hasSameUnqualifiedType(DestType, SrcType)) {
6902 TryArrayCopy(S, Kind, Entity, Initializer, DestType, *this,
6903 TreatUnavailableAsInvalid);
6904 return;
6905 }
6906 }
6907
6908 // Some kinds of initialization permit an array to be initialized from
6909 // another array of the same type, and perform elementwise initialization.
6910 if (Initializer && isa<ConstantArrayType>(DestAT) &&
6912 Entity.getType()) &&
6913 canPerformArrayCopy(Entity)) {
6914 TryArrayCopy(S, Kind, Entity, Initializer, DestType, *this,
6915 TreatUnavailableAsInvalid);
6916 return;
6917 }
6918
6919 // Note: as an GNU C extension, we allow initialization of an
6920 // array from a compound literal that creates an array of the same
6921 // type, so long as the initializer has no side effects.
6922 if (!S.getLangOpts().CPlusPlus && Initializer &&
6923 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6924 Initializer->getType()->isArrayType()) {
6925 const ArrayType *SourceAT
6926 = Context.getAsArrayType(Initializer->getType());
6927 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
6929 else if (Initializer->HasSideEffects(S.Context))
6931 else {
6932 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
6933 }
6934 }
6935 // Note: as a GNU C++ extension, we allow list-initialization of a
6936 // class member of array type from a parenthesized initializer list.
6937 else if (S.getLangOpts().CPlusPlus &&
6939 isa_and_nonnull<InitListExpr>(Initializer)) {
6941 *this, TreatUnavailableAsInvalid);
6943 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6944 Kind.getKind() == InitializationKind::IK_Direct)
6945 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6946 /*VerifyOnly=*/true);
6947 else if (DestAT->getElementType()->isCharType())
6949 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6951 else
6953
6954 return;
6955 }
6956
6957 // Determine whether we should consider writeback conversions for
6958 // Objective-C ARC.
6959 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6960 Entity.isParameterKind();
6961
6962 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
6963 return;
6964
6965 // We're at the end of the line for C: it's either a write-back conversion
6966 // or it's a C assignment. There's no need to check anything else.
6967 if (!S.getLangOpts().CPlusPlus) {
6968 assert(Initializer && "Initializer must be non-null");
6969 // If allowed, check whether this is an Objective-C writeback conversion.
6970 if (allowObjCWritebackConversion &&
6971 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
6972 return;
6973 }
6974
6975 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
6976 return;
6977
6978 // Handle initialization in C
6979 AddCAssignmentStep(DestType);
6980 MaybeProduceObjCObject(S, *this, Entity);
6981 return;
6982 }
6983
6984 assert(S.getLangOpts().CPlusPlus);
6985
6986 // - If the destination type is a (possibly cv-qualified) class type:
6987 // (except for HLSL, where user-defined record types do not have
6988 // constructors or conversion functions)
6989 if (DestType->isRecordType() &&
6990 (!S.getLangOpts().HLSL ||
6991 DestType->getAsCXXRecordDecl()->isHLSLBuiltinRecord())) {
6992 // - If the initialization is direct-initialization, or if it is
6993 // copy-initialization where the cv-unqualified version of the
6994 // source type is the same class as, or a derived class of, the
6995 // class of the destination, constructors are considered. [...]
6996 if (Kind.getKind() == InitializationKind::IK_Direct ||
6997 (Kind.getKind() == InitializationKind::IK_Copy &&
6998 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
6999 (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
7000 SourceType, DestType))))) {
7001 TryConstructorOrParenListInitialization(S, Entity, Kind, Args, DestType,
7002 *this, /*IsAggrListInit=*/false);
7003 } else {
7004 // - Otherwise (i.e., for the remaining copy-initialization cases),
7005 // user-defined conversion sequences that can convert from the
7006 // source type to the destination type or (when a conversion
7007 // function is used) to a derived class thereof are enumerated as
7008 // described in 13.3.1.4, and the best one is chosen through
7009 // overload resolution (13.3).
7010 assert(Initializer && "Initializer must be non-null");
7011 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
7012 TopLevelOfInitList);
7013 }
7014 return;
7015 }
7016
7017 assert(Args.size() >= 1 && "Zero-argument case handled above");
7018
7019 // For HLSL ext vector types we allow list initialization behavior for C++
7020 // functional cast expressions which look like constructor syntax. This is
7021 // accomplished by converting initialization arguments to InitListExpr.
7022 auto ShouldTryListInitialization = [&]() -> bool {
7023 // Only try list initialization for HLSL.
7024 if (!S.getLangOpts().HLSL)
7025 return false;
7026
7027 bool DestIsVec = DestType->isExtVectorType();
7028 bool DestIsMat = DestType->isConstantMatrixType();
7029
7030 // If the destination type is neither a vector nor a matrix, then don't try
7031 // list initialization.
7032 if (!DestIsVec && !DestIsMat)
7033 return false;
7034
7035 // If there is only a single source argument, then only try list
7036 // initialization if initializing a matrix with a vector or vice versa.
7037 if (Args.size() == 1) {
7038 assert(!SourceType.isNull() &&
7039 "Source QualType should not be null when arg size is exactly 1");
7040 bool SourceIsVec = SourceType->isExtVectorType();
7041 bool SourceIsMat = SourceType->isConstantMatrixType();
7042
7043 if (DestIsMat && !SourceIsVec)
7044 return false;
7045 if (DestIsVec && !SourceIsMat)
7046 return false;
7047 }
7048
7049 // Try list initialization if the source type is null or if the
7050 // destination and source types differ.
7051 return SourceType.isNull() ||
7052 !Context.hasSameUnqualifiedType(SourceType, DestType);
7053 };
7054 if (ShouldTryListInitialization()) {
7055 InitListExpr *ILE = new (Context)
7056 InitListExpr(S.getASTContext(), Args.front()->getBeginLoc(), Args,
7057 Args.back()->getEndLoc(), /*isExplicit=*/false);
7058 ILE->setType(DestType);
7059 Args[0] = ILE;
7060 TryListInitialization(S, Entity, Kind, ILE, *this,
7061 TreatUnavailableAsInvalid);
7062 return;
7063 }
7064
7065 // The remaining cases all need a source type.
7066 if (Args.size() > 1) {
7068 return;
7069 } else if (isa<InitListExpr>(Args[0])) {
7071 return;
7072 }
7073
7074 // - Otherwise, if the source type is a (possibly cv-qualified) class
7075 // type, conversion functions are considered.
7076 // (except for HLSL, where user-defined record types do not have
7077 // constructors or conversion functions).
7078 if (!SourceType.isNull() && SourceType->isRecordType() &&
7079 (!S.getLangOpts().HLSL ||
7080 SourceType->getAsCXXRecordDecl()->isHLSLBuiltinRecord())) {
7081 assert(Initializer && "Initializer must be non-null");
7082 // For a conversion to _Atomic(T) from either T or a class type derived
7083 // from T, initialize the T object then convert to _Atomic type.
7084 bool NeedAtomicConversion = false;
7085 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
7086 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
7087 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
7088 Atomic->getValueType())) {
7089 DestType = Atomic->getValueType();
7090 NeedAtomicConversion = true;
7091 }
7092 }
7093
7094 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
7095 TopLevelOfInitList);
7096 MaybeProduceObjCObject(S, *this, Entity);
7097 if (!Failed() && NeedAtomicConversion)
7099 return;
7100 }
7101
7102 // - Otherwise, if the initialization is direct-initialization, the source
7103 // type is std::nullptr_t, and the destination type is bool, the initial
7104 // value of the object being initialized is false.
7105 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
7106 DestType->isBooleanType() &&
7107 Kind.getKind() == InitializationKind::IK_Direct) {
7110 Initializer->isGLValue()),
7111 DestType);
7112 return;
7113 }
7114
7115 // - Otherwise, the initial value of the object being initialized is the
7116 // (possibly converted) value of the initializer expression. Standard
7117 // conversions (Clause 4) will be used, if necessary, to convert the
7118 // initializer expression to the cv-unqualified version of the
7119 // destination type; no user-defined conversions are considered.
7120
7122 = S.TryImplicitConversion(Initializer, DestType,
7123 /*SuppressUserConversions*/true,
7124 Sema::AllowedExplicit::None,
7125 /*InOverloadResolution*/ false,
7126 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
7127 allowObjCWritebackConversion);
7128
7129 if (ICS.isStandard() &&
7131 // Objective-C ARC writeback conversion.
7132
7133 // We should copy unless we're passing to an argument explicitly
7134 // marked 'out'.
7135 bool ShouldCopy = true;
7136 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
7137 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
7138
7139 // If there was an lvalue adjustment, add it as a separate conversion.
7140 if (ICS.Standard.First == ICK_Array_To_Pointer ||
7143 LvalueICS.setStandard();
7145 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
7146 LvalueICS.Standard.First = ICS.Standard.First;
7147 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
7148 }
7149
7150 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
7151 } else if (ICS.isBad()) {
7153 Initializer->getType() == Context.OverloadTy &&
7155 /*Complain=*/false, Found))
7157 else if (Initializer->getType()->isFunctionType() &&
7160 else
7162 } else {
7163 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
7164
7165 MaybeProduceObjCObject(S, *this, Entity);
7166 }
7167}
7168
7170 for (auto &S : Steps)
7171 S.Destroy();
7172}
7173
7174//===----------------------------------------------------------------------===//
7175// Perform initialization
7176//===----------------------------------------------------------------------===//
7178 bool Diagnose = false) {
7179 switch(Entity.getKind()) {
7186
7188 if (Entity.getDecl() &&
7191
7193
7195 if (Entity.getDecl() &&
7198
7199 return !Diagnose ? AssignmentAction::Passing
7201
7203 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
7205
7208 // FIXME: Can we tell apart casting vs. converting?
7210
7212 // This is really initialization, but refer to it as conversion for
7213 // consistency with CheckConvertedConstantExpression.
7215
7228 }
7229
7230 llvm_unreachable("Invalid EntityKind!");
7231}
7232
7233/// Whether we should bind a created object as a temporary when
7234/// initializing the given entity.
7267
7268/// Whether the given entity, when initialized with an object
7269/// created for that initialization, requires destruction.
7302
7303/// Get the location at which initialization diagnostics should appear.
7342
7343/// Make a (potentially elidable) temporary copy of the object
7344/// provided by the given initializer by calling the appropriate copy
7345/// constructor.
7346///
7347/// \param S The Sema object used for type-checking.
7348///
7349/// \param T The type of the temporary object, which must either be
7350/// the type of the initializer expression or a superclass thereof.
7351///
7352/// \param Entity The entity being initialized.
7353///
7354/// \param CurInit The initializer expression.
7355///
7356/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
7357/// is permitted in C++03 (but not C++0x) when binding a reference to
7358/// an rvalue.
7359///
7360/// \returns An expression that copies the initializer expression into
7361/// a temporary object, or an error expression if a copy could not be
7362/// created.
7364 QualType T,
7365 const InitializedEntity &Entity,
7366 ExprResult CurInit,
7367 bool IsExtraneousCopy) {
7368 if (CurInit.isInvalid())
7369 return CurInit;
7370 // Determine which class type we're copying to.
7371 Expr *CurInitExpr = (Expr *)CurInit.get();
7372 auto *Class = T->getAsCXXRecordDecl();
7373 if (!Class)
7374 return CurInit;
7375
7376 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
7377
7378 // Make sure that the type we are copying is complete.
7379 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
7380 return CurInit;
7381
7382 // Perform overload resolution using the class's constructors. Per
7383 // C++11 [dcl.init]p16, second bullet for class types, this initialization
7384 // is direct-initialization.
7387
7390 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
7391 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7392 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7393 /*RequireActualConstructor=*/false,
7394 /*SecondStepOfCopyInit=*/true)) {
7395 case OR_Success:
7396 break;
7397
7399 CandidateSet.NoteCandidates(
7401 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
7402 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
7403 : diag::err_temp_copy_no_viable)
7404 << (int)Entity.getKind() << CurInitExpr->getType()
7405 << CurInitExpr->getSourceRange()),
7406 S, OCD_AllCandidates, CurInitExpr);
7407 if (!IsExtraneousCopy || S.isSFINAEContext())
7408 return ExprError();
7409 return CurInit;
7410
7411 case OR_Ambiguous:
7412 CandidateSet.NoteCandidates(
7413 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
7414 << (int)Entity.getKind()
7415 << CurInitExpr->getType()
7416 << CurInitExpr->getSourceRange()),
7417 S, OCD_AmbiguousCandidates, CurInitExpr);
7418 return ExprError();
7419
7420 case OR_Deleted:
7421 S.Diag(Loc, diag::err_temp_copy_deleted)
7422 << (int)Entity.getKind() << CurInitExpr->getType()
7423 << CurInitExpr->getSourceRange();
7424 S.NoteDeletedFunction(Best->Function);
7425 return ExprError();
7426 }
7427
7428 bool HadMultipleCandidates = CandidateSet.size() > 1;
7429
7431 SmallVector<Expr*, 8> ConstructorArgs;
7432 CurInit.get(); // Ownership transferred into MultiExprArg, below.
7433
7434 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
7435 IsExtraneousCopy);
7436
7437 if (IsExtraneousCopy) {
7438 // If this is a totally extraneous copy for C++03 reference
7439 // binding purposes, just return the original initialization
7440 // expression. We don't generate an (elided) copy operation here
7441 // because doing so would require us to pass down a flag to avoid
7442 // infinite recursion, where each step adds another extraneous,
7443 // elidable copy.
7444
7445 // Instantiate the default arguments of any extra parameters in
7446 // the selected copy constructor, as if we were going to create a
7447 // proper call to the copy constructor.
7448 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
7449 ParmVarDecl *Parm = Constructor->getParamDecl(I);
7450 if (S.RequireCompleteType(Loc, Parm->getType(),
7451 diag::err_call_incomplete_argument))
7452 break;
7453
7454 // Build the default argument expression; we don't actually care
7455 // if this succeeds or not, because this routine will complain
7456 // if there was a problem.
7457 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
7458 }
7459
7460 return CurInitExpr;
7461 }
7462
7463 // Determine the arguments required to actually perform the
7464 // constructor call (we might have derived-to-base conversions, or
7465 // the copy constructor may have default arguments).
7466 if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
7467 ConstructorArgs))
7468 return ExprError();
7469
7470 // C++0x [class.copy]p32:
7471 // When certain criteria are met, an implementation is allowed to
7472 // omit the copy/move construction of a class object, even if the
7473 // copy/move constructor and/or destructor for the object have
7474 // side effects. [...]
7475 // - when a temporary class object that has not been bound to a
7476 // reference (12.2) would be copied/moved to a class object
7477 // with the same cv-unqualified type, the copy/move operation
7478 // can be omitted by constructing the temporary object
7479 // directly into the target of the omitted copy/move
7480 //
7481 // Note that the other three bullets are handled elsewhere. Copy
7482 // elision for return statements and throw expressions are handled as part
7483 // of constructor initialization, while copy elision for exception handlers
7484 // is handled by the run-time.
7485 //
7486 // FIXME: If the function parameter is not the same type as the temporary, we
7487 // should still be able to elide the copy, but we don't have a way to
7488 // represent in the AST how much should be elided in this case.
7489 bool Elidable =
7490 CurInitExpr->isTemporaryObject(S.Context, Class) &&
7492 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
7493 CurInitExpr->getType());
7494
7495 // Actually perform the constructor call.
7496 CurInit = S.BuildCXXConstructExpr(
7497 Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,
7498 HadMultipleCandidates,
7499 /*ListInit*/ false,
7500 /*StdInitListInit*/ false,
7501 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
7502
7503 // If we're supposed to bind temporaries, do so.
7504 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
7505 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7506 return CurInit;
7507}
7508
7509/// Check whether elidable copy construction for binding a reference to
7510/// a temporary would have succeeded if we were building in C++98 mode, for
7511/// -Wc++98-compat.
7513 const InitializedEntity &Entity,
7514 Expr *CurInitExpr) {
7515 assert(S.getLangOpts().CPlusPlus11);
7516
7517 auto *Record = CurInitExpr->getType()->getAsCXXRecordDecl();
7518 if (!Record)
7519 return;
7520
7521 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
7522 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
7523 return;
7524
7525 // Find constructors which would have been considered.
7528
7529 // Perform overload resolution.
7532 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
7533 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7534 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7535 /*RequireActualConstructor=*/false,
7536 /*SecondStepOfCopyInit=*/true);
7537
7538 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
7539 << OR << (int)Entity.getKind() << CurInitExpr->getType()
7540 << CurInitExpr->getSourceRange();
7541
7542 switch (OR) {
7543 case OR_Success:
7544 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
7545 Best->FoundDecl, Entity, Diag);
7546 // FIXME: Check default arguments as far as that's possible.
7547 break;
7548
7550 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7551 OCD_AllCandidates, CurInitExpr);
7552 break;
7553
7554 case OR_Ambiguous:
7555 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7556 OCD_AmbiguousCandidates, CurInitExpr);
7557 break;
7558
7559 case OR_Deleted:
7560 S.Diag(Loc, Diag);
7561 S.NoteDeletedFunction(Best->Function);
7562 break;
7563 }
7564}
7565
7566void InitializationSequence::PrintInitLocationNote(Sema &S,
7567 const InitializedEntity &Entity) {
7568 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
7569 if (Entity.getDecl()->getLocation().isInvalid())
7570 return;
7571
7572 if (Entity.getDecl()->getDeclName())
7573 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
7574 << Entity.getDecl()->getDeclName();
7575 else
7576 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
7577 }
7578 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
7579 Entity.getMethodDecl())
7580 S.Diag(Entity.getMethodDecl()->getLocation(),
7581 diag::note_method_return_type_change)
7582 << Entity.getMethodDecl()->getDeclName();
7583}
7584
7585/// Returns true if the parameters describe a constructor initialization of
7586/// an explicit temporary object, e.g. "Point(x, y)".
7587static bool isExplicitTemporary(const InitializedEntity &Entity,
7588 const InitializationKind &Kind,
7589 unsigned NumArgs) {
7590 switch (Entity.getKind()) {
7594 break;
7595 default:
7596 return false;
7597 }
7598
7599 switch (Kind.getKind()) {
7601 return true;
7602 // FIXME: Hack to work around cast weirdness.
7605 return NumArgs != 1;
7606 default:
7607 return false;
7608 }
7609}
7610
7611static ExprResult
7613 const InitializedEntity &Entity,
7614 const InitializationKind &Kind,
7615 MultiExprArg Args,
7616 const InitializationSequence::Step& Step,
7617 bool &ConstructorInitRequiresZeroInit,
7618 bool IsListInitialization,
7619 bool IsStdInitListInitialization,
7620 SourceLocation LBraceLoc,
7621 SourceLocation RBraceLoc) {
7622 unsigned NumArgs = Args.size();
7625 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7626
7627 // Build a call to the selected constructor.
7628 SmallVector<Expr*, 8> ConstructorArgs;
7629 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7630 ? Kind.getEqualLoc()
7631 : Kind.getLocation();
7632
7633 if (Kind.getKind() == InitializationKind::IK_Default) {
7634 // Force even a trivial, implicit default constructor to be
7635 // semantically checked. We do this explicitly because we don't build
7636 // the definition for completely trivial constructors.
7637 assert(Constructor->getParent() && "No parent class for constructor.");
7638 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7639 Constructor->isTrivial() && !Constructor->isUsed(false)) {
7640 S.runWithSufficientStackSpace(Loc, [&] {
7642 });
7643 }
7644 }
7645
7646 ExprResult CurInit((Expr *)nullptr);
7647
7648 // C++ [over.match.copy]p1:
7649 // - When initializing a temporary to be bound to the first parameter
7650 // of a constructor that takes a reference to possibly cv-qualified
7651 // T as its first argument, called with a single argument in the
7652 // context of direct-initialization, explicit conversion functions
7653 // are also considered.
7654 bool AllowExplicitConv =
7655 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7658
7659 // A smart pointer constructed from a nullable pointer is nullable.
7660 if (NumArgs == 1 && !Kind.isExplicitCast())
7662 Entity.getType(), Args.front()->getType(), Kind.getLocation());
7663
7664 // Determine the arguments required to actually perform the constructor
7665 // call.
7666 if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
7667 ConstructorArgs, AllowExplicitConv,
7668 IsListInitialization))
7669 return ExprError();
7670
7671 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7672 // An explicitly-constructed temporary, e.g., X(1, 2).
7673 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7674 return ExprError();
7675
7676 if (Kind.getKind() == InitializationKind::IK_Value &&
7677 Constructor->isImplicit()) {
7678 auto *RD = Step.Type.getCanonicalType()->getAsCXXRecordDecl();
7679 if (RD && RD->isAggregate() && RD->hasUninitializedExplicitInitFields()) {
7680 unsigned I = 0;
7681 for (const FieldDecl *FD : RD->fields()) {
7682 if (I >= ConstructorArgs.size() && FD->hasAttr<ExplicitInitAttr>() &&
7683 !S.isUnevaluatedContext()) {
7684 S.Diag(Loc, diag::warn_field_requires_explicit_init)
7685 << /* Var-in-Record */ 0 << FD;
7686 S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
7687 }
7688 ++I;
7689 }
7690 }
7691 }
7692
7693 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7694 if (!TSInfo)
7695 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
7696 SourceRange ParenOrBraceRange =
7697 (Kind.getKind() == InitializationKind::IK_DirectList)
7698 ? SourceRange(LBraceLoc, RBraceLoc)
7699 : Kind.getParenOrBraceRange();
7700
7701 CXXConstructorDecl *CalleeDecl = Constructor;
7702 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7703 Step.Function.FoundDecl.getDecl())) {
7704 CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
7705 }
7706 S.MarkFunctionReferenced(Loc, CalleeDecl);
7707
7708 CurInit = S.CheckForImmediateInvocation(
7710 S.Context, CalleeDecl,
7711 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7712 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7713 IsListInitialization, IsStdInitListInitialization,
7714 ConstructorInitRequiresZeroInit),
7715 CalleeDecl);
7716 } else {
7718
7719 if (Entity.getKind() == InitializedEntity::EK_Base) {
7720 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7723 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7724 ConstructKind = CXXConstructionKind::Delegating;
7725 }
7726
7727 // Only get the parenthesis or brace range if it is a list initialization or
7728 // direct construction.
7729 SourceRange ParenOrBraceRange;
7730 if (IsListInitialization)
7731 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7732 else if (Kind.getKind() == InitializationKind::IK_Direct)
7733 ParenOrBraceRange = Kind.getParenOrBraceRange();
7734
7735 // If the entity allows NRVO, mark the construction as elidable
7736 // unconditionally.
7737 if (Entity.allowsNRVO())
7738 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7739 Step.Function.FoundDecl,
7740 Constructor, /*Elidable=*/true,
7741 ConstructorArgs,
7742 HadMultipleCandidates,
7743 IsListInitialization,
7744 IsStdInitListInitialization,
7745 ConstructorInitRequiresZeroInit,
7746 ConstructKind,
7747 ParenOrBraceRange);
7748 else
7749 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7750 Step.Function.FoundDecl,
7752 ConstructorArgs,
7753 HadMultipleCandidates,
7754 IsListInitialization,
7755 IsStdInitListInitialization,
7756 ConstructorInitRequiresZeroInit,
7757 ConstructKind,
7758 ParenOrBraceRange);
7759 }
7760 if (CurInit.isInvalid())
7761 return ExprError();
7762
7763 // Only check access if all of that succeeded.
7766 return ExprError();
7767
7768 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
7770 return ExprError();
7771
7772 if (shouldBindAsTemporary(Entity))
7773 CurInit = S.MaybeBindToTemporary(CurInit.get());
7774
7775 return CurInit;
7776}
7777
7779 Expr *Init) {
7780 return sema::checkInitLifetime(*this, Entity, Init);
7781}
7782
7783static void DiagnoseNarrowingInInitList(Sema &S,
7784 const ImplicitConversionSequence &ICS,
7785 QualType PreNarrowingType,
7786 QualType EntityType,
7787 const Expr *PostInit);
7788
7789static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
7790 QualType ToType, Expr *Init);
7791
7792/// Provide warnings when std::move is used on construction.
7793static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7794 bool IsReturnStmt) {
7795 if (!InitExpr)
7796 return;
7797
7799 return;
7800
7801 QualType DestType = InitExpr->getType();
7802 if (!DestType->isRecordType())
7803 return;
7804
7805 unsigned DiagID = 0;
7806 if (IsReturnStmt) {
7807 const CXXConstructExpr *CCE =
7808 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7809 if (!CCE || CCE->getNumArgs() != 1)
7810 return;
7811
7813 return;
7814
7815 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
7816 }
7817
7818 // Find the std::move call and get the argument.
7819 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
7820 if (!CE || !CE->isCallToStdMove())
7821 return;
7822
7823 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
7824
7825 if (IsReturnStmt) {
7826 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7827 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7828 return;
7829
7830 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7831 if (!VD || !VD->hasLocalStorage())
7832 return;
7833
7834 // __block variables are not moved implicitly.
7835 if (VD->hasAttr<BlocksAttr>())
7836 return;
7837
7838 QualType SourceType = VD->getType();
7839 if (!SourceType->isRecordType())
7840 return;
7841
7842 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
7843 return;
7844 }
7845
7846 // If we're returning a function parameter, copy elision
7847 // is not possible.
7848 if (isa<ParmVarDecl>(VD))
7849 DiagID = diag::warn_redundant_move_on_return;
7850 else
7851 DiagID = diag::warn_pessimizing_move_on_return;
7852 } else {
7853 DiagID = diag::warn_pessimizing_move_on_initialization;
7854 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7855 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
7856 return;
7857 }
7858
7859 S.Diag(CE->getBeginLoc(), DiagID);
7860
7861 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7862 // is within a macro.
7863 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
7864 if (CallBegin.isMacroID())
7865 return;
7866 SourceLocation RParen = CE->getRParenLoc();
7867 if (RParen.isMacroID())
7868 return;
7869 SourceLocation LParen;
7870 SourceLocation ArgLoc = Arg->getBeginLoc();
7871
7872 // Special testing for the argument location. Since the fix-it needs the
7873 // location right before the argument, the argument location can be in a
7874 // macro only if it is at the beginning of the macro.
7875 while (ArgLoc.isMacroID() &&
7878 }
7879
7880 if (LParen.isMacroID())
7881 return;
7882
7883 LParen = ArgLoc.getLocWithOffset(-1);
7884
7885 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
7886 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
7887 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
7888}
7889
7890static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7891 // Check to see if we are dereferencing a null pointer. If so, this is
7892 // undefined behavior, so warn about it. This only handles the pattern
7893 // "*null", which is a very syntactic check.
7894 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7895 if (UO->getOpcode() == UO_Deref &&
7896 UO->getSubExpr()->IgnoreParenCasts()->
7897 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7898 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7899 S.PDiag(diag::warn_binding_null_to_reference)
7900 << UO->getSubExpr()->getSourceRange());
7901 }
7902}
7903
7906 bool BoundToLvalueReference) {
7907 auto MTE = new (Context)
7908 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7909
7910 // Order an ExprWithCleanups for lifetime marks.
7911 //
7912 // TODO: It'll be good to have a single place to check the access of the
7913 // destructor and generate ExprWithCleanups for various uses. Currently these
7914 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7915 // but there may be a chance to merge them.
7916 Cleanup.setExprNeedsCleanups(false);
7919 return MTE;
7920}
7921
7923 // In C++98, we don't want to implicitly create an xvalue. C11 added the
7924 // same rule, but C99 is broken without this behavior and so we treat the
7925 // change as applying to all C language modes.
7926 // FIXME: This means that AST consumers need to deal with "prvalues" that
7927 // denote materialized temporaries. Maybe we should add another ValueKind
7928 // for "xvalue pretending to be a prvalue" for C++98 support.
7929 if (!E->isPRValue() ||
7931 return E;
7932
7933 // C++1z [conv.rval]/1: T shall be a complete type.
7934 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7935 // If so, we should check for a non-abstract class type here too.
7936 QualType T = E->getType();
7937 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7938 return ExprError();
7939
7940 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7941}
7942
7946
7947 CastKind CK = CK_NoOp;
7948
7949 if (VK == VK_PRValue) {
7950 auto PointeeTy = Ty->getPointeeType();
7951 auto ExprPointeeTy = E->getType()->getPointeeType();
7952 if (!PointeeTy.isNull() &&
7953 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
7954 CK = CK_AddressSpaceConversion;
7955 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
7956 CK = CK_AddressSpaceConversion;
7957 }
7958
7959 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
7960}
7961
7963 const InitializedEntity &Entity,
7964 const InitializationKind &Kind,
7965 MultiExprArg Args,
7966 QualType *ResultType) {
7967 if (Failed()) {
7968 Diagnose(S, Entity, Kind, Args);
7969 return ExprError();
7970 }
7971 if (!ZeroInitializationFixit.empty()) {
7972 const Decl *D = Entity.getDecl();
7973 const auto *VD = dyn_cast_or_null<VarDecl>(D);
7974 QualType DestType = Entity.getType();
7975
7976 // The initialization would have succeeded with this fixit. Since the fixit
7977 // is on the error, we need to build a valid AST in this case, so this isn't
7978 // handled in the Failed() branch above.
7979 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
7980 // Use a more useful diagnostic for constexpr variables.
7981 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
7982 << VD
7983 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7984 ZeroInitializationFixit);
7985 } else {
7986 unsigned DiagID = diag::err_default_init_const;
7987 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
7988 DiagID = diag::ext_default_init_const;
7989
7990 S.Diag(Kind.getLocation(), DiagID)
7991 << DestType << DestType->isRecordType()
7992 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7993 ZeroInitializationFixit);
7994 }
7995 }
7996
7997 if (getKind() == DependentSequence) {
7998 // If the declaration is a non-dependent, incomplete array type
7999 // that has an initializer, then its type will be completed once
8000 // the initializer is instantiated.
8001 if (ResultType && !Entity.getType()->isDependentType() &&
8002 Args.size() == 1) {
8003 QualType DeclType = Entity.getType();
8004 if (const IncompleteArrayType *ArrayT
8005 = S.Context.getAsIncompleteArrayType(DeclType)) {
8006 // FIXME: We don't currently have the ability to accurately
8007 // compute the length of an initializer list without
8008 // performing full type-checking of the initializer list
8009 // (since we have to determine where braces are implicitly
8010 // introduced and such). So, we fall back to making the array
8011 // type a dependently-sized array type with no specified
8012 // bound.
8013 if (isa<InitListExpr>((Expr *)Args[0]))
8014 *ResultType = S.Context.getDependentSizedArrayType(
8015 ArrayT->getElementType(),
8016 /*NumElts=*/nullptr, ArrayT->getSizeModifier(),
8017 ArrayT->getIndexTypeCVRQualifiers());
8018 }
8019 }
8020 if (Kind.getKind() == InitializationKind::IK_Direct &&
8021 !Kind.isExplicitCast()) {
8022 // Rebuild the ParenListExpr.
8023 SourceRange ParenRange = Kind.getParenOrBraceRange();
8024 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
8025 Args);
8026 }
8027 assert(Kind.getKind() == InitializationKind::IK_Copy ||
8028 Kind.isExplicitCast() ||
8029 Kind.getKind() == InitializationKind::IK_DirectList);
8030 return ExprResult(Args[0]);
8031 }
8032
8033 // No steps means no initialization.
8034 if (Steps.empty())
8035 return ExprResult((Expr *)nullptr);
8036
8037 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
8038 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
8039 !Entity.isParamOrTemplateParamKind()) {
8040 // Produce a C++98 compatibility warning if we are initializing a reference
8041 // from an initializer list. For parameters, we produce a better warning
8042 // elsewhere.
8043 Expr *Init = Args[0];
8044 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
8045 << Init->getSourceRange();
8046 }
8047
8048 if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
8049 isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
8050 // Produce a Microsoft compatibility warning when initializing from a
8051 // predefined expression since MSVC treats predefined expressions as string
8052 // literals.
8053 Expr *Init = Args[0];
8054 S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
8055 }
8056
8057 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8058 QualType ETy = Entity.getType();
8059 bool HasGlobalAS = ETy.hasAddressSpace() &&
8061
8062 if (S.getLangOpts().OpenCLVersion >= 200 &&
8063 ETy->isAtomicType() && !HasGlobalAS &&
8064 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8065 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
8066 << 1
8067 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8068 return ExprError();
8069 }
8070
8071 QualType DestType = Entity.getType().getNonReferenceType();
8072 // FIXME: Ugly hack around the fact that Entity.getType() is not
8073 // the same as Entity.getDecl()->getType() in cases involving type merging,
8074 // and we want latter when it makes sense.
8075 if (ResultType)
8076 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8077 Entity.getType();
8078
8079 ExprResult CurInit((Expr *)nullptr);
8080 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8081
8082 // HLSL allows vector/matrix initialization to function like list
8083 // initialization, but use the syntax of a C++-like constructor.
8084 bool IsHLSLVectorOrMatrixInit =
8085 S.getLangOpts().HLSL &&
8086 (DestType->isExtVectorType() || DestType->isConstantMatrixType()) &&
8087 isa<InitListExpr>(Args[0]);
8088 (void)IsHLSLVectorOrMatrixInit;
8089
8090 // For initialization steps that start with a single initializer,
8091 // grab the only argument out the Args and place it into the "current"
8092 // initializer.
8093 switch (Steps.front().Kind) {
8098 case SK_BindReference:
8100 case SK_FinalCopy:
8102 case SK_UserConversion:
8111 case SK_UnwrapInitList:
8112 case SK_RewrapInitList:
8113 case SK_CAssignment:
8114 case SK_StringInit:
8116 case SK_ArrayLoopIndex:
8117 case SK_ArrayLoopInit:
8118 case SK_ArrayInit:
8119 case SK_GNUArrayInit:
8125 case SK_OCLSamplerInit:
8128 assert(Args.size() == 1 || IsHLSLVectorOrMatrixInit);
8129 CurInit = Args[0];
8130 if (!CurInit.get()) return ExprError();
8131 break;
8132 }
8133
8139 break;
8140 }
8141
8142 // Promote from an unevaluated context to an unevaluated list context in
8143 // C++11 list-initialization; we need to instantiate entities usable in
8144 // constant expressions here in order to perform narrowing checks =(
8147 isa_and_nonnull<InitListExpr>(CurInit.get()));
8148
8149 // C++ [class.abstract]p2:
8150 // no objects of an abstract class can be created except as subobjects
8151 // of a class derived from it
8152 auto checkAbstractType = [&](QualType T) -> bool {
8153 if (Entity.getKind() == InitializedEntity::EK_Base ||
8155 return false;
8156 return S.RequireNonAbstractType(Kind.getLocation(), T,
8157 diag::err_allocation_of_abstract_type);
8158 };
8159
8160 // Walk through the computed steps for the initialization sequence,
8161 // performing the specified conversions along the way.
8162 bool ConstructorInitRequiresZeroInit = false;
8163 for (step_iterator Step = step_begin(), StepEnd = step_end();
8164 Step != StepEnd; ++Step) {
8165 if (CurInit.isInvalid())
8166 return ExprError();
8167
8168 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8169
8170 switch (Step->Kind) {
8172 // Overload resolution determined which function invoke; update the
8173 // initializer to reflect that choice.
8175 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
8176 return ExprError();
8177 CurInit = S.FixOverloadedFunctionReference(CurInit,
8180 // We might get back another placeholder expression if we resolved to a
8181 // builtin.
8182 if (!CurInit.isInvalid())
8183 CurInit = S.CheckPlaceholderExpr(CurInit.get());
8184 break;
8185
8189 // We have a derived-to-base cast that produces either an rvalue or an
8190 // lvalue. Perform that cast.
8191
8192 CXXCastPath BasePath;
8193
8194 // Casts to inaccessible base classes are allowed with C-style casts.
8195 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8197 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8198 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8199 return ExprError();
8200
8203 ? VK_LValue
8205 : VK_PRValue);
8207 CK_DerivedToBase, CurInit.get(),
8208 &BasePath, VK, FPOptionsOverride());
8209 break;
8210 }
8211
8212 case SK_BindReference:
8213 // Reference binding does not have any corresponding ASTs.
8214
8215 // Check exception specifications
8216 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8217 return ExprError();
8218
8219 // We don't check for e.g. function pointers here, since address
8220 // availability checks should only occur when the function first decays
8221 // into a pointer or reference.
8222 if (CurInit.get()->getType()->isFunctionProtoType()) {
8223 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8224 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8225 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8226 DRE->getBeginLoc()))
8227 return ExprError();
8228 }
8229 }
8230 }
8231
8232 CheckForNullPointerDereference(S, CurInit.get());
8233 break;
8234
8236 // Make sure the "temporary" is actually an rvalue.
8237 assert(CurInit.get()->isPRValue() && "not a temporary");
8238
8239 // Check exception specifications
8240 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8241 return ExprError();
8242
8243 QualType MTETy = Step->Type;
8244
8245 // When this is an incomplete array type (such as when this is
8246 // initializing an array of unknown bounds from an init list), use THAT
8247 // type instead so that we propagate the array bounds.
8248 if (MTETy->isIncompleteArrayType() &&
8249 !CurInit.get()->getType()->isIncompleteArrayType() &&
8252 CurInit.get()->getType()->getPointeeOrArrayElementType()))
8253 MTETy = CurInit.get()->getType();
8254
8255 // Materialize the temporary into memory.
8257 MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8258 CurInit = MTE;
8259
8260 // If we're extending this temporary to automatic storage duration -- we
8261 // need to register its cleanup during the full-expression's cleanups.
8262 if (MTE->getStorageDuration() == SD_Automatic &&
8263 MTE->getType().isDestructedType())
8265 break;
8266 }
8267
8268 case SK_FinalCopy:
8269 if (checkAbstractType(Step->Type))
8270 return ExprError();
8271
8272 // If the overall initialization is initializing a temporary, we already
8273 // bound our argument if it was necessary to do so. If not (if we're
8274 // ultimately initializing a non-temporary), our argument needs to be
8275 // bound since it's initializing a function parameter.
8276 // FIXME: This is a mess. Rationalize temporary destruction.
8277 if (!shouldBindAsTemporary(Entity))
8278 CurInit = S.MaybeBindToTemporary(CurInit.get());
8279 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8280 /*IsExtraneousCopy=*/false);
8281 break;
8282
8284 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8285 /*IsExtraneousCopy=*/true);
8286 break;
8287
8288 case SK_UserConversion: {
8289 // We have a user-defined conversion that invokes either a constructor
8290 // or a conversion function.
8294 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8295 bool CreatedObject = false;
8296 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8297 // Build a call to the selected constructor.
8298 SmallVector<Expr*, 8> ConstructorArgs;
8299 SourceLocation Loc = CurInit.get()->getBeginLoc();
8300
8301 // Determine the arguments required to actually perform the constructor
8302 // call.
8303 Expr *Arg = CurInit.get();
8305 MultiExprArg(&Arg, 1), Loc,
8306 ConstructorArgs))
8307 return ExprError();
8308
8309 // Build an expression that constructs a temporary.
8310 CurInit = S.BuildCXXConstructExpr(
8311 Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
8312 HadMultipleCandidates,
8313 /*ListInit*/ false,
8314 /*StdInitListInit*/ false,
8315 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
8316 if (CurInit.isInvalid())
8317 return ExprError();
8318
8319 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8320 Entity);
8321 if (S.DiagnoseUseOfOverloadedDecl(Constructor, Kind.getLocation()))
8322 return ExprError();
8323
8324 CastKind = CK_ConstructorConversion;
8325 CreatedObject = true;
8326 } else {
8327 // Build a call to the conversion function.
8329 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8330 FoundFn);
8331 if (S.DiagnoseUseOfOverloadedDecl(Conversion, Kind.getLocation()))
8332 return ExprError();
8333
8334 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8335 HadMultipleCandidates);
8336 if (CurInit.isInvalid())
8337 return ExprError();
8338
8339 CastKind = CK_UserDefinedConversion;
8340 CreatedObject = Conversion->getReturnType()->isRecordType();
8341 }
8342
8343 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8344 return ExprError();
8345
8346 CurInit = ImplicitCastExpr::Create(
8347 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8348 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
8349
8350 if (shouldBindAsTemporary(Entity))
8351 // The overall entity is temporary, so this expression should be
8352 // destroyed at the end of its full-expression.
8353 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
8354 else if (CreatedObject && shouldDestroyEntity(Entity)) {
8355 // The object outlasts the full-expression, but we need to prepare for
8356 // a destructor being run on it.
8357 // FIXME: It makes no sense to do this here. This should happen
8358 // regardless of how we initialized the entity.
8359 QualType T = CurInit.get()->getType();
8360 if (auto *Record = T->castAsCXXRecordDecl()) {
8363 S.PDiag(diag::err_access_dtor_temp) << T);
8365 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
8366 return ExprError();
8367 }
8368 }
8369 break;
8370 }
8371
8375 // Perform a qualification conversion; these can never go wrong.
8378 ? VK_LValue
8380 : VK_PRValue);
8381 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
8382 break;
8383 }
8384
8386 assert(CurInit.get()->isLValue() &&
8387 "function reference should be lvalue");
8388 CurInit =
8389 S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
8390 break;
8391
8392 case SK_AtomicConversion: {
8393 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
8394 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8395 CK_NonAtomicToAtomic, VK_PRValue);
8396 break;
8397 }
8398
8401 if (const auto *FromPtrType =
8402 CurInit.get()->getType()->getAs<PointerType>()) {
8403 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
8404 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8405 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8406 // Do not check static casts here because they are checked earlier
8407 // in Sema::ActOnCXXNamedCast()
8408 if (!Kind.isStaticCast()) {
8409 S.Diag(CurInit.get()->getExprLoc(),
8410 diag::warn_noderef_to_dereferenceable_pointer)
8411 << CurInit.get()->getSourceRange();
8412 }
8413 }
8414 }
8415 }
8416 Expr *Init = CurInit.get();
8418 Kind.isCStyleCast() ? CheckedConversionKind::CStyleCast
8419 : Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast
8420 : Kind.isExplicitCast() ? CheckedConversionKind::OtherCast
8422 ExprResult CurInitExprRes = S.PerformImplicitConversion(
8423 Init, Step->Type, *Step->ICS, getAssignmentAction(Entity), CCK);
8424 if (CurInitExprRes.isInvalid())
8425 return ExprError();
8426
8428
8429 CurInit = CurInitExprRes;
8430
8432 S.getLangOpts().CPlusPlus)
8433 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
8434 CurInit.get());
8435
8436 break;
8437 }
8438
8439 case SK_ListInitialization: {
8440 if (checkAbstractType(Step->Type))
8441 return ExprError();
8442
8443 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
8444 // If we're not initializing the top-level entity, we need to create an
8445 // InitializeTemporary entity for our target type.
8446 QualType Ty = Step->Type;
8447 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
8448 InitializedEntity InitEntity =
8449 IsTemporary ? InitializedEntity::InitializeTemporary(Ty) : Entity;
8450 InitListChecker PerformInitList(S, InitEntity,
8451 InitList, Ty, /*VerifyOnly=*/false,
8452 /*TreatUnavailableAsInvalid=*/false);
8453 if (PerformInitList.HadError())
8454 return ExprError();
8455
8456 // Hack: We must update *ResultType if available in order to set the
8457 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
8458 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
8459 if (ResultType &&
8460 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
8461 if ((*ResultType)->isRValueReferenceType())
8463 else if ((*ResultType)->isLValueReferenceType())
8465 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
8466 *ResultType = Ty;
8467 }
8468
8469 InitListExpr *StructuredInitList =
8470 PerformInitList.getFullyStructuredList();
8471 CurInit = shouldBindAsTemporary(InitEntity)
8472 ? S.MaybeBindToTemporary(StructuredInitList)
8473 : StructuredInitList;
8474 break;
8475 }
8476
8478 if (checkAbstractType(Step->Type))
8479 return ExprError();
8480
8481 // When an initializer list is passed for a parameter of type "reference
8482 // to object", we don't get an EK_Temporary entity, but instead an
8483 // EK_Parameter entity with reference type.
8484 // FIXME: This is a hack. What we really should do is create a user
8485 // conversion step for this case, but this makes it considerably more
8486 // complicated. For now, this will do.
8488 Entity.getType().getNonReferenceType());
8489 bool UseTemporary = Entity.getType()->isReferenceType();
8490 assert(Args.size() == 1 && "expected a single argument for list init");
8491 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8492 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
8493 << InitList->getSourceRange();
8494 SmallVector<Expr *, 8> ExpandedInits;
8495 MultiExprArg Arg = S.getInitsWithEmbedExpanded(InitList, ExpandedInits);
8496 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
8497 Entity,
8498 Kind, Arg, *Step,
8499 ConstructorInitRequiresZeroInit,
8500 /*IsListInitialization*/true,
8501 /*IsStdInitListInit*/false,
8502 InitList->getLBraceLoc(),
8503 InitList->getRBraceLoc());
8504 break;
8505 }
8506
8507 case SK_UnwrapInitList:
8508 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
8509 break;
8510
8511 case SK_RewrapInitList: {
8512 Expr *E = CurInit.get();
8514 InitListExpr *ILE = new (S.Context)
8515 InitListExpr(S.Context, Syntactic->getLBraceLoc(), E,
8516 Syntactic->getRBraceLoc(), Syntactic->isExplicit());
8517 ILE->setSyntacticForm(Syntactic);
8518 ILE->setType(E->getType());
8519 ILE->setValueKind(E->getValueKind());
8520 CurInit = ILE;
8521 break;
8522 }
8523
8526 if (checkAbstractType(Step->Type))
8527 return ExprError();
8528
8529 // When an initializer list is passed for a parameter of type "reference
8530 // to object", we don't get an EK_Temporary entity, but instead an
8531 // EK_Parameter entity with reference type.
8532 // FIXME: This is a hack. What we really should do is create a user
8533 // conversion step for this case, but this makes it considerably more
8534 // complicated. For now, this will do.
8536 Entity.getType().getNonReferenceType());
8537 bool UseTemporary = Entity.getType()->isReferenceType();
8538 bool IsStdInitListInit =
8540 Expr *Source = CurInit.get();
8541 SourceRange Range = Kind.hasParenOrBraceRange()
8542 ? Kind.getParenOrBraceRange()
8543 : SourceRange();
8545 S, UseTemporary ? TempEntity : Entity, Kind,
8546 Source ? MultiExprArg(Source) : Args, *Step,
8547 ConstructorInitRequiresZeroInit,
8548 /*IsListInitialization*/ IsStdInitListInit,
8549 /*IsStdInitListInitialization*/ IsStdInitListInit,
8550 /*LBraceLoc*/ Range.getBegin(),
8551 /*RBraceLoc*/ Range.getEnd());
8552 break;
8553 }
8554
8555 case SK_ZeroInitialization: {
8556 step_iterator NextStep = Step;
8557 ++NextStep;
8558 if (NextStep != StepEnd &&
8559 (NextStep->Kind == SK_ConstructorInitialization ||
8560 NextStep->Kind == SK_ConstructorInitializationFromList)) {
8561 // The need for zero-initialization is recorded directly into
8562 // the call to the object's constructor within the next step.
8563 ConstructorInitRequiresZeroInit = true;
8564 } else if (Kind.getKind() == InitializationKind::IK_Value &&
8565 S.getLangOpts().CPlusPlus &&
8566 !Kind.isImplicitValueInit()) {
8567 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
8568 if (!TSInfo)
8570 Kind.getRange().getBegin());
8571
8572 CurInit = new (S.Context) CXXScalarValueInitExpr(
8573 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
8574 Kind.getRange().getEnd());
8575 } else {
8576 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
8577 // Note the return value isn't used to return a ExprError() when
8578 // initialization fails . For struct initialization allows all field
8579 // assignments to be checked rather than bailing on the first error.
8580 S.BoundsSafetyCheckInitialization(Entity, Kind,
8582 Step->Type, CurInit.get());
8583 }
8584 break;
8585 }
8586
8587 case SK_CAssignment: {
8588 QualType SourceType = CurInit.get()->getType();
8589 Expr *Init = CurInit.get();
8590
8591 // Save off the initial CurInit in case we need to emit a diagnostic
8592 ExprResult InitialCurInit = Init;
8595 Step->Type, Result, true,
8597 if (Result.isInvalid())
8598 return ExprError();
8599 CurInit = Result;
8600
8601 // If this is a call, allow conversion to a transparent union.
8602 ExprResult CurInitExprRes = CurInit;
8603 if (!S.IsAssignConvertCompatible(ConvTy) && Entity.isParameterKind() &&
8605 Step->Type, CurInitExprRes) == AssignConvertType::Compatible)
8607 if (CurInitExprRes.isInvalid())
8608 return ExprError();
8609 CurInit = CurInitExprRes;
8610
8611 if (S.getLangOpts().C23 && initializingConstexprVariable(Entity) &&
8612 !CurInit.get()->containsErrors()) {
8613 CheckC23ConstexprInitConversion(S, SourceType, Entity.getType(),
8614 CurInit.get());
8615
8616 // C23 6.7.1p6: If an object or subobject declared with storage-class
8617 // specifier constexpr has pointer, integer, or arithmetic type, any
8618 // explicit initializer value for it shall be null, an integer
8619 // constant expression, or an arithmetic constant expression,
8620 // respectively.
8622 if (Entity.getType()->getAs<PointerType>() &&
8623 CurInit.get()->EvaluateAsRValue(ER, S.Context) &&
8624 (ER.Val.isLValue() && !ER.Val.isNullPointer())) {
8625 S.Diag(Kind.getLocation(), diag::err_c23_constexpr_pointer_not_null);
8626 return ExprError();
8627 }
8628 }
8629
8630 // Note the return value isn't used to return a ExprError() when
8631 // initialization fails. For struct initialization this allows all field
8632 // assignments to be checked rather than bailing on the first error.
8633 S.BoundsSafetyCheckInitialization(Entity, Kind,
8634 getAssignmentAction(Entity, true),
8635 Step->Type, InitialCurInit.get());
8636
8637 bool Complained;
8638 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
8639 Step->Type, SourceType,
8640 InitialCurInit.get(),
8641 getAssignmentAction(Entity, true),
8642 &Complained)) {
8643 PrintInitLocationNote(S, Entity);
8644 return ExprError();
8645 } else if (Complained)
8646 PrintInitLocationNote(S, Entity);
8647 break;
8648 }
8649
8650 case SK_StringInit: {
8651 QualType Ty = Step->Type;
8652 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
8653 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
8654 S.Context.getAsArrayType(Ty), S, Entity,
8655 S.getLangOpts().C23 &&
8657 break;
8658 }
8659
8661 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8662 CK_ObjCObjectLValueCast,
8663 CurInit.get()->getValueKind());
8664 break;
8665
8666 case SK_ArrayLoopIndex: {
8667 Expr *Cur = CurInit.get();
8668 Expr *BaseExpr = new (S.Context)
8669 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8670 Cur->getValueKind(), Cur->getObjectKind(), Cur);
8671 Expr *IndexExpr =
8674 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
8675 ArrayLoopCommonExprs.push_back(BaseExpr);
8676 break;
8677 }
8678
8679 case SK_ArrayLoopInit: {
8680 assert(!ArrayLoopCommonExprs.empty() &&
8681 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8682 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8683 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8684 CurInit.get());
8685 break;
8686 }
8687
8688 case SK_GNUArrayInit:
8689 // Okay: we checked everything before creating this step. Note that
8690 // this is a GNU extension.
8691 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
8692 << Step->Type << CurInit.get()->getType()
8693 << CurInit.get()->getSourceRange();
8695 [[fallthrough]];
8696 case SK_ArrayInit:
8697 // If the destination type is an incomplete array type, update the
8698 // type accordingly.
8699 if (ResultType) {
8700 if (const IncompleteArrayType *IncompleteDest
8702 if (const ConstantArrayType *ConstantSource
8703 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
8704 *ResultType = S.Context.getConstantArrayType(
8705 IncompleteDest->getElementType(), ConstantSource->getSize(),
8706 ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
8707 }
8708 }
8709 }
8710 break;
8711
8713 // Okay: we checked everything before creating this step. Note that
8714 // this is a GNU extension.
8715 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
8716 << CurInit.get()->getSourceRange();
8717 break;
8718
8721 checkIndirectCopyRestoreSource(S, CurInit.get());
8722 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
8723 CurInit.get(), Step->Type,
8725 break;
8726
8728 CurInit = ImplicitCastExpr::Create(
8729 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
8731 break;
8732
8733 case SK_StdInitializerList: {
8734 S.Diag(CurInit.get()->getExprLoc(),
8735 diag::warn_cxx98_compat_initializer_list_init)
8736 << CurInit.get()->getSourceRange();
8737
8738 // Materialize the temporary into memory.
8740 CurInit.get()->getType(), CurInit.get(),
8741 /*BoundToLvalueReference=*/false);
8742
8743 // Wrap it in a construction of a std::initializer_list<T>.
8744 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
8745
8746 if (!Step->Type->isDependentType()) {
8747 QualType ElementType;
8748 [[maybe_unused]] bool IsStdInitializerList =
8749 S.isStdInitializerList(Step->Type, &ElementType);
8750 assert(IsStdInitializerList &&
8751 "StdInitializerList step to non-std::initializer_list");
8752 const auto *Record = Step->Type->castAsCXXRecordDecl();
8753 assert(Record->isCompleteDefinition() &&
8754 "std::initializer_list should have already be "
8755 "complete/instantiated by this point");
8756
8757 auto InvalidType = [&] {
8758 S.Diag(Record->getLocation(),
8759 diag::err_std_initializer_list_malformed)
8761 return ExprError();
8762 };
8763
8764 if (Record->isUnion() || Record->getNumBases() != 0 ||
8765 Record->isPolymorphic())
8766 return InvalidType();
8767
8768 RecordDecl::field_iterator Field = Record->field_begin();
8769 if (Field == Record->field_end())
8770 return InvalidType();
8771
8772 // Start pointer
8773 if (!Field->getType()->isPointerType() ||
8774 !S.Context.hasSameType(Field->getType()->getPointeeType(),
8775 ElementType.withConst()))
8776 return InvalidType();
8777
8778 if (++Field == Record->field_end())
8779 return InvalidType();
8780
8781 // Size or end pointer
8782 if (const auto *PT = Field->getType()->getAs<PointerType>()) {
8783 if (!S.Context.hasSameType(PT->getPointeeType(),
8784 ElementType.withConst()))
8785 return InvalidType();
8786 } else {
8787 if (Field->isBitField() ||
8788 !S.Context.hasSameType(Field->getType(), S.Context.getSizeType()))
8789 return InvalidType();
8790 }
8791
8792 if (++Field != Record->field_end())
8793 return InvalidType();
8794 }
8795
8796 // Bind the result, in case the library has given initializer_list a
8797 // non-trivial destructor.
8798 if (shouldBindAsTemporary(Entity))
8799 CurInit = S.MaybeBindToTemporary(CurInit.get());
8800 break;
8801 }
8802
8803 case SK_OCLSamplerInit: {
8804 // Sampler initialization have 5 cases:
8805 // 1. function argument passing
8806 // 1a. argument is a file-scope variable
8807 // 1b. argument is a function-scope variable
8808 // 1c. argument is one of caller function's parameters
8809 // 2. variable initialization
8810 // 2a. initializing a file-scope variable
8811 // 2b. initializing a function-scope variable
8812 //
8813 // For file-scope variables, since they cannot be initialized by function
8814 // call of __translate_sampler_initializer in LLVM IR, their references
8815 // need to be replaced by a cast from their literal initializers to
8816 // sampler type. Since sampler variables can only be used in function
8817 // calls as arguments, we only need to replace them when handling the
8818 // argument passing.
8819 assert(Step->Type->isSamplerT() &&
8820 "Sampler initialization on non-sampler type.");
8821 Expr *Init = CurInit.get()->IgnoreParens();
8822 QualType SourceType = Init->getType();
8823 // Case 1
8824 if (Entity.isParameterKind()) {
8825 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
8826 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
8827 << SourceType;
8828 break;
8829 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
8830 auto Var = cast<VarDecl>(DRE->getDecl());
8831 // Case 1b and 1c
8832 // No cast from integer to sampler is needed.
8833 if (!Var->hasGlobalStorage()) {
8834 CurInit = ImplicitCastExpr::Create(
8835 S.Context, Step->Type, CK_LValueToRValue, Init,
8836 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
8837 break;
8838 }
8839 // Case 1a
8840 // For function call with a file-scope sampler variable as argument,
8841 // get the integer literal.
8842 // Do not diagnose if the file-scope variable does not have initializer
8843 // since this has already been diagnosed when parsing the variable
8844 // declaration.
8845 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8846 break;
8847 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
8848 Var->getInit()))->getSubExpr();
8849 SourceType = Init->getType();
8850 }
8851 } else {
8852 // Case 2
8853 // Check initializer is 32 bit integer constant.
8854 // If the initializer is taken from global variable, do not diagnose since
8855 // this has already been done when parsing the variable declaration.
8856 if (!Init->isConstantInitializer(S.Context))
8857 break;
8858
8859 if (!SourceType->isIntegerType() ||
8860 32 != S.Context.getIntWidth(SourceType)) {
8861 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8862 << SourceType;
8863 break;
8864 }
8865
8866 Expr::EvalResult EVResult;
8867 Init->EvaluateAsInt(EVResult, S.Context);
8868 llvm::APSInt Result = EVResult.Val.getInt();
8869 const uint64_t SamplerValue = Result.getLimitedValue();
8870 // 32-bit value of sampler's initializer is interpreted as
8871 // bit-field with the following structure:
8872 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8873 // |31 6|5 4|3 1| 0|
8874 // This structure corresponds to enum values of sampler properties
8875 // defined in SPIR spec v1.2 and also opencl-c.h
8876 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8877 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
8878 if (FilterMode != 1 && FilterMode != 2 &&
8880 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
8881 S.Diag(Kind.getLocation(),
8882 diag::warn_sampler_initializer_invalid_bits)
8883 << "Filter Mode";
8884 if (AddressingMode > 4)
8885 S.Diag(Kind.getLocation(),
8886 diag::warn_sampler_initializer_invalid_bits)
8887 << "Addressing Mode";
8888 }
8889
8890 // Cases 1a, 2a and 2b
8891 // Insert cast from integer to sampler.
8893 CK_IntToOCLSampler);
8894 break;
8895 }
8896 case SK_OCLZeroOpaqueType: {
8897 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8899 "Wrong type for initialization of OpenCL opaque type.");
8900
8901 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8902 CK_ZeroToOCLOpaqueType,
8903 CurInit.get()->getValueKind());
8904 break;
8905 }
8907 CurInit = nullptr;
8908 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
8909 /*VerifyOnly=*/false, &CurInit);
8910 if (CurInit.get() && ResultType)
8911 *ResultType = CurInit.get()->getType();
8912 if (shouldBindAsTemporary(Entity))
8913 CurInit = S.MaybeBindToTemporary(CurInit.get());
8914 break;
8915 }
8917 CurInit = ImplicitCastExpr::Create(
8918 S.Context, Step->Type.getLocalUnqualifiedType(), CK_LValueToRValue,
8919 CurInit.get(),
8920 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
8921 break;
8922 }
8923 }
8924 }
8925
8926 Expr *Init = CurInit.get();
8927 if (!Init)
8928 return ExprError();
8929
8930 // Check whether the initializer has a shorter lifetime than the initialized
8931 // entity, and if not, either lifetime-extend or warn as appropriate.
8932 S.checkInitializerLifetime(Entity, Init);
8933
8934 // Diagnose non-fatal problems with the completed initialization.
8935 if (InitializedEntity::EntityKind EK = Entity.getKind();
8938 cast<FieldDecl>(Entity.getDecl())->isBitField())
8939 S.CheckBitFieldInitialization(Kind.getLocation(),
8940 cast<FieldDecl>(Entity.getDecl()), Init);
8941
8942 // Check for std::move on construction.
8945
8946 return Init;
8947}
8948
8949/// Somewhere within T there is an uninitialized reference subobject.
8950/// Dig it out and diagnose it.
8952 QualType T) {
8953 if (T->isReferenceType()) {
8954 S.Diag(Loc, diag::err_reference_without_init)
8955 << T.getNonReferenceType();
8956 return true;
8957 }
8958
8959 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8960 if (!RD || !RD->hasUninitializedReferenceMember())
8961 return false;
8962
8963 for (const auto *FI : RD->fields()) {
8964 if (FI->isUnnamedBitField())
8965 continue;
8966
8967 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8968 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8969 return true;
8970 }
8971 }
8972
8973 for (const auto &BI : RD->bases()) {
8974 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
8975 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8976 return true;
8977 }
8978 }
8979
8980 return false;
8981}
8982
8983
8984//===----------------------------------------------------------------------===//
8985// Diagnose initialization failures
8986//===----------------------------------------------------------------------===//
8987
8988/// Emit notes associated with an initialization that failed due to a
8989/// "simple" conversion failure.
8990static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8991 Expr *op) {
8992 QualType destType = entity.getType();
8993 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8995
8996 // Emit a possible note about the conversion failing because the
8997 // operand is a message send with a related result type.
8999
9000 // Emit a possible note about a return failing because we're
9001 // expecting a related result type.
9002 if (entity.getKind() == InitializedEntity::EK_Result)
9004 }
9005 QualType fromType = op->getType();
9006 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
9007 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
9008 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
9009 auto *destDecl = destType->getPointeeCXXRecordDecl();
9010 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
9011 destDecl->getDeclKind() == Decl::CXXRecord &&
9012 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
9013 !fromDecl->hasDefinition() &&
9014 destPointeeType.getQualifiers().compatiblyIncludes(
9015 fromPointeeType.getQualifiers(), S.getASTContext()))
9016 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
9017 << S.getASTContext().getCanonicalTagType(fromDecl)
9018 << S.getASTContext().getCanonicalTagType(destDecl);
9019}
9020
9021static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
9022 InitListExpr *InitList) {
9023 QualType DestType = Entity.getType();
9024
9025 QualType E;
9026 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
9028 E.withConst(),
9029 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
9030 InitList->getNumInitsWithEmbedExpanded()),
9032 InitializedEntity HiddenArray =
9034 return diagnoseListInit(S, HiddenArray, InitList);
9035 }
9036
9037 if (DestType->isReferenceType()) {
9038 // A list-initialization failure for a reference means that we tried to
9039 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
9040 // inner initialization failed.
9041 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
9043 SourceLocation Loc = InitList->getBeginLoc();
9044 if (auto *D = Entity.getDecl())
9045 Loc = D->getLocation();
9046 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
9047 return;
9048 }
9049
9050 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
9051 /*VerifyOnly=*/false,
9052 /*TreatUnavailableAsInvalid=*/false);
9053 assert(DiagnoseInitList.HadError() &&
9054 "Inconsistent init list check result.");
9055}
9056
9058 const InitializedEntity &Entity,
9059 const InitializationKind &Kind,
9060 ArrayRef<Expr *> Args) {
9061 if (!Failed())
9062 return false;
9063
9064 QualType DestType = Entity.getType();
9065
9066 // When we want to diagnose only one element of a braced-init-list,
9067 // we need to factor it out.
9068 Expr *OnlyArg;
9069 if (Args.size() == 1) {
9070 auto *List = dyn_cast<InitListExpr>(Args[0]);
9071 if (List && List->hasOneInit())
9072 OnlyArg = List->getInit(0);
9073 else
9074 OnlyArg = Args[0];
9075
9076 if (OnlyArg->getType() == S.Context.OverloadTy) {
9079 OnlyArg, DestType.getNonReferenceType(), /*Complain=*/false,
9080 Found)) {
9081 if (Expr *Resolved =
9082 S.FixOverloadedFunctionReference(OnlyArg, Found, FD).get())
9083 OnlyArg = Resolved;
9084 }
9085 }
9086 }
9087 else
9088 OnlyArg = nullptr;
9089
9090 switch (Failure) {
9092 // FIXME: Customize for the initialized entity?
9093 if (Args.empty()) {
9094 // Dig out the reference subobject which is uninitialized and diagnose it.
9095 // If this is value-initialization, this could be nested some way within
9096 // the target type.
9097 assert(Kind.getKind() == InitializationKind::IK_Value ||
9098 DestType->isReferenceType());
9099 bool Diagnosed =
9100 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
9101 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
9102 (void)Diagnosed;
9103 } else // FIXME: diagnostic below could be better!
9104 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
9105 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9106 break;
9108 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9109 << 1 << Entity.getType() << Args[0]->getSourceRange();
9110 break;
9111
9113 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
9114 break;
9116 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
9117 break;
9119 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
9120 break;
9122 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
9123 break;
9125 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
9126 break;
9128 S.Diag(Kind.getLocation(),
9129 diag::err_array_init_incompat_wide_string_into_wchar);
9130 break;
9132 S.Diag(Kind.getLocation(),
9133 diag::err_array_init_plain_string_into_char8_t);
9134 S.Diag(Args.front()->getBeginLoc(),
9135 diag::note_array_init_plain_string_into_char8_t)
9136 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
9137 break;
9139 S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
9140 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9141 break;
9144 S.Diag(Kind.getLocation(),
9145 (Failure == FK_ArrayTypeMismatch
9146 ? diag::err_array_init_different_type
9147 : diag::err_array_init_non_constant_array))
9148 << DestType.getNonReferenceType()
9149 << OnlyArg->getType()
9150 << Args[0]->getSourceRange();
9151 break;
9152
9154 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
9155 << Args[0]->getSourceRange();
9156 break;
9157
9161 DestType.getNonReferenceType(),
9162 true,
9163 Found);
9164 break;
9165 }
9166
9168 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
9169 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9170 OnlyArg->getBeginLoc());
9171 break;
9172 }
9173
9176 switch (FailedOverloadResult) {
9177 case OR_Ambiguous:
9178
9179 FailedCandidateSet.NoteCandidates(
9181 Kind.getLocation(),
9183 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
9184 << OnlyArg->getType() << DestType
9185 << Args[0]->getSourceRange())
9186 : (S.PDiag(diag::err_ref_init_ambiguous)
9187 << DestType << OnlyArg->getType()
9188 << Args[0]->getSourceRange())),
9189 S, OCD_AmbiguousCandidates, Args);
9190 break;
9191
9192 case OR_No_Viable_Function: {
9193 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
9194 if (!S.RequireCompleteType(Kind.getLocation(),
9195 DestType.getNonReferenceType(),
9196 diag::err_typecheck_nonviable_condition_incomplete,
9197 OnlyArg->getType(), Args[0]->getSourceRange()))
9198 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9199 << (Entity.getKind() == InitializedEntity::EK_Result)
9200 << OnlyArg->getType() << Args[0]->getSourceRange()
9201 << DestType.getNonReferenceType();
9202
9203 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9204 break;
9205 }
9206 case OR_Deleted: {
9209 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9210
9211 StringLiteral *Msg = Best->Function->getDeletedMessage();
9212 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9213 << OnlyArg->getType() << DestType.getNonReferenceType()
9214 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
9215 << Args[0]->getSourceRange();
9216 if (Ovl == OR_Deleted) {
9217 S.NoteDeletedFunction(Best->Function);
9218 } else {
9219 llvm_unreachable("Inconsistent overload resolution?");
9220 }
9221 break;
9222 }
9223
9224 case OR_Success:
9225 llvm_unreachable("Conversion did not fail!");
9226 }
9227 break;
9228
9230 if (isa<InitListExpr>(Args[0])) {
9231 S.Diag(Kind.getLocation(),
9232 diag::err_lvalue_reference_bind_to_initlist)
9234 << DestType.getNonReferenceType()
9235 << Args[0]->getSourceRange();
9236 break;
9237 }
9238 [[fallthrough]];
9239
9241 S.Diag(Kind.getLocation(),
9243 ? diag::err_lvalue_reference_bind_to_temporary
9244 : diag::err_lvalue_reference_bind_to_unrelated)
9246 << DestType.getNonReferenceType()
9247 << OnlyArg->getType()
9248 << Args[0]->getSourceRange();
9249 break;
9250
9252 // We don't necessarily have an unambiguous source bit-field.
9253 FieldDecl *BitField = Args[0]->getSourceBitField();
9254 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9255 << DestType.isVolatileQualified()
9256 << (BitField ? BitField->getDeclName() : DeclarationName())
9257 << (BitField != nullptr)
9258 << Args[0]->getSourceRange();
9259 if (BitField)
9260 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9261 break;
9262 }
9263
9265 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9266 << DestType.isVolatileQualified()
9267 << Args[0]->getSourceRange();
9268 break;
9269
9271 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9272 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9273 break;
9274
9276 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9277 << DestType.getNonReferenceType() << OnlyArg->getType()
9278 << Args[0]->getSourceRange();
9279 break;
9280
9282 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9283 << DestType << Args[0]->getSourceRange();
9284 break;
9285
9287 QualType SourceType = OnlyArg->getType();
9288 QualType NonRefType = DestType.getNonReferenceType();
9289 Qualifiers DroppedQualifiers =
9290 SourceType.getQualifiers() - NonRefType.getQualifiers();
9291
9292 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9293 SourceType.getQualifiers(), S.getASTContext()))
9294 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9295 << NonRefType << SourceType << 1 /*addr space*/
9296 << Args[0]->getSourceRange();
9297 else if (DroppedQualifiers.hasQualifiers())
9298 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9299 << NonRefType << SourceType << 0 /*cv quals*/
9300 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9301 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9302 else
9303 // FIXME: Consider decomposing the type and explaining which qualifiers
9304 // were dropped where, or on which level a 'const' is missing, etc.
9305 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9306 << NonRefType << SourceType << 2 /*incompatible quals*/
9307 << Args[0]->getSourceRange();
9308 break;
9309 }
9310
9312 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9313 << DestType.getNonReferenceType()
9314 << DestType.getNonReferenceType()->isIncompleteType()
9315 << OnlyArg->isLValue()
9316 << OnlyArg->getType()
9317 << Args[0]->getSourceRange();
9318 emitBadConversionNotes(S, Entity, Args[0]);
9319 break;
9320
9321 case FK_ConversionFailed: {
9322 QualType FromType = OnlyArg->getType();
9323 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op
9324 // type, although this is almost always an error and we advise against it.
9325 if (FromType == S.Context.AMDGPUFeaturePredicateTy &&
9326 DestType == S.Context.getLogicalOperationType()) {
9327 S.Diag(OnlyArg->getExprLoc(),
9328 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
9329 << OnlyArg << DestType;
9330 break;
9331 }
9332 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9333 << (int)Entity.getKind()
9334 << DestType
9335 << OnlyArg->isLValue()
9336 << FromType
9337 << Args[0]->getSourceRange();
9338 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9339 S.Diag(Kind.getLocation(), PDiag);
9340 emitBadConversionNotes(S, Entity, Args[0]);
9341 break;
9342 }
9343
9345 // No-op. This error has already been reported.
9346 break;
9347
9349 SourceRange R;
9350
9351 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9352 if (InitList && InitList->getNumInits() >= 1) {
9353 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9354 } else {
9355 assert(Args.size() > 1 && "Expected multiple initializers!");
9356 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9357 }
9358
9359 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
9360 if (Kind.isCStyleOrFunctionalCast())
9361 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9362 << R;
9363 else
9364 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9365 << /*scalar=*/3 << R;
9366 break;
9367 }
9368
9370 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9371 << 0 << Entity.getType() << Args[0]->getSourceRange();
9372 break;
9373
9375 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9376 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9377 break;
9378
9380 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9381 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9382 break;
9383
9386 SourceRange ArgsRange;
9387 if (Args.size())
9388 ArgsRange =
9389 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9390
9391 SmallVector<Expr *, 8> ExpandedInits;
9392 if (Failure == FK_ListConstructorOverloadFailed) {
9393 assert(Args.size() == 1 &&
9394 "List construction from other than 1 argument.");
9395 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9396 Args = S.getInitsWithEmbedExpanded(InitList, ExpandedInits);
9397 }
9398
9399 // FIXME: Using "DestType" for the entity we're printing is probably
9400 // bad.
9401 switch (FailedOverloadResult) {
9402 case OR_Ambiguous:
9403 FailedCandidateSet.NoteCandidates(
9404 PartialDiagnosticAt(Kind.getLocation(),
9405 S.PDiag(diag::err_ovl_ambiguous_init)
9406 << DestType << ArgsRange),
9407 S, OCD_AmbiguousCandidates, Args);
9408 break;
9409
9411 if (Kind.getKind() == InitializationKind::IK_Default &&
9412 (Entity.getKind() == InitializedEntity::EK_Base ||
9416 // This is implicit default initialization of a member or
9417 // base within a constructor. If no viable function was
9418 // found, notify the user that they need to explicitly
9419 // initialize this base/member.
9422 const CXXRecordDecl *InheritedFrom = nullptr;
9423 if (auto Inherited = Constructor->getInheritedConstructor())
9424 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9425 if (Entity.getKind() == InitializedEntity::EK_Base) {
9426 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9427 << (InheritedFrom ? 2
9428 : Constructor->isImplicit() ? 1
9429 : 0)
9430 << S.Context.getCanonicalTagType(Constructor->getParent())
9431 << /*base=*/0 << Entity.getType() << InheritedFrom;
9432
9433 auto *BaseDecl =
9435 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9436 << S.Context.getCanonicalTagType(BaseDecl);
9437 } else {
9438 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9439 << (InheritedFrom ? 2
9440 : Constructor->isImplicit() ? 1
9441 : 0)
9442 << S.Context.getCanonicalTagType(Constructor->getParent())
9443 << /*member=*/1 << Entity.getName() << InheritedFrom;
9444 S.Diag(Entity.getDecl()->getLocation(),
9445 diag::note_member_declared_at);
9446
9447 if (const auto *Record = Entity.getType()->getAs<RecordType>())
9448 S.Diag(Record->getDecl()->getLocation(), diag::note_previous_decl)
9449 << S.Context.getCanonicalTagType(Record->getDecl());
9450 }
9451 break;
9452 }
9453
9454 FailedCandidateSet.NoteCandidates(
9456 Kind.getLocation(),
9457 S.PDiag(diag::err_ovl_no_viable_function_in_init)
9458 << DestType << ArgsRange),
9459 S, OCD_AllCandidates, Args);
9460 break;
9461
9462 case OR_Deleted: {
9465 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9466 if (Ovl != OR_Deleted) {
9467 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9468 << DestType << ArgsRange;
9469 llvm_unreachable("Inconsistent overload resolution?");
9470 break;
9471 }
9472
9473 // If this is a defaulted or implicitly-declared function, then
9474 // it was implicitly deleted. Make it clear that the deletion was
9475 // implicit.
9476 if (S.isImplicitlyDeleted(Best->Function))
9477 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
9478 << cast<CXXMethodDecl>(Best->Function)->getSpecialMemberKind()
9479 << DestType << ArgsRange;
9480 else {
9481 StringLiteral *Msg = Best->Function->getDeletedMessage();
9482 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9483 << DestType << (Msg != nullptr)
9484 << (Msg ? Msg->getString() : StringRef()) << ArgsRange;
9485 }
9486
9487 // If it's a default constructed member, but it's not in the
9488 // constructor's initializer list, explicitly note where the member is
9489 // declared so the user can see which member is erroneously initialized
9490 // with a deleted default constructor.
9491 if (Kind.getKind() == InitializationKind::IK_Default &&
9494 S.Diag(Entity.getDecl()->getLocation(),
9495 diag::note_default_constructed_field)
9496 << Entity.getDecl();
9497 }
9498 S.NoteDeletedFunction(Best->Function);
9499 break;
9500 }
9501
9502 case OR_Success:
9503 llvm_unreachable("Conversion did not fail!");
9504 }
9505 }
9506 break;
9507
9509 if (Entity.getKind() == InitializedEntity::EK_Member &&
9511 // This is implicit default-initialization of a const member in
9512 // a constructor. Complain that it needs to be explicitly
9513 // initialized.
9515 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
9516 << (Constructor->getInheritedConstructor() ? 2
9517 : Constructor->isImplicit() ? 1
9518 : 0)
9519 << S.Context.getCanonicalTagType(Constructor->getParent())
9520 << /*const=*/1 << Entity.getName();
9521 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
9522 << Entity.getName();
9523 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
9524 VD && VD->isConstexpr()) {
9525 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
9526 << VD;
9527 } else {
9528 S.Diag(Kind.getLocation(), diag::err_default_init_const)
9529 << DestType << DestType->isRecordType();
9530 }
9531 break;
9532
9533 case FK_Incomplete:
9534 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
9535 diag::err_init_incomplete_type);
9536 break;
9537
9539 // Run the init list checker again to emit diagnostics.
9540 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9541 diagnoseListInit(S, Entity, InitList);
9542 break;
9543 }
9544
9545 case FK_PlaceholderType: {
9546 // FIXME: Already diagnosed!
9547 break;
9548 }
9549
9551 // Unlike C/C++ list initialization, there is no fallback if it fails. This
9552 // allows us to diagnose the failure when it happens in the
9553 // TryListInitialization call instead of delaying the diagnosis, which is
9554 // beneficial because the flattening is also expensive.
9555 break;
9556 }
9557
9559 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
9560 << Args[0]->getSourceRange();
9563 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9564 (void)Ovl;
9565 assert(Ovl == OR_Success && "Inconsistent overload resolution");
9566 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
9567 S.Diag(CtorDecl->getLocation(),
9568 diag::note_explicit_ctor_deduction_guide_here) << false;
9569 break;
9570 }
9571
9573 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9574 /*VerifyOnly=*/false);
9575 break;
9576
9578 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9579 S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
9580 << Entity.getType() << InitList->getSourceRange();
9581 break;
9582 }
9583
9584 PrintInitLocationNote(S, Entity);
9585 return true;
9586}
9587
9588void InitializationSequence::dump(raw_ostream &OS) const {
9589 switch (SequenceKind) {
9590 case FailedSequence: {
9591 OS << "Failed sequence: ";
9592 switch (Failure) {
9594 OS << "too many initializers for reference";
9595 break;
9596
9598 OS << "parenthesized list init for reference";
9599 break;
9600
9602 OS << "array requires initializer list";
9603 break;
9604
9606 OS << "address of unaddressable function was taken";
9607 break;
9608
9610 OS << "array requires initializer list or string literal";
9611 break;
9612
9614 OS << "array requires initializer list or wide string literal";
9615 break;
9616
9618 OS << "narrow string into wide char array";
9619 break;
9620
9622 OS << "wide string into char array";
9623 break;
9624
9626 OS << "incompatible wide string into wide char array";
9627 break;
9628
9630 OS << "plain string literal into char8_t array";
9631 break;
9632
9634 OS << "u8 string literal into char array";
9635 break;
9636
9638 OS << "array type mismatch";
9639 break;
9640
9642 OS << "non-constant array initializer";
9643 break;
9644
9646 OS << "address of overloaded function failed";
9647 break;
9648
9650 OS << "overload resolution for reference initialization failed";
9651 break;
9652
9654 OS << "non-const lvalue reference bound to temporary";
9655 break;
9656
9658 OS << "non-const lvalue reference bound to bit-field";
9659 break;
9660
9662 OS << "non-const lvalue reference bound to vector element";
9663 break;
9664
9666 OS << "non-const lvalue reference bound to matrix element";
9667 break;
9668
9670 OS << "non-const lvalue reference bound to unrelated type";
9671 break;
9672
9674 OS << "rvalue reference bound to an lvalue";
9675 break;
9676
9678 OS << "reference initialization drops qualifiers";
9679 break;
9680
9682 OS << "reference with mismatching address space bound to temporary";
9683 break;
9684
9686 OS << "reference initialization failed";
9687 break;
9688
9690 OS << "conversion failed";
9691 break;
9692
9694 OS << "conversion from property failed";
9695 break;
9696
9698 OS << "too many initializers for scalar";
9699 break;
9700
9702 OS << "parenthesized list init for reference";
9703 break;
9704
9706 OS << "referencing binding to initializer list";
9707 break;
9708
9710 OS << "initializer list for non-aggregate, non-scalar type";
9711 break;
9712
9714 OS << "overloading failed for user-defined conversion";
9715 break;
9716
9718 OS << "constructor overloading failed";
9719 break;
9720
9722 OS << "default initialization of a const variable";
9723 break;
9724
9725 case FK_Incomplete:
9726 OS << "initialization of incomplete type";
9727 break;
9728
9730 OS << "list initialization checker failure";
9731 break;
9732
9734 OS << "variable length array has an initializer";
9735 break;
9736
9737 case FK_PlaceholderType:
9738 OS << "initializer expression isn't contextually valid";
9739 break;
9740
9742 OS << "list constructor overloading failed";
9743 break;
9744
9746 OS << "list copy initialization chose explicit constructor";
9747 break;
9748
9750 OS << "parenthesized list initialization failed";
9751 break;
9752
9754 OS << "designated initializer for non-aggregate type";
9755 break;
9756
9758 OS << "HLSL initialization list flattening failed";
9759 break;
9760 }
9761 OS << '\n';
9762 return;
9763 }
9764
9765 case DependentSequence:
9766 OS << "Dependent sequence\n";
9767 return;
9768
9769 case NormalSequence:
9770 OS << "Normal sequence: ";
9771 break;
9772 }
9773
9774 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
9775 if (S != step_begin()) {
9776 OS << " -> ";
9777 }
9778
9779 switch (S->Kind) {
9781 OS << "resolve address of overloaded function";
9782 break;
9783
9785 OS << "derived-to-base (prvalue)";
9786 break;
9787
9789 OS << "derived-to-base (xvalue)";
9790 break;
9791
9793 OS << "derived-to-base (lvalue)";
9794 break;
9795
9796 case SK_BindReference:
9797 OS << "bind reference to lvalue";
9798 break;
9799
9801 OS << "bind reference to a temporary";
9802 break;
9803
9804 case SK_FinalCopy:
9805 OS << "final copy in class direct-initialization";
9806 break;
9807
9809 OS << "extraneous C++03 copy to temporary";
9810 break;
9811
9812 case SK_UserConversion:
9813 OS << "user-defined conversion via " << *S->Function.Function;
9814 break;
9815
9817 OS << "qualification conversion (prvalue)";
9818 break;
9819
9821 OS << "qualification conversion (xvalue)";
9822 break;
9823
9825 OS << "qualification conversion (lvalue)";
9826 break;
9827
9829 OS << "function reference conversion";
9830 break;
9831
9833 OS << "non-atomic-to-atomic conversion";
9834 break;
9835
9837 OS << "implicit conversion sequence (";
9838 S->ICS->dump(); // FIXME: use OS
9839 OS << ")";
9840 break;
9841
9843 OS << "implicit conversion sequence with narrowing prohibited (";
9844 S->ICS->dump(); // FIXME: use OS
9845 OS << ")";
9846 break;
9847
9849 OS << "list aggregate initialization";
9850 break;
9851
9852 case SK_UnwrapInitList:
9853 OS << "unwrap reference initializer list";
9854 break;
9855
9856 case SK_RewrapInitList:
9857 OS << "rewrap reference initializer list";
9858 break;
9859
9861 OS << "constructor initialization";
9862 break;
9863
9865 OS << "list initialization via constructor";
9866 break;
9867
9869 OS << "zero initialization";
9870 break;
9871
9872 case SK_CAssignment:
9873 OS << "C assignment";
9874 break;
9875
9876 case SK_StringInit:
9877 OS << "string initialization";
9878 break;
9879
9881 OS << "Objective-C object conversion";
9882 break;
9883
9884 case SK_ArrayLoopIndex:
9885 OS << "indexing for array initialization loop";
9886 break;
9887
9888 case SK_ArrayLoopInit:
9889 OS << "array initialization loop";
9890 break;
9891
9892 case SK_ArrayInit:
9893 OS << "array initialization";
9894 break;
9895
9896 case SK_GNUArrayInit:
9897 OS << "array initialization (GNU extension)";
9898 break;
9899
9901 OS << "parenthesized array initialization";
9902 break;
9903
9905 OS << "pass by indirect copy and restore";
9906 break;
9907
9909 OS << "pass by indirect restore";
9910 break;
9911
9913 OS << "Objective-C object retension";
9914 break;
9915
9917 OS << "std::initializer_list from initializer list";
9918 break;
9919
9921 OS << "list initialization from std::initializer_list";
9922 break;
9923
9924 case SK_OCLSamplerInit:
9925 OS << "OpenCL sampler_t from integer constant";
9926 break;
9927
9929 OS << "OpenCL opaque type from zero";
9930 break;
9931
9933 OS << "initialization from a parenthesized list of values";
9934 break;
9935
9937 OS << "HLSL buffer conversion";
9938 break;
9939 }
9940
9941 OS << " [" << S->Type << ']';
9942 }
9943
9944 OS << '\n';
9945}
9946
9948 dump(llvm::errs());
9949}
9950
9952 Sema &S, const StandardConversionSequence &SCS, const Expr *Init,
9953 APValue &ConstantValue, QualType &ConstantType) {
9954 const auto *Embed = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts());
9955 if (!Embed || Embed->getDataElementCount() <= 1)
9956 return SCS.getNarrowingKind(S.Context, Init, ConstantValue, ConstantType);
9957 for (const IntegerLiteral *Elt : Embed->underlying_data_elements())
9958 if (NarrowingKind NK =
9959 SCS.getNarrowingKind(S.Context, Elt, ConstantValue, ConstantType);
9960 NK != NK_Not_Narrowing)
9961 return NK;
9962 return NK_Not_Narrowing;
9963}
9964
9966 const ImplicitConversionSequence &ICS,
9967 QualType PreNarrowingType,
9968 QualType EntityType,
9969 const Expr *PostInit) {
9970 const StandardConversionSequence *SCS = nullptr;
9971 switch (ICS.getKind()) {
9973 SCS = &ICS.Standard;
9974 break;
9976 SCS = &ICS.UserDefined.After;
9977 break;
9982 return;
9983 }
9984
9985 auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
9986 unsigned ConstRefDiagID, unsigned WarnDiagID) {
9987 unsigned DiagID;
9988 auto &L = S.getLangOpts();
9989 if (L.CPlusPlus11 && !L.HLSL &&
9990 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))
9991 DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
9992 else
9993 DiagID = WarnDiagID;
9994 return S.Diag(PostInit->getBeginLoc(), DiagID)
9995 << PostInit->getSourceRange();
9996 };
9997
9998 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9999 APValue ConstantValue;
10000 QualType ConstantType;
10001 switch (getNarrowingKindWithEmbedExpanded(S, *SCS, PostInit, ConstantValue,
10002 ConstantType)) {
10003 case NK_Not_Narrowing:
10005 // No narrowing occurred.
10006 return;
10007
10008 case NK_Type_Narrowing: {
10009 // This was a floating-to-integer conversion, which is always considered a
10010 // narrowing conversion even if the value is a constant and can be
10011 // represented exactly as an integer.
10012 QualType T = EntityType.getNonReferenceType();
10013 MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
10014 diag::ext_init_list_type_narrowing_const_reference,
10015 diag::warn_init_list_type_narrowing)
10016 << PreNarrowingType.getLocalUnqualifiedType()
10017 << T.getLocalUnqualifiedType();
10018 break;
10019 }
10020
10021 case NK_Constant_Narrowing: {
10022 // A constant value was narrowed.
10023 MakeDiag(EntityType.getNonReferenceType() != EntityType,
10024 diag::ext_init_list_constant_narrowing,
10025 diag::ext_init_list_constant_narrowing_const_reference,
10026 diag::warn_init_list_constant_narrowing)
10027 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
10029 break;
10030 }
10031
10032 case NK_Variable_Narrowing: {
10033 // A variable's value may have been narrowed.
10034 MakeDiag(EntityType.getNonReferenceType() != EntityType,
10035 diag::ext_init_list_variable_narrowing,
10036 diag::ext_init_list_variable_narrowing_const_reference,
10037 diag::warn_init_list_variable_narrowing)
10038 << PreNarrowingType.getLocalUnqualifiedType()
10040 break;
10041 }
10042 }
10043
10044 SmallString<128> StaticCast;
10045 llvm::raw_svector_ostream OS(StaticCast);
10046 OS << "static_cast<";
10047 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
10048 // It's important to use the typedef's name if there is one so that the
10049 // fixit doesn't break code using types like int64_t.
10050 //
10051 // FIXME: This will break if the typedef requires qualification. But
10052 // getQualifiedNameAsString() includes non-machine-parsable components.
10053 OS << *TT->getDecl();
10054 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
10055 OS << BT->getName(S.getLangOpts());
10056 else {
10057 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
10058 // with a broken cast.
10059 return;
10060 }
10061 OS << ">(";
10062 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
10063 << PostInit->getSourceRange()
10064 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
10066 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
10067}
10068
10070 QualType ToType, Expr *Init) {
10071 assert(S.getLangOpts().C23);
10073 Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
10074 Sema::AllowedExplicit::None,
10075 /*InOverloadResolution*/ false,
10076 /*CStyle*/ false,
10077 /*AllowObjCWritebackConversion=*/false);
10078
10079 if (!ICS.isStandard())
10080 return;
10081
10082 APValue Value;
10083 QualType PreNarrowingType;
10084 // Reuse C++ narrowing check.
10086 PreNarrowingType)) {
10087 // The value doesn't fit.
10089 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
10090 << Value.getAsString(S.Context, PreNarrowingType) << ToType;
10091 return;
10092
10093 // Conversion to a narrower type.
10094 case NK_Type_Narrowing:
10095 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
10096 << ToType << FromType;
10097 return;
10098
10099 // Since we only reuse narrowing check for C23 constexpr variables here, we're
10100 // not really interested in these cases.
10103 case NK_Not_Narrowing:
10104 return;
10105 }
10106 llvm_unreachable("unhandled case in switch");
10107}
10108
10110 Sema &SemaRef, QualType &TT) {
10111 assert(SemaRef.getLangOpts().C23);
10112 // character that string literal contains fits into TT - target type.
10113 const ArrayType *AT = SemaRef.Context.getAsArrayType(TT);
10114 QualType CharType = AT->getElementType();
10115 uint32_t BitWidth = SemaRef.Context.getTypeSize(CharType);
10116 bool isUnsigned = CharType->isUnsignedIntegerType();
10117 llvm::APSInt Value(BitWidth, isUnsigned);
10118 for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
10119 int64_t C = SE->getCodeUnitS(I, SemaRef.Context.getCharWidth());
10120 Value = C;
10121 if (Value != C) {
10122 SemaRef.Diag(SemaRef.getLocationOfStringLiteralByte(SE, I),
10123 diag::err_c23_constexpr_init_not_representable)
10124 << C << CharType;
10125 return;
10126 }
10127 }
10128}
10129
10130//===----------------------------------------------------------------------===//
10131// Initialization helper functions
10132//===----------------------------------------------------------------------===//
10133bool
10135 ExprResult Init) {
10136 if (Init.isInvalid())
10137 return false;
10138
10139 Expr *InitE = Init.get();
10140 assert(InitE && "No initialization expression");
10141
10142 InitializationKind Kind =
10144 InitializationSequence Seq(*this, Entity, Kind, InitE);
10145 return !Seq.Failed();
10146}
10147
10150 SourceLocation EqualLoc,
10152 bool TopLevelOfInitList,
10153 bool AllowExplicit) {
10154 if (Init.isInvalid())
10155 return ExprError();
10156
10157 Expr *InitE = Init.get();
10158 assert(InitE && "No initialization expression?");
10159
10160 if (EqualLoc.isInvalid())
10161 EqualLoc = InitE->getBeginLoc();
10162
10163 if (Entity.getType().getDesugaredType(Context) ==
10164 Context.AMDGPUFeaturePredicateTy &&
10165 Entity.getDecl()) {
10166 Diag(EqualLoc, diag::err_amdgcn_predicate_type_is_not_constructible)
10167 << Entity.getDecl();
10168 return ExprError();
10169 }
10170
10172 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
10173 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10174
10175 // Prevent infinite recursion when performing parameter copy-initialization.
10176 const bool ShouldTrackCopy =
10177 Entity.isParameterKind() && Seq.isConstructorInitialization();
10178 if (ShouldTrackCopy) {
10179 if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
10180 Seq.SetOverloadFailure(
10183
10184 // Try to give a meaningful diagnostic note for the problematic
10185 // constructor.
10186 const auto LastStep = Seq.step_end() - 1;
10187 assert(LastStep->Kind ==
10189 const FunctionDecl *Function = LastStep->Function.Function;
10190 auto Candidate =
10191 llvm::find_if(Seq.getFailedCandidateSet(),
10192 [Function](const OverloadCandidate &Candidate) -> bool {
10193 return Candidate.Viable &&
10194 Candidate.Function == Function &&
10195 Candidate.Conversions.size() > 0;
10196 });
10197 if (Candidate != Seq.getFailedCandidateSet().end() &&
10198 Function->getNumParams() > 0) {
10199 Candidate->Viable = false;
10202 InitE,
10203 Function->getParamDecl(0)->getType());
10204 }
10205 }
10206 CurrentParameterCopyTypes.push_back(Entity.getType());
10207 }
10208
10209 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
10210
10211 if (ShouldTrackCopy)
10212 CurrentParameterCopyTypes.pop_back();
10213
10214 return Result;
10215}
10216
10217/// Determine whether RD is, or is derived from, a specialization of CTD.
10219 ClassTemplateDecl *CTD) {
10220 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10221 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
10222 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
10223 };
10224 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
10225}
10226
10228 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10229 const InitializationKind &Kind, MultiExprArg Inits) {
10230 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10231 TSInfo->getType()->getContainedDeducedType());
10232 assert(DeducedTST && "not a deduced template specialization type");
10233
10234 auto TemplateName = DeducedTST->getTemplateName();
10236 return SubstAutoTypeSourceInfoDependent(TSInfo)->getType();
10237
10238 // We can only perform deduction for class templates or alias templates.
10239 auto *Template =
10240 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10241 TemplateDecl *LookupTemplateDecl = Template;
10242 if (!Template) {
10243 if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
10245 DiagCompat(Kind.getLocation(), diag_compat::ctad_for_alias_templates);
10246 LookupTemplateDecl = AliasTemplate;
10247 auto UnderlyingType = AliasTemplate->getTemplatedDecl()
10248 ->getUnderlyingType()
10249 .getCanonicalType();
10250 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
10251 // of the form
10252 // [typename] [nested-name-specifier] [template] simple-template-id
10253 if (const auto *TST =
10254 UnderlyingType->getAs<TemplateSpecializationType>()) {
10255 Template = dyn_cast_or_null<ClassTemplateDecl>(
10256 TST->getTemplateName().getAsTemplateDecl());
10257 } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
10258 // Cases where template arguments in the RHS of the alias are not
10259 // dependent. e.g.
10260 // using AliasFoo = Foo<bool>;
10261 if (const auto *CTSD =
10262 llvm::dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()))
10263 Template = CTSD->getSpecializedTemplate();
10264 }
10265 }
10266 }
10267 if (!Template) {
10268 Diag(Kind.getLocation(),
10269 diag::err_deduced_non_class_or_alias_template_specialization_type)
10271 if (auto *TD = TemplateName.getAsTemplateDecl())
10273 return QualType();
10274 }
10275
10276 // Can't deduce from dependent arguments.
10278 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10279 diag::warn_cxx14_compat_class_template_argument_deduction)
10280 << TSInfo->getTypeLoc().getSourceRange() << 0;
10281 return SubstAutoTypeSourceInfoDependent(TSInfo)->getType();
10282 }
10283
10284 // FIXME: Perform "exact type" matching first, per CWG discussion?
10285 // Or implement this via an implied 'T(T) -> T' deduction guide?
10286
10287 // Look up deduction guides, including those synthesized from constructors.
10288 //
10289 // C++1z [over.match.class.deduct]p1:
10290 // A set of functions and function templates is formed comprising:
10291 // - For each constructor of the class template designated by the
10292 // template-name, a function template [...]
10293 // - For each deduction-guide, a function or function template [...]
10294 DeclarationNameInfo NameInfo(
10295 Context.DeclarationNames.getCXXDeductionGuideName(LookupTemplateDecl),
10296 TSInfo->getTypeLoc().getEndLoc());
10297 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10298 LookupQualifiedName(Guides, LookupTemplateDecl->getDeclContext());
10299
10300 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10301 // clear on this, but they're not found by name so access does not apply.
10302 Guides.suppressDiagnostics();
10303
10304 // Figure out if this is list-initialization.
10306 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10307 ? dyn_cast<InitListExpr>(Inits[0])
10308 : nullptr;
10309 SmallVector<Expr *, 8> ExpandedInits;
10310
10311 // C++1z [over.match.class.deduct]p1:
10312 // Initialization and overload resolution are performed as described in
10313 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10314 // (as appropriate for the type of initialization performed) for an object
10315 // of a hypothetical class type, where the selected functions and function
10316 // templates are considered to be the constructors of that class type
10317 //
10318 // Since we know we're initializing a class type of a type unrelated to that
10319 // of the initializer, this reduces to something fairly reasonable.
10320 OverloadCandidateSet Candidates(Kind.getLocation(),
10323
10324 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10325
10326 // Return true if the candidate is added successfully, false otherwise.
10327 auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10329 DeclAccessPair FoundDecl,
10330 bool OnlyListConstructors,
10331 bool AllowAggregateDeductionCandidate) {
10332 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10333 // For copy-initialization, the candidate functions are all the
10334 // converting constructors (12.3.1) of that class.
10335 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10336 // The converting constructors of T are candidate functions.
10337 if (!AllowExplicit) {
10338 // Overload resolution checks whether the deduction guide is declared
10339 // explicit for us.
10340
10341 // When looking for a converting constructor, deduction guides that
10342 // could never be called with one argument are not interesting to
10343 // check or note.
10344 if (GD->getMinRequiredArguments() > 1 ||
10345 (GD->getNumParams() == 0 && !GD->isVariadic()))
10346 return;
10347 }
10348
10349 // C++ [over.match.list]p1.1: (first phase list initialization)
10350 // Initially, the candidate functions are the initializer-list
10351 // constructors of the class T
10352 if (OnlyListConstructors && !isInitListConstructor(GD))
10353 return;
10354
10355 if (!AllowAggregateDeductionCandidate &&
10356 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10357 return;
10358
10359 // C++ [over.match.list]p1.2: (second phase list initialization)
10360 // the candidate functions are all the constructors of the class T
10361 // C++ [over.match.ctor]p1: (all other cases)
10362 // the candidate functions are all the constructors of the class of
10363 // the object being initialized
10364
10365 // C++ [over.best.ics]p4:
10366 // When [...] the constructor [...] is a candidate by
10367 // - [over.match.copy] (in all cases)
10368 if (TD) {
10369
10370 // As template candidates are not deduced immediately,
10371 // persist the array in the overload set.
10372 MutableArrayRef<Expr *> TmpInits =
10373 Candidates.getPersistentArgsArray(Inits.size());
10374
10375 for (auto [I, E] : llvm::enumerate(Inits)) {
10376 if (auto *DI = dyn_cast<DesignatedInitExpr>(E))
10377 TmpInits[I] = DI->getInit();
10378 else
10379 TmpInits[I] = E;
10380 }
10381
10383 TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
10384 /*SuppressUserConversions=*/false,
10385 /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
10386 /*PO=*/{}, AllowAggregateDeductionCandidate);
10387 } else {
10388 AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
10389 /*SuppressUserConversions=*/false,
10390 /*PartialOverloading=*/false, AllowExplicit);
10391 }
10392 };
10393
10394 bool FoundDeductionGuide = false;
10395
10396 auto TryToResolveOverload =
10397 [&](bool OnlyListConstructors) -> OverloadingResult {
10399 bool HasAnyDeductionGuide = false;
10400
10401 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10402 auto *Pattern = Template;
10403 while (Pattern->getInstantiatedFromMemberTemplate()) {
10404 if (Pattern->isMemberSpecialization())
10405 break;
10406 Pattern = Pattern->getInstantiatedFromMemberTemplate();
10407 }
10408
10409 auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());
10410 if (!(RD->getDefinition() && RD->isAggregate()))
10411 return;
10412 QualType Ty = Context.getCanonicalTagType(RD);
10413 SmallVector<QualType, 8> ElementTypes;
10414
10415 InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10416 if (!CheckInitList.HadError()) {
10417 // C++ [over.match.class.deduct]p1.8:
10418 // if e_i is of array type and x_i is a braced-init-list, T_i is an
10419 // rvalue reference to the declared type of e_i and
10420 // C++ [over.match.class.deduct]p1.9:
10421 // if e_i is of array type and x_i is a string-literal, T_i is an
10422 // lvalue reference to the const-qualified declared type of e_i and
10423 // C++ [over.match.class.deduct]p1.10:
10424 // otherwise, T_i is the declared type of e_i
10425 for (int I = 0, E = ListInit->getNumInits();
10426 I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
10427 if (ElementTypes[I]->isArrayType()) {
10429 ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);
10430 else if (isa<StringLiteral>(
10431 ListInit->getInit(I)->IgnoreParenImpCasts()))
10432 ElementTypes[I] =
10433 Context.getLValueReferenceType(ElementTypes[I].withConst());
10434 }
10435
10436 if (CXXDeductionGuideDecl *GD =
10438 LookupTemplateDecl, ElementTypes,
10439 TSInfo->getTypeLoc().getEndLoc())) {
10440 auto *TD = GD->getDescribedFunctionTemplate();
10441 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10442 OnlyListConstructors,
10443 /*AllowAggregateDeductionCandidate=*/true);
10444 HasAnyDeductionGuide = true;
10445 }
10446 }
10447 };
10448
10449 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10450 NamedDecl *D = (*I)->getUnderlyingDecl();
10451 if (D->isInvalidDecl())
10452 continue;
10453
10454 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10455 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10456 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10457 if (!GD)
10458 continue;
10459
10460 if (!GD->isImplicit())
10461 HasAnyDeductionGuide = true;
10462
10463 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10464 /*AllowAggregateDeductionCandidate=*/false);
10465 }
10466
10467 // C++ [over.match.class.deduct]p1.4:
10468 // if C is defined and its definition satisfies the conditions for an
10469 // aggregate class ([dcl.init.aggr]) with the assumption that any
10470 // dependent base class has no virtual functions and no virtual base
10471 // classes, and the initializer is a non-empty braced-init-list or
10472 // parenthesized expression-list, and there are no deduction-guides for
10473 // C, the set contains an additional function template, called the
10474 // aggregate deduction candidate, defined as follows.
10475 if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10476 if (ListInit && ListInit->getNumInits()) {
10477 SynthesizeAggrGuide(ListInit);
10478 } else if (Inits.size()) { // parenthesized expression-list
10479 // Inits are expressions inside the parentheses. We don't have
10480 // the parentheses source locations, use the begin/end of Inits as the
10481 // best heuristic.
10482 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10483 Inits, Inits.back()->getEndLoc(),
10484 /*isExplicit=*/false);
10485 SynthesizeAggrGuide(&TempListInit);
10486 }
10487 }
10488
10489 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10490
10491 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
10492 };
10493
10495
10496 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10497 // try initializer-list constructors.
10498 if (ListInit) {
10499 bool TryListConstructors = true;
10500
10501 // Try list constructors unless the list is empty and the class has one or
10502 // more default constructors, in which case those constructors win.
10503 if (ListInit->hasZeroInits()) {
10504 for (NamedDecl *D : Guides) {
10505 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
10506 if (FD && FD->getMinRequiredArguments() == 0) {
10507 TryListConstructors = false;
10508 break;
10509 }
10510 }
10511 } else if (ListInit->hasOneInit()) {
10512 // C++ [over.match.class.deduct]:
10513 // As an exception, the first phase in [over.match.list] (considering
10514 // initializer-list constructors) is omitted if the initializer list
10515 // consists of a single expression of type cv U, where U is a
10516 // specialization of C or a class derived from a specialization of C.
10517 Expr *E = ListInit->getInit(0);
10518 auto *RD = E->getType()->getAsCXXRecordDecl();
10519 if (!isa<InitListExpr>(E) && RD &&
10520 isCompleteType(Kind.getLocation(), E->getType()) &&
10522 TryListConstructors = false;
10523 }
10524
10525 if (TryListConstructors)
10526 Result = TryToResolveOverload(/*OnlyListConstructor*/true);
10527 // Then unwrap the initializer list and try again considering all
10528 // constructors.
10529 Inits = getInitsWithEmbedExpanded(ListInit, ExpandedInits);
10530 }
10531
10532 // If list-initialization fails, or if we're doing any other kind of
10533 // initialization, we (eventually) consider constructors.
10535 Result = TryToResolveOverload(/*OnlyListConstructor*/false);
10536
10537 switch (Result) {
10538 case OR_Ambiguous:
10539 // FIXME: For list-initialization candidates, it'd usually be better to
10540 // list why they were not viable when given the initializer list itself as
10541 // an argument.
10542 Candidates.NoteCandidates(
10544 Kind.getLocation(),
10545 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
10546 << TemplateName),
10548 return QualType();
10549
10550 case OR_No_Viable_Function: {
10551 CXXRecordDecl *Primary =
10552 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
10553 bool Complete = isCompleteType(Kind.getLocation(),
10554 Context.getCanonicalTagType(Primary));
10555 Candidates.NoteCandidates(
10557 Kind.getLocation(),
10558 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
10559 : diag::err_deduced_class_template_incomplete)
10560 << TemplateName << !Guides.empty()),
10561 *this, OCD_AllCandidates, Inits);
10562 return QualType();
10563 }
10564
10565 case OR_Deleted: {
10566 // FIXME: There are no tests for this diagnostic, and it doesn't seem
10567 // like we ever get here; attempts to trigger this seem to yield a
10568 // generic c'all to deleted function' diagnostic instead.
10569 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
10570 << TemplateName;
10571 NoteDeletedFunction(Best->Function);
10572 return QualType();
10573 }
10574
10575 case OR_Success:
10576 // C++ [over.match.list]p1:
10577 // In copy-list-initialization, if an explicit constructor is chosen, the
10578 // initialization is ill-formed.
10579 if (Kind.isCopyInit() && ListInit &&
10580 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
10581 bool IsDeductionGuide = !Best->Function->isImplicit();
10582 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
10583 << TemplateName << IsDeductionGuide;
10584 Diag(Best->Function->getLocation(),
10585 diag::note_explicit_ctor_deduction_guide_here)
10586 << IsDeductionGuide;
10587 return QualType();
10588 }
10589
10590 // Make sure we didn't select an unusable deduction guide, and mark it
10591 // as referenced.
10592 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
10593 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
10594 break;
10595 }
10596
10597 // C++ [dcl.type.class.deduct]p1:
10598 // The placeholder is replaced by the return type of the function selected
10599 // by overload resolution for class template deduction.
10600 QualType DeducedType =
10601 SubstAutoTypeSourceInfo(TSInfo, Best->Function->getReturnType())
10602 ->getType();
10603 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10604 diag::warn_cxx14_compat_class_template_argument_deduction)
10605 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10606
10607 // Warn if CTAD was used on a type that does not have any user-defined
10608 // deduction guides.
10609 if (!FoundDeductionGuide) {
10610 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10611 diag::warn_ctad_maybe_unsupported)
10612 << TemplateName;
10613 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
10614 }
10615
10616 return DeducedType;
10617}
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:567
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 NarrowingKind getNarrowingKindWithEmbedExpanded(Sema &S, const StandardConversionSequence &SCS, const Expr *Init, APValue &ConstantValue, QualType &ConstantType)
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:158
APSInt & getInt()
Definition APValue.h:573
bool isLValue() const
Definition APValue.h:554
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:1099
bool isNullPointer() const
Definition APValue.cpp:1162
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
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:971
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:6107
Represents a loop initializing the elements of an array.
Definition Expr.h:6054
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
QualType getElementType() const
Definition TypeBase.h:3832
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
Kind getKind() const
Definition TypeBase.h:3299
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:1553
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1696
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1693
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2890
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2734
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:2985
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3021
Represents a C++ deduction guide declaration.
Definition DeclCXX.h:2001
Represents a C++ destructor within a class.
Definition DeclCXX.h:2915
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2296
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition ExprCXX.cpp:2038
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:2201
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition ExprCXX.h:805
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:1178
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
SourceLocation getBeginLoc() const
Definition Expr.h:3346
bool isCallToStdMove() const
Definition Expr.cpp:3682
Expr * getCallee()
Definition Expr.h:3159
SourceLocation getRParenLoc() const
Definition Expr.h:3343
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3745
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:4460
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
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:376
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3934
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4649
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:2261
DeclContextLookupResult lookup_result
Definition DeclBase.h:2609
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:2405
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1519
ValueDecl * getDecl()
Definition Expr.h:1383
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:444
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:602
bool isInvalidDecl() const
Definition DeclBase.h:597
SourceLocation getLocation() const
Definition DeclBase.h:448
void setReferenced(bool R=true)
Definition DeclBase.h:632
DeclContext * getDeclContext()
Definition DeclBase.h:457
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:440
bool hasAttr() const
Definition DeclBase.h:586
The name of a declaration.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:833
Represents a single C99 designator.
Definition Expr.h:5680
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:5842
void setFieldDecl(FieldDecl *FD)
Definition Expr.h:5778
FieldDecl * getFieldDecl() const
Definition Expr.h:5771
SourceLocation getFieldLoc() const
Definition Expr.h:5788
const IdentifierInfo * getFieldName() const
Definition Expr.cpp:4835
SourceLocation getDotLoc() const
Definition Expr.h:5783
SourceLocation getLBracketLoc() const
Definition Expr.h:5824
Represents a C99 designated initializer expression.
Definition Expr.h:5637
bool isDirectInit() const
Whether this designated initializer should result in direct-initialization of the designated subobjec...
Definition Expr.h:5897
Expr * getArrayRangeEnd(const Designator &D) const
Definition Expr.cpp:4944
Expr * getSubExpr(unsigned Idx) const
Definition Expr.h:5919
bool usesGNUSyntax() const
Determines whether this designated initializer used the deprecated GNU syntax for designated initiali...
Definition Expr.h:5901
Expr * getArrayRangeStart(const Designator &D) const
Definition Expr.cpp:4939
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:4951
MutableArrayRef< Designator > designators()
Definition Expr.h:5870
Expr * getArrayIndex(const Designator &D) const
Definition Expr.cpp:4934
Designator * getDesignator(unsigned Idx)
Definition Expr.h:5878
Expr * getInit() const
Retrieve the initializer value.
Definition Expr.h:5905
unsigned size() const
Returns the number of designators in this initializer.
Definition Expr.h:5867
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:4913
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:4930
SourceLocation getEqualOrColonLoc() const
Retrieve the location of the '=' that precedes the initializer value itself, if present.
Definition Expr.h:5892
unsigned getNumSubExprs() const
Retrieve the total number of subexpressions in this designated initializer expression,...
Definition Expr.h:5917
static DesignatedInitExpr * Create(const ASTContext &C, ArrayRef< Designator > Designators, ArrayRef< Expr * > IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
Definition Expr.cpp:4876
InitListExpr * getUpdater() const
Definition Expr.h:6022
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:992
Represents a reference to emded data.
Definition Expr.h:5204
unsigned getStartingElementPos() const
Definition Expr.h:5225
StringLiteral * getDataStringLiteral() const
Definition Expr.h:5221
EmbedDataStorage * getData() const
Definition Expr.h:5223
fake_child_range underlying_data_elements()
Definition Expr.h:5287
SourceLocation getLocation() const
Definition Expr.h:5217
size_t getDataElementCount() const
Definition Expr.h:5226
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:4389
The return type of classify().
Definition Expr.h:341
bool isLValue() const
Definition Expr.h:392
bool isPRValue() const
Definition Expr.h:395
bool isXValue() const
Definition Expr.h:393
bool isRValue() const
Definition Expr.h:396
This represents one expression.
Definition Expr.h:114
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3134
void setType(QualType t)
Definition Expr.h:147
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:449
bool refersToVectorElement() const
Returns whether this expression refers to a vector element.
Definition Expr.cpp:4332
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
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:3129
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3117
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:248
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool isPRValue() const
Definition Expr.h:287
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:286
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3378
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:876
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:880
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:456
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:3728
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3109
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:3292
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:4110
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:466
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:519
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:481
QualType getType() const
Definition Expr.h:146
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3311
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3491
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4915
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3396
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3417
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:2071
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2944
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3912
QualType getReturnType() const
Definition Decl.h:2992
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2679
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2524
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3886
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:2109
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:626
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition Overload.h:677
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:681
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:831
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6143
Represents a C array with an unspecified size.
Definition TypeBase.h:4007
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3618
chain_iterator chain_end() const
Definition Decl.h:3641
chain_iterator chain_begin() const
Definition Decl.h:3640
ArrayRef< NamedDecl * >::const_iterator chain_iterator
Definition Decl.h:3637
Describes an C or C++ initializer list.
Definition Expr.h:5377
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition Expr.h:5501
void setSyntacticForm(InitListExpr *Init)
Definition Expr.h:5562
void markError()
Mark the semantic form of the InitListExpr as error when the semantic analysis fails.
Definition Expr.h:5463
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5504
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2501
bool hasOneInit() const
Whether getNumInitsWithEmbedExpanded() is 1, without walking the list.
Definition Expr.h:5425
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition Expr.cpp:2461
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition Expr.h:5515
unsigned getNumInits() const
Definition Expr.h:5410
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2535
void setInit(unsigned Init, Expr *expr)
Definition Expr.h:5453
bool hasZeroInits() const
Definition Expr.h:5422
SourceLocation getLBraceLoc() const
Definition Expr.h:5546
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:2465
void setArrayFiller(Expr *filler)
Definition Expr.cpp:2477
InitListExpr * getSyntacticForm() const
Definition Expr.h:5558
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5491
bool isExplicit() const
Definition Expr.h:5531
unsigned getNumInitsWithEmbedExpanded() const
getNumInits but if the list has an EmbedExpr inside includes full length of embedded data.
Definition Expr.h:5414
SourceLocation getRBraceLoc() const
Definition Expr.h:5548
InitListExpr * getSemanticForm() const
Definition Expr.h:5552
const Expr * getInit(unsigned Init) const
Definition Expr.h:5443
bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const
Is this the zero initializer {0} in a language which considers it idiomatic?
Definition Expr.cpp:2524
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2553
void setInitializedFieldInUnion(FieldDecl *FD)
Definition Expr.h:5521
bool isSyntacticForm() const
Definition Expr.h:5555
void setRBraceLoc(SourceLocation Loc)
Definition Expr.h:5549
ArrayRef< Expr * > inits() const
Definition Expr.h:5441
void sawArrayRangeDesignator(bool ARD=true)
Definition Expr.h:5572
Expr ** getInits()
Retrieve the set of initializers.
Definition Expr.h:5434
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:3715
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:4974
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4999
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4567
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4586
This represents a decl that may have a name.
Definition Decl.h:276
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:489
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
Represent a C++ namespace.
Definition Decl.h:594
Represents a place-holder for an object not to be initialized by anything.
Definition Expr.h:5963
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:1223
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:1164
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void setDestAS(LangAS AS)
Definition Overload.h:1494
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:1416
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1185
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1180
@ CSK_Normal
Normal lookup.
Definition Overload.h:1168
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1380
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:1353
Represents a parameter to a function.
Definition Decl.h:1832
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
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:8662
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8667
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3825
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:8578
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
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:8763
QualType getCanonicalType() const
Definition TypeBase.h:8630
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8651
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8699
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:3733
Represents a struct/union/class.
Definition Decl.h:4476
field_iterator field_end() const
Definition Decl.h:4682
field_range fields() const
Definition Decl.h:4679
bool isRandomized() const
Definition Decl.h:4634
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4660
bool hasUninitializedExplicitInitFields() const
Definition Decl.h:4602
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4676
bool field_empty() const
Definition Decl.h:4687
field_iterator field_begin() const
Definition Decl.cpp:5370
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3678
bool isSpelledAsLValue() const
Definition TypeBase.h:3691
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:862
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9507
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9515
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:10581
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10584
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10590
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10588
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:933
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7082
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:2106
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:1331
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:698
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:229
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:1543
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:769
ASTContext & getASTContext() const
Definition Sema.h:934
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:774
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:9187
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:927
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:1508
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition SemaExpr.cpp:80
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7118
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition Sema.h:10609
ExprResult BuildCXXAggregateDefaultInitExpr(SourceLocation Loc, FieldDecl *Field, const InitializedEntity &MemberEntity)
bool checkArrayTooLarge(QualType ElementType, const llvm::APSInt &NumElements, SourceLocation Loc, SourceRange Range=SourceRange())
Diagnose an array of NumElements elements of type ElementType that is too large.
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:8351
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
bool IsAssignConvertCompatible(AssignConvertType ConvTy)
Definition Sema.h:8218
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:7130
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1471
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:8343
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:14219
SourceManager & getSourceManager() const
Definition Sema.h:932
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:13940
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15765
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:128
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...
MultiExprArg getInitsWithEmbedExpanded(InitListExpr *ILE, SmallVectorImpl< Expr * > &Storage)
The initializers of ILE with each multi-element EmbedExpr split into one EmbedExpr per embedded eleme...
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:1334
TypeSourceInfo * SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
DiagnosticsEngine & Diags
Definition Sema.h:1333
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:928
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
friend class InitializationSequence
Definition Sema.h:1613
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:643
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:301
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:312
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition Overload.h:306
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:399
QualType getToType(unsigned Idx) const
Definition Overload.h:414
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:1844
unsigned getLength() const
Definition Expr.h:1969
StringLiteralKind getKind() const
Definition Expr.h:1973
int64_t getCodeUnitS(size_t I, uint64_t BitWidth) const
Definition Expr.h:1945
StringRef getString() const
Definition Expr.h:1912
bool isUnion() const
Definition Decl.h:4079
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:8549
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:8560
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9200
bool isBooleanType() const
Definition TypeBase.h:9341
bool isMFloat8Type() const
Definition TypeBase.h:9229
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9391
bool isIncompleteArrayType() const
Definition TypeBase.h:8922
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2392
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2299
bool isRValueReferenceType() const
Definition TypeBase.h:8847
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:8914
bool isCharType() const
Definition Type.cpp:2319
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isConstantMatrixType() const
Definition TypeBase.h:8982
bool isArrayParameterType() const
Definition TypeBase.h:8930
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isReferenceType() const
Definition TypeBase.h:8839
bool isEnumeralType() const
Definition TypeBase.h:8946
bool isScalarType() const
Definition TypeBase.h:9310
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:2080
bool isChar8Type() const
Definition Type.cpp:2335
bool isSizelessBuiltinType() const
Definition Type.cpp:2751
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isExtVectorType() const
Definition TypeBase.h:8958
bool isOCLIntelSubgroupAVCType() const
Definition TypeBase.h:9100
bool isLValueReferenceType() const
Definition TypeBase.h:8843
bool isOpenCLSpecificType() const
Definition TypeBase.h:9115
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2631
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8950
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2235
bool isQueueT() const
Definition TypeBase.h:9071
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9384
bool isAtomicType() const
Definition TypeBase.h:9007
bool isFunctionProtoType() const
Definition TypeBase.h:2665
bool isMatrixType() const
Definition TypeBase.h:8978
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isObjCObjectType() const
Definition TypeBase.h:8998
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9484
bool isEventT() const
Definition TypeBase.h:9063
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2655
bool isFunctionType() const
Definition TypeBase.h:8811
bool isObjCObjectPointerType() const
Definition TypeBase.h:8994
bool isVectorType() const
Definition TypeBase.h:8954
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2533
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3002
bool isFloatingType() const
Definition Type.cpp:2517
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:2460
bool isSamplerT() const
Definition TypeBase.h:9059
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:786
bool isNullPtrType() const
Definition TypeBase.h:9241
bool isRecordType() const
Definition TypeBase.h:8942
bool isObjCRetainableType() const
Definition Type.cpp:5609
bool isUnionType() const
Definition Type.cpp:851
DeclClass * getCorrectionDeclAs() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
const Expr * getInit() const
Definition Decl.h:1393
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1192
StorageDuration getStorageDuration() const
Get the storage duration of this variable, per C++ [basic.stc].
Definition Decl.h:1252
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4064
Represents a GCC generic vector type.
Definition TypeBase.h:4398
unsigned getNumElements() const
Definition TypeBase.h:4413
VectorKind getVectorKind() const
Definition TypeBase.h:4418
QualType getElementType() const
Definition TypeBase.h:4412
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:866
@ 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:1545
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:128
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:344
@ SD_Static
Static storage duration.
Definition Specifiers.h:345
@ SD_Automatic
Automatic storage duration (most local variables).
Definition Specifiers.h:343
@ 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:682
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:684
ExprResult ExprError()
Definition Ownership.h:265
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition Sema.h:216
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:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:148
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:143
Expr * IgnoreParensSingleStep(Expr *E)
Definition IgnoreExpr.h:157
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition Overload.h:277
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:279
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:285
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:293
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:282
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:289
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1306
U cast(CodeGen::Address addr)
Definition Address.h:327
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition Overload.h:1527
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Braces
New-expression has a C++11 list-initializer.
Definition ExprCXX.h:2253
CheckedConversionKind
The kind of conversion being performed.
Definition Sema.h:431
@ Implicit
An implicit conversion.
Definition Sema.h:433
@ CStyleCast
A C-style cast.
Definition Sema.h:435
@ OtherCast
A cast other than a C-style cast.
Definition Sema.h:439
@ FunctionalCast
A functional-style cast.
Definition Sema.h:437
unsigned long uint64_t
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 int64_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
CXXConstructorDecl * Constructor
Definition Overload.h:1519
DeclAccessPair FoundDecl
Definition Overload.h:1518
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:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:937
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1019
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:960
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:967
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6972
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:510