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
1901 // For HLSL, the error reporting for this case is handled in SemaHLSL's
1902 // initializer list diagnostics. That means the execution should require
1903 // getNumElementsFlattened to equal getNumInits. In other words the execution
1904 // should never reach this point if this condition is not true".
1905 assert(IList->getNumInits() == MT->getNumElementsFlattened() &&
1906 "Inits must equal Matrix element count");
1907
1908 QualType ElemTy = MT->getElementType();
1909
1910 Index = 0;
1911 InitializedEntity ElemEnt =
1913
1914 while (Index < IList->getNumInits()) {
1915 // Not a sublist: just consume directly.
1916 unsigned ColMajorIndex = (Index % MT->getNumRows()) * MT->getNumColumns() +
1917 (Index / MT->getNumRows());
1918 ElemEnt.setElementIndex(ColMajorIndex);
1919 CheckSubElementType(ElemEnt, IList, ElemTy, ColMajorIndex, StructuredList,
1920 StructuredIndex);
1921 ++Index;
1922 }
1923}
1924
1925void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1926 InitListExpr *IList, QualType DeclType,
1927 unsigned &Index,
1928 InitListExpr *StructuredList,
1929 unsigned &StructuredIndex) {
1930 const VectorType *VT = DeclType->castAs<VectorType>();
1931 unsigned maxElements = VT->getNumElements();
1932 unsigned numEltsInit = 0;
1933 QualType elementType = VT->getElementType();
1934
1935 if (Index >= IList->getNumInits()) {
1936 // Make sure the element type can be value-initialized.
1937 CheckEmptyInitializable(
1939 IList->getEndLoc());
1940 return;
1941 }
1942
1943 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1944 // If the initializing element is a vector, try to copy-initialize
1945 // instead of breaking it apart (which is doomed to failure anyway).
1946 Expr *Init = IList->getInit(Index);
1947 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1949 if (VerifyOnly) {
1950 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1951 Result = getDummyInit();
1952 else
1953 Result = ExprError();
1954 } else {
1955 Result =
1956 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1957 /*TopLevelOfInitList=*/true);
1958 }
1959
1960 Expr *ResultExpr = nullptr;
1961 if (Result.isInvalid())
1962 hadError = true; // types weren't compatible.
1963 else {
1964 ResultExpr = Result.getAs<Expr>();
1965
1966 if (ResultExpr != Init && !VerifyOnly) {
1967 // The type was promoted, update initializer list.
1968 // FIXME: Why are we updating the syntactic init list?
1969 IList->setInit(Index, ResultExpr);
1970 }
1971 }
1972 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1973 ++Index;
1974 if (AggrDeductionCandidateParamTypes)
1975 AggrDeductionCandidateParamTypes->push_back(elementType);
1976 return;
1977 }
1978
1979 InitializedEntity ElementEntity =
1981
1982 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1983 // Don't attempt to go past the end of the init list
1984 if (Index >= IList->getNumInits()) {
1985 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1986 break;
1987 }
1988
1989 ElementEntity.setElementIndex(Index);
1990 CheckSubElementType(ElementEntity, IList, elementType, Index,
1991 StructuredList, StructuredIndex);
1992 }
1993
1994 if (VerifyOnly)
1995 return;
1996
1997 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1998 const VectorType *T = Entity.getType()->castAs<VectorType>();
1999 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
2000 T->getVectorKind() == VectorKind::NeonPoly)) {
2001 // The ability to use vector initializer lists is a GNU vector extension
2002 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
2003 // endian machines it works fine, however on big endian machines it
2004 // exhibits surprising behaviour:
2005 //
2006 // uint32x2_t x = {42, 64};
2007 // return vget_lane_u32(x, 0); // Will return 64.
2008 //
2009 // Because of this, explicitly call out that it is non-portable.
2010 //
2011 SemaRef.Diag(IList->getBeginLoc(),
2012 diag::warn_neon_vector_initializer_non_portable);
2013
2014 const char *typeCode;
2015 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
2016
2017 if (elementType->isFloatingType())
2018 typeCode = "f";
2019 else if (elementType->isSignedIntegerType())
2020 typeCode = "s";
2021 else if (elementType->isUnsignedIntegerType())
2022 typeCode = "u";
2023 else if (elementType->isMFloat8Type())
2024 typeCode = "mf";
2025 else
2026 llvm_unreachable("Invalid element type!");
2027
2028 SemaRef.Diag(IList->getBeginLoc(),
2029 SemaRef.Context.getTypeSize(VT) > 64
2030 ? diag::note_neon_vector_initializer_non_portable_q
2031 : diag::note_neon_vector_initializer_non_portable)
2032 << typeCode << typeSize;
2033 }
2034
2035 return;
2036 }
2037
2038 InitializedEntity ElementEntity =
2040
2041 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
2042 for (unsigned i = 0; i < maxElements; ++i) {
2043 // Don't attempt to go past the end of the init list
2044 if (Index >= IList->getNumInits())
2045 break;
2046
2047 ElementEntity.setElementIndex(Index);
2048
2049 QualType IType = IList->getInit(Index)->getType();
2050 if (!IType->isVectorType()) {
2051 CheckSubElementType(ElementEntity, IList, elementType, Index,
2052 StructuredList, StructuredIndex);
2053 ++numEltsInit;
2054 } else {
2055 QualType VecType;
2056 const VectorType *IVT = IType->castAs<VectorType>();
2057 unsigned numIElts = IVT->getNumElements();
2058
2059 if (IType->isExtVectorType())
2060 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
2061 else
2062 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
2063 IVT->getVectorKind());
2064 CheckSubElementType(ElementEntity, IList, VecType, Index,
2065 StructuredList, StructuredIndex);
2066 numEltsInit += numIElts;
2067 }
2068 }
2069
2070 // OpenCL and HLSL require all elements to be initialized.
2071 if (numEltsInit != maxElements) {
2072 if (!VerifyOnly)
2073 SemaRef.Diag(IList->getBeginLoc(),
2074 diag::err_vector_incorrect_num_elements)
2075 << (numEltsInit < maxElements) << maxElements << numEltsInit
2076 << /*initialization*/ 0;
2077 hadError = true;
2078 }
2079}
2080
2081/// Check if the type of a class element has an accessible destructor, and marks
2082/// it referenced. Returns true if we shouldn't form a reference to the
2083/// destructor.
2084///
2085/// Aggregate initialization requires a class element's destructor be
2086/// accessible per 11.6.1 [dcl.init.aggr]:
2087///
2088/// The destructor for each element of class type is potentially invoked
2089/// (15.4 [class.dtor]) from the context where the aggregate initialization
2090/// occurs.
2092 Sema &SemaRef) {
2093 auto *CXXRD = ElementType->getAsCXXRecordDecl();
2094 if (!CXXRD)
2095 return false;
2096
2098 if (!Destructor)
2099 return false;
2100
2101 SemaRef.CheckDestructorAccess(Loc, Destructor,
2102 SemaRef.PDiag(diag::err_access_dtor_temp)
2103 << ElementType);
2104 SemaRef.MarkFunctionReferenced(Loc, Destructor);
2105 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
2106}
2107
2108static bool
2110 const InitializedEntity &Entity,
2111 ASTContext &Context) {
2112 QualType InitType = Entity.getType();
2113 const InitializedEntity *Parent = &Entity;
2114
2115 while (Parent) {
2116 InitType = Parent->getType();
2117 Parent = Parent->getParent();
2118 }
2119
2120 // Only one initializer, it's an embed and the types match;
2121 EmbedExpr *EE =
2122 ExprList.size() == 1
2123 ? dyn_cast_if_present<EmbedExpr>(ExprList[0]->IgnoreParens())
2124 : nullptr;
2125 if (!EE)
2126 return false;
2127
2128 if (InitType->isArrayType()) {
2129 const ArrayType *InitArrayType = InitType->getAsArrayTypeUnsafe();
2131 return IsStringInit(SL, InitArrayType, Context) == SIF_None;
2132 }
2133 return false;
2134}
2135
2136void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
2137 InitListExpr *IList, QualType &DeclType,
2138 llvm::APSInt elementIndex,
2139 bool SubobjectIsDesignatorContext,
2140 unsigned &Index,
2141 InitListExpr *StructuredList,
2142 unsigned &StructuredIndex) {
2143 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
2144
2145 if (!VerifyOnly) {
2146 if (checkDestructorReference(arrayType->getElementType(),
2147 IList->getEndLoc(), SemaRef)) {
2148 hadError = true;
2149 return;
2150 }
2151 }
2152
2153 if (canInitializeArrayWithEmbedDataString(IList->inits(), Entity,
2154 SemaRef.Context)) {
2155 EmbedExpr *Embed = cast<EmbedExpr>(IList->inits()[0]);
2156 IList->setInit(0, Embed->getDataStringLiteral());
2157 }
2158
2159 // Check for the special-case of initializing an array with a string.
2160 if (Index < IList->getNumInits()) {
2161 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
2162 SIF_None) {
2163 // We place the string literal directly into the resulting
2164 // initializer list. This is the only place where the structure
2165 // of the structured initializer list doesn't match exactly,
2166 // because doing so would involve allocating one character
2167 // constant for each string.
2168 // FIXME: Should we do these checks in verify-only mode too?
2169 if (!VerifyOnly)
2171 IList->getInit(Index), DeclType, arrayType, SemaRef, Entity,
2172 SemaRef.getLangOpts().C23 && initializingConstexprVariable(Entity));
2173 if (StructuredList) {
2174 UpdateStructuredListElement(StructuredList, StructuredIndex,
2175 IList->getInit(Index));
2176 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
2177 }
2178 ++Index;
2179 if (AggrDeductionCandidateParamTypes)
2180 AggrDeductionCandidateParamTypes->push_back(DeclType);
2181 return;
2182 }
2183 }
2184 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
2185 // Check for VLAs; in standard C it would be possible to check this
2186 // earlier, but I don't know where clang accepts VLAs (gcc accepts
2187 // them in all sorts of strange places).
2188 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
2189 if (!VerifyOnly) {
2190 // C23 6.7.10p4: An entity of variable length array type shall not be
2191 // initialized except by an empty initializer.
2192 //
2193 // The C extension warnings are issued from ParseBraceInitializer() and
2194 // do not need to be issued here. However, we continue to issue an error
2195 // in the case there are initializers or we are compiling C++. We allow
2196 // use of VLAs in C++, but it's not clear we want to allow {} to zero
2197 // init a VLA in C++ in all cases (such as with non-trivial constructors).
2198 // FIXME: should we allow this construct in C++ when it makes sense to do
2199 // so?
2200 if (HasErr)
2201 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
2202 diag::err_variable_object_no_init)
2203 << VAT->getSizeExpr()->getSourceRange();
2204 }
2205 hadError = HasErr;
2206 ++Index;
2207 ++StructuredIndex;
2208 return;
2209 }
2210
2211 // We might know the maximum number of elements in advance.
2212 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2213 elementIndex.isUnsigned());
2214 bool maxElementsKnown = false;
2215 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
2216 maxElements = CAT->getSize();
2217 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
2218 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2219 maxElementsKnown = true;
2220 }
2221
2222 QualType elementType = arrayType->getElementType();
2223 while (Index < IList->getNumInits()) {
2224 Expr *Init = IList->getInit(Index);
2225 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2226 // If we're not the subobject that matches up with the '{' for
2227 // the designator, we shouldn't be handling the
2228 // designator. Return immediately.
2229 if (!SubobjectIsDesignatorContext)
2230 return;
2231
2232 // Handle this designated initializer. elementIndex will be
2233 // updated to be the next array element we'll initialize.
2234 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2235 DeclType, nullptr, &elementIndex, Index,
2236 StructuredList, StructuredIndex, true,
2237 false)) {
2238 hadError = true;
2239 continue;
2240 }
2241
2242 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2243 maxElements = maxElements.extend(elementIndex.getBitWidth());
2244 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2245 elementIndex = elementIndex.extend(maxElements.getBitWidth());
2246 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2247
2248 // If the array is of incomplete type, keep track of the number of
2249 // elements in the initializer.
2250 if (!maxElementsKnown && elementIndex > maxElements)
2251 maxElements = elementIndex;
2252
2253 continue;
2254 }
2255
2256 // If we know the maximum number of elements, and we've already
2257 // hit it, stop consuming elements in the initializer list.
2258 if (maxElementsKnown && elementIndex == maxElements)
2259 break;
2260
2261 InitializedEntity ElementEntity = InitializedEntity::InitializeElement(
2262 SemaRef.Context, StructuredIndex, Entity);
2263 ElementEntity.setElementIndex(elementIndex.getExtValue());
2264
2265 unsigned EmbedElementIndexBeforeInit = CurEmbedIndex;
2266 // Check this element.
2267 CheckSubElementType(ElementEntity, IList, elementType, Index,
2268 StructuredList, StructuredIndex);
2269 ++elementIndex;
2270 if ((CurEmbed || isa<EmbedExpr>(Init)) && elementType->isScalarType()) {
2271 if (CurEmbed) {
2272 elementIndex =
2273 elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1;
2274 } else {
2275 auto Embed = cast<EmbedExpr>(Init);
2276 elementIndex = elementIndex + Embed->getDataElementCount() -
2277 EmbedElementIndexBeforeInit - 1;
2278 }
2279 }
2280
2281 // If the array is of incomplete type, keep track of the number of
2282 // elements in the initializer.
2283 if (!maxElementsKnown && elementIndex > maxElements)
2284 maxElements = elementIndex;
2285 }
2286 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2287 // If this is an incomplete array type, the actual type needs to
2288 // be calculated here.
2289 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2290 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2291 // Sizing an array implicitly to zero is not allowed by ISO C,
2292 // but is supported by GNU.
2293 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2294 }
2295
2296 DeclType = SemaRef.Context.getConstantArrayType(
2297 elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2298 }
2299 if (!hadError) {
2300 // If there are any members of the array that get value-initialized, check
2301 // that is possible. That happens if we know the bound and don't have
2302 // enough elements, or if we're performing an array new with an unknown
2303 // bound.
2304 if ((maxElementsKnown && elementIndex < maxElements) ||
2305 Entity.isVariableLengthArrayNew())
2306 CheckEmptyInitializable(
2308 IList->getEndLoc());
2309 }
2310}
2311
2312bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2313 Expr *InitExpr,
2314 FieldDecl *Field,
2315 bool TopLevelObject) {
2316 // Handle GNU flexible array initializers.
2317 unsigned FlexArrayDiag;
2318 if (isa<InitListExpr>(InitExpr) &&
2319 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2320 // Empty flexible array init always allowed as an extension
2321 FlexArrayDiag = diag::ext_flexible_array_init;
2322 } else if (!TopLevelObject) {
2323 // Disallow flexible array init on non-top-level object
2324 FlexArrayDiag = diag::err_flexible_array_init;
2325 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2326 // Disallow flexible array init on anything which is not a variable.
2327 FlexArrayDiag = diag::err_flexible_array_init;
2328 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2329 // Disallow flexible array init on local variables.
2330 FlexArrayDiag = diag::err_flexible_array_init;
2331 } else {
2332 // Allow other cases.
2333 FlexArrayDiag = diag::ext_flexible_array_init;
2334 }
2335
2336 if (!VerifyOnly) {
2337 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2338 << InitExpr->getBeginLoc();
2339 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2340 << Field;
2341 }
2342
2343 return FlexArrayDiag != diag::ext_flexible_array_init;
2344}
2345
2346static bool isInitializedStructuredList(const InitListExpr *StructuredList) {
2347 return StructuredList && StructuredList->getNumInits() == 1U;
2348}
2349
2350void InitListChecker::CheckStructUnionTypes(
2351 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2353 bool SubobjectIsDesignatorContext, unsigned &Index,
2354 InitListExpr *StructuredList, unsigned &StructuredIndex,
2355 bool TopLevelObject) {
2356 const RecordDecl *RD = DeclType->getAsRecordDecl();
2357
2358 // If the record is invalid, some of it's members are invalid. To avoid
2359 // confusion, we forgo checking the initializer for the entire record.
2360 if (RD->isInvalidDecl()) {
2361 // Assume it was supposed to consume a single initializer.
2362 ++Index;
2363 hadError = true;
2364 return;
2365 }
2366
2367 if (RD->isUnion() && IList->getNumInits() == 0) {
2368 if (!VerifyOnly)
2369 for (FieldDecl *FD : RD->fields()) {
2370 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2371 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2372 hadError = true;
2373 return;
2374 }
2375 }
2376
2377 // If there's a default initializer, use it.
2378 if (isa<CXXRecordDecl>(RD) &&
2379 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2380 if (!StructuredList)
2381 return;
2382 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2383 Field != FieldEnd; ++Field) {
2384 if (Field->hasInClassInitializer() ||
2385 (Field->isAnonymousStructOrUnion() &&
2386 Field->getType()
2387 ->castAsCXXRecordDecl()
2388 ->hasInClassInitializer())) {
2389 StructuredList->setInitializedFieldInUnion(*Field);
2390 // FIXME: Actually build a CXXDefaultInitExpr?
2391 return;
2392 }
2393 }
2394 llvm_unreachable("Couldn't find in-class initializer");
2395 }
2396
2397 // Value-initialize the first member of the union that isn't an unnamed
2398 // bitfield.
2399 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2400 Field != FieldEnd; ++Field) {
2401 if (!Field->isUnnamedBitField()) {
2402 CheckEmptyInitializable(
2403 InitializedEntity::InitializeMember(*Field, &Entity),
2404 IList->getEndLoc());
2405 if (StructuredList)
2406 StructuredList->setInitializedFieldInUnion(*Field);
2407 break;
2408 }
2409 }
2410 return;
2411 }
2412
2413 bool InitializedSomething = false;
2414
2415 // If we have any base classes, they are initialized prior to the fields.
2416 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2417 auto &Base = *I;
2418 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2419
2420 // Designated inits always initialize fields, so if we see one, all
2421 // remaining base classes have no explicit initializer.
2422 if (isa_and_nonnull<DesignatedInitExpr>(Init))
2423 Init = nullptr;
2424
2425 // C++ [over.match.class.deduct]p1.6:
2426 // each non-trailing aggregate element that is a pack expansion is assumed
2427 // to correspond to no elements of the initializer list, and (1.7) a
2428 // trailing aggregate element that is a pack expansion is assumed to
2429 // correspond to all remaining elements of the initializer list (if any).
2430
2431 // C++ [over.match.class.deduct]p1.9:
2432 // ... except that additional parameter packs of the form P_j... are
2433 // inserted into the parameter list in their original aggregate element
2434 // position corresponding to each non-trailing aggregate element of
2435 // type P_j that was skipped because it was a parameter pack, and the
2436 // trailing sequence of parameters corresponding to a trailing
2437 // aggregate element that is a pack expansion (if any) is replaced
2438 // by a single parameter of the form T_n....
2439 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2440 AggrDeductionCandidateParamTypes->push_back(
2441 SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2442
2443 // Trailing pack expansion
2444 if (I + 1 == E && RD->field_empty()) {
2445 if (Index < IList->getNumInits())
2446 Index = IList->getNumInits();
2447 return;
2448 }
2449
2450 continue;
2451 }
2452
2453 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2454 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2455 SemaRef.Context, &Base, false, &Entity);
2456 if (Init) {
2457 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2458 StructuredList, StructuredIndex);
2459 InitializedSomething = true;
2460 } else {
2461 CheckEmptyInitializable(BaseEntity, InitLoc);
2462 }
2463
2464 if (!VerifyOnly)
2465 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2466 hadError = true;
2467 return;
2468 }
2469 }
2470
2471 // If structDecl is a forward declaration, this loop won't do
2472 // anything except look at designated initializers; That's okay,
2473 // because an error should get printed out elsewhere. It might be
2474 // worthwhile to skip over the rest of the initializer, though.
2475 RecordDecl::field_iterator FieldEnd = RD->field_end();
2476 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2477 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2478 });
2479 bool HasDesignatedInit = false;
2480
2481 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2482
2483 while (Index < IList->getNumInits()) {
2484 Expr *Init = IList->getInit(Index);
2485 SourceLocation InitLoc = Init->getBeginLoc();
2486
2487 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2488 // If we're not the subobject that matches up with the '{' for
2489 // the designator, we shouldn't be handling the
2490 // designator. Return immediately.
2491 if (!SubobjectIsDesignatorContext)
2492 return;
2493
2494 HasDesignatedInit = true;
2495
2496 // Handle this designated initializer. Field will be updated to
2497 // the next field that we'll be initializing.
2498 bool DesignatedInitFailed = CheckDesignatedInitializer(
2499 Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2500 StructuredList, StructuredIndex, true, TopLevelObject);
2501 if (DesignatedInitFailed)
2502 hadError = true;
2503
2504 // Find the field named by the designated initializer.
2505 DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2506 if (!VerifyOnly && D->isFieldDesignator()) {
2507 FieldDecl *F = D->getFieldDecl();
2508 InitializedFields.insert(F);
2509 if (!DesignatedInitFailed) {
2510 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2511 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2512 hadError = true;
2513 return;
2514 }
2515 }
2516 }
2517
2518 InitializedSomething = true;
2519 continue;
2520 }
2521
2522 // Check if this is an initializer of forms:
2523 //
2524 // struct foo f = {};
2525 // struct foo g = {0};
2526 //
2527 // These are okay for randomized structures. [C99 6.7.8p19]
2528 //
2529 // Also, if there is only one element in the structure, we allow something
2530 // like this, because it's really not randomized in the traditional sense.
2531 //
2532 // struct foo h = {bar};
2533 auto IsZeroInitializer = [&](const Expr *I) {
2534 if (IList->getNumInits() == 1) {
2535 if (NumRecordDecls == 1)
2536 return true;
2537 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2538 return IL->getValue().isZero();
2539 }
2540 return false;
2541 };
2542
2543 // Don't allow non-designated initializers on randomized structures.
2544 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2545 if (!VerifyOnly)
2546 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2547 hadError = true;
2548 break;
2549 }
2550
2551 if (Field == FieldEnd) {
2552 // We've run out of fields. We're done.
2553 break;
2554 }
2555
2556 // We've already initialized a member of a union. We can stop entirely.
2557 if (InitializedSomething && RD->isUnion())
2558 return;
2559
2560 // Stop if we've hit a flexible array member.
2561 if (Field->getType()->isIncompleteArrayType())
2562 break;
2563
2564 if (Field->isUnnamedBitField()) {
2565 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2566 ++Field;
2567 continue;
2568 }
2569
2570 // Make sure we can use this declaration.
2571 bool InvalidUse;
2572 if (VerifyOnly)
2573 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2574 else
2575 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2576 *Field, IList->getInit(Index)->getBeginLoc());
2577 if (InvalidUse) {
2578 ++Index;
2579 ++Field;
2580 hadError = true;
2581 continue;
2582 }
2583
2584 if (!VerifyOnly) {
2585 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2586 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2587 hadError = true;
2588 return;
2589 }
2590 }
2591
2592 InitializedEntity MemberEntity =
2593 InitializedEntity::InitializeMember(*Field, &Entity);
2594 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2595 StructuredList, StructuredIndex);
2596 InitializedSomething = true;
2597 InitializedFields.insert(*Field);
2598 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2599 // Initialize the first field within the union.
2600 StructuredList->setInitializedFieldInUnion(*Field);
2601 }
2602
2603 ++Field;
2604 }
2605
2606 // Emit warnings for missing struct field initializers.
2607 // This check is disabled for designated initializers in C.
2608 // This matches gcc behaviour.
2609 bool IsCDesignatedInitializer =
2610 HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2611 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2612 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
2613 !IsCDesignatedInitializer) {
2614 // It is possible we have one or more unnamed bitfields remaining.
2615 // Find first (if any) named field and emit warning.
2616 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2617 : Field,
2618 end = RD->field_end();
2619 it != end; ++it) {
2620 if (HasDesignatedInit && InitializedFields.count(*it))
2621 continue;
2622
2623 if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2624 !it->getType()->isIncompleteArrayType()) {
2625 auto Diag = HasDesignatedInit
2626 ? diag::warn_missing_designated_field_initializers
2627 : diag::warn_missing_field_initializers;
2628 SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;
2629 break;
2630 }
2631 }
2632 }
2633
2634 // Check that any remaining fields can be value-initialized if we're not
2635 // building a structured list. (If we are, we'll check this later.)
2636 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2637 !Field->getType()->isIncompleteArrayType()) {
2638 for (; Field != FieldEnd && !hadError; ++Field) {
2639 if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())
2640 CheckEmptyInitializable(
2641 InitializedEntity::InitializeMember(*Field, &Entity),
2642 IList->getEndLoc());
2643 }
2644 }
2645
2646 // Check that the types of the remaining fields have accessible destructors.
2647 if (!VerifyOnly) {
2648 // If the initializer expression has a designated initializer, check the
2649 // elements for which a designated initializer is not provided too.
2650 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2651 : Field;
2652 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2653 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2654 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2655 hadError = true;
2656 return;
2657 }
2658 }
2659 }
2660
2661 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2662 Index >= IList->getNumInits())
2663 return;
2664
2665 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2666 TopLevelObject)) {
2667 hadError = true;
2668 ++Index;
2669 return;
2670 }
2671
2672 InitializedEntity MemberEntity =
2673 InitializedEntity::InitializeMember(*Field, &Entity);
2674
2675 if (isa<InitListExpr>(IList->getInit(Index)) ||
2676 AggrDeductionCandidateParamTypes)
2677 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2678 StructuredList, StructuredIndex);
2679 else
2680 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2681 StructuredList, StructuredIndex);
2682
2683 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2684 // Initialize the first field within the union.
2685 StructuredList->setInitializedFieldInUnion(*Field);
2686 }
2687}
2688
2689/// Expand a field designator that refers to a member of an
2690/// anonymous struct or union into a series of field designators that
2691/// refers to the field within the appropriate subobject.
2692///
2694 DesignatedInitExpr *DIE,
2695 unsigned DesigIdx,
2696 IndirectFieldDecl *IndirectField) {
2698
2699 // Build the replacement designators.
2700 SmallVector<Designator, 4> Replacements;
2701 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2702 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2703 if (PI + 1 == PE)
2704 Replacements.push_back(Designator::CreateFieldDesignator(
2705 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2706 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2707 else
2708 Replacements.push_back(Designator::CreateFieldDesignator(
2709 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2710 assert(isa<FieldDecl>(*PI));
2711 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2712 }
2713
2714 // Expand the current designator into the set of replacement
2715 // designators, so we have a full subobject path down to where the
2716 // member of the anonymous struct/union is actually stored.
2717 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2718 &Replacements[0] + Replacements.size());
2719}
2720
2722 DesignatedInitExpr *DIE) {
2723 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2724 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2725 for (unsigned I = 0; I < NumIndexExprs; ++I)
2726 IndexExprs[I] = DIE->getSubExpr(I + 1);
2727 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2728 IndexExprs,
2729 DIE->getEqualOrColonLoc(),
2730 DIE->usesGNUSyntax(), DIE->getInit());
2731}
2732
2733namespace {
2734
2735// Callback to only accept typo corrections that are for field members of
2736// the given struct or union.
2737class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2738 public:
2739 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2740 : Record(RD) {}
2741
2742 bool ValidateCandidate(const TypoCorrection &candidate) override {
2743 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2744 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2745 }
2746
2747 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2748 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2749 }
2750
2751 private:
2752 const RecordDecl *Record;
2753};
2754
2755} // end anonymous namespace
2756
2757/// Check the well-formedness of a C99 designated initializer.
2758///
2759/// Determines whether the designated initializer @p DIE, which
2760/// resides at the given @p Index within the initializer list @p
2761/// IList, is well-formed for a current object of type @p DeclType
2762/// (C99 6.7.8). The actual subobject that this designator refers to
2763/// within the current subobject is returned in either
2764/// @p NextField or @p NextElementIndex (whichever is appropriate).
2765///
2766/// @param IList The initializer list in which this designated
2767/// initializer occurs.
2768///
2769/// @param DIE The designated initializer expression.
2770///
2771/// @param DesigIdx The index of the current designator.
2772///
2773/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2774/// into which the designation in @p DIE should refer.
2775///
2776/// @param NextField If non-NULL and the first designator in @p DIE is
2777/// a field, this will be set to the field declaration corresponding
2778/// to the field named by the designator. On input, this is expected to be
2779/// the next field that would be initialized in the absence of designation,
2780/// if the complete object being initialized is a struct.
2781///
2782/// @param NextElementIndex If non-NULL and the first designator in @p
2783/// DIE is an array designator or GNU array-range designator, this
2784/// will be set to the last index initialized by this designator.
2785///
2786/// @param Index Index into @p IList where the designated initializer
2787/// @p DIE occurs.
2788///
2789/// @param StructuredList The initializer list expression that
2790/// describes all of the subobject initializers in the order they'll
2791/// actually be initialized.
2792///
2793/// @returns true if there was an error, false otherwise.
2794bool
2795InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2796 InitListExpr *IList,
2797 DesignatedInitExpr *DIE,
2798 unsigned DesigIdx,
2799 QualType &CurrentObjectType,
2800 RecordDecl::field_iterator *NextField,
2801 llvm::APSInt *NextElementIndex,
2802 unsigned &Index,
2803 InitListExpr *StructuredList,
2804 unsigned &StructuredIndex,
2805 bool FinishSubobjectInit,
2806 bool TopLevelObject) {
2807 if (DesigIdx == DIE->size()) {
2808 // C++20 designated initialization can result in direct-list-initialization
2809 // of the designated subobject. This is the only way that we can end up
2810 // performing direct initialization as part of aggregate initialization, so
2811 // it needs special handling.
2812 if (DIE->isDirectInit()) {
2813 Expr *Init = DIE->getInit();
2814 assert(isa<InitListExpr>(Init) &&
2815 "designator result in direct non-list initialization?");
2816 InitializationKind Kind = InitializationKind::CreateDirectList(
2817 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2818 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2819 /*TopLevelOfInitList*/ true);
2820 if (StructuredList) {
2821 ExprResult Result = VerifyOnly
2822 ? getDummyInit()
2823 : Seq.Perform(SemaRef, Entity, Kind, Init);
2824 UpdateStructuredListElement(StructuredList, StructuredIndex,
2825 Result.get());
2826 }
2827 ++Index;
2828 if (AggrDeductionCandidateParamTypes)
2829 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2830 return !Seq;
2831 }
2832
2833 // Check the actual initialization for the designated object type.
2834 bool prevHadError = hadError;
2835
2836 // Temporarily remove the designator expression from the
2837 // initializer list that the child calls see, so that we don't try
2838 // to re-process the designator.
2839 unsigned OldIndex = Index;
2840 auto *OldDIE =
2841 dyn_cast_if_present<DesignatedInitExpr>(IList->getInit(OldIndex));
2842 if (!OldDIE)
2843 OldDIE = DIE;
2844 IList->setInit(OldIndex, OldDIE->getInit());
2845
2846 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2847 StructuredIndex, /*DirectlyDesignated=*/true);
2848
2849 // Restore the designated initializer expression in the syntactic
2850 // form of the initializer list.
2851 if (IList->getInit(OldIndex) != OldDIE->getInit())
2852 OldDIE->setInit(IList->getInit(OldIndex));
2853 IList->setInit(OldIndex, OldDIE);
2854
2855 return hadError && !prevHadError;
2856 }
2857
2858 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2859 bool IsFirstDesignator = (DesigIdx == 0);
2860 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2861 // Determine the structural initializer list that corresponds to the
2862 // current subobject.
2863 if (IsFirstDesignator)
2864 StructuredList = FullyStructuredList;
2865 else {
2866 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2867 StructuredList->getInit(StructuredIndex) : nullptr;
2868 if (!ExistingInit && StructuredList->hasArrayFiller())
2869 ExistingInit = StructuredList->getArrayFiller();
2870
2871 if (!ExistingInit)
2872 StructuredList = getStructuredSubobjectInit(
2873 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2874 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2875 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2876 StructuredList = Result;
2877 else {
2878 // We are creating an initializer list that initializes the
2879 // subobjects of the current object, but there was already an
2880 // initialization that completely initialized the current
2881 // subobject, e.g., by a compound literal:
2882 //
2883 // struct X { int a, b; };
2884 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2885 //
2886 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2887 // designated initializer re-initializes only its current object
2888 // subobject [0].b.
2889 diagnoseInitOverride(ExistingInit,
2890 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2891 /*UnionOverride=*/false,
2892 /*FullyOverwritten=*/false);
2893
2894 if (!VerifyOnly) {
2895 if (DesignatedInitUpdateExpr *E =
2896 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2897 StructuredList = E->getUpdater();
2898 else {
2899 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2900 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2901 ExistingInit, DIE->getEndLoc());
2902 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2903 StructuredList = DIUE->getUpdater();
2904 }
2905 } else {
2906 // We don't need to track the structured representation of a
2907 // designated init update of an already-fully-initialized object in
2908 // verify-only mode. The only reason we would need the structure is
2909 // to determine where the uninitialized "holes" are, and in this
2910 // case, we know there aren't any and we can't introduce any.
2911 StructuredList = nullptr;
2912 }
2913 }
2914 }
2915 }
2916
2917 if (D->isFieldDesignator()) {
2918 // C99 6.7.8p7:
2919 //
2920 // If a designator has the form
2921 //
2922 // . identifier
2923 //
2924 // then the current object (defined below) shall have
2925 // structure or union type and the identifier shall be the
2926 // name of a member of that type.
2927 RecordDecl *RD = CurrentObjectType->getAsRecordDecl();
2928 if (!RD) {
2929 SourceLocation Loc = D->getDotLoc();
2930 if (Loc.isInvalid())
2931 Loc = D->getFieldLoc();
2932 if (!VerifyOnly)
2933 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2934 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2935 ++Index;
2936 return true;
2937 }
2938
2939 FieldDecl *KnownField = D->getFieldDecl();
2940 if (!KnownField) {
2941 const IdentifierInfo *FieldName = D->getFieldName();
2942 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2943 if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2944 KnownField = FD;
2945 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2946 // In verify mode, don't modify the original.
2947 if (VerifyOnly)
2948 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2949 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2950 D = DIE->getDesignator(DesigIdx);
2951 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2952 }
2953 if (!KnownField) {
2954 if (VerifyOnly) {
2955 ++Index;
2956 return true; // No typo correction when just trying this out.
2957 }
2958
2959 // We found a placeholder variable
2960 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2961 FieldName)) {
2962 ++Index;
2963 return true;
2964 }
2965 // Name lookup found something, but it wasn't a field.
2966 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2967 !Lookup.empty()) {
2968 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2969 << FieldName;
2970 SemaRef.Diag(Lookup.front()->getLocation(),
2971 diag::note_field_designator_found);
2972 ++Index;
2973 return true;
2974 }
2975
2976 // Name lookup didn't find anything.
2977 // Determine whether this was a typo for another field name.
2978 FieldInitializerValidatorCCC CCC(RD);
2979 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2980 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2981 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2982 CorrectTypoKind::ErrorRecovery, RD)) {
2983 SemaRef.diagnoseTypo(
2984 Corrected,
2985 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2986 << FieldName << CurrentObjectType);
2987 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2988 hadError = true;
2989 } else {
2990 // Typo correction didn't find anything.
2991 SourceLocation Loc = D->getFieldLoc();
2992
2993 // The loc can be invalid with a "null" designator (i.e. an anonymous
2994 // union/struct). Do our best to approximate the location.
2995 if (Loc.isInvalid())
2996 Loc = IList->getBeginLoc();
2997
2998 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
2999 << FieldName << CurrentObjectType << DIE->getSourceRange();
3000 ++Index;
3001 return true;
3002 }
3003 }
3004 }
3005
3006 unsigned NumBases = 0;
3007 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3008 NumBases = CXXRD->getNumBases();
3009
3010 unsigned FieldIndex = NumBases;
3011
3012 for (auto *FI : RD->fields()) {
3013 if (FI->isUnnamedBitField())
3014 continue;
3015 if (declaresSameEntity(KnownField, FI)) {
3016 KnownField = FI;
3017 break;
3018 }
3019 ++FieldIndex;
3020 }
3021
3023 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
3024
3025 // All of the fields of a union are located at the same place in
3026 // the initializer list.
3027 if (RD->isUnion()) {
3028 FieldIndex = 0;
3029 if (StructuredList) {
3030 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
3031 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
3032 assert(StructuredList->getNumInits() == 1
3033 && "A union should never have more than one initializer!");
3034
3035 Expr *ExistingInit = StructuredList->getInit(0);
3036 if (ExistingInit) {
3037 // We're about to throw away an initializer, emit warning.
3038 diagnoseInitOverride(
3039 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
3040 /*UnionOverride=*/true,
3041 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
3042 : true);
3043 }
3044
3045 // remove existing initializer
3046 StructuredList->resizeInits(SemaRef.Context, 0);
3047 StructuredList->setInitializedFieldInUnion(nullptr);
3048 }
3049
3050 StructuredList->setInitializedFieldInUnion(*Field);
3051 }
3052 }
3053
3054 // Make sure we can use this declaration.
3055 bool InvalidUse;
3056 if (VerifyOnly)
3057 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
3058 else
3059 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
3060 if (InvalidUse) {
3061 ++Index;
3062 return true;
3063 }
3064
3065 // C++20 [dcl.init.list]p3:
3066 // The ordered identifiers in the designators of the designated-
3067 // initializer-list shall form a subsequence of the ordered identifiers
3068 // in the direct non-static data members of T.
3069 //
3070 // Note that this is not a condition on forming the aggregate
3071 // initialization, only on actually performing initialization,
3072 // so it is not checked in VerifyOnly mode.
3073 //
3074 // FIXME: This is the only reordering diagnostic we produce, and it only
3075 // catches cases where we have a top-level field designator that jumps
3076 // backwards. This is the only such case that is reachable in an
3077 // otherwise-valid C++20 program, so is the only case that's required for
3078 // conformance, but for consistency, we should diagnose all the other
3079 // cases where a designator takes us backwards too.
3080 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
3081 NextField &&
3082 (*NextField == RD->field_end() ||
3083 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
3084 // Find the field that we just initialized.
3085 FieldDecl *PrevField = nullptr;
3086 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
3087 if (FI->isUnnamedBitField())
3088 continue;
3089 if (*NextField != RD->field_end() &&
3090 declaresSameEntity(*FI, **NextField))
3091 break;
3092 PrevField = *FI;
3093 }
3094
3095 if (PrevField &&
3096 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
3097 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3098 diag::ext_designated_init_reordered)
3099 << KnownField << PrevField << DIE->getSourceRange();
3100
3101 unsigned OldIndex = StructuredIndex - 1;
3102 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
3103 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
3104 SemaRef.Diag(PrevInit->getBeginLoc(),
3105 diag::note_previous_field_init)
3106 << PrevField << PrevInit->getSourceRange();
3107 }
3108 }
3109 }
3110 }
3111
3112
3113 // Update the designator with the field declaration.
3114 if (!VerifyOnly)
3115 D->setFieldDecl(*Field);
3116
3117 // Make sure that our non-designated initializer list has space
3118 // for a subobject corresponding to this field.
3119 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
3120 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
3121
3122 // This designator names a flexible array member.
3123 if (Field->getType()->isIncompleteArrayType()) {
3124 bool Invalid = false;
3125 if ((DesigIdx + 1) != DIE->size()) {
3126 // We can't designate an object within the flexible array
3127 // member (because GCC doesn't allow it).
3128 if (!VerifyOnly) {
3129 DesignatedInitExpr::Designator *NextD
3130 = DIE->getDesignator(DesigIdx + 1);
3131 SemaRef.Diag(NextD->getBeginLoc(),
3132 diag::err_designator_into_flexible_array_member)
3133 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
3134 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3135 << *Field;
3136 }
3137 Invalid = true;
3138 }
3139
3140 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
3141 !isa<StringLiteral>(DIE->getInit())) {
3142 // The initializer is not an initializer list.
3143 if (!VerifyOnly) {
3144 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3145 diag::err_flexible_array_init_needs_braces)
3146 << DIE->getInit()->getSourceRange();
3147 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3148 << *Field;
3149 }
3150 Invalid = true;
3151 }
3152
3153 // Check GNU flexible array initializer.
3154 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
3155 TopLevelObject))
3156 Invalid = true;
3157
3158 if (Invalid) {
3159 ++Index;
3160 return true;
3161 }
3162
3163 // Initialize the array.
3164 bool prevHadError = hadError;
3165 unsigned newStructuredIndex = FieldIndex;
3166 unsigned OldIndex = Index;
3167 IList->setInit(Index, DIE->getInit());
3168
3169 InitializedEntity MemberEntity =
3170 InitializedEntity::InitializeMember(*Field, &Entity);
3171 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
3172 StructuredList, newStructuredIndex);
3173
3174 IList->setInit(OldIndex, DIE);
3175 if (hadError && !prevHadError) {
3176 ++Field;
3177 ++FieldIndex;
3178 if (NextField)
3179 *NextField = Field;
3180 StructuredIndex = FieldIndex;
3181 return true;
3182 }
3183 } else {
3184 // Recurse to check later designated subobjects.
3185 QualType FieldType = Field->getType();
3186 unsigned newStructuredIndex = FieldIndex;
3187
3188 InitializedEntity MemberEntity =
3189 InitializedEntity::InitializeMember(*Field, &Entity);
3190 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
3191 FieldType, nullptr, nullptr, Index,
3192 StructuredList, newStructuredIndex,
3193 FinishSubobjectInit, false))
3194 return true;
3195 }
3196
3197 // Find the position of the next field to be initialized in this
3198 // subobject.
3199 ++Field;
3200 ++FieldIndex;
3201
3202 // If this the first designator, our caller will continue checking
3203 // the rest of this struct/class/union subobject.
3204 if (IsFirstDesignator) {
3205 if (Field != RD->field_end() && Field->isUnnamedBitField())
3206 ++Field;
3207
3208 if (NextField)
3209 *NextField = Field;
3210
3211 StructuredIndex = FieldIndex;
3212 return false;
3213 }
3214
3215 if (!FinishSubobjectInit)
3216 return false;
3217
3218 // We've already initialized something in the union; we're done.
3219 if (RD->isUnion())
3220 return hadError;
3221
3222 // Check the remaining fields within this class/struct/union subobject.
3223 bool prevHadError = hadError;
3224
3225 auto NoBases =
3228 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
3229 false, Index, StructuredList, FieldIndex);
3230 return hadError && !prevHadError;
3231 }
3232
3233 // C99 6.7.8p6:
3234 //
3235 // If a designator has the form
3236 //
3237 // [ constant-expression ]
3238 //
3239 // then the current object (defined below) shall have array
3240 // type and the expression shall be an integer constant
3241 // expression. If the array is of unknown size, any
3242 // nonnegative value is valid.
3243 //
3244 // Additionally, cope with the GNU extension that permits
3245 // designators of the form
3246 //
3247 // [ constant-expression ... constant-expression ]
3248 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
3249 if (!AT) {
3250 if (!VerifyOnly)
3251 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3252 << CurrentObjectType;
3253 ++Index;
3254 return true;
3255 }
3256
3257 Expr *IndexExpr = nullptr;
3258 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3259 if (D->isArrayDesignator()) {
3260 IndexExpr = DIE->getArrayIndex(*D);
3261 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3262 DesignatedEndIndex = DesignatedStartIndex;
3263 } else {
3264 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3265
3266 DesignatedStartIndex =
3268 DesignatedEndIndex =
3270 IndexExpr = DIE->getArrayRangeEnd(*D);
3271
3272 // Codegen can't handle evaluating array range designators that have side
3273 // effects, because we replicate the AST value for each initialized element.
3274 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3275 // elements with something that has a side effect, so codegen can emit an
3276 // "error unsupported" error instead of miscompiling the app.
3277 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3278 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3279 FullyStructuredList->sawArrayRangeDesignator();
3280 }
3281
3282 if (isa<ConstantArrayType>(AT)) {
3283 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3284 DesignatedStartIndex
3285 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3286 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3287 DesignatedEndIndex
3288 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3289 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3290 if (DesignatedEndIndex >= MaxElements) {
3291 if (!VerifyOnly)
3292 SemaRef.Diag(IndexExpr->getBeginLoc(),
3293 diag::err_array_designator_too_large)
3294 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3295 << IndexExpr->getSourceRange();
3296 ++Index;
3297 return true;
3298 }
3299 } else {
3300 unsigned DesignatedIndexBitWidth =
3302 DesignatedStartIndex =
3303 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3304 DesignatedEndIndex =
3305 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3306 DesignatedStartIndex.setIsUnsigned(true);
3307 DesignatedEndIndex.setIsUnsigned(true);
3308 }
3309
3310 bool IsStringLiteralInitUpdate =
3311 StructuredList && StructuredList->isStringLiteralInit();
3312 if (IsStringLiteralInitUpdate && VerifyOnly) {
3313 // We're just verifying an update to a string literal init. We don't need
3314 // to split the string up into individual characters to do that.
3315 StructuredList = nullptr;
3316 } else if (IsStringLiteralInitUpdate) {
3317 // We're modifying a string literal init; we have to decompose the string
3318 // so we can modify the individual characters.
3319 ASTContext &Context = SemaRef.Context;
3320 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3321
3322 // Compute the character type
3323 QualType CharTy = AT->getElementType();
3324
3325 // Compute the type of the integer literals.
3326 QualType PromotedCharTy = CharTy;
3327 if (Context.isPromotableIntegerType(CharTy))
3328 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3329 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3330
3331 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3332 // Get the length of the string.
3333 uint64_t StrLen = SL->getLength();
3334 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3335 CAT && CAT->getSize().ult(StrLen))
3336 StrLen = CAT->getZExtSize();
3337 StructuredList->resizeInits(Context, StrLen);
3338
3339 // Build a literal for each character in the string, and put them into
3340 // the init list.
3341 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3342 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3343 Expr *Init = new (Context) IntegerLiteral(
3344 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3345 if (CharTy != PromotedCharTy)
3346 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3347 Init, nullptr, VK_PRValue,
3348 FPOptionsOverride());
3349 StructuredList->updateInit(Context, i, Init);
3350 }
3351 } else {
3352 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3353 std::string Str;
3354 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3355
3356 // Get the length of the string.
3357 uint64_t StrLen = Str.size();
3358 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3359 CAT && CAT->getSize().ult(StrLen))
3360 StrLen = CAT->getZExtSize();
3361 StructuredList->resizeInits(Context, StrLen);
3362
3363 // Build a literal for each character in the string, and put them into
3364 // the init list.
3365 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3366 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3367 Expr *Init = new (Context) IntegerLiteral(
3368 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3369 if (CharTy != PromotedCharTy)
3370 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3371 Init, nullptr, VK_PRValue,
3372 FPOptionsOverride());
3373 StructuredList->updateInit(Context, i, Init);
3374 }
3375 }
3376 }
3377
3378 // Make sure that our non-designated initializer list has space
3379 // for a subobject corresponding to this array element.
3380 if (StructuredList &&
3381 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3382 StructuredList->resizeInits(SemaRef.Context,
3383 DesignatedEndIndex.getZExtValue() + 1);
3384
3385 // Repeatedly perform subobject initializations in the range
3386 // [DesignatedStartIndex, DesignatedEndIndex].
3387
3388 // Move to the next designator
3389 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3390 unsigned OldIndex = Index;
3391
3392 InitializedEntity ElementEntity =
3394
3395 while (DesignatedStartIndex <= DesignatedEndIndex) {
3396 // Recurse to check later designated subobjects.
3397 QualType ElementType = AT->getElementType();
3398 Index = OldIndex;
3399
3400 ElementEntity.setElementIndex(ElementIndex);
3401 if (CheckDesignatedInitializer(
3402 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3403 nullptr, Index, StructuredList, ElementIndex,
3404 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3405 false))
3406 return true;
3407
3408 // Move to the next index in the array that we'll be initializing.
3409 ++DesignatedStartIndex;
3410 ElementIndex = DesignatedStartIndex.getZExtValue();
3411 }
3412
3413 // If this the first designator, our caller will continue checking
3414 // the rest of this array subobject.
3415 if (IsFirstDesignator) {
3416 if (NextElementIndex)
3417 *NextElementIndex = DesignatedStartIndex;
3418 StructuredIndex = ElementIndex;
3419 return false;
3420 }
3421
3422 if (!FinishSubobjectInit)
3423 return false;
3424
3425 // Check the remaining elements within this array subobject.
3426 bool prevHadError = hadError;
3427 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3428 /*SubobjectIsDesignatorContext=*/false, Index,
3429 StructuredList, ElementIndex);
3430 return hadError && !prevHadError;
3431}
3432
3433// Get the structured initializer list for a subobject of type
3434// @p CurrentObjectType.
3435InitListExpr *
3436InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3437 QualType CurrentObjectType,
3438 InitListExpr *StructuredList,
3439 unsigned StructuredIndex,
3440 SourceRange InitRange,
3441 bool IsFullyOverwritten) {
3442 if (!StructuredList)
3443 return nullptr;
3444
3445 Expr *ExistingInit = nullptr;
3446 if (StructuredIndex < StructuredList->getNumInits())
3447 ExistingInit = StructuredList->getInit(StructuredIndex);
3448
3449 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3450 // There might have already been initializers for subobjects of the current
3451 // object, but a subsequent initializer list will overwrite the entirety
3452 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3453 //
3454 // struct P { char x[6]; };
3455 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3456 //
3457 // The first designated initializer is ignored, and l.x is just "f".
3458 if (!IsFullyOverwritten)
3459 return Result;
3460
3461 if (ExistingInit) {
3462 // We are creating an initializer list that initializes the
3463 // subobjects of the current object, but there was already an
3464 // initialization that completely initialized the current
3465 // subobject:
3466 //
3467 // struct X { int a, b; };
3468 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3469 //
3470 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3471 // designated initializer overwrites the [0].b initializer
3472 // from the prior initialization.
3473 //
3474 // When the existing initializer is an expression rather than an
3475 // initializer list, we cannot decompose and update it in this way.
3476 // For example:
3477 //
3478 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3479 //
3480 // This case is handled by CheckDesignatedInitializer.
3481 diagnoseInitOverride(ExistingInit, InitRange);
3482 }
3483
3484 unsigned ExpectedNumInits = 0;
3485 if (Index < IList->getNumInits()) {
3486 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3487 ExpectedNumInits = Init->getNumInits();
3488 else
3489 ExpectedNumInits = IList->getNumInits() - Index;
3490 }
3491
3492 InitListExpr *Result =
3493 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3494
3495 // Link this new initializer list into the structured initializer
3496 // lists.
3497 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3498 return Result;
3499}
3500
3501InitListExpr *
3502InitListChecker::createInitListExpr(QualType CurrentObjectType,
3503 SourceRange InitRange,
3504 unsigned ExpectedNumInits) {
3505 InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3506 SemaRef.Context, InitRange.getBegin(), {}, InitRange.getEnd());
3507
3508 QualType ResultType = CurrentObjectType;
3509 if (!ResultType->isArrayType())
3510 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3511 Result->setType(ResultType);
3512
3513 // Pre-allocate storage for the structured initializer list.
3514 unsigned NumElements = 0;
3515
3516 if (const ArrayType *AType
3517 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3518 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3519 NumElements = CAType->getZExtSize();
3520 // Simple heuristic so that we don't allocate a very large
3521 // initializer with many empty entries at the end.
3522 if (NumElements > ExpectedNumInits)
3523 NumElements = 0;
3524 }
3525 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3526 NumElements = VType->getNumElements();
3527 } else if (CurrentObjectType->isRecordType()) {
3528 NumElements = numStructUnionElements(CurrentObjectType);
3529 } else if (CurrentObjectType->isDependentType()) {
3530 NumElements = 1;
3531 }
3532
3533 Result->reserveInits(SemaRef.Context, NumElements);
3534
3535 return Result;
3536}
3537
3538/// Update the initializer at index @p StructuredIndex within the
3539/// structured initializer list to the value @p expr.
3540void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3541 unsigned &StructuredIndex,
3542 Expr *expr) {
3543 // No structured initializer list to update
3544 if (!StructuredList)
3545 return;
3546
3547 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3548 StructuredIndex, expr)) {
3549 // This initializer overwrites a previous initializer.
3550 // No need to diagnose when `expr` is nullptr because a more relevant
3551 // diagnostic has already been issued and this diagnostic is potentially
3552 // noise.
3553 if (expr)
3554 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3555 }
3556
3557 ++StructuredIndex;
3558}
3559
3561 const InitializedEntity &Entity, InitListExpr *From) {
3562 QualType Type = Entity.getType();
3563 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3564 /*TreatUnavailableAsInvalid=*/false,
3565 /*InOverloadResolution=*/true);
3566 return !Check.HadError();
3567}
3568
3569/// Check that the given Index expression is a valid array designator
3570/// value. This is essentially just a wrapper around
3571/// VerifyIntegerConstantExpression that also checks for negative values
3572/// and produces a reasonable diagnostic if there is a
3573/// failure. Returns the index expression, possibly with an implicit cast
3574/// added, on success. If everything went okay, Value will receive the
3575/// value of the constant expression.
3576static ExprResult
3577CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3578 SourceLocation Loc = Index->getBeginLoc();
3579
3580 // Make sure this is an integer constant expression.
3581 ExprResult Result =
3583 if (Result.isInvalid())
3584 return Result;
3585
3586 if (Value.isSigned() && Value.isNegative())
3587 return S.Diag(Loc, diag::err_array_designator_negative)
3588 << toString(Value, 10) << Index->getSourceRange();
3589
3590 Value.setIsUnsigned(true);
3591 return Result;
3592}
3593
3595 SourceLocation EqualOrColonLoc,
3596 bool GNUSyntax,
3597 ExprResult Init) {
3598 typedef DesignatedInitExpr::Designator ASTDesignator;
3599
3600 bool Invalid = false;
3602 SmallVector<Expr *, 32> InitExpressions;
3603
3604 // Build designators and check array designator expressions.
3605 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3606 const Designator &D = Desig.getDesignator(Idx);
3607
3608 if (D.isFieldDesignator()) {
3609 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3610 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3611 } else if (D.isArrayDesignator()) {
3612 Expr *Index = D.getArrayIndex();
3613 llvm::APSInt IndexValue;
3614 if (!Index->isTypeDependent() && !Index->isValueDependent())
3615 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3616 if (!Index)
3617 Invalid = true;
3618 else {
3619 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3620 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3621 InitExpressions.push_back(Index);
3622 }
3623 } else if (D.isArrayRangeDesignator()) {
3624 Expr *StartIndex = D.getArrayRangeStart();
3625 Expr *EndIndex = D.getArrayRangeEnd();
3626 llvm::APSInt StartValue;
3627 llvm::APSInt EndValue;
3628 bool StartDependent = StartIndex->isTypeDependent() ||
3629 StartIndex->isValueDependent();
3630 bool EndDependent = EndIndex->isTypeDependent() ||
3631 EndIndex->isValueDependent();
3632 if (!StartDependent)
3633 StartIndex =
3634 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3635 if (!EndDependent)
3636 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3637
3638 if (!StartIndex || !EndIndex)
3639 Invalid = true;
3640 else {
3641 // Make sure we're comparing values with the same bit width.
3642 if (StartDependent || EndDependent) {
3643 // Nothing to compute.
3644 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3645 EndValue = EndValue.extend(StartValue.getBitWidth());
3646 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3647 StartValue = StartValue.extend(EndValue.getBitWidth());
3648
3649 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3650 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3651 << toString(StartValue, 10) << toString(EndValue, 10)
3652 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3653 Invalid = true;
3654 } else {
3655 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3656 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3657 D.getRBracketLoc()));
3658 InitExpressions.push_back(StartIndex);
3659 InitExpressions.push_back(EndIndex);
3660 }
3661 }
3662 }
3663 }
3664
3665 if (Invalid || Init.isInvalid())
3666 return ExprError();
3667
3668 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3669 EqualOrColonLoc, GNUSyntax,
3670 Init.getAs<Expr>());
3671}
3672
3673//===----------------------------------------------------------------------===//
3674// Initialization entity
3675//===----------------------------------------------------------------------===//
3676
3677InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3678 const InitializedEntity &Parent)
3679 : Parent(&Parent), Index(Index)
3680{
3681 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3682 Kind = EK_ArrayElement;
3683 Type = AT->getElementType();
3684 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3685 Kind = EK_VectorElement;
3686 Type = VT->getElementType();
3687 } else if (const MatrixType *MT = Parent.getType()->getAs<MatrixType>()) {
3688 Kind = EK_MatrixElement;
3689 Type = MT->getElementType();
3690 } else {
3691 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3692 assert(CT && "Unexpected type");
3693 Kind = EK_ComplexElement;
3694 Type = CT->getElementType();
3695 }
3696}
3697
3700 const CXXBaseSpecifier *Base,
3701 bool IsInheritedVirtualBase,
3702 const InitializedEntity *Parent) {
3703 InitializedEntity Result;
3704 Result.Kind = EK_Base;
3705 Result.Parent = Parent;
3706 Result.Base = {Base, IsInheritedVirtualBase};
3707 Result.Type = Base->getType();
3708 return Result;
3709}
3710
3712 switch (getKind()) {
3713 case EK_Parameter:
3715 ParmVarDecl *D = Parameter.getPointer();
3716 return (D ? D->getDeclName() : DeclarationName());
3717 }
3718
3719 case EK_Variable:
3720 case EK_Member:
3722 case EK_Binding:
3724 return Variable.VariableOrMember->getDeclName();
3725
3726 case EK_LambdaCapture:
3727 return DeclarationName(Capture.VarID);
3728
3729 case EK_Result:
3730 case EK_StmtExprResult:
3731 case EK_Exception:
3732 case EK_New:
3733 case EK_Temporary:
3734 case EK_Base:
3735 case EK_Delegating:
3736 case EK_ArrayElement:
3737 case EK_VectorElement:
3738 case EK_MatrixElement:
3739 case EK_ComplexElement:
3740 case EK_BlockElement:
3743 case EK_RelatedResult:
3744 return DeclarationName();
3745 }
3746
3747 llvm_unreachable("Invalid EntityKind!");
3748}
3749
3751 switch (getKind()) {
3752 case EK_Variable:
3753 case EK_Member:
3755 case EK_Binding:
3757 return cast<ValueDecl>(Variable.VariableOrMember);
3758
3759 case EK_Parameter:
3761 return Parameter.getPointer();
3762
3763 case EK_Result:
3764 case EK_StmtExprResult:
3765 case EK_Exception:
3766 case EK_New:
3767 case EK_Temporary:
3768 case EK_Base:
3769 case EK_Delegating:
3770 case EK_ArrayElement:
3771 case EK_VectorElement:
3772 case EK_MatrixElement:
3773 case EK_ComplexElement:
3774 case EK_BlockElement:
3776 case EK_LambdaCapture:
3778 case EK_RelatedResult:
3779 return nullptr;
3780 }
3781
3782 llvm_unreachable("Invalid EntityKind!");
3783}
3784
3786 switch (getKind()) {
3787 case EK_Result:
3788 case EK_Exception:
3789 return LocAndNRVO.NRVO;
3790
3791 case EK_StmtExprResult:
3792 case EK_Variable:
3793 case EK_Parameter:
3796 case EK_Member:
3798 case EK_Binding:
3799 case EK_New:
3800 case EK_Temporary:
3802 case EK_Base:
3803 case EK_Delegating:
3804 case EK_ArrayElement:
3805 case EK_VectorElement:
3806 case EK_MatrixElement:
3807 case EK_ComplexElement:
3808 case EK_BlockElement:
3810 case EK_LambdaCapture:
3811 case EK_RelatedResult:
3812 break;
3813 }
3814
3815 return false;
3816}
3817
3818unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3819 assert(getParent() != this);
3820 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3821 for (unsigned I = 0; I != Depth; ++I)
3822 OS << "`-";
3823
3824 switch (getKind()) {
3825 case EK_Variable: OS << "Variable"; break;
3826 case EK_Parameter: OS << "Parameter"; break;
3827 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3828 break;
3829 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3830 case EK_Result: OS << "Result"; break;
3831 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3832 case EK_Exception: OS << "Exception"; break;
3833 case EK_Member:
3835 OS << "Member";
3836 break;
3837 case EK_Binding: OS << "Binding"; break;
3838 case EK_New: OS << "New"; break;
3839 case EK_Temporary: OS << "Temporary"; break;
3840 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3841 case EK_RelatedResult: OS << "RelatedResult"; break;
3842 case EK_Base: OS << "Base"; break;
3843 case EK_Delegating: OS << "Delegating"; break;
3844 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3845 case EK_VectorElement: OS << "VectorElement " << Index; break;
3846 case EK_MatrixElement:
3847 OS << "MatrixElement " << Index;
3848 break;
3849 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3850 case EK_BlockElement: OS << "Block"; break;
3852 OS << "Block (lambda)";
3853 break;
3854 case EK_LambdaCapture:
3855 OS << "LambdaCapture ";
3856 OS << DeclarationName(Capture.VarID);
3857 break;
3858 }
3859
3860 if (auto *D = getDecl()) {
3861 OS << " ";
3862 D->printQualifiedName(OS);
3863 }
3864
3865 OS << " '" << getType() << "'\n";
3866
3867 return Depth + 1;
3868}
3869
3870LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3871 dumpImpl(llvm::errs());
3872}
3873
3874//===----------------------------------------------------------------------===//
3875// Initialization sequence
3876//===----------------------------------------------------------------------===//
3877
3923
3925 // There can be some lvalue adjustments after the SK_BindReference step.
3926 for (const Step &S : llvm::reverse(Steps)) {
3927 if (S.Kind == SK_BindReference)
3928 return true;
3929 if (S.Kind == SK_BindReferenceToTemporary)
3930 return false;
3931 }
3932 return false;
3933}
3934
3936 if (!Failed())
3937 return false;
3938
3939 switch (getFailureKind()) {
3950 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3967 case FK_Incomplete:
3972 case FK_PlaceholderType:
3978 return false;
3979
3984 return FailedOverloadResult == OR_Ambiguous;
3985 }
3986
3987 llvm_unreachable("Invalid EntityKind!");
3988}
3989
3991 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3992}
3993
3994void
3995InitializationSequence
3996::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3998 bool HadMultipleCandidates) {
3999 Step S;
4001 S.Type = Function->getType();
4002 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4005 Steps.push_back(S);
4006}
4007
4009 ExprValueKind VK) {
4010 Step S;
4011 switch (VK) {
4012 case VK_PRValue:
4014 break;
4015 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
4016 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
4017 }
4018 S.Type = BaseType;
4019 Steps.push_back(S);
4020}
4021
4023 bool BindingTemporary) {
4024 Step S;
4025 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
4026 S.Type = T;
4027 Steps.push_back(S);
4028}
4029
4031 Step S;
4032 S.Kind = SK_FinalCopy;
4033 S.Type = T;
4034 Steps.push_back(S);
4035}
4036
4038 Step S;
4040 S.Type = T;
4041 Steps.push_back(S);
4042}
4043
4044void
4046 DeclAccessPair FoundDecl,
4047 QualType T,
4048 bool HadMultipleCandidates) {
4049 Step S;
4051 S.Type = T;
4052 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4054 S.Function.FoundDecl = FoundDecl;
4055 Steps.push_back(S);
4056}
4057
4059 ExprValueKind VK) {
4060 Step S;
4061 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
4062 switch (VK) {
4063 case VK_PRValue:
4065 break;
4066 case VK_XValue:
4068 break;
4069 case VK_LValue:
4071 break;
4072 }
4073 S.Type = Ty;
4074 Steps.push_back(S);
4075}
4076
4078 Step S;
4080 S.Type = Ty;
4081 Steps.push_back(S);
4082}
4083
4085 Step S;
4087 S.Type = Ty;
4088 Steps.push_back(S);
4089}
4090
4093 bool TopLevelOfInitList) {
4094 Step S;
4095 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
4097 S.Type = T;
4098 S.ICS = new ImplicitConversionSequence(ICS);
4099 Steps.push_back(S);
4100}
4101
4103 Step S;
4105 S.Type = T;
4106 Steps.push_back(S);
4107}
4108
4111 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
4112 Step S;
4113 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
4116 S.Type = T;
4117 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4119 S.Function.FoundDecl = FoundDecl;
4120 Steps.push_back(S);
4121}
4122
4124 Step S;
4126 S.Type = T;
4127 Steps.push_back(S);
4128}
4129
4131 Step S;
4132 S.Kind = SK_CAssignment;
4133 S.Type = T;
4134 Steps.push_back(S);
4135}
4136
4138 Step S;
4139 S.Kind = SK_StringInit;
4140 S.Type = T;
4141 Steps.push_back(S);
4142}
4143
4145 Step S;
4147 S.Type = T;
4148 Steps.push_back(S);
4149}
4150
4152 Step S;
4153 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
4154 S.Type = T;
4155 Steps.push_back(S);
4156}
4157
4159 Step S;
4161 S.Type = EltT;
4162 Steps.insert(Steps.begin(), S);
4163
4165 S.Type = T;
4166 Steps.push_back(S);
4167}
4168
4170 Step S;
4172 S.Type = T;
4173 Steps.push_back(S);
4174}
4175
4177 bool shouldCopy) {
4178 Step s;
4179 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
4181 s.Type = type;
4182 Steps.push_back(s);
4183}
4184
4186 Step S;
4188 S.Type = T;
4189 Steps.push_back(S);
4190}
4191
4193 Step S;
4195 S.Type = T;
4196 Steps.push_back(S);
4197}
4198
4200 Step S;
4202 S.Type = T;
4203 Steps.push_back(S);
4204}
4205
4207 Step S;
4209 S.Type = T;
4210 Steps.push_back(S);
4211}
4212
4214 Step S;
4216 S.Type = T;
4217 Steps.push_back(S);
4218}
4219
4221 InitListExpr *Syntactic) {
4222 assert(Syntactic->getNumInits() == 1 &&
4223 "Can only unwrap trivial init lists.");
4224 Step S;
4226 S.Type = Syntactic->getInit(0)->getType();
4227 Steps.insert(Steps.begin(), S);
4228}
4229
4231 InitListExpr *Syntactic) {
4232 assert(Syntactic->getNumInits() == 1 &&
4233 "Can only rewrap trivial init lists.");
4234 Step S;
4236 S.Type = Syntactic->getInit(0)->getType();
4237 Steps.insert(Steps.begin(), S);
4238
4240 S.Type = T;
4241 S.WrappingSyntacticList = Syntactic;
4242 Steps.push_back(S);
4243}
4244
4248 this->Failure = Failure;
4249 this->FailedOverloadResult = Result;
4250}
4251
4252//===----------------------------------------------------------------------===//
4253// Attempt initialization
4254//===----------------------------------------------------------------------===//
4255
4256/// Tries to add a zero initializer. Returns true if that worked.
4257static bool
4259 const InitializedEntity &Entity) {
4261 return false;
4262
4263 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
4264 if (VD->getInit() || VD->getEndLoc().isMacroID())
4265 return false;
4266
4267 QualType VariableTy = VD->getType().getCanonicalType();
4269 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
4270 if (!Init.empty()) {
4271 Sequence.AddZeroInitializationStep(Entity.getType());
4272 Sequence.SetZeroInitializationFixit(Init, Loc);
4273 return true;
4274 }
4275 return false;
4276}
4277
4279 InitializationSequence &Sequence,
4280 const InitializedEntity &Entity) {
4281 if (!S.getLangOpts().ObjCAutoRefCount) return;
4282
4283 /// When initializing a parameter, produce the value if it's marked
4284 /// __attribute__((ns_consumed)).
4285 if (Entity.isParameterKind()) {
4286 if (!Entity.isParameterConsumed())
4287 return;
4288
4289 assert(Entity.getType()->isObjCRetainableType() &&
4290 "consuming an object of unretainable type?");
4291 Sequence.AddProduceObjCObjectStep(Entity.getType());
4292
4293 /// When initializing a return value, if the return type is a
4294 /// retainable type, then returns need to immediately retain the
4295 /// object. If an autorelease is required, it will be done at the
4296 /// last instant.
4297 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4299 if (!Entity.getType()->isObjCRetainableType())
4300 return;
4301
4302 Sequence.AddProduceObjCObjectStep(Entity.getType());
4303 }
4304}
4305
4306/// Initialize an array from another array
4307static void TryArrayCopy(Sema &S, const InitializationKind &Kind,
4308 const InitializedEntity &Entity, Expr *Initializer,
4309 QualType DestType, InitializationSequence &Sequence,
4310 bool TreatUnavailableAsInvalid) {
4311 // If source is a prvalue, use it directly.
4312 if (Initializer->isPRValue()) {
4313 Sequence.AddArrayInitStep(DestType, /*IsGNUExtension*/ false);
4314 return;
4315 }
4316
4317 // Emit element-at-a-time copy loop.
4318 InitializedEntity Element =
4320 QualType InitEltT =
4322 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
4323 Initializer->getValueKind(),
4324 Initializer->getObjectKind());
4325 Expr *OVEAsExpr = &OVE;
4326 Sequence.InitializeFrom(S, Element, Kind, OVEAsExpr,
4327 /*TopLevelOfInitList*/ false,
4328 TreatUnavailableAsInvalid);
4329 if (Sequence)
4330 Sequence.AddArrayInitLoopStep(Entity.getType(), InitEltT);
4331}
4332
4333static void TryListInitialization(Sema &S,
4334 const InitializedEntity &Entity,
4335 const InitializationKind &Kind,
4336 InitListExpr *InitList,
4337 InitializationSequence &Sequence,
4338 bool TreatUnavailableAsInvalid);
4339
4340/// When initializing from init list via constructor, handle
4341/// initialization of an object of type std::initializer_list<T>.
4342///
4343/// \return true if we have handled initialization of an object of type
4344/// std::initializer_list<T>, false otherwise.
4346 InitListExpr *List,
4347 QualType DestType,
4348 InitializationSequence &Sequence,
4349 bool TreatUnavailableAsInvalid) {
4350 QualType E;
4351 if (!S.isStdInitializerList(DestType, &E))
4352 return false;
4353
4354 if (!S.isCompleteType(List->getExprLoc(), E)) {
4355 Sequence.setIncompleteTypeFailure(E);
4356 return true;
4357 }
4358
4359 // Try initializing a temporary array from the init list.
4361 E.withConst(),
4362 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4365 InitializedEntity HiddenArray =
4368 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4369 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4370 TreatUnavailableAsInvalid);
4371 if (Sequence)
4372 Sequence.AddStdInitializerListConstructionStep(DestType);
4373 return true;
4374}
4375
4376/// Determine if the constructor has the signature of a copy or move
4377/// constructor for the type T of the class in which it was found. That is,
4378/// determine if its first parameter is of type T or reference to (possibly
4379/// cv-qualified) T.
4381 const ConstructorInfo &Info) {
4382 if (Info.Constructor->getNumParams() == 0)
4383 return false;
4384
4385 QualType ParmT =
4387 CanQualType ClassT = Ctx.getCanonicalTagType(
4389
4390 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4391}
4392
4394 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4395 OverloadCandidateSet &CandidateSet, QualType DestType,
4397 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4398 bool IsListInit, bool RequireActualConstructor,
4399 bool SecondStepOfCopyInit = false) {
4401 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4402
4403 for (NamedDecl *D : Ctors) {
4404 auto Info = getConstructorInfo(D);
4405 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4406 continue;
4407
4408 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4409 continue;
4410
4411 // C++11 [over.best.ics]p4:
4412 // ... and the constructor or user-defined conversion function is a
4413 // candidate by
4414 // - 13.3.1.3, when the argument is the temporary in the second step
4415 // of a class copy-initialization, or
4416 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4417 // - the second phase of 13.3.1.7 when the initializer list has exactly
4418 // one element that is itself an initializer list, and the target is
4419 // the first parameter of a constructor of class X, and the conversion
4420 // is to X or reference to (possibly cv-qualified X),
4421 // user-defined conversion sequences are not considered.
4422 bool SuppressUserConversions =
4423 SecondStepOfCopyInit ||
4424 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4426
4427 if (Info.ConstructorTmpl)
4429 Info.ConstructorTmpl, Info.FoundDecl,
4430 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4431 /*PartialOverloading=*/false, AllowExplicit);
4432 else {
4433 // C++ [over.match.copy]p1:
4434 // - When initializing a temporary to be bound to the first parameter
4435 // of a constructor [for type T] that takes a reference to possibly
4436 // cv-qualified T as its first argument, called with a single
4437 // argument in the context of direct-initialization, explicit
4438 // conversion functions are also considered.
4439 // FIXME: What if a constructor template instantiates to such a signature?
4440 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4441 Args.size() == 1 &&
4443 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4444 CandidateSet, SuppressUserConversions,
4445 /*PartialOverloading=*/false, AllowExplicit,
4446 AllowExplicitConv);
4447 }
4448 }
4449
4450 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4451 //
4452 // When initializing an object of class type T by constructor
4453 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4454 // from a single expression of class type U, conversion functions of
4455 // U that convert to the non-reference type cv T are candidates.
4456 // Explicit conversion functions are only candidates during
4457 // direct-initialization.
4458 //
4459 // Note: SecondStepOfCopyInit is only ever true in this case when
4460 // evaluating whether to produce a C++98 compatibility warning.
4461 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4462 !RequireActualConstructor && !SecondStepOfCopyInit) {
4463 Expr *Initializer = Args[0];
4464 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4465 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4466 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4467 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4468 NamedDecl *D = *I;
4470 D = D->getUnderlyingDecl();
4471
4472 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4473 CXXConversionDecl *Conv;
4474 if (ConvTemplate)
4475 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4476 else
4477 Conv = cast<CXXConversionDecl>(D);
4478
4479 if (ConvTemplate)
4481 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4482 CandidateSet, AllowExplicit, AllowExplicit,
4483 /*AllowResultConversion*/ false);
4484 else
4485 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4486 DestType, CandidateSet, AllowExplicit,
4487 AllowExplicit,
4488 /*AllowResultConversion*/ false);
4489 }
4490 }
4491 }
4492
4493 // Perform overload resolution and return the result.
4494 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4495}
4496
4497/// Attempt initialization by constructor (C++ [dcl.init]), which
4498/// enumerates the constructors of the initialized entity and performs overload
4499/// resolution to select the best.
4500/// \param DestType The destination class type.
4501/// \param DestArrayType The destination type, which is either DestType or
4502/// a (possibly multidimensional) array of DestType.
4503/// \param IsListInit Is this list-initialization?
4504/// \param IsInitListCopy Is this non-list-initialization resulting from a
4505/// list-initialization from {x} where x is the same
4506/// aggregate type as the entity?
4508 const InitializedEntity &Entity,
4509 const InitializationKind &Kind,
4510 MultiExprArg Args, QualType DestType,
4511 QualType DestArrayType,
4512 InitializationSequence &Sequence,
4513 bool IsListInit = false,
4514 bool IsInitListCopy = false) {
4515 assert(((!IsListInit && !IsInitListCopy) ||
4516 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4517 "IsListInit/IsInitListCopy must come with a single initializer list "
4518 "argument.");
4519 InitListExpr *ILE =
4520 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4521 MultiExprArg UnwrappedArgs =
4522 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4523
4524 // The type we're constructing needs to be complete.
4525 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4526 Sequence.setIncompleteTypeFailure(DestType);
4527 return;
4528 }
4529
4530 bool RequireActualConstructor =
4531 !(Entity.getKind() != InitializedEntity::EK_Base &&
4533 Entity.getKind() !=
4535
4536 bool CopyElisionPossible = false;
4537 auto ElideConstructor = [&] {
4538 // Convert qualifications if necessary.
4539 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4540 if (ILE)
4541 Sequence.RewrapReferenceInitList(DestType, ILE);
4542 };
4543
4544 // C++17 [dcl.init]p17:
4545 // - If the initializer expression is a prvalue and the cv-unqualified
4546 // version of the source type is the same class as the class of the
4547 // destination, the initializer expression is used to initialize the
4548 // destination object.
4549 // Per DR (no number yet), this does not apply when initializing a base
4550 // class or delegating to another constructor from a mem-initializer.
4551 // ObjC++: Lambda captured by the block in the lambda to block conversion
4552 // should avoid copy elision.
4553 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4554 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4555 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4556 if (ILE && !DestType->isAggregateType()) {
4557 // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision
4558 // Make this an elision if this won't call an initializer-list
4559 // constructor. (Always on an aggregate type or check constructors first.)
4560
4561 // This effectively makes our resolution as follows. The parts in angle
4562 // brackets are additions.
4563 // C++17 [over.match.list]p(1.2):
4564 // - If no viable initializer-list constructor is found <and the
4565 // initializer list does not consist of exactly a single element with
4566 // the same cv-unqualified class type as T>, [...]
4567 // C++17 [dcl.init.list]p(3.6):
4568 // - Otherwise, if T is a class type, constructors are considered. The
4569 // applicable constructors are enumerated and the best one is chosen
4570 // through overload resolution. <If no constructor is found and the
4571 // initializer list consists of exactly a single element with the same
4572 // cv-unqualified class type as T, the object is initialized from that
4573 // element (by copy-initialization for copy-list-initialization, or by
4574 // direct-initialization for direct-list-initialization). Otherwise, >
4575 // if a narrowing conversion [...]
4576 assert(!IsInitListCopy &&
4577 "IsInitListCopy only possible with aggregate types");
4578 CopyElisionPossible = true;
4579 } else {
4580 ElideConstructor();
4581 return;
4582 }
4583 }
4584
4585 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
4586 // Build the candidate set directly in the initialization sequence
4587 // structure, so that it will persist if we fail.
4588 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4589
4590 // Determine whether we are allowed to call explicit constructors or
4591 // explicit conversion operators.
4592 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4593 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4594
4595 // - Otherwise, if T is a class type, constructors are considered. The
4596 // applicable constructors are enumerated, and the best one is chosen
4597 // through overload resolution.
4598 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4599
4602 bool AsInitializerList = false;
4603
4604 // C++11 [over.match.list]p1, per DR1467:
4605 // When objects of non-aggregate type T are list-initialized, such that
4606 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4607 // according to the rules in this section, overload resolution selects
4608 // the constructor in two phases:
4609 //
4610 // - Initially, the candidate functions are the initializer-list
4611 // constructors of the class T and the argument list consists of the
4612 // initializer list as a single argument.
4613 if (IsListInit) {
4614 AsInitializerList = true;
4615
4616 // If the initializer list has no elements and T has a default constructor,
4617 // the first phase is omitted.
4618 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4620 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4621 CopyInitialization, AllowExplicit,
4622 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4623
4624 if (CopyElisionPossible && Result == OR_No_Viable_Function) {
4625 // No initializer list candidate
4626 ElideConstructor();
4627 return;
4628 }
4629 }
4630
4631 // C++11 [over.match.list]p1:
4632 // - If no viable initializer-list constructor is found, overload resolution
4633 // is performed again, where the candidate functions are all the
4634 // constructors of the class T and the argument list consists of the
4635 // elements of the initializer list.
4636 if (Result == OR_No_Viable_Function) {
4637 AsInitializerList = false;
4639 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4640 Best, CopyInitialization, AllowExplicit,
4641 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4642 }
4643 if (Result) {
4644 Sequence.SetOverloadFailure(
4647 Result);
4648
4649 if (Result != OR_Deleted)
4650 return;
4651 }
4652
4653 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4654
4655 // In C++17, ResolveConstructorOverload can select a conversion function
4656 // instead of a constructor.
4657 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4658 // Add the user-defined conversion step that calls the conversion function.
4659 QualType ConvType = CD->getConversionType();
4660 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4661 "should not have selected this conversion function");
4662 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4663 HadMultipleCandidates);
4664 if (!S.Context.hasSameType(ConvType, DestType))
4665 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4666 if (IsListInit)
4667 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4668 return;
4669 }
4670
4671 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4672 if (Result != OR_Deleted) {
4673 if (!IsListInit &&
4674 (Kind.getKind() == InitializationKind::IK_Default ||
4675 Kind.getKind() == InitializationKind::IK_Direct) &&
4676 !(CtorDecl->isCopyOrMoveConstructor() && CtorDecl->isImplicit()) &&
4677 DestRecordDecl->isAggregate() &&
4678 DestRecordDecl->hasUninitializedExplicitInitFields() &&
4679 !S.isUnevaluatedContext()) {
4680 S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
4681 << /* Var-in-Record */ 1 << DestRecordDecl;
4682 emitUninitializedExplicitInitFields(S, DestRecordDecl);
4683 }
4684
4685 // C++11 [dcl.init]p6:
4686 // If a program calls for the default initialization of an object
4687 // of a const-qualified type T, T shall be a class type with a
4688 // user-provided default constructor.
4689 // C++ core issue 253 proposal:
4690 // If the implicit default constructor initializes all subobjects, no
4691 // initializer should be required.
4692 // The 253 proposal is for example needed to process libstdc++ headers
4693 // in 5.x.
4694 if (Kind.getKind() == InitializationKind::IK_Default &&
4695 Entity.getType().isConstQualified()) {
4696 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4697 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4699 return;
4700 }
4701 }
4702
4703 // C++11 [over.match.list]p1:
4704 // In copy-list-initialization, if an explicit constructor is chosen, the
4705 // initializer is ill-formed.
4706 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4708 return;
4709 }
4710 }
4711
4712 // [class.copy.elision]p3:
4713 // In some copy-initialization contexts, a two-stage overload resolution
4714 // is performed.
4715 // If the first overload resolution selects a deleted function, we also
4716 // need the initialization sequence to decide whether to perform the second
4717 // overload resolution.
4718 // For deleted functions in other contexts, there is no need to get the
4719 // initialization sequence.
4720 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4721 return;
4722
4723 // Add the constructor initialization step. Any cv-qualification conversion is
4724 // subsumed by the initialization.
4726 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4727 IsListInit | IsInitListCopy, AsInitializerList);
4728}
4729
4731 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4732 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
4733 ExprResult *Result = nullptr);
4734
4735/// Attempt to initialize an object of a class type either by
4736/// direct-initialization, or by copy-initialization from an
4737/// expression of the same or derived class type. This corresponds
4738/// to the first two sub-bullets of C++2c [dcl.init.general] p16.6.
4739///
4740/// \param IsAggrListInit Is this non-list-initialization being done as
4741/// part of a list-initialization of an aggregate
4742/// from a single expression of the same or
4743/// derived class type (C++2c [dcl.init.list] p3.2)?
4745 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4746 MultiExprArg Args, QualType DestType, InitializationSequence &Sequence,
4747 bool IsAggrListInit) {
4748 // C++2c [dcl.init.general] p16.6:
4749 // * Otherwise, if the destination type is a class type:
4750 // * If the initializer expression is a prvalue and
4751 // the cv-unqualified version of the source type is the same
4752 // as the destination type, the initializer expression is used
4753 // to initialize the destination object.
4754 // * Otherwise, if the initialization is direct-initialization,
4755 // or if it is copy-initialization where the cv-unqualified
4756 // version of the source type is the same as or is derived from
4757 // the class of the destination type, constructors are considered.
4758 // The applicable constructors are enumerated, and the best one
4759 // is chosen through overload resolution. Then:
4760 // * If overload resolution is successful, the selected
4761 // constructor is called to initialize the object, with
4762 // the initializer expression or expression-list as its
4763 // argument(s).
4764 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
4765 Sequence, /*IsListInit=*/false, IsAggrListInit);
4766
4767 // * Otherwise, if no constructor is viable, the destination type
4768 // is an aggregate class, and the initializer is a parenthesized
4769 // expression-list, the object is initialized as follows. [...]
4770 // Parenthesized initialization of aggregates is a C++20 feature.
4771 if (S.getLangOpts().CPlusPlus20 &&
4772 Kind.getKind() == InitializationKind::IK_Direct && Sequence.Failed() &&
4773 Sequence.getFailureKind() ==
4776 (IsAggrListInit || DestType->isAggregateType()))
4777 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence,
4778 /*VerifyOnly=*/true);
4779
4780 // * Otherwise, the initialization is ill-formed.
4781}
4782
4783static bool
4786 QualType &SourceType,
4787 QualType &UnqualifiedSourceType,
4788 QualType UnqualifiedTargetType,
4789 InitializationSequence &Sequence) {
4790 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4791 S.Context.OverloadTy) {
4793 bool HadMultipleCandidates = false;
4794 if (FunctionDecl *Fn
4796 UnqualifiedTargetType,
4797 false, Found,
4798 &HadMultipleCandidates)) {
4800 HadMultipleCandidates);
4801 SourceType = Fn->getType();
4802 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4803 } else if (!UnqualifiedTargetType->isRecordType()) {
4805 return true;
4806 }
4807 }
4808 return false;
4809}
4810
4811static void TryReferenceInitializationCore(Sema &S,
4812 const InitializedEntity &Entity,
4813 const InitializationKind &Kind,
4814 Expr *Initializer,
4815 QualType cv1T1, QualType T1,
4816 Qualifiers T1Quals,
4817 QualType cv2T2, QualType T2,
4818 Qualifiers T2Quals,
4819 InitializationSequence &Sequence,
4820 bool TopLevelOfInitList);
4821
4822static void TryValueInitialization(Sema &S,
4823 const InitializedEntity &Entity,
4824 const InitializationKind &Kind,
4825 InitializationSequence &Sequence,
4826 InitListExpr *InitList = nullptr);
4827
4828/// Attempt list initialization of a reference.
4830 const InitializedEntity &Entity,
4831 const InitializationKind &Kind,
4832 InitListExpr *InitList,
4833 InitializationSequence &Sequence,
4834 bool TreatUnavailableAsInvalid) {
4835 // First, catch C++03 where this isn't possible.
4836 if (!S.getLangOpts().CPlusPlus11) {
4838 return;
4839 }
4840 // Can't reference initialize a compound literal.
4843 return;
4844 }
4845
4846 QualType DestType = Entity.getType();
4847 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4848 Qualifiers T1Quals;
4849 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4850
4851 // Reference initialization via an initializer list works thus:
4852 // If the initializer list consists of a single element that is
4853 // reference-related to the referenced type, bind directly to that element
4854 // (possibly creating temporaries).
4855 // Otherwise, initialize a temporary with the initializer list and
4856 // bind to that.
4857 if (InitList->getNumInits() == 1) {
4858 Expr *Initializer = InitList->getInit(0);
4860 Qualifiers T2Quals;
4861 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4862
4863 // If this fails, creating a temporary wouldn't work either.
4865 T1, Sequence))
4866 return;
4867
4868 SourceLocation DeclLoc = Initializer->getBeginLoc();
4869 Sema::ReferenceCompareResult RefRelationship
4870 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4871 if (RefRelationship >= Sema::Ref_Related) {
4872 // Try to bind the reference here.
4873 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4874 T1Quals, cv2T2, T2, T2Quals, Sequence,
4875 /*TopLevelOfInitList=*/true);
4876 if (Sequence)
4877 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4878 return;
4879 }
4880
4881 // Update the initializer if we've resolved an overloaded function.
4882 if (!Sequence.steps().empty())
4883 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4884 }
4885 // Perform address space compatibility check.
4886 QualType cv1T1IgnoreAS = cv1T1;
4887 if (T1Quals.hasAddressSpace()) {
4888 Qualifiers T2Quals;
4889 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4890 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())) {
4891 Sequence.SetFailed(
4893 return;
4894 }
4895 // Ignore address space of reference type at this point and perform address
4896 // space conversion after the reference binding step.
4897 cv1T1IgnoreAS =
4899 }
4900 // Not reference-related. Create a temporary and bind to that.
4901 InitializedEntity TempEntity =
4903
4904 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4905 TreatUnavailableAsInvalid);
4906 if (Sequence) {
4907 if (DestType->isRValueReferenceType() ||
4908 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4909 if (S.getLangOpts().CPlusPlus20 &&
4911 DestType->isRValueReferenceType()) {
4912 // C++20 [dcl.init.list]p3.10:
4913 // List-initialization of an object or reference of type T is defined as
4914 // follows:
4915 // ..., unless T is “reference to array of unknown bound of U”, in which
4916 // case the type of the prvalue is the type of x in the declaration U
4917 // x[] H, where H is the initializer list.
4919 }
4920 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4921 /*BindingTemporary=*/true);
4922 if (T1Quals.hasAddressSpace())
4924 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4925 } else
4926 Sequence.SetFailed(
4928 }
4929}
4930
4931/// Attempt list initialization (C++0x [dcl.init.list])
4933 const InitializedEntity &Entity,
4934 const InitializationKind &Kind,
4935 InitListExpr *InitList,
4936 InitializationSequence &Sequence,
4937 bool TreatUnavailableAsInvalid) {
4938 QualType DestType = Entity.getType();
4939
4940 if (S.getLangOpts().HLSL && !S.HLSL().transformInitList(Entity, InitList)) {
4942 return;
4943 }
4944
4945 // C++ doesn't allow scalar initialization with more than one argument.
4946 // But C99 complex numbers are scalars and it makes sense there.
4947 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4948 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4950 return;
4951 }
4952 if (DestType->isReferenceType()) {
4953 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4954 TreatUnavailableAsInvalid);
4955 return;
4956 }
4957
4958 if (DestType->isRecordType() &&
4959 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4960 Sequence.setIncompleteTypeFailure(DestType);
4961 return;
4962 }
4963
4964 // C++20 [dcl.init.list]p3:
4965 // - If the braced-init-list contains a designated-initializer-list, T shall
4966 // be an aggregate class. [...] Aggregate initialization is performed.
4967 //
4968 // We allow arrays here too in order to support array designators.
4969 //
4970 // FIXME: This check should precede the handling of reference initialization.
4971 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4972 // as a tentative DR resolution.
4973 bool IsDesignatedInit = InitList->hasDesignatedInit();
4974 if (!DestType->isAggregateType() && IsDesignatedInit) {
4975 Sequence.SetFailed(
4977 return;
4978 }
4979
4980 // C++11 [dcl.init.list]p3, per DR1467 and DR2137:
4981 // - If T is an aggregate class and the initializer list has a single element
4982 // of type cv U, where U is T or a class derived from T, the object is
4983 // initialized from that element (by copy-initialization for
4984 // copy-list-initialization, or by direct-initialization for
4985 // direct-list-initialization).
4986 // - Otherwise, if T is a character array and the initializer list has a
4987 // single element that is an appropriately-typed string literal
4988 // (8.5.2 [dcl.init.string]), initialization is performed as described
4989 // in that section.
4990 // - Otherwise, if T is an aggregate, [...] (continue below).
4991 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
4992 !IsDesignatedInit) {
4993 if (DestType->isRecordType() && DestType->isAggregateType()) {
4994 QualType InitType = InitList->getInit(0)->getType();
4995 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4996 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4997 InitializationKind SubKind =
4999 ? InitializationKind::CreateDirect(Kind.getLocation(),
5000 InitList->getLBraceLoc(),
5001 InitList->getRBraceLoc())
5002 : Kind;
5003 Expr *InitListAsExpr = InitList;
5005 S, Entity, SubKind, InitListAsExpr, DestType, Sequence,
5006 /*IsAggrListInit=*/true);
5007 return;
5008 }
5009 }
5010 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
5011 Expr *SubInit[1] = {InitList->getInit(0)};
5012
5013 // C++17 [dcl.struct.bind]p1:
5014 // ... If the assignment-expression in the initializer has array type A
5015 // and no ref-qualifier is present, e has type cv A and each element is
5016 // copy-initialized or direct-initialized from the corresponding element
5017 // of the assignment-expression as specified by the form of the
5018 // initializer. ...
5019 //
5020 // This is a special case not following list-initialization.
5021 if (isa<ConstantArrayType>(DestAT) &&
5023 isa<DecompositionDecl>(Entity.getDecl())) {
5024 assert(
5025 S.Context.hasSameUnqualifiedType(SubInit[0]->getType(), DestType) &&
5026 "Deduced to other type?");
5027 assert(Kind.getKind() == clang::InitializationKind::IK_DirectList &&
5028 "List-initialize structured bindings but not "
5029 "direct-list-initialization?");
5030 TryArrayCopy(S,
5031 InitializationKind::CreateDirect(Kind.getLocation(),
5032 InitList->getLBraceLoc(),
5033 InitList->getRBraceLoc()),
5034 Entity, SubInit[0], DestType, Sequence,
5035 TreatUnavailableAsInvalid);
5036 if (Sequence)
5037 Sequence.AddUnwrapInitListInitStep(InitList);
5038 return;
5039 }
5040
5041 if (!isa<VariableArrayType>(DestAT) &&
5042 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
5043 InitializationKind SubKind =
5045 ? InitializationKind::CreateDirect(Kind.getLocation(),
5046 InitList->getLBraceLoc(),
5047 InitList->getRBraceLoc())
5048 : Kind;
5049 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
5050 /*TopLevelOfInitList*/ true,
5051 TreatUnavailableAsInvalid);
5052
5053 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
5054 // the element is not an appropriately-typed string literal, in which
5055 // case we should proceed as in C++11 (below).
5056 if (Sequence) {
5057 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5058 return;
5059 }
5060 }
5061 }
5062 }
5063
5064 // C++11 [dcl.init.list]p3:
5065 // - If T is an aggregate, aggregate initialization is performed.
5066 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
5067 (S.getLangOpts().CPlusPlus11 &&
5068 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
5069 if (S.getLangOpts().CPlusPlus11) {
5070 // - Otherwise, if the initializer list has no elements and T is a
5071 // class type with a default constructor, the object is
5072 // value-initialized.
5073 if (InitList->getNumInits() == 0) {
5074 CXXRecordDecl *RD = DestType->castAsCXXRecordDecl();
5075 if (S.LookupDefaultConstructor(RD)) {
5076 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
5077 return;
5078 }
5079 }
5080
5081 // - Otherwise, if T is a specialization of std::initializer_list<E>,
5082 // an initializer_list object constructed [...]
5083 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
5084 TreatUnavailableAsInvalid))
5085 return;
5086
5087 // - Otherwise, if T is a class type, constructors are considered.
5088 Expr *InitListAsExpr = InitList;
5089 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
5090 DestType, Sequence, /*InitListSyntax*/true);
5091 } else
5093 return;
5094 }
5095
5096 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
5097 InitList->getNumInits() == 1) {
5098 Expr *E = InitList->getInit(0);
5099
5100 // - Otherwise, if T is an enumeration with a fixed underlying type,
5101 // the initializer-list has a single element v, and the initialization
5102 // is direct-list-initialization, the object is initialized with the
5103 // value T(v); if a narrowing conversion is required to convert v to
5104 // the underlying type of T, the program is ill-formed.
5105 if (S.getLangOpts().CPlusPlus17 &&
5106 Kind.getKind() == InitializationKind::IK_DirectList &&
5107 DestType->isEnumeralType() && DestType->castAsEnumDecl()->isFixed() &&
5108 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
5110 E->getType()->isFloatingType())) {
5111 // There are two ways that T(v) can work when T is an enumeration type.
5112 // If there is either an implicit conversion sequence from v to T or
5113 // a conversion function that can convert from v to T, then we use that.
5114 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
5115 // type, it is converted to the enumeration type via its underlying type.
5116 // There is no overlap possible between these two cases (except when the
5117 // source value is already of the destination type), and the first
5118 // case is handled by the general case for single-element lists below.
5120 ICS.setStandard();
5122 if (!E->isPRValue())
5124 // If E is of a floating-point type, then the conversion is ill-formed
5125 // due to narrowing, but go through the motions in order to produce the
5126 // right diagnostic.
5130 ICS.Standard.setFromType(E->getType());
5131 ICS.Standard.setToType(0, E->getType());
5132 ICS.Standard.setToType(1, DestType);
5133 ICS.Standard.setToType(2, DestType);
5134 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
5135 /*TopLevelOfInitList*/true);
5136 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5137 return;
5138 }
5139
5140 // - Otherwise, if the initializer list has a single element of type E
5141 // [...references are handled above...], the object or reference is
5142 // initialized from that element (by copy-initialization for
5143 // copy-list-initialization, or by direct-initialization for
5144 // direct-list-initialization); if a narrowing conversion is required
5145 // to convert the element to T, the program is ill-formed.
5146 //
5147 // Per core-24034, this is direct-initialization if we were performing
5148 // direct-list-initialization and copy-initialization otherwise.
5149 // We can't use InitListChecker for this, because it always performs
5150 // copy-initialization. This only matters if we might use an 'explicit'
5151 // conversion operator, or for the special case conversion of nullptr_t to
5152 // bool, so we only need to handle those cases.
5153 //
5154 // FIXME: Why not do this in all cases?
5155 Expr *Init = InitList->getInit(0);
5156 if (Init->getType()->isRecordType() ||
5157 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
5158 InitializationKind SubKind =
5160 ? InitializationKind::CreateDirect(Kind.getLocation(),
5161 InitList->getLBraceLoc(),
5162 InitList->getRBraceLoc())
5163 : Kind;
5164 Expr *SubInit[1] = { Init };
5165 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
5166 /*TopLevelOfInitList*/true,
5167 TreatUnavailableAsInvalid);
5168 if (Sequence)
5169 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5170 return;
5171 }
5172 }
5173
5174 InitListChecker CheckInitList(S, Entity, InitList,
5175 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
5176 if (CheckInitList.HadError()) {
5178 return;
5179 }
5180
5181 // Add the list initialization step with the built init list.
5182 Sequence.AddListInitializationStep(DestType);
5183}
5184
5185/// Try a reference initialization that involves calling a conversion
5186/// function.
5188 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5189 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
5190 InitializationSequence &Sequence) {
5191 QualType DestType = Entity.getType();
5192 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5193 QualType T1 = cv1T1.getUnqualifiedType();
5194 QualType cv2T2 = Initializer->getType();
5195 QualType T2 = cv2T2.getUnqualifiedType();
5196
5197 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
5198 "Must have incompatible references when binding via conversion");
5199
5200 // Build the candidate set directly in the initialization sequence
5201 // structure, so that it will persist if we fail.
5202 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5204
5205 // Determine whether we are allowed to call explicit conversion operators.
5206 // Note that none of [over.match.copy], [over.match.conv], nor
5207 // [over.match.ref] permit an explicit constructor to be chosen when
5208 // initializing a reference, not even for direct-initialization.
5209 bool AllowExplicitCtors = false;
5210 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
5211
5212 if (AllowRValues && T1->isRecordType() &&
5213 S.isCompleteType(Kind.getLocation(), T1)) {
5214 auto *T1RecordDecl = T1->castAsCXXRecordDecl();
5215 if (T1RecordDecl->isInvalidDecl())
5216 return OR_No_Viable_Function;
5217 // The type we're converting to is a class type. Enumerate its constructors
5218 // to see if there is a suitable conversion.
5219 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
5220 auto Info = getConstructorInfo(D);
5221 if (!Info.Constructor)
5222 continue;
5223
5224 if (!Info.Constructor->isInvalidDecl() &&
5225 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5226 if (Info.ConstructorTmpl)
5228 Info.ConstructorTmpl, Info.FoundDecl,
5229 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5230 /*SuppressUserConversions=*/true,
5231 /*PartialOverloading*/ false, AllowExplicitCtors);
5232 else
5234 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
5235 /*SuppressUserConversions=*/true,
5236 /*PartialOverloading*/ false, AllowExplicitCtors);
5237 }
5238 }
5239 }
5240
5241 if (T2->isRecordType() && S.isCompleteType(Kind.getLocation(), T2)) {
5242 const auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5243 if (T2RecordDecl->isInvalidDecl())
5244 return OR_No_Viable_Function;
5245 // The type we're converting from is a class type, enumerate its conversion
5246 // functions.
5247 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5248 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5249 NamedDecl *D = *I;
5251 if (isa<UsingShadowDecl>(D))
5252 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5253
5254 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5255 CXXConversionDecl *Conv;
5256 if (ConvTemplate)
5257 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5258 else
5259 Conv = cast<CXXConversionDecl>(D);
5260
5261 // If the conversion function doesn't return a reference type,
5262 // it can't be considered for this conversion unless we're allowed to
5263 // consider rvalues.
5264 // FIXME: Do we need to make sure that we only consider conversion
5265 // candidates with reference-compatible results? That might be needed to
5266 // break recursion.
5267 if ((AllowRValues ||
5269 if (ConvTemplate)
5271 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5272 CandidateSet,
5273 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5274 else
5276 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
5277 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5278 }
5279 }
5280 }
5281
5282 SourceLocation DeclLoc = Initializer->getBeginLoc();
5283
5284 // Perform overload resolution. If it fails, return the failed result.
5286 if (OverloadingResult Result
5287 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
5288 return Result;
5289
5290 FunctionDecl *Function = Best->Function;
5291 // This is the overload that will be used for this initialization step if we
5292 // use this initialization. Mark it as referenced.
5293 Function->setReferenced();
5294
5295 // Compute the returned type and value kind of the conversion.
5296 QualType cv3T3;
5297 if (isa<CXXConversionDecl>(Function))
5298 cv3T3 = Function->getReturnType();
5299 else
5300 cv3T3 = T1;
5301
5303 if (cv3T3->isLValueReferenceType())
5304 VK = VK_LValue;
5305 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
5306 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
5307 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
5308
5309 // Add the user-defined conversion step.
5310 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5311 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
5312 HadMultipleCandidates);
5313
5314 // Determine whether we'll need to perform derived-to-base adjustments or
5315 // other conversions.
5317 Sema::ReferenceCompareResult NewRefRelationship =
5318 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
5319
5320 // Add the final conversion sequence, if necessary.
5321 if (NewRefRelationship == Sema::Ref_Incompatible) {
5322 assert(Best->HasFinalConversion && !isa<CXXConstructorDecl>(Function) &&
5323 "should not have conversion after constructor");
5324
5326 ICS.setStandard();
5327 ICS.Standard = Best->FinalConversion;
5328 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
5329
5330 // Every implicit conversion results in a prvalue, except for a glvalue
5331 // derived-to-base conversion, which we handle below.
5332 cv3T3 = ICS.Standard.getToType(2);
5333 VK = VK_PRValue;
5334 }
5335
5336 // If the converted initializer is a prvalue, its type T4 is adjusted to
5337 // type "cv1 T4" and the temporary materialization conversion is applied.
5338 //
5339 // We adjust the cv-qualifications to match the reference regardless of
5340 // whether we have a prvalue so that the AST records the change. In this
5341 // case, T4 is "cv3 T3".
5342 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
5343 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
5344 Sequence.AddQualificationConversionStep(cv1T4, VK);
5345 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
5346 VK = IsLValueRef ? VK_LValue : VK_XValue;
5347
5348 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5349 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
5350 else if (RefConv & Sema::ReferenceConversions::ObjC)
5351 Sequence.AddObjCObjectConversionStep(cv1T1);
5352 else if (RefConv & Sema::ReferenceConversions::Function)
5353 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5354 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5355 if (!S.Context.hasSameType(cv1T4, cv1T1))
5356 Sequence.AddQualificationConversionStep(cv1T1, VK);
5357 }
5358
5359 return OR_Success;
5360}
5361
5362static void CheckCXX98CompatAccessibleCopy(Sema &S,
5363 const InitializedEntity &Entity,
5364 Expr *CurInitExpr);
5365
5366/// Attempt reference initialization (C++0x [dcl.init.ref])
5368 const InitializationKind &Kind,
5370 InitializationSequence &Sequence,
5371 bool TopLevelOfInitList) {
5372 QualType DestType = Entity.getType();
5373 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5374 Qualifiers T1Quals;
5375 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
5377 Qualifiers T2Quals;
5378 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
5379
5380 // If the initializer is the address of an overloaded function, try
5381 // to resolve the overloaded function. If all goes well, T2 is the
5382 // type of the resulting function.
5384 T1, Sequence))
5385 return;
5386
5387 // Delegate everything else to a subfunction.
5388 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
5389 T1Quals, cv2T2, T2, T2Quals, Sequence,
5390 TopLevelOfInitList);
5391}
5392
5393/// Determine whether an expression is a non-referenceable glvalue (one to
5394/// which a reference can never bind). Attempting to bind a reference to
5395/// such a glvalue will always create a temporary.
5397 return E->refersToBitField() || E->refersToVectorElement() ||
5399}
5400
5401/// Reference initialization without resolving overloaded functions.
5402///
5403/// We also can get here in C if we call a builtin which is declared as
5404/// a function with a parameter of reference type (such as __builtin_va_end()).
5406 const InitializedEntity &Entity,
5407 const InitializationKind &Kind,
5409 QualType cv1T1, QualType T1,
5410 Qualifiers T1Quals,
5411 QualType cv2T2, QualType T2,
5412 Qualifiers T2Quals,
5413 InitializationSequence &Sequence,
5414 bool TopLevelOfInitList) {
5415 QualType DestType = Entity.getType();
5416 SourceLocation DeclLoc = Initializer->getBeginLoc();
5417
5418 // Compute some basic properties of the types and the initializer.
5419 bool isLValueRef = DestType->isLValueReferenceType();
5420 bool isRValueRef = !isLValueRef;
5421 Expr::Classification InitCategory = Initializer->Classify(S.Context);
5422
5424 Sema::ReferenceCompareResult RefRelationship =
5425 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
5426
5427 // C++0x [dcl.init.ref]p5:
5428 // A reference to type "cv1 T1" is initialized by an expression of type
5429 // "cv2 T2" as follows:
5430 //
5431 // - If the reference is an lvalue reference and the initializer
5432 // expression
5433 // Note the analogous bullet points for rvalue refs to functions. Because
5434 // there are no function rvalues in C++, rvalue refs to functions are treated
5435 // like lvalue refs.
5436 OverloadingResult ConvOvlResult = OR_Success;
5437 bool T1Function = T1->isFunctionType();
5438 if (isLValueRef || T1Function) {
5439 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
5440 (RefRelationship == Sema::Ref_Compatible ||
5441 (Kind.isCStyleOrFunctionalCast() &&
5442 RefRelationship == Sema::Ref_Related))) {
5443 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5444 // reference-compatible with "cv2 T2," or
5445 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5446 Sema::ReferenceConversions::ObjC)) {
5447 // If we're converting the pointee, add any qualifiers first;
5448 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5449 if (RefConv & (Sema::ReferenceConversions::Qualification))
5451 S.Context.getQualifiedType(T2, T1Quals),
5452 Initializer->getValueKind());
5453 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5454 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
5455 else
5456 Sequence.AddObjCObjectConversionStep(cv1T1);
5457 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5458 // Perform a (possibly multi-level) qualification conversion.
5459 Sequence.AddQualificationConversionStep(cv1T1,
5460 Initializer->getValueKind());
5461 } else if (RefConv & Sema::ReferenceConversions::Function) {
5462 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5463 }
5464
5465 // We only create a temporary here when binding a reference to a
5466 // bit-field or vector element. Those cases are't supposed to be
5467 // handled by this bullet, but the outcome is the same either way.
5468 Sequence.AddReferenceBindingStep(cv1T1, false);
5469 return;
5470 }
5471
5472 // - has a class type (i.e., T2 is a class type), where T1 is not
5473 // reference-related to T2, and can be implicitly converted to an
5474 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5475 // with "cv3 T3" (this conversion is selected by enumerating the
5476 // applicable conversion functions (13.3.1.6) and choosing the best
5477 // one through overload resolution (13.3)),
5478 // If we have an rvalue ref to function type here, the rhs must be
5479 // an rvalue. DR1287 removed the "implicitly" here.
5480 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5481 (isLValueRef || InitCategory.isRValue())) {
5482 if (S.getLangOpts().CPlusPlus) {
5483 // Try conversion functions only for C++.
5484 ConvOvlResult = TryRefInitWithConversionFunction(
5485 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5486 /*IsLValueRef*/ isLValueRef, Sequence);
5487 if (ConvOvlResult == OR_Success)
5488 return;
5489 if (ConvOvlResult != OR_No_Viable_Function)
5490 Sequence.SetOverloadFailure(
5492 ConvOvlResult);
5493 } else {
5494 ConvOvlResult = OR_No_Viable_Function;
5495 }
5496 }
5497 }
5498
5499 // - Otherwise, the reference shall be an lvalue reference to a
5500 // non-volatile const type (i.e., cv1 shall be const), or the reference
5501 // shall be an rvalue reference.
5502 // For address spaces, we interpret this to mean that an addr space
5503 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5504 if (isLValueRef &&
5505 !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5506 T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext()))) {
5509 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5510 Sequence.SetOverloadFailure(
5512 ConvOvlResult);
5513 else if (!InitCategory.isLValue())
5514 Sequence.SetFailed(
5515 T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())
5519 else {
5521 switch (RefRelationship) {
5523 if (Initializer->refersToBitField())
5524 FK = InitializationSequence::
5525 FK_NonConstLValueReferenceBindingToBitfield;
5526 else if (Initializer->refersToVectorElement())
5527 FK = InitializationSequence::
5528 FK_NonConstLValueReferenceBindingToVectorElement;
5529 else if (Initializer->refersToMatrixElement())
5530 FK = InitializationSequence::
5531 FK_NonConstLValueReferenceBindingToMatrixElement;
5532 else
5533 llvm_unreachable("unexpected kind of compatible initializer");
5534 break;
5535 case Sema::Ref_Related:
5537 break;
5539 FK = InitializationSequence::
5540 FK_NonConstLValueReferenceBindingToUnrelated;
5541 break;
5542 }
5543 Sequence.SetFailed(FK);
5544 }
5545 return;
5546 }
5547
5548 // - If the initializer expression
5549 // - is an
5550 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5551 // [1z] rvalue (but not a bit-field) or
5552 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5553 //
5554 // Note: functions are handled above and below rather than here...
5555 if (!T1Function &&
5556 (RefRelationship == Sema::Ref_Compatible ||
5557 (Kind.isCStyleOrFunctionalCast() &&
5558 RefRelationship == Sema::Ref_Related)) &&
5559 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5560 (InitCategory.isPRValue() &&
5561 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5562 T2->isArrayType())))) {
5563 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5564 if (InitCategory.isPRValue() && T2->isRecordType()) {
5565 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5566 // compiler the freedom to perform a copy here or bind to the
5567 // object, while C++0x requires that we bind directly to the
5568 // object. Hence, we always bind to the object without making an
5569 // extra copy. However, in C++03 requires that we check for the
5570 // presence of a suitable copy constructor:
5571 //
5572 // The constructor that would be used to make the copy shall
5573 // be callable whether or not the copy is actually done.
5574 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5575 Sequence.AddExtraneousCopyToTemporary(cv2T2);
5576 else if (S.getLangOpts().CPlusPlus11)
5578 }
5579
5580 // C++1z [dcl.init.ref]/5.2.1.2:
5581 // If the converted initializer is a prvalue, its type T4 is adjusted
5582 // to type "cv1 T4" and the temporary materialization conversion is
5583 // applied.
5584 // Postpone address space conversions to after the temporary materialization
5585 // conversion to allow creating temporaries in the alloca address space.
5586 auto T1QualsIgnoreAS = T1Quals;
5587 auto T2QualsIgnoreAS = T2Quals;
5588 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5589 T1QualsIgnoreAS.removeAddressSpace();
5590 T2QualsIgnoreAS.removeAddressSpace();
5591 }
5592 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
5593 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5594 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5595 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5596 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5597 // Add addr space conversion if required.
5598 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5599 auto T4Quals = cv1T4.getQualifiers();
5600 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5601 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5602 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5603 cv1T4 = cv1T4WithAS;
5604 }
5605
5606 // In any case, the reference is bound to the resulting glvalue (or to
5607 // an appropriate base class subobject).
5608 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5609 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5610 else if (RefConv & Sema::ReferenceConversions::ObjC)
5611 Sequence.AddObjCObjectConversionStep(cv1T1);
5612 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5613 if (!S.Context.hasSameType(cv1T4, cv1T1))
5614 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5615 }
5616 return;
5617 }
5618
5619 // - has a class type (i.e., T2 is a class type), where T1 is not
5620 // reference-related to T2, and can be implicitly converted to an
5621 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5622 // where "cv1 T1" is reference-compatible with "cv3 T3",
5623 //
5624 // DR1287 removes the "implicitly" here.
5625 if (T2->isRecordType()) {
5626 if (RefRelationship == Sema::Ref_Incompatible) {
5627 ConvOvlResult = TryRefInitWithConversionFunction(
5628 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5629 /*IsLValueRef*/ isLValueRef, Sequence);
5630 if (ConvOvlResult)
5631 Sequence.SetOverloadFailure(
5633 ConvOvlResult);
5634
5635 return;
5636 }
5637
5638 if (RefRelationship == Sema::Ref_Compatible &&
5639 isRValueRef && InitCategory.isLValue()) {
5640 Sequence.SetFailed(
5642 return;
5643 }
5644
5646 return;
5647 }
5648
5649 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5650 // from the initializer expression using the rules for a non-reference
5651 // copy-initialization (8.5). The reference is then bound to the
5652 // temporary. [...]
5653
5654 // Ignore address space of reference type at this point and perform address
5655 // space conversion after the reference binding step.
5656 QualType cv1T1IgnoreAS =
5657 T1Quals.hasAddressSpace()
5659 : cv1T1;
5660
5661 InitializedEntity TempEntity =
5663
5664 // FIXME: Why do we use an implicit conversion here rather than trying
5665 // copy-initialization?
5667 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5668 /*SuppressUserConversions=*/false,
5669 Sema::AllowedExplicit::None,
5670 /*FIXME:InOverloadResolution=*/false,
5671 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5672 /*AllowObjCWritebackConversion=*/false);
5673
5674 if (ICS.isBad()) {
5675 // FIXME: Use the conversion function set stored in ICS to turn
5676 // this into an overloading ambiguity diagnostic. However, we need
5677 // to keep that set as an OverloadCandidateSet rather than as some
5678 // other kind of set.
5679 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5680 Sequence.SetOverloadFailure(
5682 ConvOvlResult);
5683 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5685 else
5687 return;
5688 } else {
5689 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType(),
5690 TopLevelOfInitList);
5691 }
5692
5693 // [...] If T1 is reference-related to T2, cv1 must be the
5694 // same cv-qualification as, or greater cv-qualification
5695 // than, cv2; otherwise, the program is ill-formed.
5696 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5697 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5698 if (RefRelationship == Sema::Ref_Related &&
5699 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5700 !T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext()))) {
5702 return;
5703 }
5704
5705 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5706 // reference, the initializer expression shall not be an lvalue.
5707 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5708 InitCategory.isLValue()) {
5709 Sequence.SetFailed(
5711 return;
5712 }
5713
5714 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5715
5716 if (T1Quals.hasAddressSpace()) {
5719 Sequence.SetFailed(
5721 return;
5722 }
5723 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5724 : VK_XValue);
5725 }
5726}
5727
5728/// Attempt character array initialization from a string literal
5729/// (C++ [dcl.init.string], C99 6.7.8).
5731 const InitializedEntity &Entity,
5732 const InitializationKind &Kind,
5734 InitializationSequence &Sequence) {
5735 Sequence.AddStringInitStep(Entity.getType());
5736}
5737
5738/// Attempt value initialization (C++ [dcl.init]p7).
5740 const InitializedEntity &Entity,
5741 const InitializationKind &Kind,
5742 InitializationSequence &Sequence,
5743 InitListExpr *InitList) {
5744 assert((!InitList || InitList->getNumInits() == 0) &&
5745 "Shouldn't use value-init for non-empty init lists");
5746
5747 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5748 //
5749 // To value-initialize an object of type T means:
5750 QualType T = Entity.getType();
5751 assert(!T->isVoidType() && "Cannot value-init void");
5752
5753 // -- if T is an array type, then each element is value-initialized;
5755
5756 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
5757 bool NeedZeroInitialization = true;
5758 // C++98:
5759 // -- if T is a class type (clause 9) with a user-declared constructor
5760 // (12.1), then the default constructor for T is called (and the
5761 // initialization is ill-formed if T has no accessible default
5762 // constructor);
5763 // C++11:
5764 // -- if T is a class type (clause 9) with either no default constructor
5765 // (12.1 [class.ctor]) or a default constructor that is user-provided
5766 // or deleted, then the object is default-initialized;
5767 //
5768 // Note that the C++11 rule is the same as the C++98 rule if there are no
5769 // defaulted or deleted constructors, so we just use it unconditionally.
5771 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5772 NeedZeroInitialization = false;
5773
5774 // -- if T is a (possibly cv-qualified) non-union class type without a
5775 // user-provided or deleted default constructor, then the object is
5776 // zero-initialized and, if T has a non-trivial default constructor,
5777 // default-initialized;
5778 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5779 // constructor' part was removed by DR1507.
5780 if (NeedZeroInitialization)
5781 Sequence.AddZeroInitializationStep(Entity.getType());
5782
5783 // C++03:
5784 // -- if T is a non-union class type without a user-declared constructor,
5785 // then every non-static data member and base class component of T is
5786 // value-initialized;
5787 // [...] A program that calls for [...] value-initialization of an
5788 // entity of reference type is ill-formed.
5789 //
5790 // C++11 doesn't need this handling, because value-initialization does not
5791 // occur recursively there, and the implicit default constructor is
5792 // defined as deleted in the problematic cases.
5793 if (!S.getLangOpts().CPlusPlus11 &&
5794 ClassDecl->hasUninitializedReferenceMember()) {
5796 return;
5797 }
5798
5799 // If this is list-value-initialization, pass the empty init list on when
5800 // building the constructor call. This affects the semantics of a few
5801 // things (such as whether an explicit default constructor can be called).
5802 Expr *InitListAsExpr = InitList;
5803 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5804 bool InitListSyntax = InitList;
5805
5806 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5807 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5809 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5810 }
5811
5812 Sequence.AddZeroInitializationStep(Entity.getType());
5813}
5814
5815/// Attempt default initialization (C++ [dcl.init]p6).
5817 const InitializedEntity &Entity,
5818 const InitializationKind &Kind,
5819 InitializationSequence &Sequence) {
5820 assert(Kind.getKind() == InitializationKind::IK_Default);
5821
5822 // C++ [dcl.init]p6:
5823 // To default-initialize an object of type T means:
5824 // - if T is an array type, each element is default-initialized;
5825 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5826
5827 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5828 // constructor for T is called (and the initialization is ill-formed if
5829 // T has no accessible default constructor);
5830 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5831 TryConstructorInitialization(S, Entity, Kind, {}, DestType,
5832 Entity.getType(), Sequence);
5833 return;
5834 }
5835
5836 // - otherwise, no initialization is performed.
5837
5838 // If a program calls for the default initialization of an object of
5839 // a const-qualified type T, T shall be a class type with a user-provided
5840 // default constructor.
5841 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5842 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5844 return;
5845 }
5846
5847 // If the destination type has a lifetime property, zero-initialize it.
5848 if (DestType.getQualifiers().hasObjCLifetime()) {
5849 Sequence.AddZeroInitializationStep(Entity.getType());
5850 return;
5851 }
5852}
5853
5855 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5856 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5857 ExprResult *Result) {
5858 unsigned EntityIndexToProcess = 0;
5859 SmallVector<Expr *, 4> InitExprs;
5860 QualType ResultType;
5861 Expr *ArrayFiller = nullptr;
5862 FieldDecl *InitializedFieldInUnion = nullptr;
5863
5864 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5865 const InitializationKind &SubKind,
5866 Expr *Arg, Expr **InitExpr = nullptr) {
5868 S, SubEntity, SubKind,
5869 Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5870
5871 if (IS.Failed()) {
5872 if (!VerifyOnly) {
5873 IS.Diagnose(S, SubEntity, SubKind,
5874 Arg ? ArrayRef(Arg) : ArrayRef<Expr *>());
5875 } else {
5876 Sequence.SetFailed(
5878 }
5879
5880 return false;
5881 }
5882 if (!VerifyOnly) {
5883 ExprResult ER;
5884 ER = IS.Perform(S, SubEntity, SubKind,
5885 Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5886
5887 if (ER.isInvalid())
5888 return false;
5889
5890 if (InitExpr)
5891 *InitExpr = ER.get();
5892 else
5893 InitExprs.push_back(ER.get());
5894 }
5895 return true;
5896 };
5897
5898 if (const ArrayType *AT =
5899 S.getASTContext().getAsArrayType(Entity.getType())) {
5900 uint64_t ArrayLength;
5901 // C++ [dcl.init]p16.5
5902 // if the destination type is an array, the object is initialized as
5903 // follows. Let x1, . . . , xk be the elements of the expression-list. If
5904 // the destination type is an array of unknown bound, it is defined as
5905 // having k elements.
5906 if (const ConstantArrayType *CAT =
5908 ArrayLength = CAT->getZExtSize();
5909 ResultType = Entity.getType();
5910 } else if (const VariableArrayType *VAT =
5912 // Braced-initialization of variable array types is not allowed, even if
5913 // the size is greater than or equal to the number of args, so we don't
5914 // allow them to be initialized via parenthesized aggregate initialization
5915 // either.
5916 const Expr *SE = VAT->getSizeExpr();
5917 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
5918 << SE->getSourceRange();
5919 return;
5920 } else {
5921 assert(Entity.getType()->isIncompleteArrayType());
5922 ArrayLength = Args.size();
5923 }
5924 EntityIndexToProcess = ArrayLength;
5925
5926 // ...the ith array element is copy-initialized with xi for each
5927 // 1 <= i <= k
5928 for (Expr *E : Args) {
5930 S.getASTContext(), EntityIndexToProcess, Entity);
5932 E->getExprLoc(), /*isDirectInit=*/false, E);
5933 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5934 return;
5935 }
5936 // ...and value-initialized for each k < i <= n;
5937 if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {
5939 S.getASTContext(), Args.size(), Entity);
5941 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5942 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
5943 return;
5944 }
5945
5946 if (ResultType.isNull()) {
5947 ResultType = S.Context.getConstantArrayType(
5948 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
5949 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 0);
5950 }
5951 } else if (auto *RD = Entity.getType()->getAsCXXRecordDecl()) {
5952 bool IsUnion = RD->isUnion();
5953 if (RD->isInvalidDecl()) {
5954 // Exit early to avoid confusion when processing members.
5955 // We do the same for braced list initialization in
5956 // `CheckStructUnionTypes`.
5957 Sequence.SetFailed(
5959 return;
5960 }
5961
5962 if (!IsUnion) {
5963 for (const CXXBaseSpecifier &Base : RD->bases()) {
5965 S.getASTContext(), &Base, false, &Entity);
5966 if (EntityIndexToProcess < Args.size()) {
5967 // C++ [dcl.init]p16.6.2.2.
5968 // ...the object is initialized is follows. Let e1, ..., en be the
5969 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
5970 // the elements of the expression-list...The element ei is
5971 // copy-initialized with xi for 1 <= i <= k.
5972 Expr *E = Args[EntityIndexToProcess];
5974 E->getExprLoc(), /*isDirectInit=*/false, E);
5975 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5976 return;
5977 } else {
5978 // We've processed all of the args, but there are still base classes
5979 // that have to be initialized.
5980 // C++ [dcl.init]p17.6.2.2
5981 // The remaining elements...otherwise are value initialzed
5983 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
5984 /*IsImplicit=*/true);
5985 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5986 return;
5987 }
5988 EntityIndexToProcess++;
5989 }
5990 }
5991
5992 for (FieldDecl *FD : RD->fields()) {
5993 // Unnamed bitfields should not be initialized at all, either with an arg
5994 // or by default.
5995 if (FD->isUnnamedBitField())
5996 continue;
5997
5998 InitializedEntity SubEntity =
6000
6001 if (EntityIndexToProcess < Args.size()) {
6002 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
6003 Expr *E = Args[EntityIndexToProcess];
6004
6005 // Incomplete array types indicate flexible array members. Do not allow
6006 // paren list initializations of structs with these members, as GCC
6007 // doesn't either.
6008 if (FD->getType()->isIncompleteArrayType()) {
6009 if (!VerifyOnly) {
6010 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
6011 << SourceRange(E->getBeginLoc(), E->getEndLoc());
6012 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
6013 }
6014 Sequence.SetFailed(
6016 return;
6017 }
6018
6020 E->getExprLoc(), /*isDirectInit=*/false, E);
6021 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6022 return;
6023
6024 // Unions should have only one initializer expression, so we bail out
6025 // after processing the first field. If there are more initializers then
6026 // it will be caught when we later check whether EntityIndexToProcess is
6027 // less than Args.size();
6028 if (IsUnion) {
6029 InitializedFieldInUnion = FD;
6030 EntityIndexToProcess = 1;
6031 break;
6032 }
6033 } else {
6034 // We've processed all of the args, but there are still members that
6035 // have to be initialized.
6036 if (!VerifyOnly && FD->hasAttr<ExplicitInitAttr>() &&
6037 !S.isUnevaluatedContext()) {
6038 S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
6039 << /* Var-in-Record */ 0 << FD;
6040 S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
6041 }
6042
6043 if (FD->hasInClassInitializer()) {
6044 if (!VerifyOnly) {
6045 // C++ [dcl.init]p16.6.2.2
6046 // The remaining elements are initialized with their default
6047 // member initializers, if any
6049 Kind.getParenOrBraceRange().getEnd(), FD);
6050 if (DIE.isInvalid())
6051 return;
6052 S.checkInitializerLifetime(SubEntity, DIE.get());
6053 InitExprs.push_back(DIE.get());
6054 }
6055 } else {
6056 // C++ [dcl.init]p17.6.2.2
6057 // The remaining elements...otherwise are value initialzed
6058 if (FD->getType()->isReferenceType()) {
6059 Sequence.SetFailed(
6061 if (!VerifyOnly) {
6062 SourceRange SR = Kind.getParenOrBraceRange();
6063 S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
6064 << FD->getType() << SR;
6065 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
6066 }
6067 return;
6068 }
6070 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
6071 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6072 return;
6073 }
6074 }
6075 EntityIndexToProcess++;
6076 }
6077 ResultType = Entity.getType();
6078 }
6079
6080 // Not all of the args have been processed, so there must've been more args
6081 // than were required to initialize the element.
6082 if (EntityIndexToProcess < Args.size()) {
6084 if (!VerifyOnly) {
6085 QualType T = Entity.getType();
6086 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 4 : 5;
6087 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
6088 Args.back()->getEndLoc());
6089 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6090 << InitKind << ExcessInitSR;
6091 }
6092 return;
6093 }
6094
6095 if (VerifyOnly) {
6097 Sequence.AddParenthesizedListInitStep(Entity.getType());
6098 } else if (Result) {
6099 SourceRange SR = Kind.getParenOrBraceRange();
6100 auto *CPLIE = CXXParenListInitExpr::Create(
6101 S.getASTContext(), InitExprs, ResultType, Args.size(),
6102 Kind.getLocation(), SR.getBegin(), SR.getEnd());
6103 if (ArrayFiller)
6104 CPLIE->setArrayFiller(ArrayFiller);
6105 if (InitializedFieldInUnion)
6106 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
6107 *Result = CPLIE;
6108 S.Diag(Kind.getLocation(),
6109 diag::warn_cxx17_compat_aggregate_init_paren_list)
6110 << Kind.getLocation() << SR << ResultType;
6111 }
6112}
6113
6114/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
6115/// which enumerates all conversion functions and performs overload resolution
6116/// to select the best.
6118 QualType DestType,
6119 const InitializationKind &Kind,
6121 InitializationSequence &Sequence,
6122 bool TopLevelOfInitList) {
6123 assert(!DestType->isReferenceType() && "References are handled elsewhere");
6124 QualType SourceType = Initializer->getType();
6125 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
6126 "Must have a class type to perform a user-defined conversion");
6127
6128 // Build the candidate set directly in the initialization sequence
6129 // structure, so that it will persist if we fail.
6130 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
6132 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
6133
6134 // Determine whether we are allowed to call explicit constructors or
6135 // explicit conversion operators.
6136 bool AllowExplicit = Kind.AllowExplicit();
6137
6138 if (DestType->isRecordType()) {
6139 // The type we're converting to is a class type. Enumerate its constructors
6140 // to see if there is a suitable conversion.
6141 // Try to complete the type we're converting to.
6142 if (S.isCompleteType(Kind.getLocation(), DestType)) {
6143 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
6144 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
6145 auto Info = getConstructorInfo(D);
6146 if (!Info.Constructor)
6147 continue;
6148
6149 if (!Info.Constructor->isInvalidDecl() &&
6150 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
6151 if (Info.ConstructorTmpl)
6153 Info.ConstructorTmpl, Info.FoundDecl,
6154 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
6155 /*SuppressUserConversions=*/true,
6156 /*PartialOverloading*/ false, AllowExplicit);
6157 else
6158 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
6159 Initializer, CandidateSet,
6160 /*SuppressUserConversions=*/true,
6161 /*PartialOverloading*/ false, AllowExplicit);
6162 }
6163 }
6164 }
6165 }
6166
6167 SourceLocation DeclLoc = Initializer->getBeginLoc();
6168
6169 if (SourceType->isRecordType()) {
6170 // The type we're converting from is a class type, enumerate its conversion
6171 // functions.
6172
6173 // We can only enumerate the conversion functions for a complete type; if
6174 // the type isn't complete, simply skip this step.
6175 if (S.isCompleteType(DeclLoc, SourceType)) {
6176 auto *SourceRecordDecl = SourceType->castAsCXXRecordDecl();
6177 const auto &Conversions =
6178 SourceRecordDecl->getVisibleConversionFunctions();
6179 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6180 NamedDecl *D = *I;
6182 if (isa<UsingShadowDecl>(D))
6183 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6184
6185 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6186 CXXConversionDecl *Conv;
6187 if (ConvTemplate)
6188 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6189 else
6190 Conv = cast<CXXConversionDecl>(D);
6191
6192 if (ConvTemplate)
6194 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
6195 CandidateSet, AllowExplicit, AllowExplicit);
6196 else
6197 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
6198 DestType, CandidateSet, AllowExplicit,
6199 AllowExplicit);
6200 }
6201 }
6202 }
6203
6204 // Perform overload resolution. If it fails, return the failed result.
6206 if (OverloadingResult Result
6207 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
6208 Sequence.SetOverloadFailure(
6210
6211 // [class.copy.elision]p3:
6212 // In some copy-initialization contexts, a two-stage overload resolution
6213 // is performed.
6214 // If the first overload resolution selects a deleted function, we also
6215 // need the initialization sequence to decide whether to perform the second
6216 // overload resolution.
6217 if (!(Result == OR_Deleted &&
6218 Kind.getKind() == InitializationKind::IK_Copy))
6219 return;
6220 }
6221
6222 FunctionDecl *Function = Best->Function;
6223 Function->setReferenced();
6224 bool HadMultipleCandidates = (CandidateSet.size() > 1);
6225
6226 if (isa<CXXConstructorDecl>(Function)) {
6227 // Add the user-defined conversion step. Any cv-qualification conversion is
6228 // subsumed by the initialization. Per DR5, the created temporary is of the
6229 // cv-unqualified type of the destination.
6230 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
6231 DestType.getUnqualifiedType(),
6232 HadMultipleCandidates);
6233
6234 // C++14 and before:
6235 // - if the function is a constructor, the call initializes a temporary
6236 // of the cv-unqualified version of the destination type. The [...]
6237 // temporary [...] is then used to direct-initialize, according to the
6238 // rules above, the object that is the destination of the
6239 // copy-initialization.
6240 // Note that this just performs a simple object copy from the temporary.
6241 //
6242 // C++17:
6243 // - if the function is a constructor, the call is a prvalue of the
6244 // cv-unqualified version of the destination type whose return object
6245 // is initialized by the constructor. The call is used to
6246 // direct-initialize, according to the rules above, the object that
6247 // is the destination of the copy-initialization.
6248 // Therefore we need to do nothing further.
6249 //
6250 // FIXME: Mark this copy as extraneous.
6251 if (!S.getLangOpts().CPlusPlus17)
6252 Sequence.AddFinalCopy(DestType);
6253 else if (DestType.hasQualifiers())
6254 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6255 return;
6256 }
6257
6258 // Add the user-defined conversion step that calls the conversion function.
6259 QualType ConvType = Function->getCallResultType();
6260 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
6261 HadMultipleCandidates);
6262
6263 if (ConvType->isRecordType()) {
6264 // The call is used to direct-initialize [...] the object that is the
6265 // destination of the copy-initialization.
6266 //
6267 // In C++17, this does not call a constructor if we enter /17.6.1:
6268 // - If the initializer expression is a prvalue and the cv-unqualified
6269 // version of the source type is the same as the class of the
6270 // destination [... do not make an extra copy]
6271 //
6272 // FIXME: Mark this copy as extraneous.
6273 if (!S.getLangOpts().CPlusPlus17 ||
6274 Function->getReturnType()->isReferenceType() ||
6275 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
6276 Sequence.AddFinalCopy(DestType);
6277 else if (!S.Context.hasSameType(ConvType, DestType))
6278 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6279 return;
6280 }
6281
6282 // If the conversion following the call to the conversion function
6283 // is interesting, add it as a separate step.
6284 assert(Best->HasFinalConversion);
6285 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
6286 Best->FinalConversion.Third) {
6288 ICS.setStandard();
6289 ICS.Standard = Best->FinalConversion;
6290 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6291 }
6292}
6293
6294/// The non-zero enum values here are indexes into diagnostic alternatives.
6296
6297/// Determines whether this expression is an acceptable ICR source.
6299 bool isAddressOf, bool &isWeakAccess) {
6300 // Skip parens.
6301 e = e->IgnoreParens();
6302
6303 // Skip address-of nodes.
6304 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
6305 if (op->getOpcode() == UO_AddrOf)
6306 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
6307 isWeakAccess);
6308
6309 // Skip certain casts.
6310 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
6311 switch (ce->getCastKind()) {
6312 case CK_Dependent:
6313 case CK_BitCast:
6314 case CK_LValueBitCast:
6315 case CK_NoOp:
6316 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
6317
6318 case CK_ArrayToPointerDecay:
6319 return IIK_nonscalar;
6320
6321 case CK_NullToPointer:
6322 return IIK_okay;
6323
6324 default:
6325 break;
6326 }
6327
6328 // If we have a declaration reference, it had better be a local variable.
6329 } else if (isa<DeclRefExpr>(e)) {
6330 // set isWeakAccess to true, to mean that there will be an implicit
6331 // load which requires a cleanup.
6333 isWeakAccess = true;
6334
6335 if (!isAddressOf) return IIK_nonlocal;
6336
6337 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
6338 if (!var) return IIK_nonlocal;
6339
6340 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
6341
6342 // If we have a conditional operator, check both sides.
6343 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
6344 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
6345 isWeakAccess))
6346 return iik;
6347
6348 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
6349
6350 // These are never scalar.
6351 } else if (isa<ArraySubscriptExpr>(e)) {
6352 return IIK_nonscalar;
6353
6354 // Otherwise, it needs to be a null pointer constant.
6355 } else {
6358 }
6359
6360 return IIK_nonlocal;
6361}
6362
6363/// Check whether the given expression is a valid operand for an
6364/// indirect copy/restore.
6366 assert(src->isPRValue());
6367 bool isWeakAccess = false;
6368 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
6369 // If isWeakAccess to true, there will be an implicit
6370 // load which requires a cleanup.
6371 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
6373
6374 if (iik == IIK_okay) return;
6375
6376 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
6377 << ((unsigned) iik - 1) // shift index into diagnostic explanations
6378 << src->getSourceRange();
6379}
6380
6381/// Determine whether we have compatible array types for the
6382/// purposes of GNU by-copy array initialization.
6383static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
6384 const ArrayType *Source) {
6385 // If the source and destination array types are equivalent, we're
6386 // done.
6387 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
6388 return true;
6389
6390 // Make sure that the element types are the same.
6391 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
6392 return false;
6393
6394 // The only mismatch we allow is when the destination is an
6395 // incomplete array type and the source is a constant array type.
6396 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
6397}
6398
6400 InitializationSequence &Sequence,
6401 const InitializedEntity &Entity,
6402 Expr *Initializer) {
6403 bool ArrayDecay = false;
6404 QualType ArgType = Initializer->getType();
6405 QualType ArgPointee;
6406 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
6407 ArrayDecay = true;
6408 ArgPointee = ArgArrayType->getElementType();
6409 ArgType = S.Context.getPointerType(ArgPointee);
6410 }
6411
6412 // Handle write-back conversion.
6413 QualType ConvertedArgType;
6414 if (!S.ObjC().isObjCWritebackConversion(ArgType, Entity.getType(),
6415 ConvertedArgType))
6416 return false;
6417
6418 // We should copy unless we're passing to an argument explicitly
6419 // marked 'out'.
6420 bool ShouldCopy = true;
6421 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6422 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6423
6424 // Do we need an lvalue conversion?
6425 if (ArrayDecay || Initializer->isGLValue()) {
6427 ICS.setStandard();
6429
6430 QualType ResultType;
6431 if (ArrayDecay) {
6433 ResultType = S.Context.getPointerType(ArgPointee);
6434 } else {
6436 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
6437 }
6438
6439 Sequence.AddConversionSequenceStep(ICS, ResultType);
6440 }
6441
6442 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
6443 return true;
6444}
6445
6447 InitializationSequence &Sequence,
6448 QualType DestType,
6449 Expr *Initializer) {
6450 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6451 (!Initializer->isIntegerConstantExpr(S.Context) &&
6452 !Initializer->getType()->isSamplerT()))
6453 return false;
6454
6455 Sequence.AddOCLSamplerInitStep(DestType);
6456 return true;
6457}
6458
6459static bool IsZeroInitializer(const Expr *Init, ASTContext &Ctx) {
6460 std::optional<llvm::APSInt> Value = Init->getIntegerConstantExpr(Ctx);
6461 return Value && Value->isZero();
6462}
6463
6465 InitializationSequence &Sequence,
6466 QualType DestType,
6467 Expr *Initializer) {
6468 if (!S.getLangOpts().OpenCL)
6469 return false;
6470
6471 //
6472 // OpenCL 1.2 spec, s6.12.10
6473 //
6474 // The event argument can also be used to associate the
6475 // async_work_group_copy with a previous async copy allowing
6476 // an event to be shared by multiple async copies; otherwise
6477 // event should be zero.
6478 //
6479 if (DestType->isEventT() || DestType->isQueueT()) {
6481 return false;
6482
6483 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6484 return true;
6485 }
6486
6487 // We should allow zero initialization for all types defined in the
6488 // cl_intel_device_side_avc_motion_estimation extension, except
6489 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6491 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
6492 DestType->isOCLIntelSubgroupAVCType()) {
6493 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6494 DestType->isOCLIntelSubgroupAVCMceResultType())
6495 return false;
6497 return false;
6498
6499 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6500 return true;
6501 }
6502
6503 return false;
6504}
6505
6507 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6508 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6509 : FailedOverloadResult(OR_Success),
6510 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6511 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6512 TreatUnavailableAsInvalid);
6513}
6514
6515/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6516/// address of that function, this returns true. Otherwise, it returns false.
6517static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6518 auto *DRE = dyn_cast<DeclRefExpr>(E);
6519 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6520 return false;
6521
6523 cast<FunctionDecl>(DRE->getDecl()));
6524}
6525
6526/// Determine whether we can perform an elementwise array copy for this kind
6527/// of entity.
6528static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6529 switch (Entity.getKind()) {
6531 // C++ [expr.prim.lambda]p24:
6532 // For array members, the array elements are direct-initialized in
6533 // increasing subscript order.
6534 return true;
6535
6537 // C++ [dcl.decomp]p1:
6538 // [...] each element is copy-initialized or direct-initialized from the
6539 // corresponding element of the assignment-expression [...]
6540 return isa<DecompositionDecl>(Entity.getDecl());
6541
6543 // C++ [class.copy.ctor]p14:
6544 // - if the member is an array, each element is direct-initialized with
6545 // the corresponding subobject of x
6546 return Entity.isImplicitMemberInitializer();
6547
6549 // All the above cases are intended to apply recursively, even though none
6550 // of them actually say that.
6551 if (auto *E = Entity.getParent())
6552 return canPerformArrayCopy(*E);
6553 break;
6554
6555 default:
6556 break;
6557 }
6558
6559 return false;
6560}
6561
6562static const FieldDecl *getConstField(const RecordDecl *RD) {
6563 assert(!isa<CXXRecordDecl>(RD) && "Only expect to call this in C mode");
6564 for (const FieldDecl *FD : RD->fields()) {
6565 // If the field is a flexible array member, we don't want to consider it
6566 // as a const field because there's no way to initialize the FAM anyway.
6567 const ASTContext &Ctx = FD->getASTContext();
6569 Ctx, FD, FD->getType(),
6570 Ctx.getLangOpts().getStrictFlexArraysLevel(),
6571 /*IgnoreTemplateOrMacroSubstitution=*/true))
6572 continue;
6573
6574 QualType QT = FD->getType();
6575 if (QT.isConstQualified())
6576 return FD;
6577 if (const auto *RD = QT->getAsRecordDecl()) {
6578 if (const FieldDecl *FD = getConstField(RD))
6579 return FD;
6580 }
6581 }
6582 return nullptr;
6583}
6584
6586 const InitializedEntity &Entity,
6587 const InitializationKind &Kind,
6588 MultiExprArg Args,
6589 bool TopLevelOfInitList,
6590 bool TreatUnavailableAsInvalid) {
6591 ASTContext &Context = S.Context;
6592
6593 // Eliminate non-overload placeholder types in the arguments. We
6594 // need to do this before checking whether types are dependent
6595 // because lowering a pseudo-object expression might well give us
6596 // something of dependent type.
6597 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6598 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6599 // FIXME: should we be doing this here?
6600 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
6601 if (result.isInvalid()) {
6603 return;
6604 }
6605 Args[I] = result.get();
6606 }
6607
6608 // C++0x [dcl.init]p16:
6609 // The semantics of initializers are as follows. The destination type is
6610 // the type of the object or reference being initialized and the source
6611 // type is the type of the initializer expression. The source type is not
6612 // defined when the initializer is a braced-init-list or when it is a
6613 // parenthesized list of expressions.
6614 QualType DestType = Entity.getType();
6615
6616 if (DestType->isDependentType() ||
6619 return;
6620 }
6621
6622 // Almost everything is a normal sequence.
6624
6625 QualType SourceType;
6626 Expr *Initializer = nullptr;
6627 if (Args.size() == 1) {
6628 Initializer = Args[0];
6629 if (S.getLangOpts().ObjC) {
6631 Initializer->getBeginLoc(), DestType, Initializer->getType(),
6632 Initializer) ||
6634 Args[0] = Initializer;
6635 }
6637 SourceType = Initializer->getType();
6638 }
6639
6640 // - If the initializer is a (non-parenthesized) braced-init-list, the
6641 // object is list-initialized (8.5.4).
6642 if (Kind.getKind() != InitializationKind::IK_Direct) {
6643 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
6644 TryListInitialization(S, Entity, Kind, InitList, *this,
6645 TreatUnavailableAsInvalid);
6646 return;
6647 }
6648 }
6649
6650 if (!S.getLangOpts().CPlusPlus &&
6651 Kind.getKind() == InitializationKind::IK_Default) {
6652 if (RecordDecl *Rec = DestType->getAsRecordDecl()) {
6653 VarDecl *Var = dyn_cast_or_null<VarDecl>(Entity.getDecl());
6654 if (Rec->hasUninitializedExplicitInitFields()) {
6655 if (Var && !Initializer && !S.isUnevaluatedContext()) {
6656 S.Diag(Var->getLocation(), diag::warn_field_requires_explicit_init)
6657 << /* Var-in-Record */ 1 << Rec;
6659 }
6660 }
6661 // If the record has any members which are const (recursively checked),
6662 // then we want to diagnose those as being uninitialized if there is no
6663 // initializer present. However, we only do this for structure types, not
6664 // union types, because an unitialized field in a union is generally
6665 // reasonable, especially in C where unions can be used for type punning.
6666 if (Var && !Initializer && !Rec->isUnion() && !Rec->isInvalidDecl()) {
6667 if (const FieldDecl *FD = getConstField(Rec)) {
6668 unsigned DiagID = diag::warn_default_init_const_field_unsafe;
6669 if (Var->getStorageDuration() == SD_Static ||
6670 Var->getStorageDuration() == SD_Thread)
6671 DiagID = diag::warn_default_init_const_field;
6672
6673 bool EmitCppCompat = !S.Diags.isIgnored(
6674 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
6675 Var->getLocation());
6676
6677 S.Diag(Var->getLocation(), DiagID) << Var->getType() << EmitCppCompat;
6678 S.Diag(FD->getLocation(), diag::note_default_init_const_member) << FD;
6679 }
6680 }
6681 }
6682 }
6683
6684 // - If the destination type is a reference type, see 8.5.3.
6685 if (DestType->isReferenceType()) {
6686 // C++0x [dcl.init.ref]p1:
6687 // A variable declared to be a T& or T&&, that is, "reference to type T"
6688 // (8.3.2), shall be initialized by an object, or function, of type T or
6689 // by an object that can be converted into a T.
6690 // (Therefore, multiple arguments are not permitted.)
6691 if (Args.size() != 1)
6693 // C++17 [dcl.init.ref]p5:
6694 // A reference [...] is initialized by an expression [...] as follows:
6695 // If the initializer is not an expression, presumably we should reject,
6696 // but the standard fails to actually say so.
6697 else if (isa<InitListExpr>(Args[0]))
6699 else
6700 TryReferenceInitialization(S, Entity, Kind, Args[0], *this,
6701 TopLevelOfInitList);
6702 return;
6703 }
6704
6705 // - If the initializer is (), the object is value-initialized.
6706 if (Kind.getKind() == InitializationKind::IK_Value ||
6707 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6708 TryValueInitialization(S, Entity, Kind, *this);
6709 return;
6710 }
6711
6712 // Handle default initialization.
6713 if (Kind.getKind() == InitializationKind::IK_Default) {
6714 TryDefaultInitialization(S, Entity, Kind, *this);
6715 return;
6716 }
6717
6718 // - If the destination type is an array of characters, an array of
6719 // char16_t, an array of char32_t, or an array of wchar_t, and the
6720 // initializer is a string literal, see 8.5.2.
6721 // - Otherwise, if the destination type is an array, the program is
6722 // ill-formed.
6723 // - Except in HLSL, where non-decaying array parameters behave like
6724 // non-array types for initialization.
6725 if (DestType->isArrayType() && !DestType->isArrayParameterType()) {
6726 const ArrayType *DestAT = Context.getAsArrayType(DestType);
6727 if (Initializer && isa<VariableArrayType>(DestAT)) {
6729 return;
6730 }
6731
6732 if (Initializer) {
6733 switch (IsStringInit(Initializer, DestAT, Context)) {
6734 case SIF_None:
6735 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
6736 return;
6739 return;
6742 return;
6745 return;
6748 return;
6751 return;
6752 case SIF_Other:
6753 break;
6754 }
6755 }
6756
6757 if (S.getLangOpts().HLSL && Initializer && isa<ConstantArrayType>(DestAT)) {
6758 QualType SrcType = Entity.getType();
6759 if (SrcType->isArrayParameterType())
6760 SrcType =
6761 cast<ArrayParameterType>(SrcType)->getConstantArrayType(Context);
6762 if (S.Context.hasSameUnqualifiedType(DestType, SrcType)) {
6763 TryArrayCopy(S, Kind, Entity, Initializer, DestType, *this,
6764 TreatUnavailableAsInvalid);
6765 return;
6766 }
6767 }
6768
6769 // Some kinds of initialization permit an array to be initialized from
6770 // another array of the same type, and perform elementwise initialization.
6771 if (Initializer && isa<ConstantArrayType>(DestAT) &&
6773 Entity.getType()) &&
6774 canPerformArrayCopy(Entity)) {
6775 TryArrayCopy(S, Kind, Entity, Initializer, DestType, *this,
6776 TreatUnavailableAsInvalid);
6777 return;
6778 }
6779
6780 // Note: as an GNU C extension, we allow initialization of an
6781 // array from a compound literal that creates an array of the same
6782 // type, so long as the initializer has no side effects.
6783 if (!S.getLangOpts().CPlusPlus && Initializer &&
6784 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6785 Initializer->getType()->isArrayType()) {
6786 const ArrayType *SourceAT
6787 = Context.getAsArrayType(Initializer->getType());
6788 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
6790 else if (Initializer->HasSideEffects(S.Context))
6792 else {
6793 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
6794 }
6795 }
6796 // Note: as a GNU C++ extension, we allow list-initialization of a
6797 // class member of array type from a parenthesized initializer list.
6798 else if (S.getLangOpts().CPlusPlus &&
6800 isa_and_nonnull<InitListExpr>(Initializer)) {
6802 *this, TreatUnavailableAsInvalid);
6804 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6805 Kind.getKind() == InitializationKind::IK_Direct)
6806 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6807 /*VerifyOnly=*/true);
6808 else if (DestAT->getElementType()->isCharType())
6810 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6812 else
6814
6815 return;
6816 }
6817
6818 // Determine whether we should consider writeback conversions for
6819 // Objective-C ARC.
6820 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6821 Entity.isParameterKind();
6822
6823 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
6824 return;
6825
6826 // We're at the end of the line for C: it's either a write-back conversion
6827 // or it's a C assignment. There's no need to check anything else.
6828 if (!S.getLangOpts().CPlusPlus) {
6829 assert(Initializer && "Initializer must be non-null");
6830 // If allowed, check whether this is an Objective-C writeback conversion.
6831 if (allowObjCWritebackConversion &&
6832 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
6833 return;
6834 }
6835
6836 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
6837 return;
6838
6839 // Handle initialization in C
6840 AddCAssignmentStep(DestType);
6841 MaybeProduceObjCObject(S, *this, Entity);
6842 return;
6843 }
6844
6845 assert(S.getLangOpts().CPlusPlus);
6846
6847 // - If the destination type is a (possibly cv-qualified) class type:
6848 if (DestType->isRecordType()) {
6849 // - If the initialization is direct-initialization, or if it is
6850 // copy-initialization where the cv-unqualified version of the
6851 // source type is the same class as, or a derived class of, the
6852 // class of the destination, constructors are considered. [...]
6853 if (Kind.getKind() == InitializationKind::IK_Direct ||
6854 (Kind.getKind() == InitializationKind::IK_Copy &&
6855 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
6856 (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
6857 SourceType, DestType))))) {
6858 TryConstructorOrParenListInitialization(S, Entity, Kind, Args, DestType,
6859 *this, /*IsAggrListInit=*/false);
6860 } else {
6861 // - Otherwise (i.e., for the remaining copy-initialization cases),
6862 // user-defined conversion sequences that can convert from the
6863 // source type to the destination type or (when a conversion
6864 // function is used) to a derived class thereof are enumerated as
6865 // described in 13.3.1.4, and the best one is chosen through
6866 // overload resolution (13.3).
6867 assert(Initializer && "Initializer must be non-null");
6868 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6869 TopLevelOfInitList);
6870 }
6871 return;
6872 }
6873
6874 assert(Args.size() >= 1 && "Zero-argument case handled above");
6875
6876 // For HLSL ext vector types we allow list initialization behavior for C++
6877 // functional cast expressions which look like constructor syntax. This is
6878 // accomplished by converting initialization arguments to InitListExpr.
6879 if (S.getLangOpts().HLSL && Args.size() > 1 &&
6880 (DestType->isExtVectorType() || DestType->isConstantMatrixType()) &&
6881 (SourceType.isNull() ||
6882 !Context.hasSameUnqualifiedType(SourceType, DestType))) {
6883 InitListExpr *ILE = new (Context)
6884 InitListExpr(S.getASTContext(), Args.front()->getBeginLoc(), Args,
6885 Args.back()->getEndLoc());
6886 ILE->setType(DestType);
6887 Args[0] = ILE;
6888 TryListInitialization(S, Entity, Kind, ILE, *this,
6889 TreatUnavailableAsInvalid);
6890 return;
6891 }
6892
6893 // The remaining cases all need a source type.
6894 if (Args.size() > 1) {
6896 return;
6897 } else if (isa<InitListExpr>(Args[0])) {
6899 return;
6900 }
6901
6902 // - Otherwise, if the source type is a (possibly cv-qualified) class
6903 // type, conversion functions are considered.
6904 if (!SourceType.isNull() && SourceType->isRecordType()) {
6905 assert(Initializer && "Initializer must be non-null");
6906 // For a conversion to _Atomic(T) from either T or a class type derived
6907 // from T, initialize the T object then convert to _Atomic type.
6908 bool NeedAtomicConversion = false;
6909 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
6910 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
6911 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
6912 Atomic->getValueType())) {
6913 DestType = Atomic->getValueType();
6914 NeedAtomicConversion = true;
6915 }
6916 }
6917
6918 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6919 TopLevelOfInitList);
6920 MaybeProduceObjCObject(S, *this, Entity);
6921 if (!Failed() && NeedAtomicConversion)
6923 return;
6924 }
6925
6926 // - Otherwise, if the initialization is direct-initialization, the source
6927 // type is std::nullptr_t, and the destination type is bool, the initial
6928 // value of the object being initialized is false.
6929 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
6930 DestType->isBooleanType() &&
6931 Kind.getKind() == InitializationKind::IK_Direct) {
6934 Initializer->isGLValue()),
6935 DestType);
6936 return;
6937 }
6938
6939 // - Otherwise, the initial value of the object being initialized is the
6940 // (possibly converted) value of the initializer expression. Standard
6941 // conversions (Clause 4) will be used, if necessary, to convert the
6942 // initializer expression to the cv-unqualified version of the
6943 // destination type; no user-defined conversions are considered.
6944
6946 = S.TryImplicitConversion(Initializer, DestType,
6947 /*SuppressUserConversions*/true,
6948 Sema::AllowedExplicit::None,
6949 /*InOverloadResolution*/ false,
6950 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
6951 allowObjCWritebackConversion);
6952
6953 if (ICS.isStandard() &&
6955 // Objective-C ARC writeback conversion.
6956
6957 // We should copy unless we're passing to an argument explicitly
6958 // marked 'out'.
6959 bool ShouldCopy = true;
6960 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6961 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6962
6963 // If there was an lvalue adjustment, add it as a separate conversion.
6964 if (ICS.Standard.First == ICK_Array_To_Pointer ||
6967 LvalueICS.setStandard();
6969 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
6970 LvalueICS.Standard.First = ICS.Standard.First;
6971 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
6972 }
6973
6974 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
6975 } else if (ICS.isBad()) {
6977 Initializer->getType() == Context.OverloadTy &&
6979 /*Complain=*/false, Found))
6981 else if (Initializer->getType()->isFunctionType() &&
6984 else
6986 } else {
6987 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6988
6989 MaybeProduceObjCObject(S, *this, Entity);
6990 }
6991}
6992
6994 for (auto &S : Steps)
6995 S.Destroy();
6996}
6997
6998//===----------------------------------------------------------------------===//
6999// Perform initialization
7000//===----------------------------------------------------------------------===//
7002 bool Diagnose = false) {
7003 switch(Entity.getKind()) {
7010
7012 if (Entity.getDecl() &&
7015
7017
7019 if (Entity.getDecl() &&
7022
7023 return !Diagnose ? AssignmentAction::Passing
7025
7027 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
7029
7032 // FIXME: Can we tell apart casting vs. converting?
7034
7036 // This is really initialization, but refer to it as conversion for
7037 // consistency with CheckConvertedConstantExpression.
7039
7052 }
7053
7054 llvm_unreachable("Invalid EntityKind!");
7055}
7056
7057/// Whether we should bind a created object as a temporary when
7058/// initializing the given entity.
7091
7092/// Whether the given entity, when initialized with an object
7093/// created for that initialization, requires destruction.
7126
7127/// Get the location at which initialization diagnostics should appear.
7166
7167/// Make a (potentially elidable) temporary copy of the object
7168/// provided by the given initializer by calling the appropriate copy
7169/// constructor.
7170///
7171/// \param S The Sema object used for type-checking.
7172///
7173/// \param T The type of the temporary object, which must either be
7174/// the type of the initializer expression or a superclass thereof.
7175///
7176/// \param Entity The entity being initialized.
7177///
7178/// \param CurInit The initializer expression.
7179///
7180/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
7181/// is permitted in C++03 (but not C++0x) when binding a reference to
7182/// an rvalue.
7183///
7184/// \returns An expression that copies the initializer expression into
7185/// a temporary object, or an error expression if a copy could not be
7186/// created.
7188 QualType T,
7189 const InitializedEntity &Entity,
7190 ExprResult CurInit,
7191 bool IsExtraneousCopy) {
7192 if (CurInit.isInvalid())
7193 return CurInit;
7194 // Determine which class type we're copying to.
7195 Expr *CurInitExpr = (Expr *)CurInit.get();
7196 auto *Class = T->getAsCXXRecordDecl();
7197 if (!Class)
7198 return CurInit;
7199
7200 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
7201
7202 // Make sure that the type we are copying is complete.
7203 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
7204 return CurInit;
7205
7206 // Perform overload resolution using the class's constructors. Per
7207 // C++11 [dcl.init]p16, second bullet for class types, this initialization
7208 // is direct-initialization.
7211
7214 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
7215 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7216 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7217 /*RequireActualConstructor=*/false,
7218 /*SecondStepOfCopyInit=*/true)) {
7219 case OR_Success:
7220 break;
7221
7223 CandidateSet.NoteCandidates(
7225 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
7226 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
7227 : diag::err_temp_copy_no_viable)
7228 << (int)Entity.getKind() << CurInitExpr->getType()
7229 << CurInitExpr->getSourceRange()),
7230 S, OCD_AllCandidates, CurInitExpr);
7231 if (!IsExtraneousCopy || S.isSFINAEContext())
7232 return ExprError();
7233 return CurInit;
7234
7235 case OR_Ambiguous:
7236 CandidateSet.NoteCandidates(
7237 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
7238 << (int)Entity.getKind()
7239 << CurInitExpr->getType()
7240 << CurInitExpr->getSourceRange()),
7241 S, OCD_AmbiguousCandidates, CurInitExpr);
7242 return ExprError();
7243
7244 case OR_Deleted:
7245 S.Diag(Loc, diag::err_temp_copy_deleted)
7246 << (int)Entity.getKind() << CurInitExpr->getType()
7247 << CurInitExpr->getSourceRange();
7248 S.NoteDeletedFunction(Best->Function);
7249 return ExprError();
7250 }
7251
7252 bool HadMultipleCandidates = CandidateSet.size() > 1;
7253
7255 SmallVector<Expr*, 8> ConstructorArgs;
7256 CurInit.get(); // Ownership transferred into MultiExprArg, below.
7257
7258 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
7259 IsExtraneousCopy);
7260
7261 if (IsExtraneousCopy) {
7262 // If this is a totally extraneous copy for C++03 reference
7263 // binding purposes, just return the original initialization
7264 // expression. We don't generate an (elided) copy operation here
7265 // because doing so would require us to pass down a flag to avoid
7266 // infinite recursion, where each step adds another extraneous,
7267 // elidable copy.
7268
7269 // Instantiate the default arguments of any extra parameters in
7270 // the selected copy constructor, as if we were going to create a
7271 // proper call to the copy constructor.
7272 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
7273 ParmVarDecl *Parm = Constructor->getParamDecl(I);
7274 if (S.RequireCompleteType(Loc, Parm->getType(),
7275 diag::err_call_incomplete_argument))
7276 break;
7277
7278 // Build the default argument expression; we don't actually care
7279 // if this succeeds or not, because this routine will complain
7280 // if there was a problem.
7281 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
7282 }
7283
7284 return CurInitExpr;
7285 }
7286
7287 // Determine the arguments required to actually perform the
7288 // constructor call (we might have derived-to-base conversions, or
7289 // the copy constructor may have default arguments).
7290 if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
7291 ConstructorArgs))
7292 return ExprError();
7293
7294 // C++0x [class.copy]p32:
7295 // When certain criteria are met, an implementation is allowed to
7296 // omit the copy/move construction of a class object, even if the
7297 // copy/move constructor and/or destructor for the object have
7298 // side effects. [...]
7299 // - when a temporary class object that has not been bound to a
7300 // reference (12.2) would be copied/moved to a class object
7301 // with the same cv-unqualified type, the copy/move operation
7302 // can be omitted by constructing the temporary object
7303 // directly into the target of the omitted copy/move
7304 //
7305 // Note that the other three bullets are handled elsewhere. Copy
7306 // elision for return statements and throw expressions are handled as part
7307 // of constructor initialization, while copy elision for exception handlers
7308 // is handled by the run-time.
7309 //
7310 // FIXME: If the function parameter is not the same type as the temporary, we
7311 // should still be able to elide the copy, but we don't have a way to
7312 // represent in the AST how much should be elided in this case.
7313 bool Elidable =
7314 CurInitExpr->isTemporaryObject(S.Context, Class) &&
7316 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
7317 CurInitExpr->getType());
7318
7319 // Actually perform the constructor call.
7320 CurInit = S.BuildCXXConstructExpr(
7321 Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,
7322 HadMultipleCandidates,
7323 /*ListInit*/ false,
7324 /*StdInitListInit*/ false,
7325 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
7326
7327 // If we're supposed to bind temporaries, do so.
7328 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
7329 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7330 return CurInit;
7331}
7332
7333/// Check whether elidable copy construction for binding a reference to
7334/// a temporary would have succeeded if we were building in C++98 mode, for
7335/// -Wc++98-compat.
7337 const InitializedEntity &Entity,
7338 Expr *CurInitExpr) {
7339 assert(S.getLangOpts().CPlusPlus11);
7340
7341 auto *Record = CurInitExpr->getType()->getAsCXXRecordDecl();
7342 if (!Record)
7343 return;
7344
7345 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
7346 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
7347 return;
7348
7349 // Find constructors which would have been considered.
7352
7353 // Perform overload resolution.
7356 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
7357 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7358 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7359 /*RequireActualConstructor=*/false,
7360 /*SecondStepOfCopyInit=*/true);
7361
7362 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
7363 << OR << (int)Entity.getKind() << CurInitExpr->getType()
7364 << CurInitExpr->getSourceRange();
7365
7366 switch (OR) {
7367 case OR_Success:
7368 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
7369 Best->FoundDecl, Entity, Diag);
7370 // FIXME: Check default arguments as far as that's possible.
7371 break;
7372
7374 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7375 OCD_AllCandidates, CurInitExpr);
7376 break;
7377
7378 case OR_Ambiguous:
7379 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7380 OCD_AmbiguousCandidates, CurInitExpr);
7381 break;
7382
7383 case OR_Deleted:
7384 S.Diag(Loc, Diag);
7385 S.NoteDeletedFunction(Best->Function);
7386 break;
7387 }
7388}
7389
7390void InitializationSequence::PrintInitLocationNote(Sema &S,
7391 const InitializedEntity &Entity) {
7392 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
7393 if (Entity.getDecl()->getLocation().isInvalid())
7394 return;
7395
7396 if (Entity.getDecl()->getDeclName())
7397 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
7398 << Entity.getDecl()->getDeclName();
7399 else
7400 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
7401 }
7402 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
7403 Entity.getMethodDecl())
7404 S.Diag(Entity.getMethodDecl()->getLocation(),
7405 diag::note_method_return_type_change)
7406 << Entity.getMethodDecl()->getDeclName();
7407}
7408
7409/// Returns true if the parameters describe a constructor initialization of
7410/// an explicit temporary object, e.g. "Point(x, y)".
7411static bool isExplicitTemporary(const InitializedEntity &Entity,
7412 const InitializationKind &Kind,
7413 unsigned NumArgs) {
7414 switch (Entity.getKind()) {
7418 break;
7419 default:
7420 return false;
7421 }
7422
7423 switch (Kind.getKind()) {
7425 return true;
7426 // FIXME: Hack to work around cast weirdness.
7429 return NumArgs != 1;
7430 default:
7431 return false;
7432 }
7433}
7434
7435static ExprResult
7437 const InitializedEntity &Entity,
7438 const InitializationKind &Kind,
7439 MultiExprArg Args,
7440 const InitializationSequence::Step& Step,
7441 bool &ConstructorInitRequiresZeroInit,
7442 bool IsListInitialization,
7443 bool IsStdInitListInitialization,
7444 SourceLocation LBraceLoc,
7445 SourceLocation RBraceLoc) {
7446 unsigned NumArgs = Args.size();
7449 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7450
7451 // Build a call to the selected constructor.
7452 SmallVector<Expr*, 8> ConstructorArgs;
7453 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7454 ? Kind.getEqualLoc()
7455 : Kind.getLocation();
7456
7457 if (Kind.getKind() == InitializationKind::IK_Default) {
7458 // Force even a trivial, implicit default constructor to be
7459 // semantically checked. We do this explicitly because we don't build
7460 // the definition for completely trivial constructors.
7461 assert(Constructor->getParent() && "No parent class for constructor.");
7462 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7463 Constructor->isTrivial() && !Constructor->isUsed(false)) {
7464 S.runWithSufficientStackSpace(Loc, [&] {
7466 });
7467 }
7468 }
7469
7470 ExprResult CurInit((Expr *)nullptr);
7471
7472 // C++ [over.match.copy]p1:
7473 // - When initializing a temporary to be bound to the first parameter
7474 // of a constructor that takes a reference to possibly cv-qualified
7475 // T as its first argument, called with a single argument in the
7476 // context of direct-initialization, explicit conversion functions
7477 // are also considered.
7478 bool AllowExplicitConv =
7479 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7482
7483 // A smart pointer constructed from a nullable pointer is nullable.
7484 if (NumArgs == 1 && !Kind.isExplicitCast())
7486 Entity.getType(), Args.front()->getType(), Kind.getLocation());
7487
7488 // Determine the arguments required to actually perform the constructor
7489 // call.
7490 if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
7491 ConstructorArgs, AllowExplicitConv,
7492 IsListInitialization))
7493 return ExprError();
7494
7495 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7496 // An explicitly-constructed temporary, e.g., X(1, 2).
7497 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7498 return ExprError();
7499
7500 if (Kind.getKind() == InitializationKind::IK_Value &&
7501 Constructor->isImplicit()) {
7502 auto *RD = Step.Type.getCanonicalType()->getAsCXXRecordDecl();
7503 if (RD && RD->isAggregate() && RD->hasUninitializedExplicitInitFields()) {
7504 unsigned I = 0;
7505 for (const FieldDecl *FD : RD->fields()) {
7506 if (I >= ConstructorArgs.size() && FD->hasAttr<ExplicitInitAttr>() &&
7507 !S.isUnevaluatedContext()) {
7508 S.Diag(Loc, diag::warn_field_requires_explicit_init)
7509 << /* Var-in-Record */ 0 << FD;
7510 S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
7511 }
7512 ++I;
7513 }
7514 }
7515 }
7516
7517 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7518 if (!TSInfo)
7519 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
7520 SourceRange ParenOrBraceRange =
7521 (Kind.getKind() == InitializationKind::IK_DirectList)
7522 ? SourceRange(LBraceLoc, RBraceLoc)
7523 : Kind.getParenOrBraceRange();
7524
7525 CXXConstructorDecl *CalleeDecl = Constructor;
7526 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7527 Step.Function.FoundDecl.getDecl())) {
7528 CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
7529 }
7530 S.MarkFunctionReferenced(Loc, CalleeDecl);
7531
7532 CurInit = S.CheckForImmediateInvocation(
7534 S.Context, CalleeDecl,
7535 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7536 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7537 IsListInitialization, IsStdInitListInitialization,
7538 ConstructorInitRequiresZeroInit),
7539 CalleeDecl);
7540 } else {
7542
7543 if (Entity.getKind() == InitializedEntity::EK_Base) {
7544 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7547 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7548 ConstructKind = CXXConstructionKind::Delegating;
7549 }
7550
7551 // Only get the parenthesis or brace range if it is a list initialization or
7552 // direct construction.
7553 SourceRange ParenOrBraceRange;
7554 if (IsListInitialization)
7555 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7556 else if (Kind.getKind() == InitializationKind::IK_Direct)
7557 ParenOrBraceRange = Kind.getParenOrBraceRange();
7558
7559 // If the entity allows NRVO, mark the construction as elidable
7560 // unconditionally.
7561 if (Entity.allowsNRVO())
7562 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7563 Step.Function.FoundDecl,
7564 Constructor, /*Elidable=*/true,
7565 ConstructorArgs,
7566 HadMultipleCandidates,
7567 IsListInitialization,
7568 IsStdInitListInitialization,
7569 ConstructorInitRequiresZeroInit,
7570 ConstructKind,
7571 ParenOrBraceRange);
7572 else
7573 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7574 Step.Function.FoundDecl,
7576 ConstructorArgs,
7577 HadMultipleCandidates,
7578 IsListInitialization,
7579 IsStdInitListInitialization,
7580 ConstructorInitRequiresZeroInit,
7581 ConstructKind,
7582 ParenOrBraceRange);
7583 }
7584 if (CurInit.isInvalid())
7585 return ExprError();
7586
7587 // Only check access if all of that succeeded.
7590 return ExprError();
7591
7592 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
7594 return ExprError();
7595
7596 if (shouldBindAsTemporary(Entity))
7597 CurInit = S.MaybeBindToTemporary(CurInit.get());
7598
7599 return CurInit;
7600}
7601
7603 Expr *Init) {
7604 return sema::checkInitLifetime(*this, Entity, Init);
7605}
7606
7607static void DiagnoseNarrowingInInitList(Sema &S,
7608 const ImplicitConversionSequence &ICS,
7609 QualType PreNarrowingType,
7610 QualType EntityType,
7611 const Expr *PostInit);
7612
7613static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
7614 QualType ToType, Expr *Init);
7615
7616/// Provide warnings when std::move is used on construction.
7617static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7618 bool IsReturnStmt) {
7619 if (!InitExpr)
7620 return;
7621
7623 return;
7624
7625 QualType DestType = InitExpr->getType();
7626 if (!DestType->isRecordType())
7627 return;
7628
7629 unsigned DiagID = 0;
7630 if (IsReturnStmt) {
7631 const CXXConstructExpr *CCE =
7632 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7633 if (!CCE || CCE->getNumArgs() != 1)
7634 return;
7635
7637 return;
7638
7639 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
7640 }
7641
7642 // Find the std::move call and get the argument.
7643 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
7644 if (!CE || !CE->isCallToStdMove())
7645 return;
7646
7647 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
7648
7649 if (IsReturnStmt) {
7650 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7651 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7652 return;
7653
7654 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7655 if (!VD || !VD->hasLocalStorage())
7656 return;
7657
7658 // __block variables are not moved implicitly.
7659 if (VD->hasAttr<BlocksAttr>())
7660 return;
7661
7662 QualType SourceType = VD->getType();
7663 if (!SourceType->isRecordType())
7664 return;
7665
7666 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
7667 return;
7668 }
7669
7670 // If we're returning a function parameter, copy elision
7671 // is not possible.
7672 if (isa<ParmVarDecl>(VD))
7673 DiagID = diag::warn_redundant_move_on_return;
7674 else
7675 DiagID = diag::warn_pessimizing_move_on_return;
7676 } else {
7677 DiagID = diag::warn_pessimizing_move_on_initialization;
7678 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7679 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
7680 return;
7681 }
7682
7683 S.Diag(CE->getBeginLoc(), DiagID);
7684
7685 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7686 // is within a macro.
7687 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
7688 if (CallBegin.isMacroID())
7689 return;
7690 SourceLocation RParen = CE->getRParenLoc();
7691 if (RParen.isMacroID())
7692 return;
7693 SourceLocation LParen;
7694 SourceLocation ArgLoc = Arg->getBeginLoc();
7695
7696 // Special testing for the argument location. Since the fix-it needs the
7697 // location right before the argument, the argument location can be in a
7698 // macro only if it is at the beginning of the macro.
7699 while (ArgLoc.isMacroID() &&
7702 }
7703
7704 if (LParen.isMacroID())
7705 return;
7706
7707 LParen = ArgLoc.getLocWithOffset(-1);
7708
7709 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
7710 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
7711 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
7712}
7713
7714static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7715 // Check to see if we are dereferencing a null pointer. If so, this is
7716 // undefined behavior, so warn about it. This only handles the pattern
7717 // "*null", which is a very syntactic check.
7718 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7719 if (UO->getOpcode() == UO_Deref &&
7720 UO->getSubExpr()->IgnoreParenCasts()->
7721 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7722 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7723 S.PDiag(diag::warn_binding_null_to_reference)
7724 << UO->getSubExpr()->getSourceRange());
7725 }
7726}
7727
7730 bool BoundToLvalueReference) {
7731 auto MTE = new (Context)
7732 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7733
7734 // Order an ExprWithCleanups for lifetime marks.
7735 //
7736 // TODO: It'll be good to have a single place to check the access of the
7737 // destructor and generate ExprWithCleanups for various uses. Currently these
7738 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7739 // but there may be a chance to merge them.
7740 Cleanup.setExprNeedsCleanups(false);
7743 return MTE;
7744}
7745
7747 // In C++98, we don't want to implicitly create an xvalue. C11 added the
7748 // same rule, but C99 is broken without this behavior and so we treat the
7749 // change as applying to all C language modes.
7750 // FIXME: This means that AST consumers need to deal with "prvalues" that
7751 // denote materialized temporaries. Maybe we should add another ValueKind
7752 // for "xvalue pretending to be a prvalue" for C++98 support.
7753 if (!E->isPRValue() ||
7755 return E;
7756
7757 // C++1z [conv.rval]/1: T shall be a complete type.
7758 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7759 // If so, we should check for a non-abstract class type here too.
7760 QualType T = E->getType();
7761 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7762 return ExprError();
7763
7764 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7765}
7766
7770
7771 CastKind CK = CK_NoOp;
7772
7773 if (VK == VK_PRValue) {
7774 auto PointeeTy = Ty->getPointeeType();
7775 auto ExprPointeeTy = E->getType()->getPointeeType();
7776 if (!PointeeTy.isNull() &&
7777 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
7778 CK = CK_AddressSpaceConversion;
7779 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
7780 CK = CK_AddressSpaceConversion;
7781 }
7782
7783 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
7784}
7785
7787 const InitializedEntity &Entity,
7788 const InitializationKind &Kind,
7789 MultiExprArg Args,
7790 QualType *ResultType) {
7791 if (Failed()) {
7792 Diagnose(S, Entity, Kind, Args);
7793 return ExprError();
7794 }
7795 if (!ZeroInitializationFixit.empty()) {
7796 const Decl *D = Entity.getDecl();
7797 const auto *VD = dyn_cast_or_null<VarDecl>(D);
7798 QualType DestType = Entity.getType();
7799
7800 // The initialization would have succeeded with this fixit. Since the fixit
7801 // is on the error, we need to build a valid AST in this case, so this isn't
7802 // handled in the Failed() branch above.
7803 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
7804 // Use a more useful diagnostic for constexpr variables.
7805 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
7806 << VD
7807 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7808 ZeroInitializationFixit);
7809 } else {
7810 unsigned DiagID = diag::err_default_init_const;
7811 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
7812 DiagID = diag::ext_default_init_const;
7813
7814 S.Diag(Kind.getLocation(), DiagID)
7815 << DestType << DestType->isRecordType()
7816 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7817 ZeroInitializationFixit);
7818 }
7819 }
7820
7821 if (getKind() == DependentSequence) {
7822 // If the declaration is a non-dependent, incomplete array type
7823 // that has an initializer, then its type will be completed once
7824 // the initializer is instantiated.
7825 if (ResultType && !Entity.getType()->isDependentType() &&
7826 Args.size() == 1) {
7827 QualType DeclType = Entity.getType();
7828 if (const IncompleteArrayType *ArrayT
7829 = S.Context.getAsIncompleteArrayType(DeclType)) {
7830 // FIXME: We don't currently have the ability to accurately
7831 // compute the length of an initializer list without
7832 // performing full type-checking of the initializer list
7833 // (since we have to determine where braces are implicitly
7834 // introduced and such). So, we fall back to making the array
7835 // type a dependently-sized array type with no specified
7836 // bound.
7837 if (isa<InitListExpr>((Expr *)Args[0]))
7838 *ResultType = S.Context.getDependentSizedArrayType(
7839 ArrayT->getElementType(),
7840 /*NumElts=*/nullptr, ArrayT->getSizeModifier(),
7841 ArrayT->getIndexTypeCVRQualifiers());
7842 }
7843 }
7844 if (Kind.getKind() == InitializationKind::IK_Direct &&
7845 !Kind.isExplicitCast()) {
7846 // Rebuild the ParenListExpr.
7847 SourceRange ParenRange = Kind.getParenOrBraceRange();
7848 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
7849 Args);
7850 }
7851 assert(Kind.getKind() == InitializationKind::IK_Copy ||
7852 Kind.isExplicitCast() ||
7853 Kind.getKind() == InitializationKind::IK_DirectList);
7854 return ExprResult(Args[0]);
7855 }
7856
7857 // No steps means no initialization.
7858 if (Steps.empty())
7859 return ExprResult((Expr *)nullptr);
7860
7861 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
7862 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
7863 !Entity.isParamOrTemplateParamKind()) {
7864 // Produce a C++98 compatibility warning if we are initializing a reference
7865 // from an initializer list. For parameters, we produce a better warning
7866 // elsewhere.
7867 Expr *Init = Args[0];
7868 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
7869 << Init->getSourceRange();
7870 }
7871
7872 if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
7873 isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
7874 // Produce a Microsoft compatibility warning when initializing from a
7875 // predefined expression since MSVC treats predefined expressions as string
7876 // literals.
7877 Expr *Init = Args[0];
7878 S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
7879 }
7880
7881 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
7882 QualType ETy = Entity.getType();
7883 bool HasGlobalAS = ETy.hasAddressSpace() &&
7885
7886 if (S.getLangOpts().OpenCLVersion >= 200 &&
7887 ETy->isAtomicType() && !HasGlobalAS &&
7888 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
7889 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
7890 << 1
7891 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
7892 return ExprError();
7893 }
7894
7895 QualType DestType = Entity.getType().getNonReferenceType();
7896 // FIXME: Ugly hack around the fact that Entity.getType() is not
7897 // the same as Entity.getDecl()->getType() in cases involving type merging,
7898 // and we want latter when it makes sense.
7899 if (ResultType)
7900 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
7901 Entity.getType();
7902
7903 ExprResult CurInit((Expr *)nullptr);
7904 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
7905
7906 // HLSL allows vector/matrix initialization to function like list
7907 // initialization, but use the syntax of a C++-like constructor.
7908 bool IsHLSLVectorOrMatrixInit =
7909 S.getLangOpts().HLSL &&
7910 (DestType->isExtVectorType() || DestType->isConstantMatrixType()) &&
7911 isa<InitListExpr>(Args[0]);
7912 (void)IsHLSLVectorOrMatrixInit;
7913
7914 // For initialization steps that start with a single initializer,
7915 // grab the only argument out the Args and place it into the "current"
7916 // initializer.
7917 switch (Steps.front().Kind) {
7922 case SK_BindReference:
7924 case SK_FinalCopy:
7926 case SK_UserConversion:
7935 case SK_UnwrapInitList:
7936 case SK_RewrapInitList:
7937 case SK_CAssignment:
7938 case SK_StringInit:
7940 case SK_ArrayLoopIndex:
7941 case SK_ArrayLoopInit:
7942 case SK_ArrayInit:
7943 case SK_GNUArrayInit:
7949 case SK_OCLSamplerInit:
7950 case SK_OCLZeroOpaqueType: {
7951 assert(Args.size() == 1 || IsHLSLVectorOrMatrixInit);
7952 CurInit = Args[0];
7953 if (!CurInit.get()) return ExprError();
7954 break;
7955 }
7956
7962 break;
7963 }
7964
7965 // Promote from an unevaluated context to an unevaluated list context in
7966 // C++11 list-initialization; we need to instantiate entities usable in
7967 // constant expressions here in order to perform narrowing checks =(
7970 isa_and_nonnull<InitListExpr>(CurInit.get()));
7971
7972 // C++ [class.abstract]p2:
7973 // no objects of an abstract class can be created except as subobjects
7974 // of a class derived from it
7975 auto checkAbstractType = [&](QualType T) -> bool {
7976 if (Entity.getKind() == InitializedEntity::EK_Base ||
7978 return false;
7979 return S.RequireNonAbstractType(Kind.getLocation(), T,
7980 diag::err_allocation_of_abstract_type);
7981 };
7982
7983 // Walk through the computed steps for the initialization sequence,
7984 // performing the specified conversions along the way.
7985 bool ConstructorInitRequiresZeroInit = false;
7986 for (step_iterator Step = step_begin(), StepEnd = step_end();
7987 Step != StepEnd; ++Step) {
7988 if (CurInit.isInvalid())
7989 return ExprError();
7990
7991 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
7992
7993 switch (Step->Kind) {
7995 // Overload resolution determined which function invoke; update the
7996 // initializer to reflect that choice.
7998 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
7999 return ExprError();
8000 CurInit = S.FixOverloadedFunctionReference(CurInit,
8003 // We might get back another placeholder expression if we resolved to a
8004 // builtin.
8005 if (!CurInit.isInvalid())
8006 CurInit = S.CheckPlaceholderExpr(CurInit.get());
8007 break;
8008
8012 // We have a derived-to-base cast that produces either an rvalue or an
8013 // lvalue. Perform that cast.
8014
8015 CXXCastPath BasePath;
8016
8017 // Casts to inaccessible base classes are allowed with C-style casts.
8018 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8020 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8021 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8022 return ExprError();
8023
8026 ? VK_LValue
8028 : VK_PRValue);
8030 CK_DerivedToBase, CurInit.get(),
8031 &BasePath, VK, FPOptionsOverride());
8032 break;
8033 }
8034
8035 case SK_BindReference:
8036 // Reference binding does not have any corresponding ASTs.
8037
8038 // Check exception specifications
8039 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8040 return ExprError();
8041
8042 // We don't check for e.g. function pointers here, since address
8043 // availability checks should only occur when the function first decays
8044 // into a pointer or reference.
8045 if (CurInit.get()->getType()->isFunctionProtoType()) {
8046 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8047 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8048 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8049 DRE->getBeginLoc()))
8050 return ExprError();
8051 }
8052 }
8053 }
8054
8055 CheckForNullPointerDereference(S, CurInit.get());
8056 break;
8057
8059 // Make sure the "temporary" is actually an rvalue.
8060 assert(CurInit.get()->isPRValue() && "not a temporary");
8061
8062 // Check exception specifications
8063 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8064 return ExprError();
8065
8066 QualType MTETy = Step->Type;
8067
8068 // When this is an incomplete array type (such as when this is
8069 // initializing an array of unknown bounds from an init list), use THAT
8070 // type instead so that we propagate the array bounds.
8071 if (MTETy->isIncompleteArrayType() &&
8072 !CurInit.get()->getType()->isIncompleteArrayType() &&
8075 CurInit.get()->getType()->getPointeeOrArrayElementType()))
8076 MTETy = CurInit.get()->getType();
8077
8078 // Materialize the temporary into memory.
8080 MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8081 CurInit = MTE;
8082
8083 // If we're extending this temporary to automatic storage duration -- we
8084 // need to register its cleanup during the full-expression's cleanups.
8085 if (MTE->getStorageDuration() == SD_Automatic &&
8086 MTE->getType().isDestructedType())
8088 break;
8089 }
8090
8091 case SK_FinalCopy:
8092 if (checkAbstractType(Step->Type))
8093 return ExprError();
8094
8095 // If the overall initialization is initializing a temporary, we already
8096 // bound our argument if it was necessary to do so. If not (if we're
8097 // ultimately initializing a non-temporary), our argument needs to be
8098 // bound since it's initializing a function parameter.
8099 // FIXME: This is a mess. Rationalize temporary destruction.
8100 if (!shouldBindAsTemporary(Entity))
8101 CurInit = S.MaybeBindToTemporary(CurInit.get());
8102 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8103 /*IsExtraneousCopy=*/false);
8104 break;
8105
8107 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8108 /*IsExtraneousCopy=*/true);
8109 break;
8110
8111 case SK_UserConversion: {
8112 // We have a user-defined conversion that invokes either a constructor
8113 // or a conversion function.
8117 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8118 bool CreatedObject = false;
8119 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8120 // Build a call to the selected constructor.
8121 SmallVector<Expr*, 8> ConstructorArgs;
8122 SourceLocation Loc = CurInit.get()->getBeginLoc();
8123
8124 // Determine the arguments required to actually perform the constructor
8125 // call.
8126 Expr *Arg = CurInit.get();
8128 MultiExprArg(&Arg, 1), Loc,
8129 ConstructorArgs))
8130 return ExprError();
8131
8132 // Build an expression that constructs a temporary.
8133 CurInit = S.BuildCXXConstructExpr(
8134 Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
8135 HadMultipleCandidates,
8136 /*ListInit*/ false,
8137 /*StdInitListInit*/ false,
8138 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
8139 if (CurInit.isInvalid())
8140 return ExprError();
8141
8142 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8143 Entity);
8144 if (S.DiagnoseUseOfOverloadedDecl(Constructor, Kind.getLocation()))
8145 return ExprError();
8146
8147 CastKind = CK_ConstructorConversion;
8148 CreatedObject = true;
8149 } else {
8150 // Build a call to the conversion function.
8152 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8153 FoundFn);
8154 if (S.DiagnoseUseOfOverloadedDecl(Conversion, Kind.getLocation()))
8155 return ExprError();
8156
8157 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8158 HadMultipleCandidates);
8159 if (CurInit.isInvalid())
8160 return ExprError();
8161
8162 CastKind = CK_UserDefinedConversion;
8163 CreatedObject = Conversion->getReturnType()->isRecordType();
8164 }
8165
8166 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8167 return ExprError();
8168
8169 CurInit = ImplicitCastExpr::Create(
8170 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8171 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
8172
8173 if (shouldBindAsTemporary(Entity))
8174 // The overall entity is temporary, so this expression should be
8175 // destroyed at the end of its full-expression.
8176 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
8177 else if (CreatedObject && shouldDestroyEntity(Entity)) {
8178 // The object outlasts the full-expression, but we need to prepare for
8179 // a destructor being run on it.
8180 // FIXME: It makes no sense to do this here. This should happen
8181 // regardless of how we initialized the entity.
8182 QualType T = CurInit.get()->getType();
8183 if (auto *Record = T->castAsCXXRecordDecl()) {
8186 S.PDiag(diag::err_access_dtor_temp) << T);
8188 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
8189 return ExprError();
8190 }
8191 }
8192 break;
8193 }
8194
8198 // Perform a qualification conversion; these can never go wrong.
8201 ? VK_LValue
8203 : VK_PRValue);
8204 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
8205 break;
8206 }
8207
8209 assert(CurInit.get()->isLValue() &&
8210 "function reference should be lvalue");
8211 CurInit =
8212 S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
8213 break;
8214
8215 case SK_AtomicConversion: {
8216 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
8217 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8218 CK_NonAtomicToAtomic, VK_PRValue);
8219 break;
8220 }
8221
8224 if (const auto *FromPtrType =
8225 CurInit.get()->getType()->getAs<PointerType>()) {
8226 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
8227 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8228 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8229 // Do not check static casts here because they are checked earlier
8230 // in Sema::ActOnCXXNamedCast()
8231 if (!Kind.isStaticCast()) {
8232 S.Diag(CurInit.get()->getExprLoc(),
8233 diag::warn_noderef_to_dereferenceable_pointer)
8234 << CurInit.get()->getSourceRange();
8235 }
8236 }
8237 }
8238 }
8239 Expr *Init = CurInit.get();
8241 Kind.isCStyleCast() ? CheckedConversionKind::CStyleCast
8242 : Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast
8243 : Kind.isExplicitCast() ? CheckedConversionKind::OtherCast
8245 ExprResult CurInitExprRes = S.PerformImplicitConversion(
8246 Init, Step->Type, *Step->ICS, getAssignmentAction(Entity), CCK);
8247 if (CurInitExprRes.isInvalid())
8248 return ExprError();
8249
8251
8252 CurInit = CurInitExprRes;
8253
8255 S.getLangOpts().CPlusPlus)
8256 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
8257 CurInit.get());
8258
8259 break;
8260 }
8261
8262 case SK_ListInitialization: {
8263 if (checkAbstractType(Step->Type))
8264 return ExprError();
8265
8266 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
8267 // If we're not initializing the top-level entity, we need to create an
8268 // InitializeTemporary entity for our target type.
8269 QualType Ty = Step->Type;
8270 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
8271 InitializedEntity InitEntity =
8272 IsTemporary ? InitializedEntity::InitializeTemporary(Ty) : Entity;
8273 InitListChecker PerformInitList(S, InitEntity,
8274 InitList, Ty, /*VerifyOnly=*/false,
8275 /*TreatUnavailableAsInvalid=*/false);
8276 if (PerformInitList.HadError())
8277 return ExprError();
8278
8279 // Hack: We must update *ResultType if available in order to set the
8280 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
8281 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
8282 if (ResultType &&
8283 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
8284 if ((*ResultType)->isRValueReferenceType())
8286 else if ((*ResultType)->isLValueReferenceType())
8288 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
8289 *ResultType = Ty;
8290 }
8291
8292 InitListExpr *StructuredInitList =
8293 PerformInitList.getFullyStructuredList();
8294 CurInit = shouldBindAsTemporary(InitEntity)
8295 ? S.MaybeBindToTemporary(StructuredInitList)
8296 : StructuredInitList;
8297 break;
8298 }
8299
8301 if (checkAbstractType(Step->Type))
8302 return ExprError();
8303
8304 // When an initializer list is passed for a parameter of type "reference
8305 // to object", we don't get an EK_Temporary entity, but instead an
8306 // EK_Parameter entity with reference type.
8307 // FIXME: This is a hack. What we really should do is create a user
8308 // conversion step for this case, but this makes it considerably more
8309 // complicated. For now, this will do.
8311 Entity.getType().getNonReferenceType());
8312 bool UseTemporary = Entity.getType()->isReferenceType();
8313 assert(Args.size() == 1 && "expected a single argument for list init");
8314 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8315 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
8316 << InitList->getSourceRange();
8317 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
8318 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
8319 Entity,
8320 Kind, Arg, *Step,
8321 ConstructorInitRequiresZeroInit,
8322 /*IsListInitialization*/true,
8323 /*IsStdInitListInit*/false,
8324 InitList->getLBraceLoc(),
8325 InitList->getRBraceLoc());
8326 break;
8327 }
8328
8329 case SK_UnwrapInitList:
8330 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
8331 break;
8332
8333 case SK_RewrapInitList: {
8334 Expr *E = CurInit.get();
8336 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
8337 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
8338 ILE->setSyntacticForm(Syntactic);
8339 ILE->setType(E->getType());
8340 ILE->setValueKind(E->getValueKind());
8341 CurInit = ILE;
8342 break;
8343 }
8344
8347 if (checkAbstractType(Step->Type))
8348 return ExprError();
8349
8350 // When an initializer list is passed for a parameter of type "reference
8351 // to object", we don't get an EK_Temporary entity, but instead an
8352 // EK_Parameter entity with reference type.
8353 // FIXME: This is a hack. What we really should do is create a user
8354 // conversion step for this case, but this makes it considerably more
8355 // complicated. For now, this will do.
8357 Entity.getType().getNonReferenceType());
8358 bool UseTemporary = Entity.getType()->isReferenceType();
8359 bool IsStdInitListInit =
8361 Expr *Source = CurInit.get();
8362 SourceRange Range = Kind.hasParenOrBraceRange()
8363 ? Kind.getParenOrBraceRange()
8364 : SourceRange();
8366 S, UseTemporary ? TempEntity : Entity, Kind,
8367 Source ? MultiExprArg(Source) : Args, *Step,
8368 ConstructorInitRequiresZeroInit,
8369 /*IsListInitialization*/ IsStdInitListInit,
8370 /*IsStdInitListInitialization*/ IsStdInitListInit,
8371 /*LBraceLoc*/ Range.getBegin(),
8372 /*RBraceLoc*/ Range.getEnd());
8373 break;
8374 }
8375
8376 case SK_ZeroInitialization: {
8377 step_iterator NextStep = Step;
8378 ++NextStep;
8379 if (NextStep != StepEnd &&
8380 (NextStep->Kind == SK_ConstructorInitialization ||
8381 NextStep->Kind == SK_ConstructorInitializationFromList)) {
8382 // The need for zero-initialization is recorded directly into
8383 // the call to the object's constructor within the next step.
8384 ConstructorInitRequiresZeroInit = true;
8385 } else if (Kind.getKind() == InitializationKind::IK_Value &&
8386 S.getLangOpts().CPlusPlus &&
8387 !Kind.isImplicitValueInit()) {
8388 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
8389 if (!TSInfo)
8391 Kind.getRange().getBegin());
8392
8393 CurInit = new (S.Context) CXXScalarValueInitExpr(
8394 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
8395 Kind.getRange().getEnd());
8396 } else {
8397 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
8398 // Note the return value isn't used to return a ExprError() when
8399 // initialization fails . For struct initialization allows all field
8400 // assignments to be checked rather than bailing on the first error.
8401 S.BoundsSafetyCheckInitialization(Entity, Kind,
8403 Step->Type, CurInit.get());
8404 }
8405 break;
8406 }
8407
8408 case SK_CAssignment: {
8409 QualType SourceType = CurInit.get()->getType();
8410 Expr *Init = CurInit.get();
8411
8412 // Save off the initial CurInit in case we need to emit a diagnostic
8413 ExprResult InitialCurInit = Init;
8416 Step->Type, Result, true,
8418 if (Result.isInvalid())
8419 return ExprError();
8420 CurInit = Result;
8421
8422 // If this is a call, allow conversion to a transparent union.
8423 ExprResult CurInitExprRes = CurInit;
8424 if (!S.IsAssignConvertCompatible(ConvTy) && Entity.isParameterKind() &&
8426 Step->Type, CurInitExprRes) == AssignConvertType::Compatible)
8428 if (CurInitExprRes.isInvalid())
8429 return ExprError();
8430 CurInit = CurInitExprRes;
8431
8432 if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) {
8433 CheckC23ConstexprInitConversion(S, SourceType, Entity.getType(),
8434 CurInit.get());
8435
8436 // C23 6.7.1p6: If an object or subobject declared with storage-class
8437 // specifier constexpr has pointer, integer, or arithmetic type, any
8438 // explicit initializer value for it shall be null, an integer
8439 // constant expression, or an arithmetic constant expression,
8440 // respectively.
8442 if (Entity.getType()->getAs<PointerType>() &&
8443 CurInit.get()->EvaluateAsRValue(ER, S.Context) &&
8444 !ER.Val.isNullPointer()) {
8445 S.Diag(Kind.getLocation(), diag::err_c23_constexpr_pointer_not_null);
8446 }
8447 }
8448
8449 // Note the return value isn't used to return a ExprError() when
8450 // initialization fails. For struct initialization this allows all field
8451 // assignments to be checked rather than bailing on the first error.
8452 S.BoundsSafetyCheckInitialization(Entity, Kind,
8453 getAssignmentAction(Entity, true),
8454 Step->Type, InitialCurInit.get());
8455
8456 bool Complained;
8457 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
8458 Step->Type, SourceType,
8459 InitialCurInit.get(),
8460 getAssignmentAction(Entity, true),
8461 &Complained)) {
8462 PrintInitLocationNote(S, Entity);
8463 return ExprError();
8464 } else if (Complained)
8465 PrintInitLocationNote(S, Entity);
8466 break;
8467 }
8468
8469 case SK_StringInit: {
8470 QualType Ty = Step->Type;
8471 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
8472 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
8473 S.Context.getAsArrayType(Ty), S, Entity,
8474 S.getLangOpts().C23 &&
8476 break;
8477 }
8478
8480 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8481 CK_ObjCObjectLValueCast,
8482 CurInit.get()->getValueKind());
8483 break;
8484
8485 case SK_ArrayLoopIndex: {
8486 Expr *Cur = CurInit.get();
8487 Expr *BaseExpr = new (S.Context)
8488 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8489 Cur->getValueKind(), Cur->getObjectKind(), Cur);
8490 Expr *IndexExpr =
8493 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
8494 ArrayLoopCommonExprs.push_back(BaseExpr);
8495 break;
8496 }
8497
8498 case SK_ArrayLoopInit: {
8499 assert(!ArrayLoopCommonExprs.empty() &&
8500 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8501 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8502 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8503 CurInit.get());
8504 break;
8505 }
8506
8507 case SK_GNUArrayInit:
8508 // Okay: we checked everything before creating this step. Note that
8509 // this is a GNU extension.
8510 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
8511 << Step->Type << CurInit.get()->getType()
8512 << CurInit.get()->getSourceRange();
8514 [[fallthrough]];
8515 case SK_ArrayInit:
8516 // If the destination type is an incomplete array type, update the
8517 // type accordingly.
8518 if (ResultType) {
8519 if (const IncompleteArrayType *IncompleteDest
8521 if (const ConstantArrayType *ConstantSource
8522 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
8523 *ResultType = S.Context.getConstantArrayType(
8524 IncompleteDest->getElementType(), ConstantSource->getSize(),
8525 ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
8526 }
8527 }
8528 }
8529 break;
8530
8532 // Okay: we checked everything before creating this step. Note that
8533 // this is a GNU extension.
8534 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
8535 << CurInit.get()->getSourceRange();
8536 break;
8537
8540 checkIndirectCopyRestoreSource(S, CurInit.get());
8541 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
8542 CurInit.get(), Step->Type,
8544 break;
8545
8547 CurInit = ImplicitCastExpr::Create(
8548 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
8550 break;
8551
8552 case SK_StdInitializerList: {
8553 S.Diag(CurInit.get()->getExprLoc(),
8554 diag::warn_cxx98_compat_initializer_list_init)
8555 << CurInit.get()->getSourceRange();
8556
8557 // Materialize the temporary into memory.
8559 CurInit.get()->getType(), CurInit.get(),
8560 /*BoundToLvalueReference=*/false);
8561
8562 // Wrap it in a construction of a std::initializer_list<T>.
8563 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
8564
8565 if (!Step->Type->isDependentType()) {
8566 QualType ElementType;
8567 [[maybe_unused]] bool IsStdInitializerList =
8568 S.isStdInitializerList(Step->Type, &ElementType);
8569 assert(IsStdInitializerList &&
8570 "StdInitializerList step to non-std::initializer_list");
8571 const auto *Record = Step->Type->castAsCXXRecordDecl();
8572 assert(Record->isCompleteDefinition() &&
8573 "std::initializer_list should have already be "
8574 "complete/instantiated by this point");
8575
8576 auto InvalidType = [&] {
8577 S.Diag(Record->getLocation(),
8578 diag::err_std_initializer_list_malformed)
8580 return ExprError();
8581 };
8582
8583 if (Record->isUnion() || Record->getNumBases() != 0 ||
8584 Record->isPolymorphic())
8585 return InvalidType();
8586
8587 RecordDecl::field_iterator Field = Record->field_begin();
8588 if (Field == Record->field_end())
8589 return InvalidType();
8590
8591 // Start pointer
8592 if (!Field->getType()->isPointerType() ||
8593 !S.Context.hasSameType(Field->getType()->getPointeeType(),
8594 ElementType.withConst()))
8595 return InvalidType();
8596
8597 if (++Field == Record->field_end())
8598 return InvalidType();
8599
8600 // Size or end pointer
8601 if (const auto *PT = Field->getType()->getAs<PointerType>()) {
8602 if (!S.Context.hasSameType(PT->getPointeeType(),
8603 ElementType.withConst()))
8604 return InvalidType();
8605 } else {
8606 if (Field->isBitField() ||
8607 !S.Context.hasSameType(Field->getType(), S.Context.getSizeType()))
8608 return InvalidType();
8609 }
8610
8611 if (++Field != Record->field_end())
8612 return InvalidType();
8613 }
8614
8615 // Bind the result, in case the library has given initializer_list a
8616 // non-trivial destructor.
8617 if (shouldBindAsTemporary(Entity))
8618 CurInit = S.MaybeBindToTemporary(CurInit.get());
8619 break;
8620 }
8621
8622 case SK_OCLSamplerInit: {
8623 // Sampler initialization have 5 cases:
8624 // 1. function argument passing
8625 // 1a. argument is a file-scope variable
8626 // 1b. argument is a function-scope variable
8627 // 1c. argument is one of caller function's parameters
8628 // 2. variable initialization
8629 // 2a. initializing a file-scope variable
8630 // 2b. initializing a function-scope variable
8631 //
8632 // For file-scope variables, since they cannot be initialized by function
8633 // call of __translate_sampler_initializer in LLVM IR, their references
8634 // need to be replaced by a cast from their literal initializers to
8635 // sampler type. Since sampler variables can only be used in function
8636 // calls as arguments, we only need to replace them when handling the
8637 // argument passing.
8638 assert(Step->Type->isSamplerT() &&
8639 "Sampler initialization on non-sampler type.");
8640 Expr *Init = CurInit.get()->IgnoreParens();
8641 QualType SourceType = Init->getType();
8642 // Case 1
8643 if (Entity.isParameterKind()) {
8644 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
8645 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
8646 << SourceType;
8647 break;
8648 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
8649 auto Var = cast<VarDecl>(DRE->getDecl());
8650 // Case 1b and 1c
8651 // No cast from integer to sampler is needed.
8652 if (!Var->hasGlobalStorage()) {
8653 CurInit = ImplicitCastExpr::Create(
8654 S.Context, Step->Type, CK_LValueToRValue, Init,
8655 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
8656 break;
8657 }
8658 // Case 1a
8659 // For function call with a file-scope sampler variable as argument,
8660 // get the integer literal.
8661 // Do not diagnose if the file-scope variable does not have initializer
8662 // since this has already been diagnosed when parsing the variable
8663 // declaration.
8664 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8665 break;
8666 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
8667 Var->getInit()))->getSubExpr();
8668 SourceType = Init->getType();
8669 }
8670 } else {
8671 // Case 2
8672 // Check initializer is 32 bit integer constant.
8673 // If the initializer is taken from global variable, do not diagnose since
8674 // this has already been done when parsing the variable declaration.
8675 if (!Init->isConstantInitializer(S.Context, false))
8676 break;
8677
8678 if (!SourceType->isIntegerType() ||
8679 32 != S.Context.getIntWidth(SourceType)) {
8680 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8681 << SourceType;
8682 break;
8683 }
8684
8685 Expr::EvalResult EVResult;
8686 Init->EvaluateAsInt(EVResult, S.Context);
8687 llvm::APSInt Result = EVResult.Val.getInt();
8688 const uint64_t SamplerValue = Result.getLimitedValue();
8689 // 32-bit value of sampler's initializer is interpreted as
8690 // bit-field with the following structure:
8691 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8692 // |31 6|5 4|3 1| 0|
8693 // This structure corresponds to enum values of sampler properties
8694 // defined in SPIR spec v1.2 and also opencl-c.h
8695 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8696 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
8697 if (FilterMode != 1 && FilterMode != 2 &&
8699 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
8700 S.Diag(Kind.getLocation(),
8701 diag::warn_sampler_initializer_invalid_bits)
8702 << "Filter Mode";
8703 if (AddressingMode > 4)
8704 S.Diag(Kind.getLocation(),
8705 diag::warn_sampler_initializer_invalid_bits)
8706 << "Addressing Mode";
8707 }
8708
8709 // Cases 1a, 2a and 2b
8710 // Insert cast from integer to sampler.
8712 CK_IntToOCLSampler);
8713 break;
8714 }
8715 case SK_OCLZeroOpaqueType: {
8716 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8718 "Wrong type for initialization of OpenCL opaque type.");
8719
8720 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8721 CK_ZeroToOCLOpaqueType,
8722 CurInit.get()->getValueKind());
8723 break;
8724 }
8726 CurInit = nullptr;
8727 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
8728 /*VerifyOnly=*/false, &CurInit);
8729 if (CurInit.get() && ResultType)
8730 *ResultType = CurInit.get()->getType();
8731 if (shouldBindAsTemporary(Entity))
8732 CurInit = S.MaybeBindToTemporary(CurInit.get());
8733 break;
8734 }
8735 }
8736 }
8737
8738 Expr *Init = CurInit.get();
8739 if (!Init)
8740 return ExprError();
8741
8742 // Check whether the initializer has a shorter lifetime than the initialized
8743 // entity, and if not, either lifetime-extend or warn as appropriate.
8744 S.checkInitializerLifetime(Entity, Init);
8745
8746 // Diagnose non-fatal problems with the completed initialization.
8747 if (InitializedEntity::EntityKind EK = Entity.getKind();
8750 cast<FieldDecl>(Entity.getDecl())->isBitField())
8751 S.CheckBitFieldInitialization(Kind.getLocation(),
8752 cast<FieldDecl>(Entity.getDecl()), Init);
8753
8754 // Check for std::move on construction.
8757
8758 return Init;
8759}
8760
8761/// Somewhere within T there is an uninitialized reference subobject.
8762/// Dig it out and diagnose it.
8764 QualType T) {
8765 if (T->isReferenceType()) {
8766 S.Diag(Loc, diag::err_reference_without_init)
8767 << T.getNonReferenceType();
8768 return true;
8769 }
8770
8771 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8772 if (!RD || !RD->hasUninitializedReferenceMember())
8773 return false;
8774
8775 for (const auto *FI : RD->fields()) {
8776 if (FI->isUnnamedBitField())
8777 continue;
8778
8779 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8780 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8781 return true;
8782 }
8783 }
8784
8785 for (const auto &BI : RD->bases()) {
8786 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
8787 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8788 return true;
8789 }
8790 }
8791
8792 return false;
8793}
8794
8795
8796//===----------------------------------------------------------------------===//
8797// Diagnose initialization failures
8798//===----------------------------------------------------------------------===//
8799
8800/// Emit notes associated with an initialization that failed due to a
8801/// "simple" conversion failure.
8802static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8803 Expr *op) {
8804 QualType destType = entity.getType();
8805 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8807
8808 // Emit a possible note about the conversion failing because the
8809 // operand is a message send with a related result type.
8811
8812 // Emit a possible note about a return failing because we're
8813 // expecting a related result type.
8814 if (entity.getKind() == InitializedEntity::EK_Result)
8816 }
8817 QualType fromType = op->getType();
8818 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
8819 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
8820 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
8821 auto *destDecl = destType->getPointeeCXXRecordDecl();
8822 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
8823 destDecl->getDeclKind() == Decl::CXXRecord &&
8824 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
8825 !fromDecl->hasDefinition() &&
8826 destPointeeType.getQualifiers().compatiblyIncludes(
8827 fromPointeeType.getQualifiers(), S.getASTContext()))
8828 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
8829 << S.getASTContext().getCanonicalTagType(fromDecl)
8830 << S.getASTContext().getCanonicalTagType(destDecl);
8831}
8832
8833static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8834 InitListExpr *InitList) {
8835 QualType DestType = Entity.getType();
8836
8837 QualType E;
8838 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
8840 E.withConst(),
8841 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
8842 InitList->getNumInits()),
8844 InitializedEntity HiddenArray =
8846 return diagnoseListInit(S, HiddenArray, InitList);
8847 }
8848
8849 if (DestType->isReferenceType()) {
8850 // A list-initialization failure for a reference means that we tried to
8851 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
8852 // inner initialization failed.
8853 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
8855 SourceLocation Loc = InitList->getBeginLoc();
8856 if (auto *D = Entity.getDecl())
8857 Loc = D->getLocation();
8858 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
8859 return;
8860 }
8861
8862 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
8863 /*VerifyOnly=*/false,
8864 /*TreatUnavailableAsInvalid=*/false);
8865 assert(DiagnoseInitList.HadError() &&
8866 "Inconsistent init list check result.");
8867}
8868
8870 const InitializedEntity &Entity,
8871 const InitializationKind &Kind,
8872 ArrayRef<Expr *> Args) {
8873 if (!Failed())
8874 return false;
8875
8876 QualType DestType = Entity.getType();
8877
8878 // When we want to diagnose only one element of a braced-init-list,
8879 // we need to factor it out.
8880 Expr *OnlyArg;
8881 if (Args.size() == 1) {
8882 auto *List = dyn_cast<InitListExpr>(Args[0]);
8883 if (List && List->getNumInits() == 1)
8884 OnlyArg = List->getInit(0);
8885 else
8886 OnlyArg = Args[0];
8887
8888 if (OnlyArg->getType() == S.Context.OverloadTy) {
8891 OnlyArg, DestType.getNonReferenceType(), /*Complain=*/false,
8892 Found)) {
8893 if (Expr *Resolved =
8894 S.FixOverloadedFunctionReference(OnlyArg, Found, FD).get())
8895 OnlyArg = Resolved;
8896 }
8897 }
8898 }
8899 else
8900 OnlyArg = nullptr;
8901
8902 switch (Failure) {
8904 // FIXME: Customize for the initialized entity?
8905 if (Args.empty()) {
8906 // Dig out the reference subobject which is uninitialized and diagnose it.
8907 // If this is value-initialization, this could be nested some way within
8908 // the target type.
8909 assert(Kind.getKind() == InitializationKind::IK_Value ||
8910 DestType->isReferenceType());
8911 bool Diagnosed =
8912 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
8913 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
8914 (void)Diagnosed;
8915 } else // FIXME: diagnostic below could be better!
8916 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
8917 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
8918 break;
8920 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8921 << 1 << Entity.getType() << Args[0]->getSourceRange();
8922 break;
8923
8925 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
8926 break;
8928 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
8929 break;
8931 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
8932 break;
8934 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
8935 break;
8937 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
8938 break;
8940 S.Diag(Kind.getLocation(),
8941 diag::err_array_init_incompat_wide_string_into_wchar);
8942 break;
8944 S.Diag(Kind.getLocation(),
8945 diag::err_array_init_plain_string_into_char8_t);
8946 S.Diag(Args.front()->getBeginLoc(),
8947 diag::note_array_init_plain_string_into_char8_t)
8948 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
8949 break;
8951 S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
8952 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
8953 break;
8956 S.Diag(Kind.getLocation(),
8957 (Failure == FK_ArrayTypeMismatch
8958 ? diag::err_array_init_different_type
8959 : diag::err_array_init_non_constant_array))
8960 << DestType.getNonReferenceType()
8961 << OnlyArg->getType()
8962 << Args[0]->getSourceRange();
8963 break;
8964
8966 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
8967 << Args[0]->getSourceRange();
8968 break;
8969
8973 DestType.getNonReferenceType(),
8974 true,
8975 Found);
8976 break;
8977 }
8978
8980 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
8981 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8982 OnlyArg->getBeginLoc());
8983 break;
8984 }
8985
8988 switch (FailedOverloadResult) {
8989 case OR_Ambiguous:
8990
8991 FailedCandidateSet.NoteCandidates(
8993 Kind.getLocation(),
8995 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
8996 << OnlyArg->getType() << DestType
8997 << Args[0]->getSourceRange())
8998 : (S.PDiag(diag::err_ref_init_ambiguous)
8999 << DestType << OnlyArg->getType()
9000 << Args[0]->getSourceRange())),
9001 S, OCD_AmbiguousCandidates, Args);
9002 break;
9003
9004 case OR_No_Viable_Function: {
9005 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
9006 if (!S.RequireCompleteType(Kind.getLocation(),
9007 DestType.getNonReferenceType(),
9008 diag::err_typecheck_nonviable_condition_incomplete,
9009 OnlyArg->getType(), Args[0]->getSourceRange()))
9010 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9011 << (Entity.getKind() == InitializedEntity::EK_Result)
9012 << OnlyArg->getType() << Args[0]->getSourceRange()
9013 << DestType.getNonReferenceType();
9014
9015 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9016 break;
9017 }
9018 case OR_Deleted: {
9021 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9022
9023 StringLiteral *Msg = Best->Function->getDeletedMessage();
9024 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9025 << OnlyArg->getType() << DestType.getNonReferenceType()
9026 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
9027 << Args[0]->getSourceRange();
9028 if (Ovl == OR_Deleted) {
9029 S.NoteDeletedFunction(Best->Function);
9030 } else {
9031 llvm_unreachable("Inconsistent overload resolution?");
9032 }
9033 break;
9034 }
9035
9036 case OR_Success:
9037 llvm_unreachable("Conversion did not fail!");
9038 }
9039 break;
9040
9042 if (isa<InitListExpr>(Args[0])) {
9043 S.Diag(Kind.getLocation(),
9044 diag::err_lvalue_reference_bind_to_initlist)
9046 << DestType.getNonReferenceType()
9047 << Args[0]->getSourceRange();
9048 break;
9049 }
9050 [[fallthrough]];
9051
9053 S.Diag(Kind.getLocation(),
9055 ? diag::err_lvalue_reference_bind_to_temporary
9056 : diag::err_lvalue_reference_bind_to_unrelated)
9058 << DestType.getNonReferenceType()
9059 << OnlyArg->getType()
9060 << Args[0]->getSourceRange();
9061 break;
9062
9064 // We don't necessarily have an unambiguous source bit-field.
9065 FieldDecl *BitField = Args[0]->getSourceBitField();
9066 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9067 << DestType.isVolatileQualified()
9068 << (BitField ? BitField->getDeclName() : DeclarationName())
9069 << (BitField != nullptr)
9070 << Args[0]->getSourceRange();
9071 if (BitField)
9072 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9073 break;
9074 }
9075
9077 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9078 << DestType.isVolatileQualified()
9079 << Args[0]->getSourceRange();
9080 break;
9081
9083 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9084 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9085 break;
9086
9088 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9089 << DestType.getNonReferenceType() << OnlyArg->getType()
9090 << Args[0]->getSourceRange();
9091 break;
9092
9094 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9095 << DestType << Args[0]->getSourceRange();
9096 break;
9097
9099 QualType SourceType = OnlyArg->getType();
9100 QualType NonRefType = DestType.getNonReferenceType();
9101 Qualifiers DroppedQualifiers =
9102 SourceType.getQualifiers() - NonRefType.getQualifiers();
9103
9104 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9105 SourceType.getQualifiers(), S.getASTContext()))
9106 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9107 << NonRefType << SourceType << 1 /*addr space*/
9108 << Args[0]->getSourceRange();
9109 else if (DroppedQualifiers.hasQualifiers())
9110 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9111 << NonRefType << SourceType << 0 /*cv quals*/
9112 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9113 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9114 else
9115 // FIXME: Consider decomposing the type and explaining which qualifiers
9116 // were dropped where, or on which level a 'const' is missing, etc.
9117 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9118 << NonRefType << SourceType << 2 /*incompatible quals*/
9119 << Args[0]->getSourceRange();
9120 break;
9121 }
9122
9124 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9125 << DestType.getNonReferenceType()
9126 << DestType.getNonReferenceType()->isIncompleteType()
9127 << OnlyArg->isLValue()
9128 << OnlyArg->getType()
9129 << Args[0]->getSourceRange();
9130 emitBadConversionNotes(S, Entity, Args[0]);
9131 break;
9132
9133 case FK_ConversionFailed: {
9134 QualType FromType = OnlyArg->getType();
9135 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9136 << (int)Entity.getKind()
9137 << DestType
9138 << OnlyArg->isLValue()
9139 << FromType
9140 << Args[0]->getSourceRange();
9141 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9142 S.Diag(Kind.getLocation(), PDiag);
9143 emitBadConversionNotes(S, Entity, Args[0]);
9144 break;
9145 }
9146
9148 // No-op. This error has already been reported.
9149 break;
9150
9152 SourceRange R;
9153
9154 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9155 if (InitList && InitList->getNumInits() >= 1) {
9156 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9157 } else {
9158 assert(Args.size() > 1 && "Expected multiple initializers!");
9159 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9160 }
9161
9163 if (Kind.isCStyleOrFunctionalCast())
9164 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9165 << R;
9166 else
9167 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9168 << /*scalar=*/3 << R;
9169 break;
9170 }
9171
9173 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9174 << 0 << Entity.getType() << Args[0]->getSourceRange();
9175 break;
9176
9178 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9179 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9180 break;
9181
9183 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9184 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9185 break;
9186
9189 SourceRange ArgsRange;
9190 if (Args.size())
9191 ArgsRange =
9192 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9193
9194 if (Failure == FK_ListConstructorOverloadFailed) {
9195 assert(Args.size() == 1 &&
9196 "List construction from other than 1 argument.");
9197 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9198 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9199 }
9200
9201 // FIXME: Using "DestType" for the entity we're printing is probably
9202 // bad.
9203 switch (FailedOverloadResult) {
9204 case OR_Ambiguous:
9205 FailedCandidateSet.NoteCandidates(
9206 PartialDiagnosticAt(Kind.getLocation(),
9207 S.PDiag(diag::err_ovl_ambiguous_init)
9208 << DestType << ArgsRange),
9209 S, OCD_AmbiguousCandidates, Args);
9210 break;
9211
9213 if (Kind.getKind() == InitializationKind::IK_Default &&
9214 (Entity.getKind() == InitializedEntity::EK_Base ||
9218 // This is implicit default initialization of a member or
9219 // base within a constructor. If no viable function was
9220 // found, notify the user that they need to explicitly
9221 // initialize this base/member.
9224 const CXXRecordDecl *InheritedFrom = nullptr;
9225 if (auto Inherited = Constructor->getInheritedConstructor())
9226 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9227 if (Entity.getKind() == InitializedEntity::EK_Base) {
9228 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9229 << (InheritedFrom ? 2
9230 : Constructor->isImplicit() ? 1
9231 : 0)
9232 << S.Context.getCanonicalTagType(Constructor->getParent())
9233 << /*base=*/0 << Entity.getType() << InheritedFrom;
9234
9235 auto *BaseDecl =
9237 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9238 << S.Context.getCanonicalTagType(BaseDecl);
9239 } else {
9240 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9241 << (InheritedFrom ? 2
9242 : Constructor->isImplicit() ? 1
9243 : 0)
9244 << S.Context.getCanonicalTagType(Constructor->getParent())
9245 << /*member=*/1 << Entity.getName() << InheritedFrom;
9246 S.Diag(Entity.getDecl()->getLocation(),
9247 diag::note_member_declared_at);
9248
9249 if (const auto *Record = Entity.getType()->getAs<RecordType>())
9250 S.Diag(Record->getDecl()->getLocation(), diag::note_previous_decl)
9251 << S.Context.getCanonicalTagType(Record->getDecl());
9252 }
9253 break;
9254 }
9255
9256 FailedCandidateSet.NoteCandidates(
9258 Kind.getLocation(),
9259 S.PDiag(diag::err_ovl_no_viable_function_in_init)
9260 << DestType << ArgsRange),
9261 S, OCD_AllCandidates, Args);
9262 break;
9263
9264 case OR_Deleted: {
9267 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9268 if (Ovl != OR_Deleted) {
9269 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9270 << DestType << ArgsRange;
9271 llvm_unreachable("Inconsistent overload resolution?");
9272 break;
9273 }
9274
9275 // If this is a defaulted or implicitly-declared function, then
9276 // it was implicitly deleted. Make it clear that the deletion was
9277 // implicit.
9278 if (S.isImplicitlyDeleted(Best->Function))
9279 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
9280 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
9281 << DestType << ArgsRange;
9282 else {
9283 StringLiteral *Msg = Best->Function->getDeletedMessage();
9284 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9285 << DestType << (Msg != nullptr)
9286 << (Msg ? Msg->getString() : StringRef()) << ArgsRange;
9287 }
9288
9289 // If it's a default constructed member, but it's not in the
9290 // constructor's initializer list, explicitly note where the member is
9291 // declared so the user can see which member is erroneously initialized
9292 // with a deleted default constructor.
9293 if (Kind.getKind() == InitializationKind::IK_Default &&
9296 S.Diag(Entity.getDecl()->getLocation(),
9297 diag::note_default_constructed_field)
9298 << Entity.getDecl();
9299 }
9300 S.NoteDeletedFunction(Best->Function);
9301 break;
9302 }
9303
9304 case OR_Success:
9305 llvm_unreachable("Conversion did not fail!");
9306 }
9307 }
9308 break;
9309
9311 if (Entity.getKind() == InitializedEntity::EK_Member &&
9313 // This is implicit default-initialization of a const member in
9314 // a constructor. Complain that it needs to be explicitly
9315 // initialized.
9317 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
9318 << (Constructor->getInheritedConstructor() ? 2
9319 : Constructor->isImplicit() ? 1
9320 : 0)
9321 << S.Context.getCanonicalTagType(Constructor->getParent())
9322 << /*const=*/1 << Entity.getName();
9323 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
9324 << Entity.getName();
9325 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
9326 VD && VD->isConstexpr()) {
9327 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
9328 << VD;
9329 } else {
9330 S.Diag(Kind.getLocation(), diag::err_default_init_const)
9331 << DestType << DestType->isRecordType();
9332 }
9333 break;
9334
9335 case FK_Incomplete:
9336 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
9337 diag::err_init_incomplete_type);
9338 break;
9339
9341 // Run the init list checker again to emit diagnostics.
9342 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9343 diagnoseListInit(S, Entity, InitList);
9344 break;
9345 }
9346
9347 case FK_PlaceholderType: {
9348 // FIXME: Already diagnosed!
9349 break;
9350 }
9351
9353 // Unlike C/C++ list initialization, there is no fallback if it fails. This
9354 // allows us to diagnose the failure when it happens in the
9355 // TryListInitialization call instead of delaying the diagnosis, which is
9356 // beneficial because the flattening is also expensive.
9357 break;
9358 }
9359
9361 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
9362 << Args[0]->getSourceRange();
9365 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9366 (void)Ovl;
9367 assert(Ovl == OR_Success && "Inconsistent overload resolution");
9368 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
9369 S.Diag(CtorDecl->getLocation(),
9370 diag::note_explicit_ctor_deduction_guide_here) << false;
9371 break;
9372 }
9373
9375 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9376 /*VerifyOnly=*/false);
9377 break;
9378
9380 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9381 S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
9382 << Entity.getType() << InitList->getSourceRange();
9383 break;
9384 }
9385
9386 PrintInitLocationNote(S, Entity);
9387 return true;
9388}
9389
9390void InitializationSequence::dump(raw_ostream &OS) const {
9391 switch (SequenceKind) {
9392 case FailedSequence: {
9393 OS << "Failed sequence: ";
9394 switch (Failure) {
9396 OS << "too many initializers for reference";
9397 break;
9398
9400 OS << "parenthesized list init for reference";
9401 break;
9402
9404 OS << "array requires initializer list";
9405 break;
9406
9408 OS << "address of unaddressable function was taken";
9409 break;
9410
9412 OS << "array requires initializer list or string literal";
9413 break;
9414
9416 OS << "array requires initializer list or wide string literal";
9417 break;
9418
9420 OS << "narrow string into wide char array";
9421 break;
9422
9424 OS << "wide string into char array";
9425 break;
9426
9428 OS << "incompatible wide string into wide char array";
9429 break;
9430
9432 OS << "plain string literal into char8_t array";
9433 break;
9434
9436 OS << "u8 string literal into char array";
9437 break;
9438
9440 OS << "array type mismatch";
9441 break;
9442
9444 OS << "non-constant array initializer";
9445 break;
9446
9448 OS << "address of overloaded function failed";
9449 break;
9450
9452 OS << "overload resolution for reference initialization failed";
9453 break;
9454
9456 OS << "non-const lvalue reference bound to temporary";
9457 break;
9458
9460 OS << "non-const lvalue reference bound to bit-field";
9461 break;
9462
9464 OS << "non-const lvalue reference bound to vector element";
9465 break;
9466
9468 OS << "non-const lvalue reference bound to matrix element";
9469 break;
9470
9472 OS << "non-const lvalue reference bound to unrelated type";
9473 break;
9474
9476 OS << "rvalue reference bound to an lvalue";
9477 break;
9478
9480 OS << "reference initialization drops qualifiers";
9481 break;
9482
9484 OS << "reference with mismatching address space bound to temporary";
9485 break;
9486
9488 OS << "reference initialization failed";
9489 break;
9490
9492 OS << "conversion failed";
9493 break;
9494
9496 OS << "conversion from property failed";
9497 break;
9498
9500 OS << "too many initializers for scalar";
9501 break;
9502
9504 OS << "parenthesized list init for reference";
9505 break;
9506
9508 OS << "referencing binding to initializer list";
9509 break;
9510
9512 OS << "initializer list for non-aggregate, non-scalar type";
9513 break;
9514
9516 OS << "overloading failed for user-defined conversion";
9517 break;
9518
9520 OS << "constructor overloading failed";
9521 break;
9522
9524 OS << "default initialization of a const variable";
9525 break;
9526
9527 case FK_Incomplete:
9528 OS << "initialization of incomplete type";
9529 break;
9530
9532 OS << "list initialization checker failure";
9533 break;
9534
9536 OS << "variable length array has an initializer";
9537 break;
9538
9539 case FK_PlaceholderType:
9540 OS << "initializer expression isn't contextually valid";
9541 break;
9542
9544 OS << "list constructor overloading failed";
9545 break;
9546
9548 OS << "list copy initialization chose explicit constructor";
9549 break;
9550
9552 OS << "parenthesized list initialization failed";
9553 break;
9554
9556 OS << "designated initializer for non-aggregate type";
9557 break;
9558
9560 OS << "HLSL initialization list flattening failed";
9561 break;
9562 }
9563 OS << '\n';
9564 return;
9565 }
9566
9567 case DependentSequence:
9568 OS << "Dependent sequence\n";
9569 return;
9570
9571 case NormalSequence:
9572 OS << "Normal sequence: ";
9573 break;
9574 }
9575
9576 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
9577 if (S != step_begin()) {
9578 OS << " -> ";
9579 }
9580
9581 switch (S->Kind) {
9583 OS << "resolve address of overloaded function";
9584 break;
9585
9587 OS << "derived-to-base (prvalue)";
9588 break;
9589
9591 OS << "derived-to-base (xvalue)";
9592 break;
9593
9595 OS << "derived-to-base (lvalue)";
9596 break;
9597
9598 case SK_BindReference:
9599 OS << "bind reference to lvalue";
9600 break;
9601
9603 OS << "bind reference to a temporary";
9604 break;
9605
9606 case SK_FinalCopy:
9607 OS << "final copy in class direct-initialization";
9608 break;
9609
9611 OS << "extraneous C++03 copy to temporary";
9612 break;
9613
9614 case SK_UserConversion:
9615 OS << "user-defined conversion via " << *S->Function.Function;
9616 break;
9617
9619 OS << "qualification conversion (prvalue)";
9620 break;
9621
9623 OS << "qualification conversion (xvalue)";
9624 break;
9625
9627 OS << "qualification conversion (lvalue)";
9628 break;
9629
9631 OS << "function reference conversion";
9632 break;
9633
9635 OS << "non-atomic-to-atomic conversion";
9636 break;
9637
9639 OS << "implicit conversion sequence (";
9640 S->ICS->dump(); // FIXME: use OS
9641 OS << ")";
9642 break;
9643
9645 OS << "implicit conversion sequence with narrowing prohibited (";
9646 S->ICS->dump(); // FIXME: use OS
9647 OS << ")";
9648 break;
9649
9651 OS << "list aggregate initialization";
9652 break;
9653
9654 case SK_UnwrapInitList:
9655 OS << "unwrap reference initializer list";
9656 break;
9657
9658 case SK_RewrapInitList:
9659 OS << "rewrap reference initializer list";
9660 break;
9661
9663 OS << "constructor initialization";
9664 break;
9665
9667 OS << "list initialization via constructor";
9668 break;
9669
9671 OS << "zero initialization";
9672 break;
9673
9674 case SK_CAssignment:
9675 OS << "C assignment";
9676 break;
9677
9678 case SK_StringInit:
9679 OS << "string initialization";
9680 break;
9681
9683 OS << "Objective-C object conversion";
9684 break;
9685
9686 case SK_ArrayLoopIndex:
9687 OS << "indexing for array initialization loop";
9688 break;
9689
9690 case SK_ArrayLoopInit:
9691 OS << "array initialization loop";
9692 break;
9693
9694 case SK_ArrayInit:
9695 OS << "array initialization";
9696 break;
9697
9698 case SK_GNUArrayInit:
9699 OS << "array initialization (GNU extension)";
9700 break;
9701
9703 OS << "parenthesized array initialization";
9704 break;
9705
9707 OS << "pass by indirect copy and restore";
9708 break;
9709
9711 OS << "pass by indirect restore";
9712 break;
9713
9715 OS << "Objective-C object retension";
9716 break;
9717
9719 OS << "std::initializer_list from initializer list";
9720 break;
9721
9723 OS << "list initialization from std::initializer_list";
9724 break;
9725
9726 case SK_OCLSamplerInit:
9727 OS << "OpenCL sampler_t from integer constant";
9728 break;
9729
9731 OS << "OpenCL opaque type from zero";
9732 break;
9734 OS << "initialization from a parenthesized list of values";
9735 break;
9736 }
9737
9738 OS << " [" << S->Type << ']';
9739 }
9740
9741 OS << '\n';
9742}
9743
9745 dump(llvm::errs());
9746}
9747
9749 const ImplicitConversionSequence &ICS,
9750 QualType PreNarrowingType,
9751 QualType EntityType,
9752 const Expr *PostInit) {
9753 const StandardConversionSequence *SCS = nullptr;
9754 switch (ICS.getKind()) {
9756 SCS = &ICS.Standard;
9757 break;
9759 SCS = &ICS.UserDefined.After;
9760 break;
9765 return;
9766 }
9767
9768 auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
9769 unsigned ConstRefDiagID, unsigned WarnDiagID) {
9770 unsigned DiagID;
9771 auto &L = S.getLangOpts();
9772 if (L.CPlusPlus11 && !L.HLSL &&
9773 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))
9774 DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
9775 else
9776 DiagID = WarnDiagID;
9777 return S.Diag(PostInit->getBeginLoc(), DiagID)
9778 << PostInit->getSourceRange();
9779 };
9780
9781 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9782 APValue ConstantValue;
9783 QualType ConstantType;
9784 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
9785 ConstantType)) {
9786 case NK_Not_Narrowing:
9788 // No narrowing occurred.
9789 return;
9790
9791 case NK_Type_Narrowing: {
9792 // This was a floating-to-integer conversion, which is always considered a
9793 // narrowing conversion even if the value is a constant and can be
9794 // represented exactly as an integer.
9795 QualType T = EntityType.getNonReferenceType();
9796 MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
9797 diag::ext_init_list_type_narrowing_const_reference,
9798 diag::warn_init_list_type_narrowing)
9799 << PreNarrowingType.getLocalUnqualifiedType()
9800 << T.getLocalUnqualifiedType();
9801 break;
9802 }
9803
9804 case NK_Constant_Narrowing: {
9805 // A constant value was narrowed.
9806 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9807 diag::ext_init_list_constant_narrowing,
9808 diag::ext_init_list_constant_narrowing_const_reference,
9809 diag::warn_init_list_constant_narrowing)
9810 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
9812 break;
9813 }
9814
9815 case NK_Variable_Narrowing: {
9816 // A variable's value may have been narrowed.
9817 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9818 diag::ext_init_list_variable_narrowing,
9819 diag::ext_init_list_variable_narrowing_const_reference,
9820 diag::warn_init_list_variable_narrowing)
9821 << PreNarrowingType.getLocalUnqualifiedType()
9823 break;
9824 }
9825 }
9826
9827 SmallString<128> StaticCast;
9828 llvm::raw_svector_ostream OS(StaticCast);
9829 OS << "static_cast<";
9830 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
9831 // It's important to use the typedef's name if there is one so that the
9832 // fixit doesn't break code using types like int64_t.
9833 //
9834 // FIXME: This will break if the typedef requires qualification. But
9835 // getQualifiedNameAsString() includes non-machine-parsable components.
9836 OS << *TT->getDecl();
9837 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
9838 OS << BT->getName(S.getLangOpts());
9839 else {
9840 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
9841 // with a broken cast.
9842 return;
9843 }
9844 OS << ">(";
9845 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
9846 << PostInit->getSourceRange()
9847 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
9849 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
9850}
9851
9853 QualType ToType, Expr *Init) {
9854 assert(S.getLangOpts().C23);
9856 Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
9857 Sema::AllowedExplicit::None,
9858 /*InOverloadResolution*/ false,
9859 /*CStyle*/ false,
9860 /*AllowObjCWritebackConversion=*/false);
9861
9862 if (!ICS.isStandard())
9863 return;
9864
9865 APValue Value;
9866 QualType PreNarrowingType;
9867 // Reuse C++ narrowing check.
9868 switch (ICS.Standard.getNarrowingKind(
9869 S.Context, Init, Value, PreNarrowingType,
9870 /*IgnoreFloatToIntegralConversion*/ false)) {
9871 // The value doesn't fit.
9873 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
9874 << Value.getAsString(S.Context, PreNarrowingType) << ToType;
9875 return;
9876
9877 // Conversion to a narrower type.
9878 case NK_Type_Narrowing:
9879 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
9880 << ToType << FromType;
9881 return;
9882
9883 // Since we only reuse narrowing check for C23 constexpr variables here, we're
9884 // not really interested in these cases.
9887 case NK_Not_Narrowing:
9888 return;
9889 }
9890 llvm_unreachable("unhandled case in switch");
9891}
9892
9894 Sema &SemaRef, QualType &TT) {
9895 assert(SemaRef.getLangOpts().C23);
9896 // character that string literal contains fits into TT - target type.
9897 const ArrayType *AT = SemaRef.Context.getAsArrayType(TT);
9898 QualType CharType = AT->getElementType();
9899 uint32_t BitWidth = SemaRef.Context.getTypeSize(CharType);
9900 bool isUnsigned = CharType->isUnsignedIntegerType();
9901 llvm::APSInt Value(BitWidth, isUnsigned);
9902 for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
9903 int64_t C = SE->getCodeUnitS(I, SemaRef.Context.getCharWidth());
9904 Value = C;
9905 if (Value != C) {
9906 SemaRef.Diag(SemaRef.getLocationOfStringLiteralByte(SE, I),
9907 diag::err_c23_constexpr_init_not_representable)
9908 << C << CharType;
9909 return;
9910 }
9911 }
9912}
9913
9914//===----------------------------------------------------------------------===//
9915// Initialization helper functions
9916//===----------------------------------------------------------------------===//
9917bool
9919 ExprResult Init) {
9920 if (Init.isInvalid())
9921 return false;
9922
9923 Expr *InitE = Init.get();
9924 assert(InitE && "No initialization expression");
9925
9926 InitializationKind Kind =
9928 InitializationSequence Seq(*this, Entity, Kind, InitE);
9929 return !Seq.Failed();
9930}
9931
9934 SourceLocation EqualLoc,
9936 bool TopLevelOfInitList,
9937 bool AllowExplicit) {
9938 if (Init.isInvalid())
9939 return ExprError();
9940
9941 Expr *InitE = Init.get();
9942 assert(InitE && "No initialization expression?");
9943
9944 if (EqualLoc.isInvalid())
9945 EqualLoc = InitE->getBeginLoc();
9946
9948 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
9949 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
9950
9951 // Prevent infinite recursion when performing parameter copy-initialization.
9952 const bool ShouldTrackCopy =
9953 Entity.isParameterKind() && Seq.isConstructorInitialization();
9954 if (ShouldTrackCopy) {
9955 if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
9956 Seq.SetOverloadFailure(
9959
9960 // Try to give a meaningful diagnostic note for the problematic
9961 // constructor.
9962 const auto LastStep = Seq.step_end() - 1;
9963 assert(LastStep->Kind ==
9965 const FunctionDecl *Function = LastStep->Function.Function;
9966 auto Candidate =
9967 llvm::find_if(Seq.getFailedCandidateSet(),
9968 [Function](const OverloadCandidate &Candidate) -> bool {
9969 return Candidate.Viable &&
9970 Candidate.Function == Function &&
9971 Candidate.Conversions.size() > 0;
9972 });
9973 if (Candidate != Seq.getFailedCandidateSet().end() &&
9974 Function->getNumParams() > 0) {
9975 Candidate->Viable = false;
9978 InitE,
9979 Function->getParamDecl(0)->getType());
9980 }
9981 }
9982 CurrentParameterCopyTypes.push_back(Entity.getType());
9983 }
9984
9985 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
9986
9987 if (ShouldTrackCopy)
9988 CurrentParameterCopyTypes.pop_back();
9989
9990 return Result;
9991}
9992
9993/// Determine whether RD is, or is derived from, a specialization of CTD.
9995 ClassTemplateDecl *CTD) {
9996 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
9997 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
9998 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
9999 };
10000 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
10001}
10002
10004 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10005 const InitializationKind &Kind, MultiExprArg Inits) {
10006 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10007 TSInfo->getType()->getContainedDeducedType());
10008 assert(DeducedTST && "not a deduced template specialization type");
10009
10010 auto TemplateName = DeducedTST->getTemplateName();
10012 return SubstAutoTypeSourceInfoDependent(TSInfo)->getType();
10013
10014 // We can only perform deduction for class templates or alias templates.
10015 auto *Template =
10016 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10017 TemplateDecl *LookupTemplateDecl = Template;
10018 if (!Template) {
10019 if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
10021 DiagCompat(Kind.getLocation(), diag_compat::ctad_for_alias_templates);
10022 LookupTemplateDecl = AliasTemplate;
10023 auto UnderlyingType = AliasTemplate->getTemplatedDecl()
10024 ->getUnderlyingType()
10025 .getCanonicalType();
10026 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
10027 // of the form
10028 // [typename] [nested-name-specifier] [template] simple-template-id
10029 if (const auto *TST =
10030 UnderlyingType->getAs<TemplateSpecializationType>()) {
10031 Template = dyn_cast_or_null<ClassTemplateDecl>(
10032 TST->getTemplateName().getAsTemplateDecl());
10033 } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
10034 // Cases where template arguments in the RHS of the alias are not
10035 // dependent. e.g.
10036 // using AliasFoo = Foo<bool>;
10037 if (const auto *CTSD =
10038 llvm::dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()))
10039 Template = CTSD->getSpecializedTemplate();
10040 }
10041 }
10042 }
10043 if (!Template) {
10044 Diag(Kind.getLocation(),
10045 diag::err_deduced_non_class_or_alias_template_specialization_type)
10047 if (auto *TD = TemplateName.getAsTemplateDecl())
10049 return QualType();
10050 }
10051
10052 // Can't deduce from dependent arguments.
10054 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10055 diag::warn_cxx14_compat_class_template_argument_deduction)
10056 << TSInfo->getTypeLoc().getSourceRange() << 0;
10057 return SubstAutoTypeSourceInfoDependent(TSInfo)->getType();
10058 }
10059
10060 // FIXME: Perform "exact type" matching first, per CWG discussion?
10061 // Or implement this via an implied 'T(T) -> T' deduction guide?
10062
10063 // Look up deduction guides, including those synthesized from constructors.
10064 //
10065 // C++1z [over.match.class.deduct]p1:
10066 // A set of functions and function templates is formed comprising:
10067 // - For each constructor of the class template designated by the
10068 // template-name, a function template [...]
10069 // - For each deduction-guide, a function or function template [...]
10070 DeclarationNameInfo NameInfo(
10071 Context.DeclarationNames.getCXXDeductionGuideName(LookupTemplateDecl),
10072 TSInfo->getTypeLoc().getEndLoc());
10073 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10074 LookupQualifiedName(Guides, LookupTemplateDecl->getDeclContext());
10075
10076 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10077 // clear on this, but they're not found by name so access does not apply.
10078 Guides.suppressDiagnostics();
10079
10080 // Figure out if this is list-initialization.
10082 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10083 ? dyn_cast<InitListExpr>(Inits[0])
10084 : nullptr;
10085
10086 // C++1z [over.match.class.deduct]p1:
10087 // Initialization and overload resolution are performed as described in
10088 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10089 // (as appropriate for the type of initialization performed) for an object
10090 // of a hypothetical class type, where the selected functions and function
10091 // templates are considered to be the constructors of that class type
10092 //
10093 // Since we know we're initializing a class type of a type unrelated to that
10094 // of the initializer, this reduces to something fairly reasonable.
10095 OverloadCandidateSet Candidates(Kind.getLocation(),
10098
10099 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10100
10101 // Return true if the candidate is added successfully, false otherwise.
10102 auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10104 DeclAccessPair FoundDecl,
10105 bool OnlyListConstructors,
10106 bool AllowAggregateDeductionCandidate) {
10107 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10108 // For copy-initialization, the candidate functions are all the
10109 // converting constructors (12.3.1) of that class.
10110 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10111 // The converting constructors of T are candidate functions.
10112 if (!AllowExplicit) {
10113 // Overload resolution checks whether the deduction guide is declared
10114 // explicit for us.
10115
10116 // When looking for a converting constructor, deduction guides that
10117 // could never be called with one argument are not interesting to
10118 // check or note.
10119 if (GD->getMinRequiredArguments() > 1 ||
10120 (GD->getNumParams() == 0 && !GD->isVariadic()))
10121 return;
10122 }
10123
10124 // C++ [over.match.list]p1.1: (first phase list initialization)
10125 // Initially, the candidate functions are the initializer-list
10126 // constructors of the class T
10127 if (OnlyListConstructors && !isInitListConstructor(GD))
10128 return;
10129
10130 if (!AllowAggregateDeductionCandidate &&
10131 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10132 return;
10133
10134 // C++ [over.match.list]p1.2: (second phase list initialization)
10135 // the candidate functions are all the constructors of the class T
10136 // C++ [over.match.ctor]p1: (all other cases)
10137 // the candidate functions are all the constructors of the class of
10138 // the object being initialized
10139
10140 // C++ [over.best.ics]p4:
10141 // When [...] the constructor [...] is a candidate by
10142 // - [over.match.copy] (in all cases)
10143 if (TD) {
10144
10145 // As template candidates are not deduced immediately,
10146 // persist the array in the overload set.
10147 MutableArrayRef<Expr *> TmpInits =
10148 Candidates.getPersistentArgsArray(Inits.size());
10149
10150 for (auto [I, E] : llvm::enumerate(Inits)) {
10151 if (auto *DI = dyn_cast<DesignatedInitExpr>(E))
10152 TmpInits[I] = DI->getInit();
10153 else
10154 TmpInits[I] = E;
10155 }
10156
10158 TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
10159 /*SuppressUserConversions=*/false,
10160 /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
10161 /*PO=*/{}, AllowAggregateDeductionCandidate);
10162 } else {
10163 AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
10164 /*SuppressUserConversions=*/false,
10165 /*PartialOverloading=*/false, AllowExplicit);
10166 }
10167 };
10168
10169 bool FoundDeductionGuide = false;
10170
10171 auto TryToResolveOverload =
10172 [&](bool OnlyListConstructors) -> OverloadingResult {
10174 bool HasAnyDeductionGuide = false;
10175
10176 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10177 auto *Pattern = Template;
10178 while (Pattern->getInstantiatedFromMemberTemplate()) {
10179 if (Pattern->isMemberSpecialization())
10180 break;
10181 Pattern = Pattern->getInstantiatedFromMemberTemplate();
10182 }
10183
10184 auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());
10185 if (!(RD->getDefinition() && RD->isAggregate()))
10186 return;
10187 QualType Ty = Context.getCanonicalTagType(RD);
10188 SmallVector<QualType, 8> ElementTypes;
10189
10190 InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10191 if (!CheckInitList.HadError()) {
10192 // C++ [over.match.class.deduct]p1.8:
10193 // if e_i is of array type and x_i is a braced-init-list, T_i is an
10194 // rvalue reference to the declared type of e_i and
10195 // C++ [over.match.class.deduct]p1.9:
10196 // if e_i is of array type and x_i is a string-literal, T_i is an
10197 // lvalue reference to the const-qualified declared type of e_i and
10198 // C++ [over.match.class.deduct]p1.10:
10199 // otherwise, T_i is the declared type of e_i
10200 for (int I = 0, E = ListInit->getNumInits();
10201 I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
10202 if (ElementTypes[I]->isArrayType()) {
10204 ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);
10205 else if (isa<StringLiteral>(
10206 ListInit->getInit(I)->IgnoreParenImpCasts()))
10207 ElementTypes[I] =
10208 Context.getLValueReferenceType(ElementTypes[I].withConst());
10209 }
10210
10211 if (FunctionTemplateDecl *TD =
10213 LookupTemplateDecl, ElementTypes,
10214 TSInfo->getTypeLoc().getEndLoc())) {
10216 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10217 OnlyListConstructors,
10218 /*AllowAggregateDeductionCandidate=*/true);
10219 HasAnyDeductionGuide = true;
10220 }
10221 }
10222 };
10223
10224 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10225 NamedDecl *D = (*I)->getUnderlyingDecl();
10226 if (D->isInvalidDecl())
10227 continue;
10228
10229 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10230 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10231 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10232 if (!GD)
10233 continue;
10234
10235 if (!GD->isImplicit())
10236 HasAnyDeductionGuide = true;
10237
10238 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10239 /*AllowAggregateDeductionCandidate=*/false);
10240 }
10241
10242 // C++ [over.match.class.deduct]p1.4:
10243 // if C is defined and its definition satisfies the conditions for an
10244 // aggregate class ([dcl.init.aggr]) with the assumption that any
10245 // dependent base class has no virtual functions and no virtual base
10246 // classes, and the initializer is a non-empty braced-init-list or
10247 // parenthesized expression-list, and there are no deduction-guides for
10248 // C, the set contains an additional function template, called the
10249 // aggregate deduction candidate, defined as follows.
10250 if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10251 if (ListInit && ListInit->getNumInits()) {
10252 SynthesizeAggrGuide(ListInit);
10253 } else if (Inits.size()) { // parenthesized expression-list
10254 // Inits are expressions inside the parentheses. We don't have
10255 // the parentheses source locations, use the begin/end of Inits as the
10256 // best heuristic.
10257 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10258 Inits, Inits.back()->getEndLoc());
10259 SynthesizeAggrGuide(&TempListInit);
10260 }
10261 }
10262
10263 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10264
10265 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
10266 };
10267
10269
10270 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10271 // try initializer-list constructors.
10272 if (ListInit) {
10273 bool TryListConstructors = true;
10274
10275 // Try list constructors unless the list is empty and the class has one or
10276 // more default constructors, in which case those constructors win.
10277 if (!ListInit->getNumInits()) {
10278 for (NamedDecl *D : Guides) {
10279 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
10280 if (FD && FD->getMinRequiredArguments() == 0) {
10281 TryListConstructors = false;
10282 break;
10283 }
10284 }
10285 } else if (ListInit->getNumInits() == 1) {
10286 // C++ [over.match.class.deduct]:
10287 // As an exception, the first phase in [over.match.list] (considering
10288 // initializer-list constructors) is omitted if the initializer list
10289 // consists of a single expression of type cv U, where U is a
10290 // specialization of C or a class derived from a specialization of C.
10291 Expr *E = ListInit->getInit(0);
10292 auto *RD = E->getType()->getAsCXXRecordDecl();
10293 if (!isa<InitListExpr>(E) && RD &&
10294 isCompleteType(Kind.getLocation(), E->getType()) &&
10296 TryListConstructors = false;
10297 }
10298
10299 if (TryListConstructors)
10300 Result = TryToResolveOverload(/*OnlyListConstructor*/true);
10301 // Then unwrap the initializer list and try again considering all
10302 // constructors.
10303 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
10304 }
10305
10306 // If list-initialization fails, or if we're doing any other kind of
10307 // initialization, we (eventually) consider constructors.
10309 Result = TryToResolveOverload(/*OnlyListConstructor*/false);
10310
10311 switch (Result) {
10312 case OR_Ambiguous:
10313 // FIXME: For list-initialization candidates, it'd usually be better to
10314 // list why they were not viable when given the initializer list itself as
10315 // an argument.
10316 Candidates.NoteCandidates(
10318 Kind.getLocation(),
10319 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
10320 << TemplateName),
10321 *this, OCD_AmbiguousCandidates, Inits);
10322 return QualType();
10323
10324 case OR_No_Viable_Function: {
10325 CXXRecordDecl *Primary =
10326 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
10327 bool Complete = isCompleteType(Kind.getLocation(),
10328 Context.getCanonicalTagType(Primary));
10329 Candidates.NoteCandidates(
10331 Kind.getLocation(),
10332 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
10333 : diag::err_deduced_class_template_incomplete)
10334 << TemplateName << !Guides.empty()),
10335 *this, OCD_AllCandidates, Inits);
10336 return QualType();
10337 }
10338
10339 case OR_Deleted: {
10340 // FIXME: There are no tests for this diagnostic, and it doesn't seem
10341 // like we ever get here; attempts to trigger this seem to yield a
10342 // generic c'all to deleted function' diagnostic instead.
10343 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
10344 << TemplateName;
10345 NoteDeletedFunction(Best->Function);
10346 return QualType();
10347 }
10348
10349 case OR_Success:
10350 // C++ [over.match.list]p1:
10351 // In copy-list-initialization, if an explicit constructor is chosen, the
10352 // initialization is ill-formed.
10353 if (Kind.isCopyInit() && ListInit &&
10354 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
10355 bool IsDeductionGuide = !Best->Function->isImplicit();
10356 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
10357 << TemplateName << IsDeductionGuide;
10358 Diag(Best->Function->getLocation(),
10359 diag::note_explicit_ctor_deduction_guide_here)
10360 << IsDeductionGuide;
10361 return QualType();
10362 }
10363
10364 // Make sure we didn't select an unusable deduction guide, and mark it
10365 // as referenced.
10366 DiagnoseUseOfDecl(Best->FoundDecl, Kind.getLocation());
10367 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
10368 break;
10369 }
10370
10371 // C++ [dcl.type.class.deduct]p1:
10372 // The placeholder is replaced by the return type of the function selected
10373 // by overload resolution for class template deduction.
10374 QualType DeducedType =
10375 SubstAutoTypeSourceInfo(TSInfo, Best->Function->getReturnType())
10376 ->getType();
10377 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10378 diag::warn_cxx14_compat_class_template_argument_deduction)
10379 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10380
10381 // Warn if CTAD was used on a type that does not have any user-defined
10382 // deduction guides.
10383 if (!FoundDeductionGuide) {
10384 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10385 diag::warn_ctad_maybe_unsupported)
10386 << TemplateName;
10387 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
10388 }
10389
10390 return DeducedType;
10391}
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:938
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:903
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:2939
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2979
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:3622
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 getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4392
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4389
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:4672
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:4781
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:4776
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:4788
MutableArrayRef< Designator > designators()
Definition Expr.h:5718
Expr * getArrayIndex(const Designator &D) const
Definition Expr.cpp:4771
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:4750
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:4767
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:4713
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:3093
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:4260
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:3088
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3076
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3084
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:3337
@ 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:3668
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3068
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:3251
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:4045
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:276
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:4818
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:3839
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:3818
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:2071
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:2460
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition Expr.cpp:2420
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:2494
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:2424
void setArrayFiller(Expr *filler)
Definition Expr.cpp:2436
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:2483
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2512
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:5205
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:6289
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9314
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9322
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:10371
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10374
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10380
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10378
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:6912
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:6924
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:680
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:756
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:8996
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:6945
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition Sema.h:10399
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:8160
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
bool IsAssignConvertCompatible(AssignConvertType ConvTy)
Definition Sema.h:8027
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:6957
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:8152
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:13896
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 isSFINAEContext() const
Definition Sema.h:13631
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:15375
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:6723
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:625
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:6834
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6802
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
Definition Sema.h:6840
std::optional< InitializationContext > DelayedDefaultInitializationContext
Definition Sema.h:6857
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:499