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