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