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