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