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