clang 19.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
14#include "clang/AST/DeclObjC.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ExprObjC.h"
20#include "clang/AST/TypeLoc.h"
28#include "clang/Sema/Lookup.h"
31#include "clang/Sema/SemaObjC.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/FoldingSet.h"
34#include "llvm/ADT/PointerIntPair.h"
35#include "llvm/ADT/STLForwardCompat.h"
36#include "llvm/ADT/SmallString.h"
37#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/StringExtras.h"
39#include "llvm/Support/ErrorHandling.h"
40#include "llvm/Support/raw_ostream.h"
41
42using namespace clang;
43
44//===----------------------------------------------------------------------===//
45// Sema Initialization Checking
46//===----------------------------------------------------------------------===//
47
48/// Check whether T is compatible with a wide character type (wchar_t,
49/// char16_t or char32_t).
50static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
51 if (Context.typesAreCompatible(Context.getWideCharType(), T))
52 return true;
53 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
54 return Context.typesAreCompatible(Context.Char16Ty, T) ||
55 Context.typesAreCompatible(Context.Char32Ty, T);
56 }
57 return false;
58}
59
68};
69
70/// Check whether the array of type AT can be initialized by the Init
71/// expression by means of string initialization. Returns SIF_None if so,
72/// otherwise returns a StringInitFailureKind that describes why the
73/// initialization would not work.
75 ASTContext &Context) {
76 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
77 return SIF_Other;
78
79 // See if this is a string literal or @encode.
80 Init = Init->IgnoreParens();
81
82 // Handle @encode, which is a narrow string.
83 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
84 return SIF_None;
85
86 // Otherwise we can only handle string literals.
87 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
88 if (!SL)
89 return SIF_Other;
90
91 const QualType ElemTy =
93
94 auto IsCharOrUnsignedChar = [](const QualType &T) {
95 const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
96 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
97 };
98
99 switch (SL->getKind()) {
100 case StringLiteralKind::UTF8:
101 // char8_t array can be initialized with a UTF-8 string.
102 // - C++20 [dcl.init.string] (DR)
103 // Additionally, an array of char or unsigned char may be initialized
104 // by a UTF-8 string literal.
105 if (ElemTy->isChar8Type() ||
106 (Context.getLangOpts().Char8 &&
107 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
108 return SIF_None;
109 [[fallthrough]];
110 case StringLiteralKind::Ordinary:
111 // char array can be initialized with a narrow string.
112 // Only allow char x[] = "foo"; not char x[] = L"foo";
113 if (ElemTy->isCharType())
114 return (SL->getKind() == StringLiteralKind::UTF8 &&
115 Context.getLangOpts().Char8)
117 : SIF_None;
118 if (ElemTy->isChar8Type())
120 if (IsWideCharCompatible(ElemTy, Context))
122 return SIF_Other;
123 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
124 // "An array with element type compatible with a qualified or unqualified
125 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
126 // string literal with the corresponding encoding prefix (L, u, or U,
127 // respectively), optionally enclosed in braces.
128 case StringLiteralKind::UTF16:
129 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
130 return SIF_None;
131 if (ElemTy->isCharType() || ElemTy->isChar8Type())
133 if (IsWideCharCompatible(ElemTy, Context))
135 return SIF_Other;
136 case StringLiteralKind::UTF32:
137 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
138 return SIF_None;
139 if (ElemTy->isCharType() || ElemTy->isChar8Type())
141 if (IsWideCharCompatible(ElemTy, Context))
143 return SIF_Other;
144 case StringLiteralKind::Wide:
145 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
146 return SIF_None;
147 if (ElemTy->isCharType() || ElemTy->isChar8Type())
149 if (IsWideCharCompatible(ElemTy, Context))
151 return SIF_Other;
152 case StringLiteralKind::Unevaluated:
153 assert(false && "Unevaluated string literal in initialization");
154 break;
155 }
156
157 llvm_unreachable("missed a StringLiteral kind?");
158}
159
161 ASTContext &Context) {
162 const ArrayType *arrayType = Context.getAsArrayType(declType);
163 if (!arrayType)
164 return SIF_Other;
165 return IsStringInit(init, arrayType, Context);
166}
167
169 return ::IsStringInit(Init, AT, Context) == SIF_None;
170}
171
172/// Update the type of a string literal, including any surrounding parentheses,
173/// to match the type of the object which it is initializing.
175 while (true) {
176 E->setType(Ty);
178 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
179 break;
181 }
182}
183
184/// Fix a compound literal initializing an array so it's correctly marked
185/// as an rvalue.
187 while (true) {
189 if (isa<CompoundLiteralExpr>(E))
190 break;
192 }
193}
194
196 Decl *D = Entity.getDecl();
197 const InitializedEntity *Parent = &Entity;
198
199 while (Parent) {
200 D = Parent->getDecl();
201 Parent = Parent->getParent();
202 }
203
204 if (const auto *VD = dyn_cast_if_present<VarDecl>(D); VD && VD->isConstexpr())
205 return true;
206
207 return false;
208}
209
211 Sema &SemaRef, QualType &TT);
212
213static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
214 Sema &S, bool CheckC23ConstexprInit = false) {
215 // Get the length of the string as parsed.
216 auto *ConstantArrayTy =
217 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
218 uint64_t StrLength = ConstantArrayTy->getZExtSize();
219
220 if (CheckC23ConstexprInit)
221 if (const StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens()))
223
224 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
225 // C99 6.7.8p14. We have an array of character type with unknown size
226 // being initialized to a string literal.
227 llvm::APInt ConstVal(32, StrLength);
228 // Return a new array type (C99 6.7.8p22).
230 IAT->getElementType(), ConstVal, nullptr, ArraySizeModifier::Normal, 0);
231 updateStringLiteralType(Str, DeclT);
232 return;
233 }
234
235 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
236
237 // We have an array of character type with known size. However,
238 // the size may be smaller or larger than the string we are initializing.
239 // FIXME: Avoid truncation for 64-bit length strings.
240 if (S.getLangOpts().CPlusPlus) {
241 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
242 // For Pascal strings it's OK to strip off the terminating null character,
243 // so the example below is valid:
244 //
245 // unsigned char a[2] = "\pa";
246 if (SL->isPascal())
247 StrLength--;
248 }
249
250 // [dcl.init.string]p2
251 if (StrLength > CAT->getZExtSize())
252 S.Diag(Str->getBeginLoc(),
253 diag::err_initializer_string_for_char_array_too_long)
254 << CAT->getZExtSize() << StrLength << Str->getSourceRange();
255 } else {
256 // C99 6.7.8p14.
257 if (StrLength - 1 > CAT->getZExtSize())
258 S.Diag(Str->getBeginLoc(),
259 diag::ext_initializer_string_for_char_array_too_long)
260 << Str->getSourceRange();
261 }
262
263 // Set the type to the actual size that we are initializing. If we have
264 // something like:
265 // char x[1] = "foo";
266 // then this will set the string literal's type to char[1].
267 updateStringLiteralType(Str, DeclT);
268}
269
270//===----------------------------------------------------------------------===//
271// Semantic checking for initializer lists.
272//===----------------------------------------------------------------------===//
273
274namespace {
275
276/// Semantic checking for initializer lists.
277///
278/// The InitListChecker class contains a set of routines that each
279/// handle the initialization of a certain kind of entity, e.g.,
280/// arrays, vectors, struct/union types, scalars, etc. The
281/// InitListChecker itself performs a recursive walk of the subobject
282/// structure of the type to be initialized, while stepping through
283/// the initializer list one element at a time. The IList and Index
284/// parameters to each of the Check* routines contain the active
285/// (syntactic) initializer list and the index into that initializer
286/// list that represents the current initializer. Each routine is
287/// responsible for moving that Index forward as it consumes elements.
288///
289/// Each Check* routine also has a StructuredList/StructuredIndex
290/// arguments, which contains the current "structured" (semantic)
291/// initializer list and the index into that initializer list where we
292/// are copying initializers as we map them over to the semantic
293/// list. Once we have completed our recursive walk of the subobject
294/// structure, we will have constructed a full semantic initializer
295/// list.
296///
297/// C99 designators cause changes in the initializer list traversal,
298/// because they make the initialization "jump" into a specific
299/// subobject and then continue the initialization from that
300/// point. CheckDesignatedInitializer() recursively steps into the
301/// designated subobject and manages backing out the recursion to
302/// initialize the subobjects after the one designated.
303///
304/// If an initializer list contains any designators, we build a placeholder
305/// structured list even in 'verify only' mode, so that we can track which
306/// elements need 'empty' initializtion.
307class InitListChecker {
308 Sema &SemaRef;
309 bool hadError = false;
310 bool VerifyOnly; // No diagnostics.
311 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
312 bool InOverloadResolution;
313 InitListExpr *FullyStructuredList = nullptr;
314 NoInitExpr *DummyExpr = nullptr;
315 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;
316
317 NoInitExpr *getDummyInit() {
318 if (!DummyExpr)
319 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
320 return DummyExpr;
321 }
322
323 void CheckImplicitInitList(const InitializedEntity &Entity,
324 InitListExpr *ParentIList, QualType T,
325 unsigned &Index, InitListExpr *StructuredList,
326 unsigned &StructuredIndex);
327 void CheckExplicitInitList(const InitializedEntity &Entity,
328 InitListExpr *IList, QualType &T,
329 InitListExpr *StructuredList,
330 bool TopLevelObject = false);
331 void CheckListElementTypes(const InitializedEntity &Entity,
332 InitListExpr *IList, QualType &DeclType,
333 bool SubobjectIsDesignatorContext,
334 unsigned &Index,
335 InitListExpr *StructuredList,
336 unsigned &StructuredIndex,
337 bool TopLevelObject = false);
338 void CheckSubElementType(const InitializedEntity &Entity,
339 InitListExpr *IList, QualType ElemType,
340 unsigned &Index,
341 InitListExpr *StructuredList,
342 unsigned &StructuredIndex,
343 bool DirectlyDesignated = false);
344 void CheckComplexType(const InitializedEntity &Entity,
345 InitListExpr *IList, QualType DeclType,
346 unsigned &Index,
347 InitListExpr *StructuredList,
348 unsigned &StructuredIndex);
349 void CheckScalarType(const InitializedEntity &Entity,
350 InitListExpr *IList, QualType DeclType,
351 unsigned &Index,
352 InitListExpr *StructuredList,
353 unsigned &StructuredIndex);
354 void CheckReferenceType(const InitializedEntity &Entity,
355 InitListExpr *IList, QualType DeclType,
356 unsigned &Index,
357 InitListExpr *StructuredList,
358 unsigned &StructuredIndex);
359 void CheckVectorType(const InitializedEntity &Entity,
360 InitListExpr *IList, QualType DeclType, unsigned &Index,
361 InitListExpr *StructuredList,
362 unsigned &StructuredIndex);
363 void CheckStructUnionTypes(const InitializedEntity &Entity,
364 InitListExpr *IList, QualType DeclType,
367 bool SubobjectIsDesignatorContext, unsigned &Index,
368 InitListExpr *StructuredList,
369 unsigned &StructuredIndex,
370 bool TopLevelObject = false);
371 void CheckArrayType(const InitializedEntity &Entity,
372 InitListExpr *IList, QualType &DeclType,
373 llvm::APSInt elementIndex,
374 bool SubobjectIsDesignatorContext, unsigned &Index,
375 InitListExpr *StructuredList,
376 unsigned &StructuredIndex);
377 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
378 InitListExpr *IList, DesignatedInitExpr *DIE,
379 unsigned DesigIdx,
380 QualType &CurrentObjectType,
382 llvm::APSInt *NextElementIndex,
383 unsigned &Index,
384 InitListExpr *StructuredList,
385 unsigned &StructuredIndex,
386 bool FinishSubobjectInit,
387 bool TopLevelObject);
388 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
389 QualType CurrentObjectType,
390 InitListExpr *StructuredList,
391 unsigned StructuredIndex,
392 SourceRange InitRange,
393 bool IsFullyOverwritten = false);
394 void UpdateStructuredListElement(InitListExpr *StructuredList,
395 unsigned &StructuredIndex,
396 Expr *expr);
397 InitListExpr *createInitListExpr(QualType CurrentObjectType,
398 SourceRange InitRange,
399 unsigned ExpectedNumInits);
400 int numArrayElements(QualType DeclType);
401 int numStructUnionElements(QualType DeclType);
402 static RecordDecl *getRecordDecl(QualType DeclType);
403
404 ExprResult PerformEmptyInit(SourceLocation Loc,
405 const InitializedEntity &Entity);
406
407 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
408 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
409 bool UnionOverride = false,
410 bool FullyOverwritten = true) {
411 // Overriding an initializer via a designator is valid with C99 designated
412 // initializers, but ill-formed with C++20 designated initializers.
413 unsigned DiagID =
414 SemaRef.getLangOpts().CPlusPlus
415 ? (UnionOverride ? diag::ext_initializer_union_overrides
416 : diag::ext_initializer_overrides)
417 : diag::warn_initializer_overrides;
418
419 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
420 // In overload resolution, we have to strictly enforce the rules, and so
421 // don't allow any overriding of prior initializers. This matters for a
422 // case such as:
423 //
424 // union U { int a, b; };
425 // struct S { int a, b; };
426 // void f(U), f(S);
427 //
428 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
429 // consistency, we disallow all overriding of prior initializers in
430 // overload resolution, not only overriding of union members.
431 hadError = true;
432 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
433 // If we'll be keeping around the old initializer but overwriting part of
434 // the object it initialized, and that object is not trivially
435 // destructible, this can leak. Don't allow that, not even as an
436 // extension.
437 //
438 // FIXME: It might be reasonable to allow this in cases where the part of
439 // the initializer that we're overriding has trivial destruction.
440 DiagID = diag::err_initializer_overrides_destructed;
441 } else if (!OldInit->getSourceRange().isValid()) {
442 // We need to check on source range validity because the previous
443 // initializer does not have to be an explicit initializer. e.g.,
444 //
445 // struct P { int a, b; };
446 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
447 //
448 // There is an overwrite taking place because the first braced initializer
449 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
450 //
451 // Such overwrites are harmless, so we don't diagnose them. (Note that in
452 // C++, this cannot be reached unless we've already seen and diagnosed a
453 // different conformance issue, such as a mixture of designated and
454 // non-designated initializers or a multi-level designator.)
455 return;
456 }
457
458 if (!VerifyOnly) {
459 SemaRef.Diag(NewInitRange.getBegin(), DiagID)
460 << NewInitRange << FullyOverwritten << OldInit->getType();
461 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
462 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
463 << OldInit->getSourceRange();
464 }
465 }
466
467 // Explanation on the "FillWithNoInit" mode:
468 //
469 // Assume we have the following definitions (Case#1):
470 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
471 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
472 //
473 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
474 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
475 //
476 // But if we have (Case#2):
477 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
478 //
479 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
480 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
481 //
482 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
483 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
484 // initializers but with special "NoInitExpr" place holders, which tells the
485 // CodeGen not to generate any initializers for these parts.
486 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
487 const InitializedEntity &ParentEntity,
488 InitListExpr *ILE, bool &RequiresSecondPass,
489 bool FillWithNoInit);
490 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
491 const InitializedEntity &ParentEntity,
492 InitListExpr *ILE, bool &RequiresSecondPass,
493 bool FillWithNoInit = false);
494 void FillInEmptyInitializations(const InitializedEntity &Entity,
495 InitListExpr *ILE, bool &RequiresSecondPass,
496 InitListExpr *OuterILE, unsigned OuterIndex,
497 bool FillWithNoInit = false);
498 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
499 Expr *InitExpr, FieldDecl *Field,
500 bool TopLevelObject);
501 void CheckEmptyInitializable(const InitializedEntity &Entity,
503
504public:
505 InitListChecker(
506 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
507 bool VerifyOnly, bool TreatUnavailableAsInvalid,
508 bool InOverloadResolution = false,
509 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);
510 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
511 QualType &T,
512 SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)
513 : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,
514 /*TreatUnavailableAsInvalid=*/false,
515 /*InOverloadResolution=*/false,
516 &AggrDeductionCandidateParamTypes){};
517
518 bool HadError() { return hadError; }
519
520 // Retrieves the fully-structured initializer list used for
521 // semantic analysis and code generation.
522 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
523};
524
525} // end anonymous namespace
526
527ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
528 const InitializedEntity &Entity) {
530 true);
531 MultiExprArg SubInit;
532 Expr *InitExpr;
533 InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc);
534
535 // C++ [dcl.init.aggr]p7:
536 // If there are fewer initializer-clauses in the list than there are
537 // members in the aggregate, then each member not explicitly initialized
538 // ...
539 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
541 if (EmptyInitList) {
542 // C++1y / DR1070:
543 // shall be initialized [...] from an empty initializer list.
544 //
545 // We apply the resolution of this DR to C++11 but not C++98, since C++98
546 // does not have useful semantics for initialization from an init list.
547 // We treat this as copy-initialization, because aggregate initialization
548 // always performs copy-initialization on its elements.
549 //
550 // Only do this if we're initializing a class type, to avoid filling in
551 // the initializer list where possible.
552 InitExpr = VerifyOnly
553 ? &DummyInitList
554 : new (SemaRef.Context)
555 InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc);
556 InitExpr->setType(SemaRef.Context.VoidTy);
557 SubInit = InitExpr;
559 } else {
560 // C++03:
561 // shall be value-initialized.
562 }
563
564 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
565 // libstdc++4.6 marks the vector default constructor as explicit in
566 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
567 // stlport does so too. Look for std::__debug for libstdc++, and for
568 // std:: for stlport. This is effectively a compiler-side implementation of
569 // LWG2193.
570 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
574 InitSeq.getFailedCandidateSet()
575 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
576 (void)O;
577 assert(O == OR_Success && "Inconsistent overload resolution");
578 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
579 CXXRecordDecl *R = CtorDecl->getParent();
580
581 if (CtorDecl->getMinRequiredArguments() == 0 &&
582 CtorDecl->isExplicit() && R->getDeclName() &&
583 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
584 bool IsInStd = false;
585 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
586 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
588 IsInStd = true;
589 }
590
591 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
592 .Cases("basic_string", "deque", "forward_list", true)
593 .Cases("list", "map", "multimap", "multiset", true)
594 .Cases("priority_queue", "queue", "set", "stack", true)
595 .Cases("unordered_map", "unordered_set", "vector", true)
596 .Default(false)) {
597 InitSeq.InitializeFrom(
598 SemaRef, Entity,
600 MultiExprArg(), /*TopLevelOfInitList=*/false,
601 TreatUnavailableAsInvalid);
602 // Emit a warning for this. System header warnings aren't shown
603 // by default, but people working on system headers should see it.
604 if (!VerifyOnly) {
605 SemaRef.Diag(CtorDecl->getLocation(),
606 diag::warn_invalid_initializer_from_system_header);
608 SemaRef.Diag(Entity.getDecl()->getLocation(),
609 diag::note_used_in_initialization_here);
610 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
611 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
612 }
613 }
614 }
615 }
616 if (!InitSeq) {
617 if (!VerifyOnly) {
618 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
620 SemaRef.Diag(Entity.getDecl()->getLocation(),
621 diag::note_in_omitted_aggregate_initializer)
622 << /*field*/1 << Entity.getDecl();
623 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
624 bool IsTrailingArrayNewMember =
625 Entity.getParent() &&
627 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
628 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
629 << Entity.getElementIndex();
630 }
631 }
632 hadError = true;
633 return ExprError();
634 }
635
636 return VerifyOnly ? ExprResult()
637 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
638}
639
640void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
642 // If we're building a fully-structured list, we'll check this at the end
643 // once we know which elements are actually initialized. Otherwise, we know
644 // that there are no designators so we can just check now.
645 if (FullyStructuredList)
646 return;
647 PerformEmptyInit(Loc, Entity);
648}
649
650void InitListChecker::FillInEmptyInitForBase(
651 unsigned Init, const CXXBaseSpecifier &Base,
652 const InitializedEntity &ParentEntity, InitListExpr *ILE,
653 bool &RequiresSecondPass, bool FillWithNoInit) {
655 SemaRef.Context, &Base, false, &ParentEntity);
656
657 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
658 ExprResult BaseInit = FillWithNoInit
659 ? new (SemaRef.Context) NoInitExpr(Base.getType())
660 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
661 if (BaseInit.isInvalid()) {
662 hadError = true;
663 return;
664 }
665
666 if (!VerifyOnly) {
667 assert(Init < ILE->getNumInits() && "should have been expanded");
668 ILE->setInit(Init, BaseInit.getAs<Expr>());
669 }
670 } else if (InitListExpr *InnerILE =
671 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
672 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
673 ILE, Init, FillWithNoInit);
674 } else if (DesignatedInitUpdateExpr *InnerDIUE =
675 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
676 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
677 RequiresSecondPass, ILE, Init,
678 /*FillWithNoInit =*/true);
679 }
680}
681
682void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
683 const InitializedEntity &ParentEntity,
684 InitListExpr *ILE,
685 bool &RequiresSecondPass,
686 bool FillWithNoInit) {
688 unsigned NumInits = ILE->getNumInits();
689 InitializedEntity MemberEntity
690 = InitializedEntity::InitializeMember(Field, &ParentEntity);
691
692 if (Init >= NumInits || !ILE->getInit(Init)) {
693 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
694 if (!RType->getDecl()->isUnion())
695 assert((Init < NumInits || VerifyOnly) &&
696 "This ILE should have been expanded");
697
698 if (FillWithNoInit) {
699 assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
700 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
701 if (Init < NumInits)
702 ILE->setInit(Init, Filler);
703 else
704 ILE->updateInit(SemaRef.Context, Init, Filler);
705 return;
706 }
707 // C++1y [dcl.init.aggr]p7:
708 // If there are fewer initializer-clauses in the list than there are
709 // members in the aggregate, then each member not explicitly initialized
710 // shall be initialized from its brace-or-equal-initializer [...]
711 if (Field->hasInClassInitializer()) {
712 if (VerifyOnly)
713 return;
714
715 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
716 if (DIE.isInvalid()) {
717 hadError = true;
718 return;
719 }
720 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
721 if (Init < NumInits)
722 ILE->setInit(Init, DIE.get());
723 else {
724 ILE->updateInit(SemaRef.Context, Init, DIE.get());
725 RequiresSecondPass = true;
726 }
727 return;
728 }
729
730 if (Field->getType()->isReferenceType()) {
731 if (!VerifyOnly) {
732 // C++ [dcl.init.aggr]p9:
733 // If an incomplete or empty initializer-list leaves a
734 // member of reference type uninitialized, the program is
735 // ill-formed.
736 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
737 << Field->getType()
738 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
739 ->getSourceRange();
740 SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
741 }
742 hadError = true;
743 return;
744 }
745
746 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
747 if (MemberInit.isInvalid()) {
748 hadError = true;
749 return;
750 }
751
752 if (hadError || VerifyOnly) {
753 // Do nothing
754 } else if (Init < NumInits) {
755 ILE->setInit(Init, MemberInit.getAs<Expr>());
756 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
757 // Empty initialization requires a constructor call, so
758 // extend the initializer list to include the constructor
759 // call and make a note that we'll need to take another pass
760 // through the initializer list.
761 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
762 RequiresSecondPass = true;
763 }
764 } else if (InitListExpr *InnerILE
765 = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
766 FillInEmptyInitializations(MemberEntity, InnerILE,
767 RequiresSecondPass, ILE, Init, FillWithNoInit);
768 } else if (DesignatedInitUpdateExpr *InnerDIUE =
769 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
770 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
771 RequiresSecondPass, ILE, Init,
772 /*FillWithNoInit =*/true);
773 }
774}
775
776/// Recursively replaces NULL values within the given initializer list
777/// with expressions that perform value-initialization of the
778/// appropriate type, and finish off the InitListExpr formation.
779void
780InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
781 InitListExpr *ILE,
782 bool &RequiresSecondPass,
783 InitListExpr *OuterILE,
784 unsigned OuterIndex,
785 bool FillWithNoInit) {
786 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
787 "Should not have void type");
788
789 // We don't need to do any checks when just filling NoInitExprs; that can't
790 // fail.
791 if (FillWithNoInit && VerifyOnly)
792 return;
793
794 // If this is a nested initializer list, we might have changed its contents
795 // (and therefore some of its properties, such as instantiation-dependence)
796 // while filling it in. Inform the outer initializer list so that its state
797 // can be updated to match.
798 // FIXME: We should fully build the inner initializers before constructing
799 // the outer InitListExpr instead of mutating AST nodes after they have
800 // been used as subexpressions of other nodes.
801 struct UpdateOuterILEWithUpdatedInit {
802 InitListExpr *Outer;
803 unsigned OuterIndex;
804 ~UpdateOuterILEWithUpdatedInit() {
805 if (Outer)
806 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
807 }
808 } UpdateOuterRAII = {OuterILE, OuterIndex};
809
810 // A transparent ILE is not performing aggregate initialization and should
811 // not be filled in.
812 if (ILE->isTransparent())
813 return;
814
815 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
816 const RecordDecl *RDecl = RType->getDecl();
817 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
818 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
819 Entity, ILE, RequiresSecondPass, FillWithNoInit);
820 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
821 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
822 for (auto *Field : RDecl->fields()) {
823 if (Field->hasInClassInitializer()) {
824 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
825 FillWithNoInit);
826 break;
827 }
828 }
829 } else {
830 // The fields beyond ILE->getNumInits() are default initialized, so in
831 // order to leave them uninitialized, the ILE is expanded and the extra
832 // fields are then filled with NoInitExpr.
833 unsigned NumElems = numStructUnionElements(ILE->getType());
834 if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
835 ++NumElems;
836 if (!VerifyOnly && ILE->getNumInits() < NumElems)
837 ILE->resizeInits(SemaRef.Context, NumElems);
838
839 unsigned Init = 0;
840
841 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
842 for (auto &Base : CXXRD->bases()) {
843 if (hadError)
844 return;
845
846 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
847 FillWithNoInit);
848 ++Init;
849 }
850 }
851
852 for (auto *Field : RDecl->fields()) {
853 if (Field->isUnnamedBitField())
854 continue;
855
856 if (hadError)
857 return;
858
859 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
860 FillWithNoInit);
861 if (hadError)
862 return;
863
864 ++Init;
865
866 // Only look at the first initialization of a union.
867 if (RDecl->isUnion())
868 break;
869 }
870 }
871
872 return;
873 }
874
875 QualType ElementType;
876
877 InitializedEntity ElementEntity = Entity;
878 unsigned NumInits = ILE->getNumInits();
879 uint64_t NumElements = NumInits;
880 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
881 ElementType = AType->getElementType();
882 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
883 NumElements = CAType->getZExtSize();
884 // For an array new with an unknown bound, ask for one additional element
885 // in order to populate the array filler.
886 if (Entity.isVariableLengthArrayNew())
887 ++NumElements;
888 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
889 0, Entity);
890 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
891 ElementType = VType->getElementType();
892 NumElements = VType->getNumElements();
893 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
894 0, Entity);
895 } else
896 ElementType = ILE->getType();
897
898 bool SkipEmptyInitChecks = false;
899 for (uint64_t Init = 0; Init != NumElements; ++Init) {
900 if (hadError)
901 return;
902
903 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
905 ElementEntity.setElementIndex(Init);
906
907 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
908 return;
909
910 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
911 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
912 ILE->setInit(Init, ILE->getArrayFiller());
913 else if (!InitExpr && !ILE->hasArrayFiller()) {
914 // In VerifyOnly mode, there's no point performing empty initialization
915 // more than once.
916 if (SkipEmptyInitChecks)
917 continue;
918
919 Expr *Filler = nullptr;
920
921 if (FillWithNoInit)
922 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
923 else {
924 ExprResult ElementInit =
925 PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
926 if (ElementInit.isInvalid()) {
927 hadError = true;
928 return;
929 }
930
931 Filler = ElementInit.getAs<Expr>();
932 }
933
934 if (hadError) {
935 // Do nothing
936 } else if (VerifyOnly) {
937 SkipEmptyInitChecks = true;
938 } else if (Init < NumInits) {
939 // For arrays, just set the expression used for value-initialization
940 // of the "holes" in the array.
941 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
942 ILE->setArrayFiller(Filler);
943 else
944 ILE->setInit(Init, Filler);
945 } else {
946 // For arrays, just set the expression used for value-initialization
947 // of the rest of elements and exit.
948 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
949 ILE->setArrayFiller(Filler);
950 return;
951 }
952
953 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
954 // Empty initialization requires a constructor call, so
955 // extend the initializer list to include the constructor
956 // call and make a note that we'll need to take another pass
957 // through the initializer list.
958 ILE->updateInit(SemaRef.Context, Init, Filler);
959 RequiresSecondPass = true;
960 }
961 }
962 } else if (InitListExpr *InnerILE
963 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
964 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
965 ILE, Init, FillWithNoInit);
966 } else if (DesignatedInitUpdateExpr *InnerDIUE =
967 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
968 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
969 RequiresSecondPass, ILE, Init,
970 /*FillWithNoInit =*/true);
971 }
972 }
973}
974
975static bool hasAnyDesignatedInits(const InitListExpr *IL) {
976 for (const Stmt *Init : *IL)
977 if (isa_and_nonnull<DesignatedInitExpr>(Init))
978 return true;
979 return false;
980}
981
982InitListChecker::InitListChecker(
983 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
984 bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,
985 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)
986 : SemaRef(S), VerifyOnly(VerifyOnly),
987 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
988 InOverloadResolution(InOverloadResolution),
989 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
990 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
991 FullyStructuredList =
992 createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
993
994 // FIXME: Check that IL isn't already the semantic form of some other
995 // InitListExpr. If it is, we'd create a broken AST.
996 if (!VerifyOnly)
997 FullyStructuredList->setSyntacticForm(IL);
998 }
999
1000 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
1001 /*TopLevelObject=*/true);
1002
1003 if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
1004 bool RequiresSecondPass = false;
1005 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
1006 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
1007 if (RequiresSecondPass && !hadError)
1008 FillInEmptyInitializations(Entity, FullyStructuredList,
1009 RequiresSecondPass, nullptr, 0);
1010 }
1011 if (hadError && FullyStructuredList)
1012 FullyStructuredList->markError();
1013}
1014
1015int InitListChecker::numArrayElements(QualType DeclType) {
1016 // FIXME: use a proper constant
1017 int maxElements = 0x7FFFFFFF;
1018 if (const ConstantArrayType *CAT =
1019 SemaRef.Context.getAsConstantArrayType(DeclType)) {
1020 maxElements = static_cast<int>(CAT->getZExtSize());
1021 }
1022 return maxElements;
1023}
1024
1025int InitListChecker::numStructUnionElements(QualType DeclType) {
1026 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
1027 int InitializableMembers = 0;
1028 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1029 InitializableMembers += CXXRD->getNumBases();
1030 for (const auto *Field : structDecl->fields())
1031 if (!Field->isUnnamedBitField())
1032 ++InitializableMembers;
1033
1034 if (structDecl->isUnion())
1035 return std::min(InitializableMembers, 1);
1036 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1037}
1038
1039RecordDecl *InitListChecker::getRecordDecl(QualType DeclType) {
1040 if (const auto *RT = DeclType->getAs<RecordType>())
1041 return RT->getDecl();
1042 if (const auto *Inject = DeclType->getAs<InjectedClassNameType>())
1043 return Inject->getDecl();
1044 return nullptr;
1045}
1046
1047/// Determine whether Entity is an entity for which it is idiomatic to elide
1048/// the braces in aggregate initialization.
1050 // Recursive initialization of the one and only field within an aggregate
1051 // class is considered idiomatic. This case arises in particular for
1052 // initialization of std::array, where the C++ standard suggests the idiom of
1053 //
1054 // std::array<T, N> arr = {1, 2, 3};
1055 //
1056 // (where std::array is an aggregate struct containing a single array field.
1057
1058 if (!Entity.getParent())
1059 return false;
1060
1061 // Allows elide brace initialization for aggregates with empty base.
1062 if (Entity.getKind() == InitializedEntity::EK_Base) {
1063 auto *ParentRD =
1064 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1065 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1066 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1067 }
1068
1069 // Allow brace elision if the only subobject is a field.
1070 if (Entity.getKind() == InitializedEntity::EK_Member) {
1071 auto *ParentRD =
1072 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1073 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1074 if (CXXRD->getNumBases()) {
1075 return false;
1076 }
1077 }
1078 auto FieldIt = ParentRD->field_begin();
1079 assert(FieldIt != ParentRD->field_end() &&
1080 "no fields but have initializer for member?");
1081 return ++FieldIt == ParentRD->field_end();
1082 }
1083
1084 return false;
1085}
1086
1087/// Check whether the range of the initializer \p ParentIList from element
1088/// \p Index onwards can be used to initialize an object of type \p T. Update
1089/// \p Index to indicate how many elements of the list were consumed.
1090///
1091/// This also fills in \p StructuredList, from element \p StructuredIndex
1092/// onwards, with the fully-braced, desugared form of the initialization.
1093void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1094 InitListExpr *ParentIList,
1095 QualType T, unsigned &Index,
1096 InitListExpr *StructuredList,
1097 unsigned &StructuredIndex) {
1098 int maxElements = 0;
1099
1100 if (T->isArrayType())
1101 maxElements = numArrayElements(T);
1102 else if (T->isRecordType())
1103 maxElements = numStructUnionElements(T);
1104 else if (T->isVectorType())
1105 maxElements = T->castAs<VectorType>()->getNumElements();
1106 else
1107 llvm_unreachable("CheckImplicitInitList(): Illegal type");
1108
1109 if (maxElements == 0) {
1110 if (!VerifyOnly)
1111 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1112 diag::err_implicit_empty_initializer);
1113 ++Index;
1114 hadError = true;
1115 return;
1116 }
1117
1118 // Build a structured initializer list corresponding to this subobject.
1119 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1120 ParentIList, Index, T, StructuredList, StructuredIndex,
1121 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1122 ParentIList->getSourceRange().getEnd()));
1123 unsigned StructuredSubobjectInitIndex = 0;
1124
1125 // Check the element types and build the structural subobject.
1126 unsigned StartIndex = Index;
1127 CheckListElementTypes(Entity, ParentIList, T,
1128 /*SubobjectIsDesignatorContext=*/false, Index,
1129 StructuredSubobjectInitList,
1130 StructuredSubobjectInitIndex);
1131
1132 if (StructuredSubobjectInitList) {
1133 StructuredSubobjectInitList->setType(T);
1134
1135 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1136 // Update the structured sub-object initializer so that it's ending
1137 // range corresponds with the end of the last initializer it used.
1138 if (EndIndex < ParentIList->getNumInits() &&
1139 ParentIList->getInit(EndIndex)) {
1140 SourceLocation EndLoc
1141 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1142 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1143 }
1144
1145 // Complain about missing braces.
1146 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1147 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1149 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1150 diag::warn_missing_braces)
1151 << StructuredSubobjectInitList->getSourceRange()
1153 StructuredSubobjectInitList->getBeginLoc(), "{")
1155 SemaRef.getLocForEndOfToken(
1156 StructuredSubobjectInitList->getEndLoc()),
1157 "}");
1158 }
1159
1160 // Warn if this type won't be an aggregate in future versions of C++.
1161 auto *CXXRD = T->getAsCXXRecordDecl();
1162 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1163 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1164 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1165 << StructuredSubobjectInitList->getSourceRange() << T;
1166 }
1167 }
1168}
1169
1170/// Warn that \p Entity was of scalar type and was initialized by a
1171/// single-element braced initializer list.
1172static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1174 // Don't warn during template instantiation. If the initialization was
1175 // non-dependent, we warned during the initial parse; otherwise, the
1176 // type might not be scalar in some uses of the template.
1178 return;
1179
1180 unsigned DiagID = 0;
1181
1182 switch (Entity.getKind()) {
1191 // Extra braces here are suspicious.
1192 DiagID = diag::warn_braces_around_init;
1193 break;
1194
1196 // Warn on aggregate initialization but not on ctor init list or
1197 // default member initializer.
1198 if (Entity.getParent())
1199 DiagID = diag::warn_braces_around_init;
1200 break;
1201
1204 // No warning, might be direct-list-initialization.
1205 // FIXME: Should we warn for copy-list-initialization in these cases?
1206 break;
1207
1211 // No warning, braces are part of the syntax of the underlying construct.
1212 break;
1213
1215 // No warning, we already warned when initializing the result.
1216 break;
1217
1225 llvm_unreachable("unexpected braced scalar init");
1226 }
1227
1228 if (DiagID) {
1229 S.Diag(Braces.getBegin(), DiagID)
1230 << Entity.getType()->isSizelessBuiltinType() << Braces
1231 << FixItHint::CreateRemoval(Braces.getBegin())
1232 << FixItHint::CreateRemoval(Braces.getEnd());
1233 }
1234}
1235
1236/// Check whether the initializer \p IList (that was written with explicit
1237/// braces) can be used to initialize an object of type \p T.
1238///
1239/// This also fills in \p StructuredList with the fully-braced, desugared
1240/// form of the initialization.
1241void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1242 InitListExpr *IList, QualType &T,
1243 InitListExpr *StructuredList,
1244 bool TopLevelObject) {
1245 unsigned Index = 0, StructuredIndex = 0;
1246 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1247 Index, StructuredList, StructuredIndex, TopLevelObject);
1248 if (StructuredList) {
1249 QualType ExprTy = T;
1250 if (!ExprTy->isArrayType())
1251 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1252 if (!VerifyOnly)
1253 IList->setType(ExprTy);
1254 StructuredList->setType(ExprTy);
1255 }
1256 if (hadError)
1257 return;
1258
1259 // Don't complain for incomplete types, since we'll get an error elsewhere.
1260 if (Index < IList->getNumInits() && !T->isIncompleteType()) {
1261 // We have leftover initializers
1262 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1263 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1264 hadError = ExtraInitsIsError;
1265 if (VerifyOnly) {
1266 return;
1267 } else if (StructuredIndex == 1 &&
1268 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1269 SIF_None) {
1270 unsigned DK =
1271 ExtraInitsIsError
1272 ? diag::err_excess_initializers_in_char_array_initializer
1273 : diag::ext_excess_initializers_in_char_array_initializer;
1274 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1275 << IList->getInit(Index)->getSourceRange();
1276 } else if (T->isSizelessBuiltinType()) {
1277 unsigned DK = ExtraInitsIsError
1278 ? diag::err_excess_initializers_for_sizeless_type
1279 : diag::ext_excess_initializers_for_sizeless_type;
1280 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1281 << T << IList->getInit(Index)->getSourceRange();
1282 } else {
1283 int initKind = T->isArrayType() ? 0 :
1284 T->isVectorType() ? 1 :
1285 T->isScalarType() ? 2 :
1286 T->isUnionType() ? 3 :
1287 4;
1288
1289 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1290 : diag::ext_excess_initializers;
1291 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1292 << initKind << IList->getInit(Index)->getSourceRange();
1293 }
1294 }
1295
1296 if (!VerifyOnly) {
1297 if (T->isScalarType() && IList->getNumInits() == 1 &&
1298 !isa<InitListExpr>(IList->getInit(0)))
1299 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1300
1301 // Warn if this is a class type that won't be an aggregate in future
1302 // versions of C++.
1303 auto *CXXRD = T->getAsCXXRecordDecl();
1304 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1305 // Don't warn if there's an equivalent default constructor that would be
1306 // used instead.
1307 bool HasEquivCtor = false;
1308 if (IList->getNumInits() == 0) {
1309 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1310 HasEquivCtor = CD && !CD->isDeleted();
1311 }
1312
1313 if (!HasEquivCtor) {
1314 SemaRef.Diag(IList->getBeginLoc(),
1315 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1316 << IList->getSourceRange() << T;
1317 }
1318 }
1319 }
1320}
1321
1322void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1323 InitListExpr *IList,
1324 QualType &DeclType,
1325 bool SubobjectIsDesignatorContext,
1326 unsigned &Index,
1327 InitListExpr *StructuredList,
1328 unsigned &StructuredIndex,
1329 bool TopLevelObject) {
1330 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1331 // Explicitly braced initializer for complex type can be real+imaginary
1332 // parts.
1333 CheckComplexType(Entity, IList, DeclType, Index,
1334 StructuredList, StructuredIndex);
1335 } else if (DeclType->isScalarType()) {
1336 CheckScalarType(Entity, IList, DeclType, Index,
1337 StructuredList, StructuredIndex);
1338 } else if (DeclType->isVectorType()) {
1339 CheckVectorType(Entity, IList, DeclType, Index,
1340 StructuredList, StructuredIndex);
1341 } else if (const RecordDecl *RD = getRecordDecl(DeclType)) {
1342 auto Bases =
1345 if (DeclType->isRecordType()) {
1346 assert(DeclType->isAggregateType() &&
1347 "non-aggregate records should be handed in CheckSubElementType");
1348 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1349 Bases = CXXRD->bases();
1350 } else {
1351 Bases = cast<CXXRecordDecl>(RD)->bases();
1352 }
1353 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1354 SubobjectIsDesignatorContext, Index, StructuredList,
1355 StructuredIndex, TopLevelObject);
1356 } else if (DeclType->isArrayType()) {
1357 llvm::APSInt Zero(
1358 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1359 false);
1360 CheckArrayType(Entity, IList, DeclType, Zero,
1361 SubobjectIsDesignatorContext, Index,
1362 StructuredList, StructuredIndex);
1363 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1364 // This type is invalid, issue a diagnostic.
1365 ++Index;
1366 if (!VerifyOnly)
1367 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1368 << DeclType;
1369 hadError = true;
1370 } else if (DeclType->isReferenceType()) {
1371 CheckReferenceType(Entity, IList, DeclType, Index,
1372 StructuredList, StructuredIndex);
1373 } else if (DeclType->isObjCObjectType()) {
1374 if (!VerifyOnly)
1375 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1376 hadError = true;
1377 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1378 DeclType->isSizelessBuiltinType()) {
1379 // Checks for scalar type are sufficient for these types too.
1380 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1381 StructuredIndex);
1382 } else if (DeclType->isDependentType()) {
1383 // C++ [over.match.class.deduct]p1.5:
1384 // brace elision is not considered for any aggregate element that has a
1385 // dependent non-array type or an array type with a value-dependent bound
1386 ++Index;
1387 assert(AggrDeductionCandidateParamTypes);
1388 AggrDeductionCandidateParamTypes->push_back(DeclType);
1389 } else {
1390 if (!VerifyOnly)
1391 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1392 << DeclType;
1393 hadError = true;
1394 }
1395}
1396
1397void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1398 InitListExpr *IList,
1399 QualType ElemType,
1400 unsigned &Index,
1401 InitListExpr *StructuredList,
1402 unsigned &StructuredIndex,
1403 bool DirectlyDesignated) {
1404 Expr *expr = IList->getInit(Index);
1405
1406 if (ElemType->isReferenceType())
1407 return CheckReferenceType(Entity, IList, ElemType, Index,
1408 StructuredList, StructuredIndex);
1409
1410 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1411 if (SubInitList->getNumInits() == 1 &&
1412 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1413 SIF_None) {
1414 // FIXME: It would be more faithful and no less correct to include an
1415 // InitListExpr in the semantic form of the initializer list in this case.
1416 expr = SubInitList->getInit(0);
1417 }
1418 // Nested aggregate initialization and C++ initialization are handled later.
1419 } else if (isa<ImplicitValueInitExpr>(expr)) {
1420 // This happens during template instantiation when we see an InitListExpr
1421 // that we've already checked once.
1422 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1423 "found implicit initialization for the wrong type");
1424 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1425 ++Index;
1426 return;
1427 }
1428
1429 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1430 // C++ [dcl.init.aggr]p2:
1431 // Each member is copy-initialized from the corresponding
1432 // initializer-clause.
1433
1434 // FIXME: Better EqualLoc?
1437
1438 // Vector elements can be initialized from other vectors in which case
1439 // we need initialization entity with a type of a vector (and not a vector
1440 // element!) initializing multiple vector elements.
1441 auto TmpEntity =
1442 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1444 : Entity;
1445
1446 if (TmpEntity.getType()->isDependentType()) {
1447 // C++ [over.match.class.deduct]p1.5:
1448 // brace elision is not considered for any aggregate element that has a
1449 // dependent non-array type or an array type with a value-dependent
1450 // bound
1451 assert(AggrDeductionCandidateParamTypes);
1452 if (!isa_and_nonnull<ConstantArrayType>(
1453 SemaRef.Context.getAsArrayType(ElemType))) {
1454 ++Index;
1455 AggrDeductionCandidateParamTypes->push_back(ElemType);
1456 return;
1457 }
1458 } else {
1459 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1460 /*TopLevelOfInitList*/ true);
1461 // C++14 [dcl.init.aggr]p13:
1462 // If the assignment-expression can initialize a member, the member is
1463 // initialized. Otherwise [...] brace elision is assumed
1464 //
1465 // Brace elision is never performed if the element is not an
1466 // assignment-expression.
1467 if (Seq || isa<InitListExpr>(expr)) {
1468 if (!VerifyOnly) {
1469 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1470 if (Result.isInvalid())
1471 hadError = true;
1472
1473 UpdateStructuredListElement(StructuredList, StructuredIndex,
1474 Result.getAs<Expr>());
1475 } else if (!Seq) {
1476 hadError = true;
1477 } else if (StructuredList) {
1478 UpdateStructuredListElement(StructuredList, StructuredIndex,
1479 getDummyInit());
1480 }
1481 ++Index;
1482 if (AggrDeductionCandidateParamTypes)
1483 AggrDeductionCandidateParamTypes->push_back(ElemType);
1484 return;
1485 }
1486 }
1487
1488 // Fall through for subaggregate initialization
1489 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1490 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1491 return CheckScalarType(Entity, IList, ElemType, Index,
1492 StructuredList, StructuredIndex);
1493 } else if (const ArrayType *arrayType =
1494 SemaRef.Context.getAsArrayType(ElemType)) {
1495 // arrayType can be incomplete if we're initializing a flexible
1496 // array member. There's nothing we can do with the completed
1497 // type here, though.
1498
1499 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1500 // FIXME: Should we do this checking in verify-only mode?
1501 if (!VerifyOnly)
1502 CheckStringInit(expr, ElemType, arrayType, SemaRef,
1503 SemaRef.getLangOpts().C23 &&
1505 if (StructuredList)
1506 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1507 ++Index;
1508 return;
1509 }
1510
1511 // Fall through for subaggregate initialization.
1512
1513 } else {
1514 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1515 ElemType->isOpenCLSpecificType()) && "Unexpected type");
1516
1517 // C99 6.7.8p13:
1518 //
1519 // The initializer for a structure or union object that has
1520 // automatic storage duration shall be either an initializer
1521 // list as described below, or a single expression that has
1522 // compatible structure or union type. In the latter case, the
1523 // initial value of the object, including unnamed members, is
1524 // that of the expression.
1525 ExprResult ExprRes = expr;
1527 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1528 if (ExprRes.isInvalid())
1529 hadError = true;
1530 else {
1531 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1532 if (ExprRes.isInvalid())
1533 hadError = true;
1534 }
1535 UpdateStructuredListElement(StructuredList, StructuredIndex,
1536 ExprRes.getAs<Expr>());
1537 ++Index;
1538 return;
1539 }
1540 ExprRes.get();
1541 // Fall through for subaggregate initialization
1542 }
1543
1544 // C++ [dcl.init.aggr]p12:
1545 //
1546 // [...] Otherwise, if the member is itself a non-empty
1547 // subaggregate, brace elision is assumed and the initializer is
1548 // considered for the initialization of the first member of
1549 // the subaggregate.
1550 // OpenCL vector initializer is handled elsewhere.
1551 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1552 ElemType->isAggregateType()) {
1553 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1554 StructuredIndex);
1555 ++StructuredIndex;
1556
1557 // In C++20, brace elision is not permitted for a designated initializer.
1558 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1559 if (InOverloadResolution)
1560 hadError = true;
1561 if (!VerifyOnly) {
1562 SemaRef.Diag(expr->getBeginLoc(),
1563 diag::ext_designated_init_brace_elision)
1564 << expr->getSourceRange()
1565 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1567 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1568 }
1569 }
1570 } else {
1571 if (!VerifyOnly) {
1572 // We cannot initialize this element, so let PerformCopyInitialization
1573 // produce the appropriate diagnostic. We already checked that this
1574 // initialization will fail.
1577 /*TopLevelOfInitList=*/true);
1578 (void)Copy;
1579 assert(Copy.isInvalid() &&
1580 "expected non-aggregate initialization to fail");
1581 }
1582 hadError = true;
1583 ++Index;
1584 ++StructuredIndex;
1585 }
1586}
1587
1588void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1589 InitListExpr *IList, QualType DeclType,
1590 unsigned &Index,
1591 InitListExpr *StructuredList,
1592 unsigned &StructuredIndex) {
1593 assert(Index == 0 && "Index in explicit init list must be zero");
1594
1595 // As an extension, clang supports complex initializers, which initialize
1596 // a complex number component-wise. When an explicit initializer list for
1597 // a complex number contains two initializers, this extension kicks in:
1598 // it expects the initializer list to contain two elements convertible to
1599 // the element type of the complex type. The first element initializes
1600 // the real part, and the second element intitializes the imaginary part.
1601
1602 if (IList->getNumInits() < 2)
1603 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1604 StructuredIndex);
1605
1606 // This is an extension in C. (The builtin _Complex type does not exist
1607 // in the C++ standard.)
1608 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1609 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1610 << IList->getSourceRange();
1611
1612 // Initialize the complex number.
1613 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1614 InitializedEntity ElementEntity =
1616
1617 for (unsigned i = 0; i < 2; ++i) {
1618 ElementEntity.setElementIndex(Index);
1619 CheckSubElementType(ElementEntity, IList, elementType, Index,
1620 StructuredList, StructuredIndex);
1621 }
1622}
1623
1624void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1625 InitListExpr *IList, QualType DeclType,
1626 unsigned &Index,
1627 InitListExpr *StructuredList,
1628 unsigned &StructuredIndex) {
1629 if (Index >= IList->getNumInits()) {
1630 if (!VerifyOnly) {
1631 if (SemaRef.getLangOpts().CPlusPlus) {
1632 if (DeclType->isSizelessBuiltinType())
1633 SemaRef.Diag(IList->getBeginLoc(),
1634 SemaRef.getLangOpts().CPlusPlus11
1635 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1636 : diag::err_empty_sizeless_initializer)
1637 << DeclType << IList->getSourceRange();
1638 else
1639 SemaRef.Diag(IList->getBeginLoc(),
1640 SemaRef.getLangOpts().CPlusPlus11
1641 ? diag::warn_cxx98_compat_empty_scalar_initializer
1642 : diag::err_empty_scalar_initializer)
1643 << IList->getSourceRange();
1644 }
1645 }
1646 hadError =
1647 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1648 ++Index;
1649 ++StructuredIndex;
1650 return;
1651 }
1652
1653 Expr *expr = IList->getInit(Index);
1654 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1655 // FIXME: This is invalid, and accepting it causes overload resolution
1656 // to pick the wrong overload in some corner cases.
1657 if (!VerifyOnly)
1658 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1659 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1660
1661 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1662 StructuredIndex);
1663 return;
1664 } else if (isa<DesignatedInitExpr>(expr)) {
1665 if (!VerifyOnly)
1666 SemaRef.Diag(expr->getBeginLoc(),
1667 diag::err_designator_for_scalar_or_sizeless_init)
1668 << DeclType->isSizelessBuiltinType() << DeclType
1669 << expr->getSourceRange();
1670 hadError = true;
1671 ++Index;
1672 ++StructuredIndex;
1673 return;
1674 }
1675
1676 ExprResult Result;
1677 if (VerifyOnly) {
1678 if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1679 Result = getDummyInit();
1680 else
1681 Result = ExprError();
1682 } else {
1683 Result =
1684 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1685 /*TopLevelOfInitList=*/true);
1686 }
1687
1688 Expr *ResultExpr = nullptr;
1689
1690 if (Result.isInvalid())
1691 hadError = true; // types weren't compatible.
1692 else {
1693 ResultExpr = Result.getAs<Expr>();
1694
1695 if (ResultExpr != expr && !VerifyOnly) {
1696 // The type was promoted, update initializer list.
1697 // FIXME: Why are we updating the syntactic init list?
1698 IList->setInit(Index, ResultExpr);
1699 }
1700 }
1701 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1702 ++Index;
1703 if (AggrDeductionCandidateParamTypes)
1704 AggrDeductionCandidateParamTypes->push_back(DeclType);
1705}
1706
1707void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1708 InitListExpr *IList, QualType DeclType,
1709 unsigned &Index,
1710 InitListExpr *StructuredList,
1711 unsigned &StructuredIndex) {
1712 if (Index >= IList->getNumInits()) {
1713 // FIXME: It would be wonderful if we could point at the actual member. In
1714 // general, it would be useful to pass location information down the stack,
1715 // so that we know the location (or decl) of the "current object" being
1716 // initialized.
1717 if (!VerifyOnly)
1718 SemaRef.Diag(IList->getBeginLoc(),
1719 diag::err_init_reference_member_uninitialized)
1720 << DeclType << IList->getSourceRange();
1721 hadError = true;
1722 ++Index;
1723 ++StructuredIndex;
1724 return;
1725 }
1726
1727 Expr *expr = IList->getInit(Index);
1728 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1729 if (!VerifyOnly)
1730 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1731 << DeclType << IList->getSourceRange();
1732 hadError = true;
1733 ++Index;
1734 ++StructuredIndex;
1735 return;
1736 }
1737
1738 ExprResult Result;
1739 if (VerifyOnly) {
1740 if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1741 Result = getDummyInit();
1742 else
1743 Result = ExprError();
1744 } else {
1745 Result =
1746 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1747 /*TopLevelOfInitList=*/true);
1748 }
1749
1750 if (Result.isInvalid())
1751 hadError = true;
1752
1753 expr = Result.getAs<Expr>();
1754 // FIXME: Why are we updating the syntactic init list?
1755 if (!VerifyOnly && expr)
1756 IList->setInit(Index, expr);
1757
1758 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1759 ++Index;
1760 if (AggrDeductionCandidateParamTypes)
1761 AggrDeductionCandidateParamTypes->push_back(DeclType);
1762}
1763
1764void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1765 InitListExpr *IList, QualType DeclType,
1766 unsigned &Index,
1767 InitListExpr *StructuredList,
1768 unsigned &StructuredIndex) {
1769 const VectorType *VT = DeclType->castAs<VectorType>();
1770 unsigned maxElements = VT->getNumElements();
1771 unsigned numEltsInit = 0;
1772 QualType elementType = VT->getElementType();
1773
1774 if (Index >= IList->getNumInits()) {
1775 // Make sure the element type can be value-initialized.
1776 CheckEmptyInitializable(
1778 IList->getEndLoc());
1779 return;
1780 }
1781
1782 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1783 // If the initializing element is a vector, try to copy-initialize
1784 // instead of breaking it apart (which is doomed to failure anyway).
1785 Expr *Init = IList->getInit(Index);
1786 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1787 ExprResult Result;
1788 if (VerifyOnly) {
1789 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1790 Result = getDummyInit();
1791 else
1792 Result = ExprError();
1793 } else {
1794 Result =
1795 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1796 /*TopLevelOfInitList=*/true);
1797 }
1798
1799 Expr *ResultExpr = nullptr;
1800 if (Result.isInvalid())
1801 hadError = true; // types weren't compatible.
1802 else {
1803 ResultExpr = Result.getAs<Expr>();
1804
1805 if (ResultExpr != Init && !VerifyOnly) {
1806 // The type was promoted, update initializer list.
1807 // FIXME: Why are we updating the syntactic init list?
1808 IList->setInit(Index, ResultExpr);
1809 }
1810 }
1811 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1812 ++Index;
1813 if (AggrDeductionCandidateParamTypes)
1814 AggrDeductionCandidateParamTypes->push_back(elementType);
1815 return;
1816 }
1817
1818 InitializedEntity ElementEntity =
1820
1821 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1822 // Don't attempt to go past the end of the init list
1823 if (Index >= IList->getNumInits()) {
1824 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1825 break;
1826 }
1827
1828 ElementEntity.setElementIndex(Index);
1829 CheckSubElementType(ElementEntity, IList, elementType, Index,
1830 StructuredList, StructuredIndex);
1831 }
1832
1833 if (VerifyOnly)
1834 return;
1835
1836 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1837 const VectorType *T = Entity.getType()->castAs<VectorType>();
1838 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
1839 T->getVectorKind() == VectorKind::NeonPoly)) {
1840 // The ability to use vector initializer lists is a GNU vector extension
1841 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1842 // endian machines it works fine, however on big endian machines it
1843 // exhibits surprising behaviour:
1844 //
1845 // uint32x2_t x = {42, 64};
1846 // return vget_lane_u32(x, 0); // Will return 64.
1847 //
1848 // Because of this, explicitly call out that it is non-portable.
1849 //
1850 SemaRef.Diag(IList->getBeginLoc(),
1851 diag::warn_neon_vector_initializer_non_portable);
1852
1853 const char *typeCode;
1854 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1855
1856 if (elementType->isFloatingType())
1857 typeCode = "f";
1858 else if (elementType->isSignedIntegerType())
1859 typeCode = "s";
1860 else if (elementType->isUnsignedIntegerType())
1861 typeCode = "u";
1862 else
1863 llvm_unreachable("Invalid element type!");
1864
1865 SemaRef.Diag(IList->getBeginLoc(),
1866 SemaRef.Context.getTypeSize(VT) > 64
1867 ? diag::note_neon_vector_initializer_non_portable_q
1868 : diag::note_neon_vector_initializer_non_portable)
1869 << typeCode << typeSize;
1870 }
1871
1872 return;
1873 }
1874
1875 InitializedEntity ElementEntity =
1877
1878 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
1879 for (unsigned i = 0; i < maxElements; ++i) {
1880 // Don't attempt to go past the end of the init list
1881 if (Index >= IList->getNumInits())
1882 break;
1883
1884 ElementEntity.setElementIndex(Index);
1885
1886 QualType IType = IList->getInit(Index)->getType();
1887 if (!IType->isVectorType()) {
1888 CheckSubElementType(ElementEntity, IList, elementType, Index,
1889 StructuredList, StructuredIndex);
1890 ++numEltsInit;
1891 } else {
1892 QualType VecType;
1893 const VectorType *IVT = IType->castAs<VectorType>();
1894 unsigned numIElts = IVT->getNumElements();
1895
1896 if (IType->isExtVectorType())
1897 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1898 else
1899 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1900 IVT->getVectorKind());
1901 CheckSubElementType(ElementEntity, IList, VecType, Index,
1902 StructuredList, StructuredIndex);
1903 numEltsInit += numIElts;
1904 }
1905 }
1906
1907 // OpenCL and HLSL require all elements to be initialized.
1908 if (numEltsInit != maxElements) {
1909 if (!VerifyOnly)
1910 SemaRef.Diag(IList->getBeginLoc(),
1911 diag::err_vector_incorrect_num_initializers)
1912 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1913 hadError = true;
1914 }
1915}
1916
1917/// Check if the type of a class element has an accessible destructor, and marks
1918/// it referenced. Returns true if we shouldn't form a reference to the
1919/// destructor.
1920///
1921/// Aggregate initialization requires a class element's destructor be
1922/// accessible per 11.6.1 [dcl.init.aggr]:
1923///
1924/// The destructor for each element of class type is potentially invoked
1925/// (15.4 [class.dtor]) from the context where the aggregate initialization
1926/// occurs.
1928 Sema &SemaRef) {
1929 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1930 if (!CXXRD)
1931 return false;
1932
1935 SemaRef.PDiag(diag::err_access_dtor_temp)
1936 << ElementType);
1938 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1939}
1940
1941void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1942 InitListExpr *IList, QualType &DeclType,
1943 llvm::APSInt elementIndex,
1944 bool SubobjectIsDesignatorContext,
1945 unsigned &Index,
1946 InitListExpr *StructuredList,
1947 unsigned &StructuredIndex) {
1948 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1949
1950 if (!VerifyOnly) {
1951 if (checkDestructorReference(arrayType->getElementType(),
1952 IList->getEndLoc(), SemaRef)) {
1953 hadError = true;
1954 return;
1955 }
1956 }
1957
1958 // Check for the special-case of initializing an array with a string.
1959 if (Index < IList->getNumInits()) {
1960 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1961 SIF_None) {
1962 // We place the string literal directly into the resulting
1963 // initializer list. This is the only place where the structure
1964 // of the structured initializer list doesn't match exactly,
1965 // because doing so would involve allocating one character
1966 // constant for each string.
1967 // FIXME: Should we do these checks in verify-only mode too?
1968 if (!VerifyOnly)
1969 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef,
1970 SemaRef.getLangOpts().C23 &&
1972 if (StructuredList) {
1973 UpdateStructuredListElement(StructuredList, StructuredIndex,
1974 IList->getInit(Index));
1975 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1976 }
1977 ++Index;
1978 if (AggrDeductionCandidateParamTypes)
1979 AggrDeductionCandidateParamTypes->push_back(DeclType);
1980 return;
1981 }
1982 }
1983 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1984 // Check for VLAs; in standard C it would be possible to check this
1985 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1986 // them in all sorts of strange places).
1987 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
1988 if (!VerifyOnly) {
1989 // C23 6.7.10p4: An entity of variable length array type shall not be
1990 // initialized except by an empty initializer.
1991 //
1992 // The C extension warnings are issued from ParseBraceInitializer() and
1993 // do not need to be issued here. However, we continue to issue an error
1994 // in the case there are initializers or we are compiling C++. We allow
1995 // use of VLAs in C++, but it's not clear we want to allow {} to zero
1996 // init a VLA in C++ in all cases (such as with non-trivial constructors).
1997 // FIXME: should we allow this construct in C++ when it makes sense to do
1998 // so?
1999 if (HasErr)
2000 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
2001 diag::err_variable_object_no_init)
2002 << VAT->getSizeExpr()->getSourceRange();
2003 }
2004 hadError = HasErr;
2005 ++Index;
2006 ++StructuredIndex;
2007 return;
2008 }
2009
2010 // We might know the maximum number of elements in advance.
2011 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2012 elementIndex.isUnsigned());
2013 bool maxElementsKnown = false;
2014 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
2015 maxElements = CAT->getSize();
2016 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
2017 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2018 maxElementsKnown = true;
2019 }
2020
2021 QualType elementType = arrayType->getElementType();
2022 while (Index < IList->getNumInits()) {
2023 Expr *Init = IList->getInit(Index);
2024 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2025 // If we're not the subobject that matches up with the '{' for
2026 // the designator, we shouldn't be handling the
2027 // designator. Return immediately.
2028 if (!SubobjectIsDesignatorContext)
2029 return;
2030
2031 // Handle this designated initializer. elementIndex will be
2032 // updated to be the next array element we'll initialize.
2033 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2034 DeclType, nullptr, &elementIndex, Index,
2035 StructuredList, StructuredIndex, true,
2036 false)) {
2037 hadError = true;
2038 continue;
2039 }
2040
2041 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2042 maxElements = maxElements.extend(elementIndex.getBitWidth());
2043 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2044 elementIndex = elementIndex.extend(maxElements.getBitWidth());
2045 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2046
2047 // If the array is of incomplete type, keep track of the number of
2048 // elements in the initializer.
2049 if (!maxElementsKnown && elementIndex > maxElements)
2050 maxElements = elementIndex;
2051
2052 continue;
2053 }
2054
2055 // If we know the maximum number of elements, and we've already
2056 // hit it, stop consuming elements in the initializer list.
2057 if (maxElementsKnown && elementIndex == maxElements)
2058 break;
2059
2060 InitializedEntity ElementEntity =
2061 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
2062 Entity);
2063 // Check this element.
2064 CheckSubElementType(ElementEntity, IList, elementType, Index,
2065 StructuredList, StructuredIndex);
2066 ++elementIndex;
2067
2068 // If the array is of incomplete type, keep track of the number of
2069 // elements in the initializer.
2070 if (!maxElementsKnown && elementIndex > maxElements)
2071 maxElements = elementIndex;
2072 }
2073 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2074 // If this is an incomplete array type, the actual type needs to
2075 // be calculated here.
2076 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2077 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2078 // Sizing an array implicitly to zero is not allowed by ISO C,
2079 // but is supported by GNU.
2080 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2081 }
2082
2083 DeclType = SemaRef.Context.getConstantArrayType(
2084 elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2085 }
2086 if (!hadError) {
2087 // If there are any members of the array that get value-initialized, check
2088 // that is possible. That happens if we know the bound and don't have
2089 // enough elements, or if we're performing an array new with an unknown
2090 // bound.
2091 if ((maxElementsKnown && elementIndex < maxElements) ||
2092 Entity.isVariableLengthArrayNew())
2093 CheckEmptyInitializable(
2095 IList->getEndLoc());
2096 }
2097}
2098
2099bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2100 Expr *InitExpr,
2101 FieldDecl *Field,
2102 bool TopLevelObject) {
2103 // Handle GNU flexible array initializers.
2104 unsigned FlexArrayDiag;
2105 if (isa<InitListExpr>(InitExpr) &&
2106 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2107 // Empty flexible array init always allowed as an extension
2108 FlexArrayDiag = diag::ext_flexible_array_init;
2109 } else if (!TopLevelObject) {
2110 // Disallow flexible array init on non-top-level object
2111 FlexArrayDiag = diag::err_flexible_array_init;
2112 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2113 // Disallow flexible array init on anything which is not a variable.
2114 FlexArrayDiag = diag::err_flexible_array_init;
2115 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2116 // Disallow flexible array init on local variables.
2117 FlexArrayDiag = diag::err_flexible_array_init;
2118 } else {
2119 // Allow other cases.
2120 FlexArrayDiag = diag::ext_flexible_array_init;
2121 }
2122
2123 if (!VerifyOnly) {
2124 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2125 << InitExpr->getBeginLoc();
2126 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2127 << Field;
2128 }
2129
2130 return FlexArrayDiag != diag::ext_flexible_array_init;
2131}
2132
2133void InitListChecker::CheckStructUnionTypes(
2134 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2136 bool SubobjectIsDesignatorContext, unsigned &Index,
2137 InitListExpr *StructuredList, unsigned &StructuredIndex,
2138 bool TopLevelObject) {
2139 const RecordDecl *RD = getRecordDecl(DeclType);
2140
2141 // If the record is invalid, some of it's members are invalid. To avoid
2142 // confusion, we forgo checking the initializer for the entire record.
2143 if (RD->isInvalidDecl()) {
2144 // Assume it was supposed to consume a single initializer.
2145 ++Index;
2146 hadError = true;
2147 return;
2148 }
2149
2150 if (RD->isUnion() && IList->getNumInits() == 0) {
2151 if (!VerifyOnly)
2152 for (FieldDecl *FD : RD->fields()) {
2153 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2154 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2155 hadError = true;
2156 return;
2157 }
2158 }
2159
2160 // If there's a default initializer, use it.
2161 if (isa<CXXRecordDecl>(RD) &&
2162 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2163 if (!StructuredList)
2164 return;
2165 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2166 Field != FieldEnd; ++Field) {
2167 if (Field->hasInClassInitializer()) {
2168 StructuredList->setInitializedFieldInUnion(*Field);
2169 // FIXME: Actually build a CXXDefaultInitExpr?
2170 return;
2171 }
2172 }
2173 }
2174
2175 // Value-initialize the first member of the union that isn't an unnamed
2176 // bitfield.
2177 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2178 Field != FieldEnd; ++Field) {
2179 if (!Field->isUnnamedBitField()) {
2180 CheckEmptyInitializable(
2181 InitializedEntity::InitializeMember(*Field, &Entity),
2182 IList->getEndLoc());
2183 if (StructuredList)
2184 StructuredList->setInitializedFieldInUnion(*Field);
2185 break;
2186 }
2187 }
2188 return;
2189 }
2190
2191 bool InitializedSomething = false;
2192
2193 // If we have any base classes, they are initialized prior to the fields.
2194 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2195 auto &Base = *I;
2196 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2197
2198 // Designated inits always initialize fields, so if we see one, all
2199 // remaining base classes have no explicit initializer.
2200 if (Init && isa<DesignatedInitExpr>(Init))
2201 Init = nullptr;
2202
2203 // C++ [over.match.class.deduct]p1.6:
2204 // each non-trailing aggregate element that is a pack expansion is assumed
2205 // to correspond to no elements of the initializer list, and (1.7) a
2206 // trailing aggregate element that is a pack expansion is assumed to
2207 // correspond to all remaining elements of the initializer list (if any).
2208
2209 // C++ [over.match.class.deduct]p1.9:
2210 // ... except that additional parameter packs of the form P_j... are
2211 // inserted into the parameter list in their original aggregate element
2212 // position corresponding to each non-trailing aggregate element of
2213 // type P_j that was skipped because it was a parameter pack, and the
2214 // trailing sequence of parameters corresponding to a trailing
2215 // aggregate element that is a pack expansion (if any) is replaced
2216 // by a single parameter of the form T_n....
2217 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2218 AggrDeductionCandidateParamTypes->push_back(
2219 SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2220
2221 // Trailing pack expansion
2222 if (I + 1 == E && RD->field_empty()) {
2223 if (Index < IList->getNumInits())
2224 Index = IList->getNumInits();
2225 return;
2226 }
2227
2228 continue;
2229 }
2230
2231 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2233 SemaRef.Context, &Base, false, &Entity);
2234 if (Init) {
2235 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2236 StructuredList, StructuredIndex);
2237 InitializedSomething = true;
2238 } else {
2239 CheckEmptyInitializable(BaseEntity, InitLoc);
2240 }
2241
2242 if (!VerifyOnly)
2243 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2244 hadError = true;
2245 return;
2246 }
2247 }
2248
2249 // If structDecl is a forward declaration, this loop won't do
2250 // anything except look at designated initializers; That's okay,
2251 // because an error should get printed out elsewhere. It might be
2252 // worthwhile to skip over the rest of the initializer, though.
2253 RecordDecl::field_iterator FieldEnd = RD->field_end();
2254 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2255 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2256 });
2257 bool HasDesignatedInit = false;
2258
2259 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2260
2261 while (Index < IList->getNumInits()) {
2262 Expr *Init = IList->getInit(Index);
2263 SourceLocation InitLoc = Init->getBeginLoc();
2264
2265 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2266 // If we're not the subobject that matches up with the '{' for
2267 // the designator, we shouldn't be handling the
2268 // designator. Return immediately.
2269 if (!SubobjectIsDesignatorContext)
2270 return;
2271
2272 HasDesignatedInit = true;
2273
2274 // Handle this designated initializer. Field will be updated to
2275 // the next field that we'll be initializing.
2276 bool DesignatedInitFailed = CheckDesignatedInitializer(
2277 Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2278 StructuredList, StructuredIndex, true, TopLevelObject);
2279 if (DesignatedInitFailed)
2280 hadError = true;
2281
2282 // Find the field named by the designated initializer.
2283 DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2284 if (!VerifyOnly && D->isFieldDesignator()) {
2285 FieldDecl *F = D->getFieldDecl();
2286 InitializedFields.insert(F);
2287 if (!DesignatedInitFailed) {
2288 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2289 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2290 hadError = true;
2291 return;
2292 }
2293 }
2294 }
2295
2296 InitializedSomething = true;
2297 continue;
2298 }
2299
2300 // Check if this is an initializer of forms:
2301 //
2302 // struct foo f = {};
2303 // struct foo g = {0};
2304 //
2305 // These are okay for randomized structures. [C99 6.7.8p19]
2306 //
2307 // Also, if there is only one element in the structure, we allow something
2308 // like this, because it's really not randomized in the traditional sense.
2309 //
2310 // struct foo h = {bar};
2311 auto IsZeroInitializer = [&](const Expr *I) {
2312 if (IList->getNumInits() == 1) {
2313 if (NumRecordDecls == 1)
2314 return true;
2315 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2316 return IL->getValue().isZero();
2317 }
2318 return false;
2319 };
2320
2321 // Don't allow non-designated initializers on randomized structures.
2322 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2323 if (!VerifyOnly)
2324 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2325 hadError = true;
2326 break;
2327 }
2328
2329 if (Field == FieldEnd) {
2330 // We've run out of fields. We're done.
2331 break;
2332 }
2333
2334 // We've already initialized a member of a union. We can stop entirely.
2335 if (InitializedSomething && RD->isUnion())
2336 return;
2337
2338 // Stop if we've hit a flexible array member.
2339 if (Field->getType()->isIncompleteArrayType())
2340 break;
2341
2342 if (Field->isUnnamedBitField()) {
2343 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2344 ++Field;
2345 continue;
2346 }
2347
2348 // Make sure we can use this declaration.
2349 bool InvalidUse;
2350 if (VerifyOnly)
2351 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2352 else
2353 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2354 *Field, IList->getInit(Index)->getBeginLoc());
2355 if (InvalidUse) {
2356 ++Index;
2357 ++Field;
2358 hadError = true;
2359 continue;
2360 }
2361
2362 if (!VerifyOnly) {
2363 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2364 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2365 hadError = true;
2366 return;
2367 }
2368 }
2369
2370 InitializedEntity MemberEntity =
2371 InitializedEntity::InitializeMember(*Field, &Entity);
2372 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2373 StructuredList, StructuredIndex);
2374 InitializedSomething = true;
2375 InitializedFields.insert(*Field);
2376
2377 if (RD->isUnion() && StructuredList) {
2378 // Initialize the first field within the union.
2379 StructuredList->setInitializedFieldInUnion(*Field);
2380 }
2381
2382 ++Field;
2383 }
2384
2385 // Emit warnings for missing struct field initializers.
2386 // This check is disabled for designated initializers in C.
2387 // This matches gcc behaviour.
2388 bool IsCDesignatedInitializer =
2389 HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2390 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2391 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
2392 !IsCDesignatedInitializer) {
2393 // It is possible we have one or more unnamed bitfields remaining.
2394 // Find first (if any) named field and emit warning.
2395 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2396 : Field,
2397 end = RD->field_end();
2398 it != end; ++it) {
2399 if (HasDesignatedInit && InitializedFields.count(*it))
2400 continue;
2401
2402 if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2403 !it->getType()->isIncompleteArrayType()) {
2404 auto Diag = HasDesignatedInit
2405 ? diag::warn_missing_designated_field_initializers
2406 : diag::warn_missing_field_initializers;
2407 SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;
2408 break;
2409 }
2410 }
2411 }
2412
2413 // Check that any remaining fields can be value-initialized if we're not
2414 // building a structured list. (If we are, we'll check this later.)
2415 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2416 !Field->getType()->isIncompleteArrayType()) {
2417 for (; Field != FieldEnd && !hadError; ++Field) {
2418 if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())
2419 CheckEmptyInitializable(
2420 InitializedEntity::InitializeMember(*Field, &Entity),
2421 IList->getEndLoc());
2422 }
2423 }
2424
2425 // Check that the types of the remaining fields have accessible destructors.
2426 if (!VerifyOnly) {
2427 // If the initializer expression has a designated initializer, check the
2428 // elements for which a designated initializer is not provided too.
2429 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2430 : Field;
2431 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2432 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2433 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2434 hadError = true;
2435 return;
2436 }
2437 }
2438 }
2439
2440 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2441 Index >= IList->getNumInits())
2442 return;
2443
2444 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2445 TopLevelObject)) {
2446 hadError = true;
2447 ++Index;
2448 return;
2449 }
2450
2451 InitializedEntity MemberEntity =
2452 InitializedEntity::InitializeMember(*Field, &Entity);
2453
2454 if (isa<InitListExpr>(IList->getInit(Index)) ||
2455 AggrDeductionCandidateParamTypes)
2456 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2457 StructuredList, StructuredIndex);
2458 else
2459 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2460 StructuredList, StructuredIndex);
2461
2462 if (RD->isUnion() && StructuredList) {
2463 // Initialize the first field within the union.
2464 StructuredList->setInitializedFieldInUnion(*Field);
2465 }
2466}
2467
2468/// Expand a field designator that refers to a member of an
2469/// anonymous struct or union into a series of field designators that
2470/// refers to the field within the appropriate subobject.
2471///
2473 DesignatedInitExpr *DIE,
2474 unsigned DesigIdx,
2475 IndirectFieldDecl *IndirectField) {
2477
2478 // Build the replacement designators.
2479 SmallVector<Designator, 4> Replacements;
2480 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2481 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2482 if (PI + 1 == PE)
2483 Replacements.push_back(Designator::CreateFieldDesignator(
2484 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2485 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2486 else
2487 Replacements.push_back(Designator::CreateFieldDesignator(
2488 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2489 assert(isa<FieldDecl>(*PI));
2490 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2491 }
2492
2493 // Expand the current designator into the set of replacement
2494 // designators, so we have a full subobject path down to where the
2495 // member of the anonymous struct/union is actually stored.
2496 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2497 &Replacements[0] + Replacements.size());
2498}
2499
2501 DesignatedInitExpr *DIE) {
2502 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2503 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2504 for (unsigned I = 0; I < NumIndexExprs; ++I)
2505 IndexExprs[I] = DIE->getSubExpr(I + 1);
2506 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2507 IndexExprs,
2508 DIE->getEqualOrColonLoc(),
2509 DIE->usesGNUSyntax(), DIE->getInit());
2510}
2511
2512namespace {
2513
2514// Callback to only accept typo corrections that are for field members of
2515// the given struct or union.
2516class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2517 public:
2518 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2519 : Record(RD) {}
2520
2521 bool ValidateCandidate(const TypoCorrection &candidate) override {
2522 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2523 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2524 }
2525
2526 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2527 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2528 }
2529
2530 private:
2531 const RecordDecl *Record;
2532};
2533
2534} // end anonymous namespace
2535
2536/// Check the well-formedness of a C99 designated initializer.
2537///
2538/// Determines whether the designated initializer @p DIE, which
2539/// resides at the given @p Index within the initializer list @p
2540/// IList, is well-formed for a current object of type @p DeclType
2541/// (C99 6.7.8). The actual subobject that this designator refers to
2542/// within the current subobject is returned in either
2543/// @p NextField or @p NextElementIndex (whichever is appropriate).
2544///
2545/// @param IList The initializer list in which this designated
2546/// initializer occurs.
2547///
2548/// @param DIE The designated initializer expression.
2549///
2550/// @param DesigIdx The index of the current designator.
2551///
2552/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2553/// into which the designation in @p DIE should refer.
2554///
2555/// @param NextField If non-NULL and the first designator in @p DIE is
2556/// a field, this will be set to the field declaration corresponding
2557/// to the field named by the designator. On input, this is expected to be
2558/// the next field that would be initialized in the absence of designation,
2559/// if the complete object being initialized is a struct.
2560///
2561/// @param NextElementIndex If non-NULL and the first designator in @p
2562/// DIE is an array designator or GNU array-range designator, this
2563/// will be set to the last index initialized by this designator.
2564///
2565/// @param Index Index into @p IList where the designated initializer
2566/// @p DIE occurs.
2567///
2568/// @param StructuredList The initializer list expression that
2569/// describes all of the subobject initializers in the order they'll
2570/// actually be initialized.
2571///
2572/// @returns true if there was an error, false otherwise.
2573bool
2574InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2575 InitListExpr *IList,
2576 DesignatedInitExpr *DIE,
2577 unsigned DesigIdx,
2578 QualType &CurrentObjectType,
2579 RecordDecl::field_iterator *NextField,
2580 llvm::APSInt *NextElementIndex,
2581 unsigned &Index,
2582 InitListExpr *StructuredList,
2583 unsigned &StructuredIndex,
2584 bool FinishSubobjectInit,
2585 bool TopLevelObject) {
2586 if (DesigIdx == DIE->size()) {
2587 // C++20 designated initialization can result in direct-list-initialization
2588 // of the designated subobject. This is the only way that we can end up
2589 // performing direct initialization as part of aggregate initialization, so
2590 // it needs special handling.
2591 if (DIE->isDirectInit()) {
2592 Expr *Init = DIE->getInit();
2593 assert(isa<InitListExpr>(Init) &&
2594 "designator result in direct non-list initialization?");
2596 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2597 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2598 /*TopLevelOfInitList*/ true);
2599 if (StructuredList) {
2600 ExprResult Result = VerifyOnly
2601 ? getDummyInit()
2602 : Seq.Perform(SemaRef, Entity, Kind, Init);
2603 UpdateStructuredListElement(StructuredList, StructuredIndex,
2604 Result.get());
2605 }
2606 ++Index;
2607 if (AggrDeductionCandidateParamTypes)
2608 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2609 return !Seq;
2610 }
2611
2612 // Check the actual initialization for the designated object type.
2613 bool prevHadError = hadError;
2614
2615 // Temporarily remove the designator expression from the
2616 // initializer list that the child calls see, so that we don't try
2617 // to re-process the designator.
2618 unsigned OldIndex = Index;
2619 IList->setInit(OldIndex, DIE->getInit());
2620
2621 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2622 StructuredIndex, /*DirectlyDesignated=*/true);
2623
2624 // Restore the designated initializer expression in the syntactic
2625 // form of the initializer list.
2626 if (IList->getInit(OldIndex) != DIE->getInit())
2627 DIE->setInit(IList->getInit(OldIndex));
2628 IList->setInit(OldIndex, DIE);
2629
2630 return hadError && !prevHadError;
2631 }
2632
2634 bool IsFirstDesignator = (DesigIdx == 0);
2635 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2636 // Determine the structural initializer list that corresponds to the
2637 // current subobject.
2638 if (IsFirstDesignator)
2639 StructuredList = FullyStructuredList;
2640 else {
2641 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2642 StructuredList->getInit(StructuredIndex) : nullptr;
2643 if (!ExistingInit && StructuredList->hasArrayFiller())
2644 ExistingInit = StructuredList->getArrayFiller();
2645
2646 if (!ExistingInit)
2647 StructuredList = getStructuredSubobjectInit(
2648 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2649 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2650 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2651 StructuredList = Result;
2652 else {
2653 // We are creating an initializer list that initializes the
2654 // subobjects of the current object, but there was already an
2655 // initialization that completely initialized the current
2656 // subobject, e.g., by a compound literal:
2657 //
2658 // struct X { int a, b; };
2659 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2660 //
2661 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2662 // designated initializer re-initializes only its current object
2663 // subobject [0].b.
2664 diagnoseInitOverride(ExistingInit,
2665 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2666 /*UnionOverride=*/false,
2667 /*FullyOverwritten=*/false);
2668
2669 if (!VerifyOnly) {
2671 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2672 StructuredList = E->getUpdater();
2673 else {
2674 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2676 ExistingInit, DIE->getEndLoc());
2677 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2678 StructuredList = DIUE->getUpdater();
2679 }
2680 } else {
2681 // We don't need to track the structured representation of a
2682 // designated init update of an already-fully-initialized object in
2683 // verify-only mode. The only reason we would need the structure is
2684 // to determine where the uninitialized "holes" are, and in this
2685 // case, we know there aren't any and we can't introduce any.
2686 StructuredList = nullptr;
2687 }
2688 }
2689 }
2690 }
2691
2692 if (D->isFieldDesignator()) {
2693 // C99 6.7.8p7:
2694 //
2695 // If a designator has the form
2696 //
2697 // . identifier
2698 //
2699 // then the current object (defined below) shall have
2700 // structure or union type and the identifier shall be the
2701 // name of a member of that type.
2702 RecordDecl *RD = getRecordDecl(CurrentObjectType);
2703 if (!RD) {
2705 if (Loc.isInvalid())
2706 Loc = D->getFieldLoc();
2707 if (!VerifyOnly)
2708 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2709 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2710 ++Index;
2711 return true;
2712 }
2713
2714 FieldDecl *KnownField = D->getFieldDecl();
2715 if (!KnownField) {
2716 const IdentifierInfo *FieldName = D->getFieldName();
2717 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2718 if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2719 KnownField = FD;
2720 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2721 // In verify mode, don't modify the original.
2722 if (VerifyOnly)
2723 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2724 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2725 D = DIE->getDesignator(DesigIdx);
2726 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2727 }
2728 if (!KnownField) {
2729 if (VerifyOnly) {
2730 ++Index;
2731 return true; // No typo correction when just trying this out.
2732 }
2733
2734 // We found a placeholder variable
2735 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2736 FieldName)) {
2737 ++Index;
2738 return true;
2739 }
2740 // Name lookup found something, but it wasn't a field.
2741 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2742 !Lookup.empty()) {
2743 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2744 << FieldName;
2745 SemaRef.Diag(Lookup.front()->getLocation(),
2746 diag::note_field_designator_found);
2747 ++Index;
2748 return true;
2749 }
2750
2751 // Name lookup didn't find anything.
2752 // Determine whether this was a typo for another field name.
2753 FieldInitializerValidatorCCC CCC(RD);
2754 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2755 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2756 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2758 SemaRef.diagnoseTypo(
2759 Corrected,
2760 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2761 << FieldName << CurrentObjectType);
2762 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2763 hadError = true;
2764 } else {
2765 // Typo correction didn't find anything.
2767
2768 // The loc can be invalid with a "null" designator (i.e. an anonymous
2769 // union/struct). Do our best to approximate the location.
2770 if (Loc.isInvalid())
2771 Loc = IList->getBeginLoc();
2772
2773 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
2774 << FieldName << CurrentObjectType << DIE->getSourceRange();
2775 ++Index;
2776 return true;
2777 }
2778 }
2779 }
2780
2781 unsigned NumBases = 0;
2782 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2783 NumBases = CXXRD->getNumBases();
2784
2785 unsigned FieldIndex = NumBases;
2786
2787 for (auto *FI : RD->fields()) {
2788 if (FI->isUnnamedBitField())
2789 continue;
2790 if (declaresSameEntity(KnownField, FI)) {
2791 KnownField = FI;
2792 break;
2793 }
2794 ++FieldIndex;
2795 }
2796
2799
2800 // All of the fields of a union are located at the same place in
2801 // the initializer list.
2802 if (RD->isUnion()) {
2803 FieldIndex = 0;
2804 if (StructuredList) {
2805 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2806 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2807 assert(StructuredList->getNumInits() == 1
2808 && "A union should never have more than one initializer!");
2809
2810 Expr *ExistingInit = StructuredList->getInit(0);
2811 if (ExistingInit) {
2812 // We're about to throw away an initializer, emit warning.
2813 diagnoseInitOverride(
2814 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2815 /*UnionOverride=*/true,
2816 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
2817 : true);
2818 }
2819
2820 // remove existing initializer
2821 StructuredList->resizeInits(SemaRef.Context, 0);
2822 StructuredList->setInitializedFieldInUnion(nullptr);
2823 }
2824
2825 StructuredList->setInitializedFieldInUnion(*Field);
2826 }
2827 }
2828
2829 // Make sure we can use this declaration.
2830 bool InvalidUse;
2831 if (VerifyOnly)
2832 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2833 else
2834 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2835 if (InvalidUse) {
2836 ++Index;
2837 return true;
2838 }
2839
2840 // C++20 [dcl.init.list]p3:
2841 // The ordered identifiers in the designators of the designated-
2842 // initializer-list shall form a subsequence of the ordered identifiers
2843 // in the direct non-static data members of T.
2844 //
2845 // Note that this is not a condition on forming the aggregate
2846 // initialization, only on actually performing initialization,
2847 // so it is not checked in VerifyOnly mode.
2848 //
2849 // FIXME: This is the only reordering diagnostic we produce, and it only
2850 // catches cases where we have a top-level field designator that jumps
2851 // backwards. This is the only such case that is reachable in an
2852 // otherwise-valid C++20 program, so is the only case that's required for
2853 // conformance, but for consistency, we should diagnose all the other
2854 // cases where a designator takes us backwards too.
2855 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
2856 NextField &&
2857 (*NextField == RD->field_end() ||
2858 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
2859 // Find the field that we just initialized.
2860 FieldDecl *PrevField = nullptr;
2861 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
2862 if (FI->isUnnamedBitField())
2863 continue;
2864 if (*NextField != RD->field_end() &&
2865 declaresSameEntity(*FI, **NextField))
2866 break;
2867 PrevField = *FI;
2868 }
2869
2870 if (PrevField &&
2871 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2872 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2873 diag::ext_designated_init_reordered)
2874 << KnownField << PrevField << DIE->getSourceRange();
2875
2876 unsigned OldIndex = StructuredIndex - 1;
2877 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
2878 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
2879 SemaRef.Diag(PrevInit->getBeginLoc(),
2880 diag::note_previous_field_init)
2881 << PrevField << PrevInit->getSourceRange();
2882 }
2883 }
2884 }
2885 }
2886
2887
2888 // Update the designator with the field declaration.
2889 if (!VerifyOnly)
2890 D->setFieldDecl(*Field);
2891
2892 // Make sure that our non-designated initializer list has space
2893 // for a subobject corresponding to this field.
2894 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
2895 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2896
2897 // This designator names a flexible array member.
2898 if (Field->getType()->isIncompleteArrayType()) {
2899 bool Invalid = false;
2900 if ((DesigIdx + 1) != DIE->size()) {
2901 // We can't designate an object within the flexible array
2902 // member (because GCC doesn't allow it).
2903 if (!VerifyOnly) {
2905 = DIE->getDesignator(DesigIdx + 1);
2906 SemaRef.Diag(NextD->getBeginLoc(),
2907 diag::err_designator_into_flexible_array_member)
2908 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2909 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2910 << *Field;
2911 }
2912 Invalid = true;
2913 }
2914
2915 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2916 !isa<StringLiteral>(DIE->getInit())) {
2917 // The initializer is not an initializer list.
2918 if (!VerifyOnly) {
2919 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2920 diag::err_flexible_array_init_needs_braces)
2921 << DIE->getInit()->getSourceRange();
2922 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2923 << *Field;
2924 }
2925 Invalid = true;
2926 }
2927
2928 // Check GNU flexible array initializer.
2929 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2930 TopLevelObject))
2931 Invalid = true;
2932
2933 if (Invalid) {
2934 ++Index;
2935 return true;
2936 }
2937
2938 // Initialize the array.
2939 bool prevHadError = hadError;
2940 unsigned newStructuredIndex = FieldIndex;
2941 unsigned OldIndex = Index;
2942 IList->setInit(Index, DIE->getInit());
2943
2944 InitializedEntity MemberEntity =
2945 InitializedEntity::InitializeMember(*Field, &Entity);
2946 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2947 StructuredList, newStructuredIndex);
2948
2949 IList->setInit(OldIndex, DIE);
2950 if (hadError && !prevHadError) {
2951 ++Field;
2952 ++FieldIndex;
2953 if (NextField)
2954 *NextField = Field;
2955 StructuredIndex = FieldIndex;
2956 return true;
2957 }
2958 } else {
2959 // Recurse to check later designated subobjects.
2960 QualType FieldType = Field->getType();
2961 unsigned newStructuredIndex = FieldIndex;
2962
2963 InitializedEntity MemberEntity =
2964 InitializedEntity::InitializeMember(*Field, &Entity);
2965 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2966 FieldType, nullptr, nullptr, Index,
2967 StructuredList, newStructuredIndex,
2968 FinishSubobjectInit, false))
2969 return true;
2970 }
2971
2972 // Find the position of the next field to be initialized in this
2973 // subobject.
2974 ++Field;
2975 ++FieldIndex;
2976
2977 // If this the first designator, our caller will continue checking
2978 // the rest of this struct/class/union subobject.
2979 if (IsFirstDesignator) {
2980 if (Field != RD->field_end() && Field->isUnnamedBitField())
2981 ++Field;
2982
2983 if (NextField)
2984 *NextField = Field;
2985
2986 StructuredIndex = FieldIndex;
2987 return false;
2988 }
2989
2990 if (!FinishSubobjectInit)
2991 return false;
2992
2993 // We've already initialized something in the union; we're done.
2994 if (RD->isUnion())
2995 return hadError;
2996
2997 // Check the remaining fields within this class/struct/union subobject.
2998 bool prevHadError = hadError;
2999
3000 auto NoBases =
3003 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
3004 false, Index, StructuredList, FieldIndex);
3005 return hadError && !prevHadError;
3006 }
3007
3008 // C99 6.7.8p6:
3009 //
3010 // If a designator has the form
3011 //
3012 // [ constant-expression ]
3013 //
3014 // then the current object (defined below) shall have array
3015 // type and the expression shall be an integer constant
3016 // expression. If the array is of unknown size, any
3017 // nonnegative value is valid.
3018 //
3019 // Additionally, cope with the GNU extension that permits
3020 // designators of the form
3021 //
3022 // [ constant-expression ... constant-expression ]
3023 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
3024 if (!AT) {
3025 if (!VerifyOnly)
3026 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3027 << CurrentObjectType;
3028 ++Index;
3029 return true;
3030 }
3031
3032 Expr *IndexExpr = nullptr;
3033 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3034 if (D->isArrayDesignator()) {
3035 IndexExpr = DIE->getArrayIndex(*D);
3036 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3037 DesignatedEndIndex = DesignatedStartIndex;
3038 } else {
3039 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3040
3041 DesignatedStartIndex =
3043 DesignatedEndIndex =
3045 IndexExpr = DIE->getArrayRangeEnd(*D);
3046
3047 // Codegen can't handle evaluating array range designators that have side
3048 // effects, because we replicate the AST value for each initialized element.
3049 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3050 // elements with something that has a side effect, so codegen can emit an
3051 // "error unsupported" error instead of miscompiling the app.
3052 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3053 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3054 FullyStructuredList->sawArrayRangeDesignator();
3055 }
3056
3057 if (isa<ConstantArrayType>(AT)) {
3058 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3059 DesignatedStartIndex
3060 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3061 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3062 DesignatedEndIndex
3063 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3064 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3065 if (DesignatedEndIndex >= MaxElements) {
3066 if (!VerifyOnly)
3067 SemaRef.Diag(IndexExpr->getBeginLoc(),
3068 diag::err_array_designator_too_large)
3069 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3070 << IndexExpr->getSourceRange();
3071 ++Index;
3072 return true;
3073 }
3074 } else {
3075 unsigned DesignatedIndexBitWidth =
3077 DesignatedStartIndex =
3078 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3079 DesignatedEndIndex =
3080 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3081 DesignatedStartIndex.setIsUnsigned(true);
3082 DesignatedEndIndex.setIsUnsigned(true);
3083 }
3084
3085 bool IsStringLiteralInitUpdate =
3086 StructuredList && StructuredList->isStringLiteralInit();
3087 if (IsStringLiteralInitUpdate && VerifyOnly) {
3088 // We're just verifying an update to a string literal init. We don't need
3089 // to split the string up into individual characters to do that.
3090 StructuredList = nullptr;
3091 } else if (IsStringLiteralInitUpdate) {
3092 // We're modifying a string literal init; we have to decompose the string
3093 // so we can modify the individual characters.
3094 ASTContext &Context = SemaRef.Context;
3095 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3096
3097 // Compute the character type
3098 QualType CharTy = AT->getElementType();
3099
3100 // Compute the type of the integer literals.
3101 QualType PromotedCharTy = CharTy;
3102 if (Context.isPromotableIntegerType(CharTy))
3103 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3104 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3105
3106 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3107 // Get the length of the string.
3108 uint64_t StrLen = SL->getLength();
3109 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3110 StrLen = cast<ConstantArrayType>(AT)->getZExtSize();
3111 StructuredList->resizeInits(Context, StrLen);
3112
3113 // Build a literal for each character in the string, and put them into
3114 // the init list.
3115 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3116 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3117 Expr *Init = new (Context) IntegerLiteral(
3118 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3119 if (CharTy != PromotedCharTy)
3120 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3121 Init, nullptr, VK_PRValue,
3123 StructuredList->updateInit(Context, i, Init);
3124 }
3125 } else {
3126 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3127 std::string Str;
3128 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3129
3130 // Get the length of the string.
3131 uint64_t StrLen = Str.size();
3132 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3133 StrLen = cast<ConstantArrayType>(AT)->getZExtSize();
3134 StructuredList->resizeInits(Context, StrLen);
3135
3136 // Build a literal for each character in the string, and put them into
3137 // the init list.
3138 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3139 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3140 Expr *Init = new (Context) IntegerLiteral(
3141 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3142 if (CharTy != PromotedCharTy)
3143 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3144 Init, nullptr, VK_PRValue,
3146 StructuredList->updateInit(Context, i, Init);
3147 }
3148 }
3149 }
3150
3151 // Make sure that our non-designated initializer list has space
3152 // for a subobject corresponding to this array element.
3153 if (StructuredList &&
3154 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3155 StructuredList->resizeInits(SemaRef.Context,
3156 DesignatedEndIndex.getZExtValue() + 1);
3157
3158 // Repeatedly perform subobject initializations in the range
3159 // [DesignatedStartIndex, DesignatedEndIndex].
3160
3161 // Move to the next designator
3162 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3163 unsigned OldIndex = Index;
3164
3165 InitializedEntity ElementEntity =
3167
3168 while (DesignatedStartIndex <= DesignatedEndIndex) {
3169 // Recurse to check later designated subobjects.
3170 QualType ElementType = AT->getElementType();
3171 Index = OldIndex;
3172
3173 ElementEntity.setElementIndex(ElementIndex);
3174 if (CheckDesignatedInitializer(
3175 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3176 nullptr, Index, StructuredList, ElementIndex,
3177 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3178 false))
3179 return true;
3180
3181 // Move to the next index in the array that we'll be initializing.
3182 ++DesignatedStartIndex;
3183 ElementIndex = DesignatedStartIndex.getZExtValue();
3184 }
3185
3186 // If this the first designator, our caller will continue checking
3187 // the rest of this array subobject.
3188 if (IsFirstDesignator) {
3189 if (NextElementIndex)
3190 *NextElementIndex = DesignatedStartIndex;
3191 StructuredIndex = ElementIndex;
3192 return false;
3193 }
3194
3195 if (!FinishSubobjectInit)
3196 return false;
3197
3198 // Check the remaining elements within this array subobject.
3199 bool prevHadError = hadError;
3200 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3201 /*SubobjectIsDesignatorContext=*/false, Index,
3202 StructuredList, ElementIndex);
3203 return hadError && !prevHadError;
3204}
3205
3206// Get the structured initializer list for a subobject of type
3207// @p CurrentObjectType.
3209InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3210 QualType CurrentObjectType,
3211 InitListExpr *StructuredList,
3212 unsigned StructuredIndex,
3213 SourceRange InitRange,
3214 bool IsFullyOverwritten) {
3215 if (!StructuredList)
3216 return nullptr;
3217
3218 Expr *ExistingInit = nullptr;
3219 if (StructuredIndex < StructuredList->getNumInits())
3220 ExistingInit = StructuredList->getInit(StructuredIndex);
3221
3222 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3223 // There might have already been initializers for subobjects of the current
3224 // object, but a subsequent initializer list will overwrite the entirety
3225 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3226 //
3227 // struct P { char x[6]; };
3228 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3229 //
3230 // The first designated initializer is ignored, and l.x is just "f".
3231 if (!IsFullyOverwritten)
3232 return Result;
3233
3234 if (ExistingInit) {
3235 // We are creating an initializer list that initializes the
3236 // subobjects of the current object, but there was already an
3237 // initialization that completely initialized the current
3238 // subobject:
3239 //
3240 // struct X { int a, b; };
3241 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3242 //
3243 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3244 // designated initializer overwrites the [0].b initializer
3245 // from the prior initialization.
3246 //
3247 // When the existing initializer is an expression rather than an
3248 // initializer list, we cannot decompose and update it in this way.
3249 // For example:
3250 //
3251 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3252 //
3253 // This case is handled by CheckDesignatedInitializer.
3254 diagnoseInitOverride(ExistingInit, InitRange);
3255 }
3256
3257 unsigned ExpectedNumInits = 0;
3258 if (Index < IList->getNumInits()) {
3259 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3260 ExpectedNumInits = Init->getNumInits();
3261 else
3262 ExpectedNumInits = IList->getNumInits() - Index;
3263 }
3264
3265 InitListExpr *Result =
3266 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3267
3268 // Link this new initializer list into the structured initializer
3269 // lists.
3270 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3271 return Result;
3272}
3273
3275InitListChecker::createInitListExpr(QualType CurrentObjectType,
3276 SourceRange InitRange,
3277 unsigned ExpectedNumInits) {
3278 InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3279 SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd());
3280
3281 QualType ResultType = CurrentObjectType;
3282 if (!ResultType->isArrayType())
3283 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3284 Result->setType(ResultType);
3285
3286 // Pre-allocate storage for the structured initializer list.
3287 unsigned NumElements = 0;
3288
3289 if (const ArrayType *AType
3290 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3291 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3292 NumElements = CAType->getZExtSize();
3293 // Simple heuristic so that we don't allocate a very large
3294 // initializer with many empty entries at the end.
3295 if (NumElements > ExpectedNumInits)
3296 NumElements = 0;
3297 }
3298 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3299 NumElements = VType->getNumElements();
3300 } else if (CurrentObjectType->isRecordType()) {
3301 NumElements = numStructUnionElements(CurrentObjectType);
3302 } else if (CurrentObjectType->isDependentType()) {
3303 NumElements = 1;
3304 }
3305
3306 Result->reserveInits(SemaRef.Context, NumElements);
3307
3308 return Result;
3309}
3310
3311/// Update the initializer at index @p StructuredIndex within the
3312/// structured initializer list to the value @p expr.
3313void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3314 unsigned &StructuredIndex,
3315 Expr *expr) {
3316 // No structured initializer list to update
3317 if (!StructuredList)
3318 return;
3319
3320 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3321 StructuredIndex, expr)) {
3322 // This initializer overwrites a previous initializer.
3323 // No need to diagnose when `expr` is nullptr because a more relevant
3324 // diagnostic has already been issued and this diagnostic is potentially
3325 // noise.
3326 if (expr)
3327 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3328 }
3329
3330 ++StructuredIndex;
3331}
3332
3333/// Determine whether we can perform aggregate initialization for the purposes
3334/// of overload resolution.
3336 const InitializedEntity &Entity, InitListExpr *From) {
3337 QualType Type = Entity.getType();
3338 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3339 /*TreatUnavailableAsInvalid=*/false,
3340 /*InOverloadResolution=*/true);
3341 return !Check.HadError();
3342}
3343
3344/// Check that the given Index expression is a valid array designator
3345/// value. This is essentially just a wrapper around
3346/// VerifyIntegerConstantExpression that also checks for negative values
3347/// and produces a reasonable diagnostic if there is a
3348/// failure. Returns the index expression, possibly with an implicit cast
3349/// added, on success. If everything went okay, Value will receive the
3350/// value of the constant expression.
3351static ExprResult
3352CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3353 SourceLocation Loc = Index->getBeginLoc();
3354
3355 // Make sure this is an integer constant expression.
3358 if (Result.isInvalid())
3359 return Result;
3360
3361 if (Value.isSigned() && Value.isNegative())
3362 return S.Diag(Loc, diag::err_array_designator_negative)
3363 << toString(Value, 10) << Index->getSourceRange();
3364
3365 Value.setIsUnsigned(true);
3366 return Result;
3367}
3368
3370 SourceLocation EqualOrColonLoc,
3371 bool GNUSyntax,
3372 ExprResult Init) {
3373 typedef DesignatedInitExpr::Designator ASTDesignator;
3374
3375 bool Invalid = false;
3377 SmallVector<Expr *, 32> InitExpressions;
3378
3379 // Build designators and check array designator expressions.
3380 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3381 const Designator &D = Desig.getDesignator(Idx);
3382
3383 if (D.isFieldDesignator()) {
3384 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3385 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3386 } else if (D.isArrayDesignator()) {
3387 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3388 llvm::APSInt IndexValue;
3389 if (!Index->isTypeDependent() && !Index->isValueDependent())
3390 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3391 if (!Index)
3392 Invalid = true;
3393 else {
3394 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3395 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3396 InitExpressions.push_back(Index);
3397 }
3398 } else if (D.isArrayRangeDesignator()) {
3399 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3400 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3401 llvm::APSInt StartValue;
3402 llvm::APSInt EndValue;
3403 bool StartDependent = StartIndex->isTypeDependent() ||
3404 StartIndex->isValueDependent();
3405 bool EndDependent = EndIndex->isTypeDependent() ||
3406 EndIndex->isValueDependent();
3407 if (!StartDependent)
3408 StartIndex =
3409 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3410 if (!EndDependent)
3411 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3412
3413 if (!StartIndex || !EndIndex)
3414 Invalid = true;
3415 else {
3416 // Make sure we're comparing values with the same bit width.
3417 if (StartDependent || EndDependent) {
3418 // Nothing to compute.
3419 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3420 EndValue = EndValue.extend(StartValue.getBitWidth());
3421 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3422 StartValue = StartValue.extend(EndValue.getBitWidth());
3423
3424 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3425 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3426 << toString(StartValue, 10) << toString(EndValue, 10)
3427 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3428 Invalid = true;
3429 } else {
3430 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3431 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3432 D.getRBracketLoc()));
3433 InitExpressions.push_back(StartIndex);
3434 InitExpressions.push_back(EndIndex);
3435 }
3436 }
3437 }
3438 }
3439
3440 if (Invalid || Init.isInvalid())
3441 return ExprError();
3442
3443 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3444 EqualOrColonLoc, GNUSyntax,
3445 Init.getAs<Expr>());
3446}
3447
3448//===----------------------------------------------------------------------===//
3449// Initialization entity
3450//===----------------------------------------------------------------------===//
3451
3452InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3454 : Parent(&Parent), Index(Index)
3455{
3456 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3457 Kind = EK_ArrayElement;
3458 Type = AT->getElementType();
3459 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3460 Kind = EK_VectorElement;
3461 Type = VT->getElementType();
3462 } else {
3463 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3464 assert(CT && "Unexpected type");
3465 Kind = EK_ComplexElement;
3466 Type = CT->getElementType();
3467 }
3468}
3469
3472 const CXXBaseSpecifier *Base,
3473 bool IsInheritedVirtualBase,
3474 const InitializedEntity *Parent) {
3476 Result.Kind = EK_Base;
3477 Result.Parent = Parent;
3478 Result.Base = {Base, IsInheritedVirtualBase};
3479 Result.Type = Base->getType();
3480 return Result;
3481}
3482
3484 switch (getKind()) {
3485 case EK_Parameter:
3487 ParmVarDecl *D = Parameter.getPointer();
3488 return (D ? D->getDeclName() : DeclarationName());
3489 }
3490
3491 case EK_Variable:
3492 case EK_Member:
3494 case EK_Binding:
3496 return Variable.VariableOrMember->getDeclName();
3497
3498 case EK_LambdaCapture:
3499 return DeclarationName(Capture.VarID);
3500
3501 case EK_Result:
3502 case EK_StmtExprResult:
3503 case EK_Exception:
3504 case EK_New:
3505 case EK_Temporary:
3506 case EK_Base:
3507 case EK_Delegating:
3508 case EK_ArrayElement:
3509 case EK_VectorElement:
3510 case EK_ComplexElement:
3511 case EK_BlockElement:
3514 case EK_RelatedResult:
3515 return DeclarationName();
3516 }
3517
3518 llvm_unreachable("Invalid EntityKind!");
3519}
3520
3522 switch (getKind()) {
3523 case EK_Variable:
3524 case EK_Member:
3526 case EK_Binding:
3528 return Variable.VariableOrMember;
3529
3530 case EK_Parameter:
3532 return Parameter.getPointer();
3533
3534 case EK_Result:
3535 case EK_StmtExprResult:
3536 case EK_Exception:
3537 case EK_New:
3538 case EK_Temporary:
3539 case EK_Base:
3540 case EK_Delegating:
3541 case EK_ArrayElement:
3542 case EK_VectorElement:
3543 case EK_ComplexElement:
3544 case EK_BlockElement:
3546 case EK_LambdaCapture:
3548 case EK_RelatedResult:
3549 return nullptr;
3550 }
3551
3552 llvm_unreachable("Invalid EntityKind!");
3553}
3554
3556 switch (getKind()) {
3557 case EK_Result:
3558 case EK_Exception:
3559 return LocAndNRVO.NRVO;
3560
3561 case EK_StmtExprResult:
3562 case EK_Variable:
3563 case EK_Parameter:
3566 case EK_Member:
3568 case EK_Binding:
3569 case EK_New:
3570 case EK_Temporary:
3572 case EK_Base:
3573 case EK_Delegating:
3574 case EK_ArrayElement:
3575 case EK_VectorElement:
3576 case EK_ComplexElement:
3577 case EK_BlockElement:
3579 case EK_LambdaCapture:
3580 case EK_RelatedResult:
3581 break;
3582 }
3583
3584 return false;
3585}
3586
3587unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3588 assert(getParent() != this);
3589 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3590 for (unsigned I = 0; I != Depth; ++I)
3591 OS << "`-";
3592
3593 switch (getKind()) {
3594 case EK_Variable: OS << "Variable"; break;
3595 case EK_Parameter: OS << "Parameter"; break;
3596 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3597 break;
3598 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3599 case EK_Result: OS << "Result"; break;
3600 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3601 case EK_Exception: OS << "Exception"; break;
3602 case EK_Member:
3604 OS << "Member";
3605 break;
3606 case EK_Binding: OS << "Binding"; break;
3607 case EK_New: OS << "New"; break;
3608 case EK_Temporary: OS << "Temporary"; break;
3609 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3610 case EK_RelatedResult: OS << "RelatedResult"; break;
3611 case EK_Base: OS << "Base"; break;
3612 case EK_Delegating: OS << "Delegating"; break;
3613 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3614 case EK_VectorElement: OS << "VectorElement " << Index; break;
3615 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3616 case EK_BlockElement: OS << "Block"; break;
3618 OS << "Block (lambda)";
3619 break;
3620 case EK_LambdaCapture:
3621 OS << "LambdaCapture ";
3622 OS << DeclarationName(Capture.VarID);
3623 break;
3624 }
3625
3626 if (auto *D = getDecl()) {
3627 OS << " ";
3628 D->printQualifiedName(OS);
3629 }
3630
3631 OS << " '" << getType() << "'\n";
3632
3633 return Depth + 1;
3634}
3635
3636LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3637 dumpImpl(llvm::errs());
3638}
3639
3640//===----------------------------------------------------------------------===//
3641// Initialization sequence
3642//===----------------------------------------------------------------------===//
3643
3645 switch (Kind) {
3650 case SK_BindReference:
3652 case SK_FinalCopy:
3654 case SK_UserConversion:
3661 case SK_UnwrapInitList:
3662 case SK_RewrapInitList:
3666 case SK_CAssignment:
3667 case SK_StringInit:
3669 case SK_ArrayLoopIndex:
3670 case SK_ArrayLoopInit:
3671 case SK_ArrayInit:
3672 case SK_GNUArrayInit:
3679 case SK_OCLSamplerInit:
3682 break;
3683
3686 delete ICS;
3687 }
3688}
3689
3691 // There can be some lvalue adjustments after the SK_BindReference step.
3692 for (const Step &S : llvm::reverse(Steps)) {
3693 if (S.Kind == SK_BindReference)
3694 return true;
3695 if (S.Kind == SK_BindReferenceToTemporary)
3696 return false;
3697 }
3698 return false;
3699}
3700
3702 if (!Failed())
3703 return false;
3704
3705 switch (getFailureKind()) {
3716 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3733 case FK_Incomplete:
3738 case FK_PlaceholderType:
3743 return false;
3744
3749 return FailedOverloadResult == OR_Ambiguous;
3750 }
3751
3752 llvm_unreachable("Invalid EntityKind!");
3753}
3754
3756 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3757}
3758
3759void
3760InitializationSequence
3761::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3762 DeclAccessPair Found,
3763 bool HadMultipleCandidates) {
3764 Step S;
3766 S.Type = Function->getType();
3767 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3768 S.Function.Function = Function;
3769 S.Function.FoundDecl = Found;
3770 Steps.push_back(S);
3771}
3772
3774 ExprValueKind VK) {
3775 Step S;
3776 switch (VK) {
3777 case VK_PRValue:
3779 break;
3780 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3781 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3782 }
3783 S.Type = BaseType;
3784 Steps.push_back(S);
3785}
3786
3788 bool BindingTemporary) {
3789 Step S;
3790 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3791 S.Type = T;
3792 Steps.push_back(S);
3793}
3794
3796 Step S;
3797 S.Kind = SK_FinalCopy;
3798 S.Type = T;
3799 Steps.push_back(S);
3800}
3801
3803 Step S;
3805 S.Type = T;
3806 Steps.push_back(S);
3807}
3808
3809void
3811 DeclAccessPair FoundDecl,
3812 QualType T,
3813 bool HadMultipleCandidates) {
3814 Step S;
3815 S.Kind = SK_UserConversion;
3816 S.Type = T;
3817 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3818 S.Function.Function = Function;
3819 S.Function.FoundDecl = FoundDecl;
3820 Steps.push_back(S);
3821}
3822
3824 ExprValueKind VK) {
3825 Step S;
3826 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
3827 switch (VK) {
3828 case VK_PRValue:
3830 break;
3831 case VK_XValue:
3833 break;
3834 case VK_LValue:
3836 break;
3837 }
3838 S.Type = Ty;
3839 Steps.push_back(S);
3840}
3841
3843 Step S;
3845 S.Type = Ty;
3846 Steps.push_back(S);
3847}
3848
3850 Step S;
3851 S.Kind = SK_AtomicConversion;
3852 S.Type = Ty;
3853 Steps.push_back(S);
3854}
3855
3858 bool TopLevelOfInitList) {
3859 Step S;
3860 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3862 S.Type = T;
3863 S.ICS = new ImplicitConversionSequence(ICS);
3864 Steps.push_back(S);
3865}
3866
3868 Step S;
3869 S.Kind = SK_ListInitialization;
3870 S.Type = T;
3871 Steps.push_back(S);
3872}
3873
3875 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3876 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3877 Step S;
3878 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3881 S.Type = T;
3882 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3883 S.Function.Function = Constructor;
3884 S.Function.FoundDecl = FoundDecl;
3885 Steps.push_back(S);
3886}
3887
3889 Step S;
3890 S.Kind = SK_ZeroInitialization;
3891 S.Type = T;
3892 Steps.push_back(S);
3893}
3894
3896 Step S;
3897 S.Kind = SK_CAssignment;
3898 S.Type = T;
3899 Steps.push_back(S);
3900}
3901
3903 Step S;
3904 S.Kind = SK_StringInit;
3905 S.Type = T;
3906 Steps.push_back(S);
3907}
3908
3910 Step S;
3911 S.Kind = SK_ObjCObjectConversion;
3912 S.Type = T;
3913 Steps.push_back(S);
3914}
3915
3917 Step S;
3918 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3919 S.Type = T;
3920 Steps.push_back(S);
3921}
3922
3924 Step S;
3925 S.Kind = SK_ArrayLoopIndex;
3926 S.Type = EltT;
3927 Steps.insert(Steps.begin(), S);
3928
3929 S.Kind = SK_ArrayLoopInit;
3930 S.Type = T;
3931 Steps.push_back(S);
3932}
3933
3935 Step S;
3937 S.Type = T;
3938 Steps.push_back(S);
3939}
3940
3942 bool shouldCopy) {
3943 Step s;
3944 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3946 s.Type = type;
3947 Steps.push_back(s);
3948}
3949
3951 Step S;
3952 S.Kind = SK_ProduceObjCObject;
3953 S.Type = T;
3954 Steps.push_back(S);
3955}
3956
3958 Step S;
3959 S.Kind = SK_StdInitializerList;
3960 S.Type = T;
3961 Steps.push_back(S);
3962}
3963
3965 Step S;
3966 S.Kind = SK_OCLSamplerInit;
3967 S.Type = T;
3968 Steps.push_back(S);
3969}
3970
3972 Step S;
3973 S.Kind = SK_OCLZeroOpaqueType;
3974 S.Type = T;
3975 Steps.push_back(S);
3976}
3977
3979 Step S;
3980 S.Kind = SK_ParenthesizedListInit;
3981 S.Type = T;
3982 Steps.push_back(S);
3983}
3984
3986 InitListExpr *Syntactic) {
3987 assert(Syntactic->getNumInits() == 1 &&
3988 "Can only rewrap trivial init lists.");
3989 Step S;
3990 S.Kind = SK_UnwrapInitList;
3991 S.Type = Syntactic->getInit(0)->getType();
3992 Steps.insert(Steps.begin(), S);
3993
3994 S.Kind = SK_RewrapInitList;
3995 S.Type = T;
3996 S.WrappingSyntacticList = Syntactic;
3997 Steps.push_back(S);
3998}
3999
4003 this->Failure = Failure;
4004 this->FailedOverloadResult = Result;
4005}
4006
4007//===----------------------------------------------------------------------===//
4008// Attempt initialization
4009//===----------------------------------------------------------------------===//
4010
4011/// Tries to add a zero initializer. Returns true if that worked.
4012static bool
4014 const InitializedEntity &Entity) {
4016 return false;
4017
4018 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
4019 if (VD->getInit() || VD->getEndLoc().isMacroID())
4020 return false;
4021
4022 QualType VariableTy = VD->getType().getCanonicalType();
4024 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
4025 if (!Init.empty()) {
4026 Sequence.AddZeroInitializationStep(Entity.getType());
4028 return true;
4029 }
4030 return false;
4031}
4032
4034 InitializationSequence &Sequence,
4035 const InitializedEntity &Entity) {
4036 if (!S.getLangOpts().ObjCAutoRefCount) return;
4037
4038 /// When initializing a parameter, produce the value if it's marked
4039 /// __attribute__((ns_consumed)).
4040 if (Entity.isParameterKind()) {
4041 if (!Entity.isParameterConsumed())
4042 return;
4043
4044 assert(Entity.getType()->isObjCRetainableType() &&
4045 "consuming an object of unretainable type?");
4046 Sequence.AddProduceObjCObjectStep(Entity.getType());
4047
4048 /// When initializing a return value, if the return type is a
4049 /// retainable type, then returns need to immediately retain the
4050 /// object. If an autorelease is required, it will be done at the
4051 /// last instant.
4052 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4054 if (!Entity.getType()->isObjCRetainableType())
4055 return;
4056
4057 Sequence.AddProduceObjCObjectStep(Entity.getType());
4058 }
4059}
4060
4061static void TryListInitialization(Sema &S,
4062 const InitializedEntity &Entity,
4063 const InitializationKind &Kind,
4064 InitListExpr *InitList,
4065 InitializationSequence &Sequence,
4066 bool TreatUnavailableAsInvalid);
4067
4068/// When initializing from init list via constructor, handle
4069/// initialization of an object of type std::initializer_list<T>.
4070///
4071/// \return true if we have handled initialization of an object of type
4072/// std::initializer_list<T>, false otherwise.
4074 InitListExpr *List,
4075 QualType DestType,
4076 InitializationSequence &Sequence,
4077 bool TreatUnavailableAsInvalid) {
4078 QualType E;
4079 if (!S.isStdInitializerList(DestType, &E))
4080 return false;
4081
4082 if (!S.isCompleteType(List->getExprLoc(), E)) {
4083 Sequence.setIncompleteTypeFailure(E);
4084 return true;
4085 }
4086
4087 // Try initializing a temporary array from the init list.
4089 E.withConst(),
4090 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4091 List->getNumInits()),
4093 InitializedEntity HiddenArray =
4096 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4097 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4098 TreatUnavailableAsInvalid);
4099 if (Sequence)
4100 Sequence.AddStdInitializerListConstructionStep(DestType);
4101 return true;
4102}
4103
4104/// Determine if the constructor has the signature of a copy or move
4105/// constructor for the type T of the class in which it was found. That is,
4106/// determine if its first parameter is of type T or reference to (possibly
4107/// cv-qualified) T.
4109 const ConstructorInfo &Info) {
4110 if (Info.Constructor->getNumParams() == 0)
4111 return false;
4112
4113 QualType ParmT =
4115 QualType ClassT =
4116 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
4117
4118 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4119}
4120
4122 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4123 OverloadCandidateSet &CandidateSet, QualType DestType,
4125 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4126 bool IsListInit, bool RequireActualConstructor,
4127 bool SecondStepOfCopyInit = false) {
4129 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4130
4131 for (NamedDecl *D : Ctors) {
4132 auto Info = getConstructorInfo(D);
4133 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4134 continue;
4135
4136 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4137 continue;
4138
4139 // C++11 [over.best.ics]p4:
4140 // ... and the constructor or user-defined conversion function is a
4141 // candidate by
4142 // - 13.3.1.3, when the argument is the temporary in the second step
4143 // of a class copy-initialization, or
4144 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4145 // - the second phase of 13.3.1.7 when the initializer list has exactly
4146 // one element that is itself an initializer list, and the target is
4147 // the first parameter of a constructor of class X, and the conversion
4148 // is to X or reference to (possibly cv-qualified X),
4149 // user-defined conversion sequences are not considered.
4150 bool SuppressUserConversions =
4151 SecondStepOfCopyInit ||
4152 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4154
4155 if (Info.ConstructorTmpl)
4157 Info.ConstructorTmpl, Info.FoundDecl,
4158 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4159 /*PartialOverloading=*/false, AllowExplicit);
4160 else {
4161 // C++ [over.match.copy]p1:
4162 // - When initializing a temporary to be bound to the first parameter
4163 // of a constructor [for type T] that takes a reference to possibly
4164 // cv-qualified T as its first argument, called with a single
4165 // argument in the context of direct-initialization, explicit
4166 // conversion functions are also considered.
4167 // FIXME: What if a constructor template instantiates to such a signature?
4168 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4169 Args.size() == 1 &&
4171 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4172 CandidateSet, SuppressUserConversions,
4173 /*PartialOverloading=*/false, AllowExplicit,
4174 AllowExplicitConv);
4175 }
4176 }
4177
4178 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4179 //
4180 // When initializing an object of class type T by constructor
4181 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4182 // from a single expression of class type U, conversion functions of
4183 // U that convert to the non-reference type cv T are candidates.
4184 // Explicit conversion functions are only candidates during
4185 // direct-initialization.
4186 //
4187 // Note: SecondStepOfCopyInit is only ever true in this case when
4188 // evaluating whether to produce a C++98 compatibility warning.
4189 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4190 !RequireActualConstructor && !SecondStepOfCopyInit) {
4191 Expr *Initializer = Args[0];
4192 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4193 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4194 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4195 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4196 NamedDecl *D = *I;
4197 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4198 D = D->getUnderlyingDecl();
4199
4200 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4201 CXXConversionDecl *Conv;
4202 if (ConvTemplate)
4203 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4204 else
4205 Conv = cast<CXXConversionDecl>(D);
4206
4207 if (ConvTemplate)
4209 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4210 CandidateSet, AllowExplicit, AllowExplicit,
4211 /*AllowResultConversion*/ false);
4212 else
4213 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4214 DestType, CandidateSet, AllowExplicit,
4215 AllowExplicit,
4216 /*AllowResultConversion*/ false);
4217 }
4218 }
4219 }
4220
4221 // Perform overload resolution and return the result.
4222 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4223}
4224
4225/// Attempt initialization by constructor (C++ [dcl.init]), which
4226/// enumerates the constructors of the initialized entity and performs overload
4227/// resolution to select the best.
4228/// \param DestType The destination class type.
4229/// \param DestArrayType The destination type, which is either DestType or
4230/// a (possibly multidimensional) array of DestType.
4231/// \param IsListInit Is this list-initialization?
4232/// \param IsInitListCopy Is this non-list-initialization resulting from a
4233/// list-initialization from {x} where x is the same
4234/// type as the entity?
4236 const InitializedEntity &Entity,
4237 const InitializationKind &Kind,
4238 MultiExprArg Args, QualType DestType,
4239 QualType DestArrayType,
4240 InitializationSequence &Sequence,
4241 bool IsListInit = false,
4242 bool IsInitListCopy = false) {
4243 assert(((!IsListInit && !IsInitListCopy) ||
4244 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4245 "IsListInit/IsInitListCopy must come with a single initializer list "
4246 "argument.");
4247 InitListExpr *ILE =
4248 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4249 MultiExprArg UnwrappedArgs =
4250 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4251
4252 // The type we're constructing needs to be complete.
4253 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4254 Sequence.setIncompleteTypeFailure(DestType);
4255 return;
4256 }
4257
4258 bool RequireActualConstructor =
4259 !(Entity.getKind() != InitializedEntity::EK_Base &&
4261 Entity.getKind() !=
4263
4264 // C++17 [dcl.init]p17:
4265 // - If the initializer expression is a prvalue and the cv-unqualified
4266 // version of the source type is the same class as the class of the
4267 // destination, the initializer expression is used to initialize the
4268 // destination object.
4269 // Per DR (no number yet), this does not apply when initializing a base
4270 // class or delegating to another constructor from a mem-initializer.
4271 // ObjC++: Lambda captured by the block in the lambda to block conversion
4272 // should avoid copy elision.
4273 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4274 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4275 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4276 // Convert qualifications if necessary.
4277 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4278 if (ILE)
4279 Sequence.RewrapReferenceInitList(DestType, ILE);
4280 return;
4281 }
4282
4283 const RecordType *DestRecordType = DestType->getAs<RecordType>();
4284 assert(DestRecordType && "Constructor initialization requires record type");
4285 CXXRecordDecl *DestRecordDecl
4286 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4287
4288 // Build the candidate set directly in the initialization sequence
4289 // structure, so that it will persist if we fail.
4290 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4291
4292 // Determine whether we are allowed to call explicit constructors or
4293 // explicit conversion operators.
4294 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4295 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4296
4297 // - Otherwise, if T is a class type, constructors are considered. The
4298 // applicable constructors are enumerated, and the best one is chosen
4299 // through overload resolution.
4300 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4301
4304 bool AsInitializerList = false;
4305
4306 // C++11 [over.match.list]p1, per DR1467:
4307 // When objects of non-aggregate type T are list-initialized, such that
4308 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4309 // according to the rules in this section, overload resolution selects
4310 // the constructor in two phases:
4311 //
4312 // - Initially, the candidate functions are the initializer-list
4313 // constructors of the class T and the argument list consists of the
4314 // initializer list as a single argument.
4315 if (IsListInit) {
4316 AsInitializerList = true;
4317
4318 // If the initializer list has no elements and T has a default constructor,
4319 // the first phase is omitted.
4320 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4322 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4323 CopyInitialization, AllowExplicit,
4324 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4325 }
4326
4327 // C++11 [over.match.list]p1:
4328 // - If no viable initializer-list constructor is found, overload resolution
4329 // is performed again, where the candidate functions are all the
4330 // constructors of the class T and the argument list consists of the
4331 // elements of the initializer list.
4333 AsInitializerList = false;
4335 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4336 Best, CopyInitialization, AllowExplicit,
4337 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4338 }
4339 if (Result) {
4340 Sequence.SetOverloadFailure(
4343 Result);
4344
4345 if (Result != OR_Deleted)
4346 return;
4347 }
4348
4349 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4350
4351 // In C++17, ResolveConstructorOverload can select a conversion function
4352 // instead of a constructor.
4353 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4354 // Add the user-defined conversion step that calls the conversion function.
4355 QualType ConvType = CD->getConversionType();
4356 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4357 "should not have selected this conversion function");
4358 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4359 HadMultipleCandidates);
4360 if (!S.Context.hasSameType(ConvType, DestType))
4361 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4362 if (IsListInit)
4363 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4364 return;
4365 }
4366
4367 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4368 if (Result != OR_Deleted) {
4369 // C++11 [dcl.init]p6:
4370 // If a program calls for the default initialization of an object
4371 // of a const-qualified type T, T shall be a class type with a
4372 // user-provided default constructor.
4373 // C++ core issue 253 proposal:
4374 // If the implicit default constructor initializes all subobjects, no
4375 // initializer should be required.
4376 // The 253 proposal is for example needed to process libstdc++ headers
4377 // in 5.x.
4378 if (Kind.getKind() == InitializationKind::IK_Default &&
4379 Entity.getType().isConstQualified()) {
4380 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4381 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4383 return;
4384 }
4385 }
4386
4387 // C++11 [over.match.list]p1:
4388 // In copy-list-initialization, if an explicit constructor is chosen, the
4389 // initializer is ill-formed.
4390 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4392 return;
4393 }
4394 }
4395
4396 // [class.copy.elision]p3:
4397 // In some copy-initialization contexts, a two-stage overload resolution
4398 // is performed.
4399 // If the first overload resolution selects a deleted function, we also
4400 // need the initialization sequence to decide whether to perform the second
4401 // overload resolution.
4402 // For deleted functions in other contexts, there is no need to get the
4403 // initialization sequence.
4404 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4405 return;
4406
4407 // Add the constructor initialization step. Any cv-qualification conversion is
4408 // subsumed by the initialization.
4410 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4411 IsListInit | IsInitListCopy, AsInitializerList);
4412}
4413
4414static bool
4417 QualType &SourceType,
4418 QualType &UnqualifiedSourceType,
4419 QualType UnqualifiedTargetType,
4420 InitializationSequence &Sequence) {
4421 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4422 S.Context.OverloadTy) {
4423 DeclAccessPair Found;
4424 bool HadMultipleCandidates = false;
4425 if (FunctionDecl *Fn
4427 UnqualifiedTargetType,
4428 false, Found,
4429 &HadMultipleCandidates)) {
4430 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4431 HadMultipleCandidates);
4432 SourceType = Fn->getType();
4433 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4434 } else if (!UnqualifiedTargetType->isRecordType()) {
4436 return true;
4437 }
4438 }
4439 return false;
4440}
4441
4443 const InitializedEntity &Entity,
4444 const InitializationKind &Kind,
4446 QualType cv1T1, QualType T1,
4447 Qualifiers T1Quals,
4448 QualType cv2T2, QualType T2,
4449 Qualifiers T2Quals,
4450 InitializationSequence &Sequence,
4451 bool TopLevelOfInitList);
4452
4453static void TryValueInitialization(Sema &S,
4454 const InitializedEntity &Entity,
4455 const InitializationKind &Kind,
4456 InitializationSequence &Sequence,
4457 InitListExpr *InitList = nullptr);
4458
4459/// Attempt list initialization of a reference.
4461 const InitializedEntity &Entity,
4462 const InitializationKind &Kind,
4463 InitListExpr *InitList,
4464 InitializationSequence &Sequence,
4465 bool TreatUnavailableAsInvalid) {
4466 // First, catch C++03 where this isn't possible.
4467 if (!S.getLangOpts().CPlusPlus11) {
4469 return;
4470 }
4471 // Can't reference initialize a compound literal.
4474 return;
4475 }
4476
4477 QualType DestType = Entity.getType();
4478 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4479 Qualifiers T1Quals;
4480 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4481
4482 // Reference initialization via an initializer list works thus:
4483 // If the initializer list consists of a single element that is
4484 // reference-related to the referenced type, bind directly to that element
4485 // (possibly creating temporaries).
4486 // Otherwise, initialize a temporary with the initializer list and
4487 // bind to that.
4488 if (InitList->getNumInits() == 1) {
4489 Expr *Initializer = InitList->getInit(0);
4491 Qualifiers T2Quals;
4492 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4493
4494 // If this fails, creating a temporary wouldn't work either.
4496 T1, Sequence))
4497 return;
4498
4499 SourceLocation DeclLoc = Initializer->getBeginLoc();
4500 Sema::ReferenceCompareResult RefRelationship
4501 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4502 if (RefRelationship >= Sema::Ref_Related) {
4503 // Try to bind the reference here.
4504 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4505 T1Quals, cv2T2, T2, T2Quals, Sequence,
4506 /*TopLevelOfInitList=*/true);
4507 if (Sequence)
4508 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4509 return;
4510 }
4511
4512 // Update the initializer if we've resolved an overloaded function.
4513 if (Sequence.step_begin() != Sequence.step_end())
4514 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4515 }
4516 // Perform address space compatibility check.
4517 QualType cv1T1IgnoreAS = cv1T1;
4518 if (T1Quals.hasAddressSpace()) {
4519 Qualifiers T2Quals;
4520 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4521 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4522 Sequence.SetFailed(
4524 return;
4525 }
4526 // Ignore address space of reference type at this point and perform address
4527 // space conversion after the reference binding step.
4528 cv1T1IgnoreAS =
4530 }
4531 // Not reference-related. Create a temporary and bind to that.
4532 InitializedEntity TempEntity =
4534
4535 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4536 TreatUnavailableAsInvalid);
4537 if (Sequence) {
4538 if (DestType->isRValueReferenceType() ||
4539 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4540 if (S.getLangOpts().CPlusPlus20 &&
4541 isa<IncompleteArrayType>(T1->getUnqualifiedDesugaredType()) &&
4542 DestType->isRValueReferenceType()) {
4543 // C++20 [dcl.init.list]p3.10:
4544 // List-initialization of an object or reference of type T is defined as
4545 // follows:
4546 // ..., unless T is “reference to array of unknown bound of U”, in which
4547 // case the type of the prvalue is the type of x in the declaration U
4548 // x[] H, where H is the initializer list.
4550 }
4551 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4552 /*BindingTemporary=*/true);
4553 if (T1Quals.hasAddressSpace())
4555 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4556 } else
4557 Sequence.SetFailed(
4559 }
4560}
4561
4562/// Attempt list initialization (C++0x [dcl.init.list])
4564 const InitializedEntity &Entity,
4565 const InitializationKind &Kind,
4566 InitListExpr *InitList,
4567 InitializationSequence &Sequence,
4568 bool TreatUnavailableAsInvalid) {
4569 QualType DestType = Entity.getType();
4570
4571 // C++ doesn't allow scalar initialization with more than one argument.
4572 // But C99 complex numbers are scalars and it makes sense there.
4573 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4574 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4576 return;
4577 }
4578 if (DestType->isReferenceType()) {
4579 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4580 TreatUnavailableAsInvalid);
4581 return;
4582 }
4583
4584 if (DestType->isRecordType() &&
4585 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4586 Sequence.setIncompleteTypeFailure(DestType);
4587 return;
4588 }
4589
4590 // C++20 [dcl.init.list]p3:
4591 // - If the braced-init-list contains a designated-initializer-list, T shall
4592 // be an aggregate class. [...] Aggregate initialization is performed.
4593 //
4594 // We allow arrays here too in order to support array designators.
4595 //
4596 // FIXME: This check should precede the handling of reference initialization.
4597 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4598 // as a tentative DR resolution.
4599 bool IsDesignatedInit = InitList->hasDesignatedInit();
4600 if (!DestType->isAggregateType() && IsDesignatedInit) {
4601 Sequence.SetFailed(
4603 return;
4604 }
4605
4606 // C++11 [dcl.init.list]p3, per DR1467:
4607 // - If T is a class type and the initializer list has a single element of
4608 // type cv U, where U is T or a class derived from T, the object is
4609 // initialized from that element (by copy-initialization for
4610 // copy-list-initialization, or by direct-initialization for
4611 // direct-list-initialization).
4612 // - Otherwise, if T is a character array and the initializer list has a
4613 // single element that is an appropriately-typed string literal
4614 // (8.5.2 [dcl.init.string]), initialization is performed as described
4615 // in that section.
4616 // - Otherwise, if T is an aggregate, [...] (continue below).
4617 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
4618 !IsDesignatedInit) {
4619 if (DestType->isRecordType()) {
4620 QualType InitType = InitList->getInit(0)->getType();
4621 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4622 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4623 Expr *InitListAsExpr = InitList;
4624 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4625 DestType, Sequence,
4626 /*InitListSyntax*/false,
4627 /*IsInitListCopy*/true);
4628 return;
4629 }
4630 }
4631 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4632 Expr *SubInit[1] = {InitList->getInit(0)};
4633 if (!isa<VariableArrayType>(DestAT) &&
4634 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4635 InitializationKind SubKind =
4636 Kind.getKind() == InitializationKind::IK_DirectList
4637 ? InitializationKind::CreateDirect(Kind.getLocation(),
4638 InitList->getLBraceLoc(),
4639 InitList->getRBraceLoc())
4640 : Kind;
4641 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4642 /*TopLevelOfInitList*/ true,
4643 TreatUnavailableAsInvalid);
4644
4645 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4646 // the element is not an appropriately-typed string literal, in which
4647 // case we should proceed as in C++11 (below).
4648 if (Sequence) {
4649 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4650 return;
4651 }
4652 }
4653 }
4654 }
4655
4656 // C++11 [dcl.init.list]p3:
4657 // - If T is an aggregate, aggregate initialization is performed.
4658 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4659 (S.getLangOpts().CPlusPlus11 &&
4660 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
4661 if (S.getLangOpts().CPlusPlus11) {
4662 // - Otherwise, if the initializer list has no elements and T is a
4663 // class type with a default constructor, the object is
4664 // value-initialized.
4665 if (InitList->getNumInits() == 0) {
4666 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4667 if (S.LookupDefaultConstructor(RD)) {
4668 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4669 return;
4670 }
4671 }
4672
4673 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4674 // an initializer_list object constructed [...]
4675 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4676 TreatUnavailableAsInvalid))
4677 return;
4678
4679 // - Otherwise, if T is a class type, constructors are considered.
4680 Expr *InitListAsExpr = InitList;
4681 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4682 DestType, Sequence, /*InitListSyntax*/true);
4683 } else
4685 return;
4686 }
4687
4688 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4689 InitList->getNumInits() == 1) {
4690 Expr *E = InitList->getInit(0);
4691
4692 // - Otherwise, if T is an enumeration with a fixed underlying type,
4693 // the initializer-list has a single element v, and the initialization
4694 // is direct-list-initialization, the object is initialized with the
4695 // value T(v); if a narrowing conversion is required to convert v to
4696 // the underlying type of T, the program is ill-formed.
4697 auto *ET = DestType->getAs<EnumType>();
4698 if (S.getLangOpts().CPlusPlus17 &&
4699 Kind.getKind() == InitializationKind::IK_DirectList &&
4700 ET && ET->getDecl()->isFixed() &&
4701 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4703 E->getType()->isFloatingType())) {
4704 // There are two ways that T(v) can work when T is an enumeration type.
4705 // If there is either an implicit conversion sequence from v to T or
4706 // a conversion function that can convert from v to T, then we use that.
4707 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4708 // type, it is converted to the enumeration type via its underlying type.
4709 // There is no overlap possible between these two cases (except when the
4710 // source value is already of the destination type), and the first
4711 // case is handled by the general case for single-element lists below.
4713 ICS.setStandard();
4715 if (!E->isPRValue())
4717 // If E is of a floating-point type, then the conversion is ill-formed
4718 // due to narrowing, but go through the motions in order to produce the
4719 // right diagnostic.
4723 ICS.Standard.setFromType(E->getType());
4724 ICS.Standard.setToType(0, E->getType());
4725 ICS.Standard.setToType(1, DestType);
4726 ICS.Standard.setToType(2, DestType);
4727 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4728 /*TopLevelOfInitList*/true);
4729 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4730 return;
4731 }
4732
4733 // - Otherwise, if the initializer list has a single element of type E
4734 // [...references are handled above...], the object or reference is
4735 // initialized from that element (by copy-initialization for
4736 // copy-list-initialization, or by direct-initialization for
4737 // direct-list-initialization); if a narrowing conversion is required
4738 // to convert the element to T, the program is ill-formed.
4739 //
4740 // Per core-24034, this is direct-initialization if we were performing
4741 // direct-list-initialization and copy-initialization otherwise.
4742 // We can't use InitListChecker for this, because it always performs
4743 // copy-initialization. This only matters if we might use an 'explicit'
4744 // conversion operator, or for the special case conversion of nullptr_t to
4745 // bool, so we only need to handle those cases.
4746 //
4747 // FIXME: Why not do this in all cases?
4748 Expr *Init = InitList->getInit(0);
4749 if (Init->getType()->isRecordType() ||
4750 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
4751 InitializationKind SubKind =
4752 Kind.getKind() == InitializationKind::IK_DirectList
4753 ? InitializationKind::CreateDirect(Kind.getLocation(),
4754 InitList->getLBraceLoc(),
4755 InitList->getRBraceLoc())
4756 : Kind;
4757 Expr *SubInit[1] = { Init };
4758 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4759 /*TopLevelOfInitList*/true,
4760 TreatUnavailableAsInvalid);
4761 if (Sequence)
4762 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4763 return;
4764 }
4765 }
4766
4767 InitListChecker CheckInitList(S, Entity, InitList,
4768 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4769 if (CheckInitList.HadError()) {
4771 return;
4772 }
4773
4774 // Add the list initialization step with the built init list.
4775 Sequence.AddListInitializationStep(DestType);
4776}
4777
4778/// Try a reference initialization that involves calling a conversion
4779/// function.
4781 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4782 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4783 InitializationSequence &Sequence) {
4784 QualType DestType = Entity.getType();
4785 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4786 QualType T1 = cv1T1.getUnqualifiedType();
4787 QualType cv2T2 = Initializer->getType();
4788 QualType T2 = cv2T2.getUnqualifiedType();
4789
4790 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
4791 "Must have incompatible references when binding via conversion");
4792
4793 // Build the candidate set directly in the initialization sequence
4794 // structure, so that it will persist if we fail.
4795 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4797
4798 // Determine whether we are allowed to call explicit conversion operators.
4799 // Note that none of [over.match.copy], [over.match.conv], nor
4800 // [over.match.ref] permit an explicit constructor to be chosen when
4801 // initializing a reference, not even for direct-initialization.
4802 bool AllowExplicitCtors = false;
4803 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4804
4805 const RecordType *T1RecordType = nullptr;
4806 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4807 S.isCompleteType(Kind.getLocation(), T1)) {
4808 // The type we're converting to is a class type. Enumerate its constructors
4809 // to see if there is a suitable conversion.
4810 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4811
4812 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4813 auto Info = getConstructorInfo(D);
4814 if (!Info.Constructor)
4815 continue;
4816
4817 if (!Info.Constructor->isInvalidDecl() &&
4818 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
4819 if (Info.ConstructorTmpl)
4821 Info.ConstructorTmpl, Info.FoundDecl,
4822 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4823 /*SuppressUserConversions=*/true,
4824 /*PartialOverloading*/ false, AllowExplicitCtors);
4825 else
4827 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4828 /*SuppressUserConversions=*/true,
4829 /*PartialOverloading*/ false, AllowExplicitCtors);
4830 }
4831 }
4832 }
4833 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4834 return OR_No_Viable_Function;
4835
4836 const RecordType *T2RecordType = nullptr;
4837 if ((T2RecordType = T2->getAs<RecordType>()) &&
4838 S.isCompleteType(Kind.getLocation(), T2)) {
4839 // The type we're converting from is a class type, enumerate its conversion
4840 // functions.
4841 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4842
4843 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4844 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4845 NamedDecl *D = *I;
4846 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4847 if (isa<UsingShadowDecl>(D))
4848 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4849
4850 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4851 CXXConversionDecl *Conv;
4852 if (ConvTemplate)
4853 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4854 else
4855 Conv = cast<CXXConversionDecl>(D);
4856
4857 // If the conversion function doesn't return a reference type,
4858 // it can't be considered for this conversion unless we're allowed to
4859 // consider rvalues.
4860 // FIXME: Do we need to make sure that we only consider conversion
4861 // candidates with reference-compatible results? That might be needed to
4862 // break recursion.
4863 if ((AllowRValues ||
4865 if (ConvTemplate)
4867 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4868 CandidateSet,
4869 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4870 else
4872 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4873 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4874 }
4875 }
4876 }
4877 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4878 return OR_No_Viable_Function;
4879
4880 SourceLocation DeclLoc = Initializer->getBeginLoc();
4881
4882 // Perform overload resolution. If it fails, return the failed result.
4885 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4886 return Result;
4887
4888 FunctionDecl *Function = Best->Function;
4889 // This is the overload that will be used for this initialization step if we
4890 // use this initialization. Mark it as referenced.
4891 Function->setReferenced();
4892
4893 // Compute the returned type and value kind of the conversion.
4894 QualType cv3T3;
4895 if (isa<CXXConversionDecl>(Function))
4896 cv3T3 = Function->getReturnType();
4897 else
4898 cv3T3 = T1;
4899
4901 if (cv3T3->isLValueReferenceType())
4902 VK = VK_LValue;
4903 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4904 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4905 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4906
4907 // Add the user-defined conversion step.
4908 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4909 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4910 HadMultipleCandidates);
4911
4912 // Determine whether we'll need to perform derived-to-base adjustments or
4913 // other conversions.
4915 Sema::ReferenceCompareResult NewRefRelationship =
4916 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
4917
4918 // Add the final conversion sequence, if necessary.
4919 if (NewRefRelationship == Sema::Ref_Incompatible) {
4920 assert(!isa<CXXConstructorDecl>(Function) &&
4921 "should not have conversion after constructor");
4922
4924 ICS.setStandard();
4925 ICS.Standard = Best->FinalConversion;
4926 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4927
4928 // Every implicit conversion results in a prvalue, except for a glvalue
4929 // derived-to-base conversion, which we handle below.
4930 cv3T3 = ICS.Standard.getToType(2);
4931 VK = VK_PRValue;
4932 }
4933
4934 // If the converted initializer is a prvalue, its type T4 is adjusted to
4935 // type "cv1 T4" and the temporary materialization conversion is applied.
4936 //
4937 // We adjust the cv-qualifications to match the reference regardless of
4938 // whether we have a prvalue so that the AST records the change. In this
4939 // case, T4 is "cv3 T3".
4940 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4941 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4942 Sequence.AddQualificationConversionStep(cv1T4, VK);
4943 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
4944 VK = IsLValueRef ? VK_LValue : VK_XValue;
4945
4946 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4947 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4948 else if (RefConv & Sema::ReferenceConversions::ObjC)
4949 Sequence.AddObjCObjectConversionStep(cv1T1);
4950 else if (RefConv & Sema::ReferenceConversions::Function)
4951 Sequence.AddFunctionReferenceConversionStep(cv1T1);
4952 else if (RefConv & Sema::ReferenceConversions::Qualification) {
4953 if (!S.Context.hasSameType(cv1T4, cv1T1))
4954 Sequence.AddQualificationConversionStep(cv1T1, VK);
4955 }
4956
4957 return OR_Success;
4958}
4959
4961 const InitializedEntity &Entity,
4962 Expr *CurInitExpr);
4963
4964/// Attempt reference initialization (C++0x [dcl.init.ref])
4966 const InitializationKind &Kind,
4968 InitializationSequence &Sequence,
4969 bool TopLevelOfInitList) {
4970 QualType DestType = Entity.getType();
4971 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4972 Qualifiers T1Quals;
4973 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4975 Qualifiers T2Quals;
4976 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4977
4978 // If the initializer is the address of an overloaded function, try
4979 // to resolve the overloaded function. If all goes well, T2 is the
4980 // type of the resulting function.
4982 T1, Sequence))
4983 return;
4984
4985 // Delegate everything else to a subfunction.
4986 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4987 T1Quals, cv2T2, T2, T2Quals, Sequence,
4988 TopLevelOfInitList);
4989}
4990
4991/// Determine whether an expression is a non-referenceable glvalue (one to
4992/// which a reference can never bind). Attempting to bind a reference to
4993/// such a glvalue will always create a temporary.
4995 return E->refersToBitField() || E->refersToVectorElement() ||
4997}
4998
4999/// Reference initialization without resolving overloaded functions.
5000///
5001/// We also can get here in C if we call a builtin which is declared as
5002/// a function with a parameter of reference type (such as __builtin_va_end()).
5004 const InitializedEntity &Entity,
5005 const InitializationKind &Kind,
5007 QualType cv1T1, QualType T1,
5008 Qualifiers T1Quals,
5009 QualType cv2T2, QualType T2,
5010 Qualifiers T2Quals,
5011 InitializationSequence &Sequence,
5012 bool TopLevelOfInitList) {
5013 QualType DestType = Entity.getType();
5014 SourceLocation DeclLoc = Initializer->getBeginLoc();
5015
5016 // Compute some basic properties of the types and the initializer.
5017 bool isLValueRef = DestType->isLValueReferenceType();
5018 bool isRValueRef = !isLValueRef;
5019 Expr::Classification InitCategory = Initializer->Classify(S.Context);
5020
5022 Sema::ReferenceCompareResult RefRelationship =
5023 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
5024
5025 // C++0x [dcl.init.ref]p5:
5026 // A reference to type "cv1 T1" is initialized by an expression of type
5027 // "cv2 T2" as follows:
5028 //
5029 // - If the reference is an lvalue reference and the initializer
5030 // expression
5031 // Note the analogous bullet points for rvalue refs to functions. Because
5032 // there are no function rvalues in C++, rvalue refs to functions are treated
5033 // like lvalue refs.
5034 OverloadingResult ConvOvlResult = OR_Success;
5035 bool T1Function = T1->isFunctionType();
5036 if (isLValueRef || T1Function) {
5037 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
5038 (RefRelationship == Sema::Ref_Compatible ||
5039 (Kind.isCStyleOrFunctionalCast() &&
5040 RefRelationship == Sema::Ref_Related))) {
5041 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5042 // reference-compatible with "cv2 T2," or
5043 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5044 Sema::ReferenceConversions::ObjC)) {
5045 // If we're converting the pointee, add any qualifiers first;
5046 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5047 if (RefConv & (Sema::ReferenceConversions::Qualification))
5049 S.Context.getQualifiedType(T2, T1Quals),
5050 Initializer->getValueKind());
5051 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5052 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
5053 else
5054 Sequence.AddObjCObjectConversionStep(cv1T1);
5055 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5056 // Perform a (possibly multi-level) qualification conversion.
5057 Sequence.AddQualificationConversionStep(cv1T1,
5058 Initializer->getValueKind());
5059 } else if (RefConv & Sema::ReferenceConversions::Function) {
5060 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5061 }
5062
5063 // We only create a temporary here when binding a reference to a
5064 // bit-field or vector element. Those cases are't supposed to be
5065 // handled by this bullet, but the outcome is the same either way.
5066 Sequence.AddReferenceBindingStep(cv1T1, false);
5067 return;
5068 }
5069
5070 // - has a class type (i.e., T2 is a class type), where T1 is not
5071 // reference-related to T2, and can be implicitly converted to an
5072 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5073 // with "cv3 T3" (this conversion is selected by enumerating the
5074 // applicable conversion functions (13.3.1.6) and choosing the best
5075 // one through overload resolution (13.3)),
5076 // If we have an rvalue ref to function type here, the rhs must be
5077 // an rvalue. DR1287 removed the "implicitly" here.
5078 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5079 (isLValueRef || InitCategory.isRValue())) {
5080 if (S.getLangOpts().CPlusPlus) {
5081 // Try conversion functions only for C++.
5082 ConvOvlResult = TryRefInitWithConversionFunction(
5083 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5084 /*IsLValueRef*/ isLValueRef, Sequence);
5085 if (ConvOvlResult == OR_Success)
5086 return;
5087 if (ConvOvlResult != OR_No_Viable_Function)
5088 Sequence.SetOverloadFailure(
5090 ConvOvlResult);
5091 } else {
5092 ConvOvlResult = OR_No_Viable_Function;
5093 }
5094 }
5095 }
5096
5097 // - Otherwise, the reference shall be an lvalue reference to a
5098 // non-volatile const type (i.e., cv1 shall be const), or the reference
5099 // shall be an rvalue reference.
5100 // For address spaces, we interpret this to mean that an addr space
5101 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5102 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5103 T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5106 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5107 Sequence.SetOverloadFailure(
5109 ConvOvlResult);
5110 else if (!InitCategory.isLValue())
5111 Sequence.SetFailed(
5112 T1Quals.isAddressSpaceSupersetOf(T2Quals)
5116 else {
5118 switch (RefRelationship) {
5120 if (Initializer->refersToBitField())
5123 else if (Initializer->refersToVectorElement())
5126 else if (Initializer->refersToMatrixElement())
5129 else
5130 llvm_unreachable("unexpected kind of compatible initializer");
5131 break;
5132 case Sema::Ref_Related:
5134 break;
5138 break;
5139 }
5140 Sequence.SetFailed(FK);
5141 }
5142 return;
5143 }
5144
5145 // - If the initializer expression
5146 // - is an
5147 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5148 // [1z] rvalue (but not a bit-field) or
5149 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5150 //
5151 // Note: functions are handled above and below rather than here...
5152 if (!T1Function &&
5153 (RefRelationship == Sema::Ref_Compatible ||
5154 (Kind.isCStyleOrFunctionalCast() &&
5155 RefRelationship == Sema::Ref_Related)) &&
5156 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5157 (InitCategory.isPRValue() &&
5158 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5159 T2->isArrayType())))) {
5160 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5161 if (InitCategory.isPRValue() && T2->isRecordType()) {
5162 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5163 // compiler the freedom to perform a copy here or bind to the
5164 // object, while C++0x requires that we bind directly to the
5165 // object. Hence, we always bind to the object without making an
5166 // extra copy. However, in C++03 requires that we check for the
5167 // presence of a suitable copy constructor:
5168 //
5169 // The constructor that would be used to make the copy shall
5170 // be callable whether or not the copy is actually done.
5171 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5172 Sequence.AddExtraneousCopyToTemporary(cv2T2);
5173 else if (S.getLangOpts().CPlusPlus11)
5175 }
5176
5177 // C++1z [dcl.init.ref]/5.2.1.2:
5178 // If the converted initializer is a prvalue, its type T4 is adjusted
5179 // to type "cv1 T4" and the temporary materialization conversion is
5180 // applied.
5181 // Postpone address space conversions to after the temporary materialization
5182 // conversion to allow creating temporaries in the alloca address space.
5183 auto T1QualsIgnoreAS = T1Quals;
5184 auto T2QualsIgnoreAS = T2Quals;
5185 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5186 T1QualsIgnoreAS.removeAddressSpace();
5187 T2QualsIgnoreAS.removeAddressSpace();
5188 }
5189 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
5190 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5191 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5192 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5193 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5194 // Add addr space conversion if required.
5195 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5196 auto T4Quals = cv1T4.getQualifiers();
5197 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5198 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5199 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5200 cv1T4 = cv1T4WithAS;
5201 }
5202
5203 // In any case, the reference is bound to the resulting glvalue (or to
5204 // an appropriate base class subobject).
5205 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5206 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5207 else if (RefConv & Sema::ReferenceConversions::ObjC)
5208 Sequence.AddObjCObjectConversionStep(cv1T1);
5209 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5210 if (!S.Context.hasSameType(cv1T4, cv1T1))
5211 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5212 }
5213 return;
5214 }
5215
5216 // - has a class type (i.e., T2 is a class type), where T1 is not
5217 // reference-related to T2, and can be implicitly converted to an
5218 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5219 // where "cv1 T1" is reference-compatible with "cv3 T3",
5220 //
5221 // DR1287 removes the "implicitly" here.
5222 if (T2->isRecordType()) {
5223 if (RefRelationship == Sema::Ref_Incompatible) {
5224 ConvOvlResult = TryRefInitWithConversionFunction(
5225 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5226 /*IsLValueRef*/ isLValueRef, Sequence);
5227 if (ConvOvlResult)
5228 Sequence.SetOverloadFailure(
5230 ConvOvlResult);
5231
5232 return;
5233 }
5234
5235 if (RefRelationship == Sema::Ref_Compatible &&
5236 isRValueRef && InitCategory.isLValue()) {
5237 Sequence.SetFailed(
5239 return;
5240 }
5241
5243 return;
5244 }
5245
5246 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5247 // from the initializer expression using the rules for a non-reference
5248 // copy-initialization (8.5). The reference is then bound to the
5249 // temporary. [...]
5250
5251 // Ignore address space of reference type at this point and perform address
5252 // space conversion after the reference binding step.
5253 QualType cv1T1IgnoreAS =
5254 T1Quals.hasAddressSpace()
5256 : cv1T1;
5257
5258 InitializedEntity TempEntity =
5260
5261 // FIXME: Why do we use an implicit conversion here rather than trying
5262 // copy-initialization?
5264 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5265 /*SuppressUserConversions=*/false,
5266 Sema::AllowedExplicit::None,
5267 /*FIXME:InOverloadResolution=*/false,
5268 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5269 /*AllowObjCWritebackConversion=*/false);
5270
5271 if (ICS.isBad()) {
5272 // FIXME: Use the conversion function set stored in ICS to turn
5273 // this into an overloading ambiguity diagnostic. However, we need
5274 // to keep that set as an OverloadCandidateSet rather than as some
5275 // other kind of set.
5276 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5277 Sequence.SetOverloadFailure(
5279 ConvOvlResult);
5280 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5282 else
5284 return;
5285 } else {
5286 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType(),
5287 TopLevelOfInitList);
5288 }
5289
5290 // [...] If T1 is reference-related to T2, cv1 must be the
5291 // same cv-qualification as, or greater cv-qualification
5292 // than, cv2; otherwise, the program is ill-formed.
5293 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5294 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5295 if (RefRelationship == Sema::Ref_Related &&
5296 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5297 !T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5299 return;
5300 }
5301
5302 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5303 // reference, the initializer expression shall not be an lvalue.
5304 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5305 InitCategory.isLValue()) {
5306 Sequence.SetFailed(
5308 return;
5309 }
5310
5311 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5312
5313 if (T1Quals.hasAddressSpace()) {
5315 LangAS::Default)) {
5316 Sequence.SetFailed(
5318 return;
5319 }
5320 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5321 : VK_XValue);
5322 }
5323}
5324
5325/// Attempt character array initialization from a string literal
5326/// (C++ [dcl.init.string], C99 6.7.8).
5328 const InitializedEntity &Entity,
5329 const InitializationKind &Kind,
5331 InitializationSequence &Sequence) {
5332 Sequence.AddStringInitStep(Entity.getType());
5333}
5334
5335/// Attempt value initialization (C++ [dcl.init]p7).
5337 const InitializedEntity &Entity,
5338 const InitializationKind &Kind,
5339 InitializationSequence &Sequence,
5340 InitListExpr *InitList) {
5341 assert((!InitList || InitList->getNumInits() == 0) &&
5342 "Shouldn't use value-init for non-empty init lists");
5343
5344 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5345 //
5346 // To value-initialize an object of type T means:
5347 QualType T = Entity.getType();
5348
5349 // -- if T is an array type, then each element is value-initialized;
5351
5352 if (const RecordType *RT = T->getAs<RecordType>()) {
5353 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5354 bool NeedZeroInitialization = true;
5355 // C++98:
5356 // -- if T is a class type (clause 9) with a user-declared constructor
5357 // (12.1), then the default constructor for T is called (and the
5358 // initialization is ill-formed if T has no accessible default
5359 // constructor);
5360 // C++11:
5361 // -- if T is a class type (clause 9) with either no default constructor
5362 // (12.1 [class.ctor]) or a default constructor that is user-provided
5363 // or deleted, then the object is default-initialized;
5364 //
5365 // Note that the C++11 rule is the same as the C++98 rule if there are no
5366 // defaulted or deleted constructors, so we just use it unconditionally.
5368 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5369 NeedZeroInitialization = false;
5370
5371 // -- if T is a (possibly cv-qualified) non-union class type without a
5372 // user-provided or deleted default constructor, then the object is
5373 // zero-initialized and, if T has a non-trivial default constructor,
5374 // default-initialized;
5375 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5376 // constructor' part was removed by DR1507.
5377 if (NeedZeroInitialization)
5378 Sequence.AddZeroInitializationStep(Entity.getType());
5379
5380 // C++03:
5381 // -- if T is a non-union class type without a user-declared constructor,
5382 // then every non-static data member and base class component of T is
5383 // value-initialized;
5384 // [...] A program that calls for [...] value-initialization of an
5385 // entity of reference type is ill-formed.
5386 //
5387 // C++11 doesn't need this handling, because value-initialization does not
5388 // occur recursively there, and the implicit default constructor is
5389 // defined as deleted in the problematic cases.
5390 if (!S.getLangOpts().CPlusPlus11 &&
5391 ClassDecl->hasUninitializedReferenceMember()) {
5393 return;
5394 }
5395
5396 // If this is list-value-initialization, pass the empty init list on when
5397 // building the constructor call. This affects the semantics of a few
5398 // things (such as whether an explicit default constructor can be called).
5399 Expr *InitListAsExpr = InitList;
5400 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5401 bool InitListSyntax = InitList;
5402
5403 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5404 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5406 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5407 }
5408 }
5409
5410 Sequence.AddZeroInitializationStep(Entity.getType());
5411}
5412
5413/// Attempt default initialization (C++ [dcl.init]p6).
5415 const InitializedEntity &Entity,
5416 const InitializationKind &Kind,
5417 InitializationSequence &Sequence) {
5418 assert(Kind.getKind() == InitializationKind::IK_Default);
5419
5420 // C++ [dcl.init]p6:
5421 // To default-initialize an object of type T means:
5422 // - if T is an array type, each element is default-initialized;
5423 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5424
5425 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5426 // constructor for T is called (and the initialization is ill-formed if
5427 // T has no accessible default constructor);
5428 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5429 TryConstructorInitialization(S, Entity, Kind, std::nullopt, DestType,
5430 Entity.getType(), Sequence);
5431 return;
5432 }
5433
5434 // - otherwise, no initialization is performed.
5435
5436 // If a program calls for the default initialization of an object of
5437 // a const-qualified type T, T shall be a class type with a user-provided
5438 // default constructor.
5439 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5440 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5442 return;
5443 }
5444
5445 // If the destination type has a lifetime property, zero-initialize it.
5446 if (DestType.getQualifiers().hasObjCLifetime()) {
5447 Sequence.AddZeroInitializationStep(Entity.getType());
5448 return;
5449 }
5450}
5451
5453 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5454 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5455 ExprResult *Result = nullptr) {
5456 unsigned EntityIndexToProcess = 0;
5457 SmallVector<Expr *, 4> InitExprs;
5458 QualType ResultType;
5459 Expr *ArrayFiller = nullptr;
5460 FieldDecl *InitializedFieldInUnion = nullptr;
5461
5462 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5463 const InitializationKind &SubKind,
5464 Expr *Arg, Expr **InitExpr = nullptr) {
5466 S, SubEntity, SubKind, Arg ? MultiExprArg(Arg) : std::nullopt);
5467
5468 if (IS.Failed()) {
5469 if (!VerifyOnly) {
5470 IS.Diagnose(S, SubEntity, SubKind, Arg ? ArrayRef(Arg) : std::nullopt);
5471 } else {
5472 Sequence.SetFailed(
5474 }
5475
5476 return false;
5477 }
5478 if (!VerifyOnly) {
5479 ExprResult ER;
5480 ER = IS.Perform(S, SubEntity, SubKind,
5481 Arg ? MultiExprArg(Arg) : std::nullopt);
5482 if (InitExpr)
5483 *InitExpr = ER.get();
5484 else
5485 InitExprs.push_back(ER.get());
5486 }
5487 return true;
5488 };
5489
5490 if (const ArrayType *AT =
5491 S.getASTContext().getAsArrayType(Entity.getType())) {
5492 SmallVector<InitializedEntity, 4> ElementEntities;
5493 uint64_t ArrayLength;
5494 // C++ [dcl.init]p16.5
5495 // if the destination type is an array, the object is initialized as
5496 // follows. Let x1, . . . , xk be the elements of the expression-list. If
5497 // the destination type is an array of unknown bound, it is defined as
5498 // having k elements.
5499 if (const ConstantArrayType *CAT =
5501 ArrayLength = CAT->getZExtSize();
5502 ResultType = Entity.getType();
5503 } else if (const VariableArrayType *VAT =
5505 // Braced-initialization of variable array types is not allowed, even if
5506 // the size is greater than or equal to the number of args, so we don't
5507 // allow them to be initialized via parenthesized aggregate initialization
5508 // either.
5509 const Expr *SE = VAT->getSizeExpr();
5510 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
5511 << SE->getSourceRange();
5512 return;
5513 } else {
5514 assert(isa<IncompleteArrayType>(Entity.getType()));
5515 ArrayLength = Args.size();
5516 }
5517 EntityIndexToProcess = ArrayLength;
5518
5519 // ...the ith array element is copy-initialized with xi for each
5520 // 1 <= i <= k
5521 for (Expr *E : Args) {
5523 S.getASTContext(), EntityIndexToProcess, Entity);
5525 E->getExprLoc(), /*isDirectInit=*/false, E);
5526 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5527 return;
5528 }
5529 // ...and value-initialized for each k < i <= n;
5530 if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {
5532 S.getASTContext(), Args.size(), Entity);
5534 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5535 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
5536 return;
5537 }
5538
5539 if (ResultType.isNull()) {
5540 ResultType = S.Context.getConstantArrayType(
5541 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
5542 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 0);
5543 }
5544 } else if (auto *RT = Entity.getType()->getAs<RecordType>()) {
5545 bool IsUnion = RT->isUnionType();
5546 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5547 if (RD->isInvalidDecl()) {
5548 // Exit early to avoid confusion when processing members.
5549 // We do the same for braced list initialization in
5550 // `CheckStructUnionTypes`.
5551 Sequence.SetFailed(
5553 return;
5554 }
5555
5556 if (!IsUnion) {
5557 for (const CXXBaseSpecifier &Base : RD->bases()) {
5559 S.getASTContext(), &Base, false, &Entity);
5560 if (EntityIndexToProcess < Args.size()) {
5561 // C++ [dcl.init]p16.6.2.2.
5562 // ...the object is initialized is follows. Let e1, ..., en be the
5563 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
5564 // the elements of the expression-list...The element ei is
5565 // copy-initialized with xi for 1 <= i <= k.
5566 Expr *E = Args[EntityIndexToProcess];
5568 E->getExprLoc(), /*isDirectInit=*/false, E);
5569 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5570 return;
5571 } else {
5572 // We've processed all of the args, but there are still base classes
5573 // that have to be initialized.
5574 // C++ [dcl.init]p17.6.2.2
5575 // The remaining elements...otherwise are value initialzed
5577 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
5578 /*IsImplicit=*/true);
5579 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5580 return;
5581 }
5582 EntityIndexToProcess++;
5583 }
5584 }
5585
5586 for (FieldDecl *FD : RD->fields()) {
5587 // Unnamed bitfields should not be initialized at all, either with an arg
5588 // or by default.
5589 if (FD->isUnnamedBitField())
5590 continue;
5591
5592 InitializedEntity SubEntity =
5594
5595 if (EntityIndexToProcess < Args.size()) {
5596 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
5597 Expr *E = Args[EntityIndexToProcess];
5598
5599 // Incomplete array types indicate flexible array members. Do not allow
5600 // paren list initializations of structs with these members, as GCC
5601 // doesn't either.
5602 if (FD->getType()->isIncompleteArrayType()) {
5603 if (!VerifyOnly) {
5604 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
5605 << SourceRange(E->getBeginLoc(), E->getEndLoc());
5606 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
5607 }
5608 Sequence.SetFailed(
5610 return;
5611 }
5612
5614 E->getExprLoc(), /*isDirectInit=*/false, E);
5615 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5616 return;
5617
5618 // Unions should have only one initializer expression, so we bail out
5619 // after processing the first field. If there are more initializers then
5620 // it will be caught when we later check whether EntityIndexToProcess is
5621 // less than Args.size();
5622 if (IsUnion) {
5623 InitializedFieldInUnion = FD;
5624 EntityIndexToProcess = 1;
5625 break;
5626 }
5627 } else {
5628 // We've processed all of the args, but there are still members that
5629 // have to be initialized.
5630 if (FD->hasInClassInitializer()) {
5631 if (!VerifyOnly) {
5632 // C++ [dcl.init]p16.6.2.2
5633 // The remaining elements are initialized with their default
5634 // member initializers, if any
5636 Kind.getParenOrBraceRange().getEnd(), FD);
5637 if (DIE.isInvalid())
5638 return;
5639 S.checkInitializerLifetime(SubEntity, DIE.get());
5640 InitExprs.push_back(DIE.get());
5641 }
5642 } else {
5643 // C++ [dcl.init]p17.6.2.2
5644 // The remaining elements...otherwise are value initialzed
5645 if (FD->getType()->isReferenceType()) {
5646 Sequence.SetFailed(
5648 if (!VerifyOnly) {
5649 SourceRange SR = Kind.getParenOrBraceRange();
5650 S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
5651 << FD->getType() << SR;
5652 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
5653 }
5654 return;
5655 }
5657 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5658 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5659 return;
5660 }
5661 }
5662 EntityIndexToProcess++;
5663 }
5664 ResultType = Entity.getType();
5665 }
5666
5667 // Not all of the args have been processed, so there must've been more args
5668 // than were required to initialize the element.
5669 if (EntityIndexToProcess < Args.size()) {
5671 if (!VerifyOnly) {
5672 QualType T = Entity.getType();
5673 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4;
5674 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
5675 Args.back()->getEndLoc());
5676 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5677 << InitKind << ExcessInitSR;
5678 }
5679 return;
5680 }
5681
5682 if (VerifyOnly) {
5684 Sequence.AddParenthesizedListInitStep(Entity.getType());
5685 } else if (Result) {
5686 SourceRange SR = Kind.getParenOrBraceRange();
5687 auto *CPLIE = CXXParenListInitExpr::Create(
5688 S.getASTContext(), InitExprs, ResultType, Args.size(),
5689 Kind.getLocation(), SR.getBegin(), SR.getEnd());
5690 if (ArrayFiller)
5691 CPLIE->setArrayFiller(ArrayFiller);
5692 if (InitializedFieldInUnion)
5693 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
5694 *Result = CPLIE;
5695 S.Diag(Kind.getLocation(),
5696 diag::warn_cxx17_compat_aggregate_init_paren_list)
5697 << Kind.getLocation() << SR << ResultType;
5698 }
5699}
5700
5701/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
5702/// which enumerates all conversion functions and performs overload resolution
5703/// to select the best.
5705 QualType DestType,
5706 const InitializationKind &Kind,
5708 InitializationSequence &Sequence,
5709 bool TopLevelOfInitList) {
5710 assert(!DestType->isReferenceType() && "References are handled elsewhere");
5711 QualType SourceType = Initializer->getType();
5712 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
5713 "Must have a class type to perform a user-defined conversion");
5714
5715 // Build the candidate set directly in the initialization sequence
5716 // structure, so that it will persist if we fail.
5717 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5719 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
5720
5721 // Determine whether we are allowed to call explicit constructors or
5722 // explicit conversion operators.
5723 bool AllowExplicit = Kind.AllowExplicit();
5724
5725 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5726 // The type we're converting to is a class type. Enumerate its constructors
5727 // to see if there is a suitable conversion.
5728 CXXRecordDecl *DestRecordDecl
5729 = cast<CXXRecordDecl>(DestRecordType->getDecl());
5730
5731 // Try to complete the type we're converting to.
5732 if (S.isCompleteType(Kind.getLocation(), DestType)) {
5733 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
5734 auto Info = getConstructorInfo(D);
5735 if (!Info.Constructor)
5736 continue;
5737
5738 if (!Info.Constructor->isInvalidDecl() &&
5739 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5740 if (Info.ConstructorTmpl)
5742 Info.ConstructorTmpl, Info.FoundDecl,
5743 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5744 /*SuppressUserConversions=*/true,
5745 /*PartialOverloading*/ false, AllowExplicit);
5746 else
5747 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
5748 Initializer, CandidateSet,
5749 /*SuppressUserConversions=*/true,
5750 /*PartialOverloading*/ false, AllowExplicit);
5751 }
5752 }
5753 }
5754 }
5755
5756 SourceLocation DeclLoc = Initializer->getBeginLoc();
5757
5758 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5759 // The type we're converting from is a class type, enumerate its conversion
5760 // functions.
5761
5762 // We can only enumerate the conversion functions for a complete type; if
5763 // the type isn't complete, simply skip this step.
5764 if (S.isCompleteType(DeclLoc, SourceType)) {
5765 CXXRecordDecl *SourceRecordDecl
5766 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
5767
5768 const auto &Conversions =
5769 SourceRecordDecl->getVisibleConversionFunctions();
5770 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5771 NamedDecl *D = *I;
5772 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5773 if (isa<UsingShadowDecl>(D))
5774 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5775
5776 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5777 CXXConversionDecl *Conv;
5778 if (ConvTemplate)
5779 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5780 else
5781 Conv = cast<CXXConversionDecl>(D);
5782
5783 if (ConvTemplate)
5785 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5786 CandidateSet, AllowExplicit, AllowExplicit);
5787 else
5788 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
5789 DestType, CandidateSet, AllowExplicit,
5790 AllowExplicit);
5791 }
5792 }
5793 }
5794
5795 // Perform overload resolution. If it fails, return the failed result.
5798 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5799 Sequence.SetOverloadFailure(
5801
5802 // [class.copy.elision]p3:
5803 // In some copy-initialization contexts, a two-stage overload resolution
5804 // is performed.
5805 // If the first overload resolution selects a deleted function, we also
5806 // need the initialization sequence to decide whether to perform the second
5807 // overload resolution.
5808 if (!(Result == OR_Deleted &&
5809 Kind.getKind() == InitializationKind::IK_Copy))
5810 return;
5811 }
5812
5813 FunctionDecl *Function = Best->Function;
5814 Function->setReferenced();
5815 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5816
5817 if (isa<CXXConstructorDecl>(Function)) {
5818 // Add the user-defined conversion step. Any cv-qualification conversion is
5819 // subsumed by the initialization. Per DR5, the created temporary is of the
5820 // cv-unqualified type of the destination.
5821 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5822 DestType.getUnqualifiedType(),
5823 HadMultipleCandidates);
5824
5825 // C++14 and before:
5826 // - if the function is a constructor, the call initializes a temporary
5827 // of the cv-unqualified version of the destination type. The [...]
5828 // temporary [...] is then used to direct-initialize, according to the
5829 // rules above, the object that is the destination of the
5830 // copy-initialization.
5831 // Note that this just performs a simple object copy from the temporary.
5832 //
5833 // C++17:
5834 // - if the function is a constructor, the call is a prvalue of the
5835 // cv-unqualified version of the destination type whose return object
5836 // is initialized by the constructor. The call is used to
5837 // direct-initialize, according to the rules above, the object that
5838 // is the destination of the copy-initialization.
5839 // Therefore we need to do nothing further.
5840 //
5841 // FIXME: Mark this copy as extraneous.
5842 if (!S.getLangOpts().CPlusPlus17)
5843 Sequence.AddFinalCopy(DestType);
5844 else if (DestType.hasQualifiers())
5845 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5846 return;
5847 }
5848
5849 // Add the user-defined conversion step that calls the conversion function.
5850 QualType ConvType = Function->getCallResultType();
5851 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5852 HadMultipleCandidates);
5853
5854 if (ConvType->getAs<RecordType>()) {
5855 // The call is used to direct-initialize [...] the object that is the
5856 // destination of the copy-initialization.
5857 //
5858 // In C++17, this does not call a constructor if we enter /17.6.1:
5859 // - If the initializer expression is a prvalue and the cv-unqualified
5860 // version of the source type is the same as the class of the
5861 // destination [... do not make an extra copy]
5862 //
5863 // FIXME: Mark this copy as extraneous.
5864 if (!S.getLangOpts().CPlusPlus17 ||
5865 Function->getReturnType()->isReferenceType() ||
5866 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5867 Sequence.AddFinalCopy(DestType);
5868 else if (!S.Context.hasSameType(ConvType, DestType))
5869 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5870 return;
5871 }
5872
5873 // If the conversion following the call to the conversion function
5874 // is interesting, add it as a separate step.
5875 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5876 Best->FinalConversion.Third) {
5878 ICS.setStandard();
5879 ICS.Standard = Best->FinalConversion;
5880 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5881 }
5882}
5883
5884/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5885/// a function with a pointer return type contains a 'return false;' statement.
5886/// In C++11, 'false' is not a null pointer, so this breaks the build of any
5887/// code using that header.
5888///
5889/// Work around this by treating 'return false;' as zero-initializing the result
5890/// if it's used in a pointer-returning function in a system header.
5892 const InitializedEntity &Entity,
5893 const Expr *Init) {
5894 return S.getLangOpts().CPlusPlus11 &&
5896 Entity.getType()->isPointerType() &&
5897 isa<CXXBoolLiteralExpr>(Init) &&
5898 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5899 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5900}
5901
5902/// The non-zero enum values here are indexes into diagnostic alternatives.
5904
5905/// Determines whether this expression is an acceptable ICR source.
5907 bool isAddressOf, bool &isWeakAccess) {
5908 // Skip parens.
5909 e = e->IgnoreParens();
5910
5911 // Skip address-of nodes.
5912 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5913 if (op->getOpcode() == UO_AddrOf)
5914 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5915 isWeakAccess);
5916
5917 // Skip certain casts.
5918 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5919 switch (ce->getCastKind()) {
5920 case CK_Dependent:
5921 case CK_BitCast:
5922 case CK_LValueBitCast:
5923 case CK_NoOp:
5924 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
5925
5926 case CK_ArrayToPointerDecay:
5927 return IIK_nonscalar;
5928
5929 case CK_NullToPointer:
5930 return IIK_okay;
5931
5932 default:
5933 break;
5934 }
5935
5936 // If we have a declaration reference, it had better be a local variable.
5937 } else if (isa<DeclRefExpr>(e)) {
5938 // set isWeakAccess to true, to mean that there will be an implicit
5939 // load which requires a cleanup.
5941 isWeakAccess = true;
5942
5943 if (!isAddressOf) return IIK_nonlocal;
5944
5945 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5946 if (!var) return IIK_nonlocal;
5947
5948 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5949
5950 // If we have a conditional operator, check both sides.
5951 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5952 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5953 isWeakAccess))
5954 return iik;
5955
5956 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5957
5958 // These are never scalar.
5959 } else if (isa<ArraySubscriptExpr>(e)) {
5960 return IIK_nonscalar;
5961
5962 // Otherwise, it needs to be a null pointer constant.
5963 } else {
5966 }
5967
5968 return IIK_nonlocal;
5969}
5970
5971/// Check whether the given expression is a valid operand for an
5972/// indirect copy/restore.
5974 assert(src->isPRValue());
5975 bool isWeakAccess = false;
5976 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5977 // If isWeakAccess to true, there will be an implicit
5978 // load which requires a cleanup.
5979 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5981
5982 if (iik == IIK_okay) return;
5983
5984 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5985 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5986 << src->getSourceRange();
5987}
5988
5989/// Determine whether we have compatible array types for the
5990/// purposes of GNU by-copy array initialization.
5991static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5992 const ArrayType *Source) {
5993 // If the source and destination array types are equivalent, we're
5994 // done.
5995 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5996 return true;
5997
5998 // Make sure that the element types are the same.
5999 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
6000 return false;
6001
6002 // The only mismatch we allow is when the destination is an
6003 // incomplete array type and the source is a constant array type.
6004 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
6005}
6006
6008 InitializationSequence &Sequence,
6009 const InitializedEntity &Entity,
6010 Expr *Initializer) {
6011 bool ArrayDecay = false;
6012 QualType ArgType = Initializer->getType();
6013 QualType ArgPointee;
6014 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
6015 ArrayDecay = true;
6016 ArgPointee = ArgArrayType->getElementType();
6017 ArgType = S.Context.getPointerType(ArgPointee);
6018 }
6019
6020 // Handle write-back conversion.
6021 QualType ConvertedArgType;
6022 if (!S.ObjC().isObjCWritebackConversion(ArgType, Entity.getType(),
6023 ConvertedArgType))
6024 return false;
6025
6026 // We should copy unless we're passing to an argument explicitly
6027 // marked 'out'.
6028 bool ShouldCopy = true;
6029 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6030 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6031
6032 // Do we need an lvalue conversion?
6033 if (ArrayDecay || Initializer->isGLValue()) {
6035 ICS.setStandard();
6037
6038 QualType ResultType;
6039 if (ArrayDecay) {
6041 ResultType = S.Context.getPointerType(ArgPointee);
6042 } else {
6044 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
6045 }
6046
6047 Sequence.AddConversionSequenceStep(ICS, ResultType);
6048 }
6049
6050 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
6051 return true;
6052}
6053
6055 InitializationSequence &Sequence,
6056 QualType DestType,
6057 Expr *Initializer) {
6058 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6059 (!Initializer->isIntegerConstantExpr(S.Context) &&
6060 !Initializer->getType()->isSamplerT()))
6061 return false;
6062
6063 Sequence.AddOCLSamplerInitStep(DestType);
6064 return true;
6065}
6066
6068 return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
6069 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
6070}
6071
6073 InitializationSequence &Sequence,
6074 QualType DestType,
6075 Expr *Initializer) {
6076 if (!S.getLangOpts().OpenCL)
6077 return false;
6078
6079 //
6080 // OpenCL 1.2 spec, s6.12.10
6081 //
6082 // The event argument can also be used to associate the
6083 // async_work_group_copy with a previous async copy allowing
6084 // an event to be shared by multiple async copies; otherwise
6085 // event should be zero.
6086 //
6087 if (DestType->isEventT() || DestType->isQueueT()) {
6089 return false;
6090
6091 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6092 return true;
6093 }
6094
6095 // We should allow zero initialization for all types defined in the
6096 // cl_intel_device_side_avc_motion_estimation extension, except
6097 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6099 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
6100 DestType->isOCLIntelSubgroupAVCType()) {
6101 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6102 DestType->isOCLIntelSubgroupAVCMceResultType())
6103 return false;
6105 return false;
6106
6107 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6108 return true;
6109 }
6110
6111 return false;
6112}
6113
6115 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6116 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6117 : FailedOverloadResult(OR_Success),
6118 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6119 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6120 TreatUnavailableAsInvalid);
6121}
6122
6123/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6124/// address of that function, this returns true. Otherwise, it returns false.
6125static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6126 auto *DRE = dyn_cast<DeclRefExpr>(E);
6127 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6128 return false;
6129
6131 cast<FunctionDecl>(DRE->getDecl()));
6132}
6133
6134/// Determine whether we can perform an elementwise array copy for this kind
6135/// of entity.
6136static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6137 switch (Entity.getKind()) {
6139 // C++ [expr.prim.lambda]p24:
6140 // For array members, the array elements are direct-initialized in
6141 // increasing subscript order.
6142 return true;
6143
6145 // C++ [dcl.decomp]p1:
6146 // [...] each element is copy-initialized or direct-initialized from the
6147 // corresponding element of the assignment-expression [...]
6148 return isa<DecompositionDecl>(Entity.getDecl());
6149
6151 // C++ [class.copy.ctor]p14:
6152 // - if the member is an array, each element is direct-initialized with
6153 // the corresponding subobject of x
6154 return Entity.isImplicitMemberInitializer();
6155
6157 // All the above cases are intended to apply recursively, even though none
6158 // of them actually say that.
6159 if (auto *E = Entity.getParent())
6160 return canPerformArrayCopy(*E);
6161 break;
6162
6163 default:
6164 break;
6165 }
6166
6167 return false;
6168}
6169
6171 const InitializedEntity &Entity,
6172 const InitializationKind &Kind,
6173 MultiExprArg Args,
6174 bool TopLevelOfInitList,
6175 bool TreatUnavailableAsInvalid) {
6176 ASTContext &Context = S.Context;
6177
6178 // Eliminate non-overload placeholder types in the arguments. We
6179 // need to do this before checking whether types are dependent
6180 // because lowering a pseudo-object expression might well give us
6181 // something of dependent type.
6182 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6183 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6184 // FIXME: should we be doing this here?
6185 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
6186 if (result.isInvalid()) {
6188 return;
6189 }
6190 Args[I] = result.get();
6191 }
6192
6193 // C++0x [dcl.init]p16:
6194 // The semantics of initializers are as follows. The destination type is
6195 // the type of the object or reference being initialized and the source
6196 // type is the type of the initializer expression. The source type is not
6197 // defined when the initializer is a braced-init-list or when it is a
6198 // parenthesized list of expressions.
6199 QualType DestType = Entity.getType();
6200
6201 if (DestType->isDependentType() ||
6204 return;
6205 }
6206
6207 // Almost everything is a normal sequence.
6209
6210 QualType SourceType;
6211 Expr *Initializer = nullptr;
6212 if (Args.size() == 1) {
6213 Initializer = Args[0];
6214 if (S.getLangOpts().ObjC) {
6216 Initializer->getBeginLoc(), DestType, Initializer->getType(),
6217 Initializer) ||
6219 Args[0] = Initializer;
6220 }
6221 if (!isa<InitListExpr>(Initializer))
6222 SourceType = Initializer->getType();
6223 }
6224
6225 // - If the initializer is a (non-parenthesized) braced-init-list, the
6226 // object is list-initialized (8.5.4).
6227 if (Kind.getKind() != InitializationKind::IK_Direct) {
6228 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
6229 TryListInitialization(S, Entity, Kind, InitList, *this,
6230 TreatUnavailableAsInvalid);
6231 return;
6232 }
6233 }
6234
6235 // - If the destination type is a reference type, see 8.5.3.
6236 if (DestType->isReferenceType()) {
6237 // C++0x [dcl.init.ref]p1:
6238 // A variable declared to be a T& or T&&, that is, "reference to type T"
6239 // (8.3.2), shall be initialized by an object, or function, of type T or
6240 // by an object that can be converted into a T.
6241 // (Therefore, multiple arguments are not permitted.)
6242 if (Args.size() != 1)
6244 // C++17 [dcl.init.ref]p5:
6245 // A reference [...] is initialized by an expression [...] as follows:
6246 // If the initializer is not an expression, presumably we should reject,
6247 // but the standard fails to actually say so.
6248 else if (isa<InitListExpr>(Args[0]))
6250 else
6251 TryReferenceInitialization(S, Entity, Kind, Args[0], *this,
6252 TopLevelOfInitList);
6253 return;
6254 }
6255
6256 // - If the initializer is (), the object is value-initialized.
6257 if (Kind.getKind() == InitializationKind::IK_Value ||
6258 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6259 TryValueInitialization(S, Entity, Kind, *this);
6260 return;
6261 }
6262
6263 // Handle default initialization.
6264 if (Kind.getKind() == InitializationKind::IK_Default) {
6265 TryDefaultInitialization(S, Entity, Kind, *this);
6266 return;
6267 }
6268
6269 // - If the destination type is an array of characters, an array of
6270 // char16_t, an array of char32_t, or an array of wchar_t, and the
6271 // initializer is a string literal, see 8.5.2.
6272 // - Otherwise, if the destination type is an array, the program is
6273 // ill-formed.
6274 // - Except in HLSL, where non-decaying array parameters behave like
6275 // non-array types for initialization.
6276 if (DestType->isArrayType() && !DestType->isArrayParameterType()) {
6277 const ArrayType *DestAT = Context.getAsArrayType(DestType);
6278 if (Initializer && isa<VariableArrayType>(DestAT)) {
6280 return;
6281 }
6282
6283 if (Initializer) {
6284 switch (IsStringInit(Initializer, DestAT, Context)) {
6285 case SIF_None:
6286 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
6287 return;
6290 return;
6293 return;
6296 return;
6299 return;
6302 return;
6303 case SIF_Other:
6304 break;
6305 }
6306 }
6307
6308 // Some kinds of initialization permit an array to be initialized from
6309 // another array of the same type, and perform elementwise initialization.
6310 if (Initializer && isa<ConstantArrayType>(DestAT) &&
6312 Entity.getType()) &&
6313 canPerformArrayCopy(Entity)) {
6314 // If source is a prvalue, use it directly.
6315 if (Initializer->isPRValue()) {
6316 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
6317 return;
6318 }
6319
6320 // Emit element-at-a-time copy loop.
6321 InitializedEntity Element =
6323 QualType InitEltT =
6324 Context.getAsArrayType(Initializer->getType())->getElementType();
6325 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
6326 Initializer->getValueKind(),
6327 Initializer->getObjectKind());
6328 Expr *OVEAsExpr = &OVE;
6329 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
6330 TreatUnavailableAsInvalid);
6331 if (!Failed())
6332 AddArrayInitLoopStep(Entity.getType(), InitEltT);
6333 return;
6334 }
6335
6336 // Note: as an GNU C extension, we allow initialization of an
6337 // array from a compound literal that creates an array of the same
6338 // type, so long as the initializer has no side effects.
6339 if (!S.getLangOpts().CPlusPlus && Initializer &&
6340 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6341 Initializer->getType()->isArrayType()) {
6342 const ArrayType *SourceAT
6343 = Context.getAsArrayType(Initializer->getType());
6344 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
6346 else if (Initializer->HasSideEffects(S.Context))
6348 else {
6349 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
6350 }
6351 }
6352 // Note: as a GNU C++ extension, we allow list-initialization of a
6353 // class member of array type from a parenthesized initializer list.
6354 else if (S.getLangOpts().CPlusPlus &&
6356 Initializer && isa<InitListExpr>(Initializer)) {
6357 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
6358 *this, TreatUnavailableAsInvalid);
6360 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6361 Kind.getKind() == InitializationKind::IK_Direct)
6362 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6363 /*VerifyOnly=*/true);
6364 else if (DestAT->getElementType()->isCharType())
6366 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6368 else
6370
6371 return;
6372 }
6373
6374 // Determine whether we should consider writeback conversions for
6375 // Objective-C ARC.
6376 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6377 Entity.isParameterKind();
6378
6379 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
6380 return;
6381
6382 // We're at the end of the line for C: it's either a write-back conversion
6383 // or it's a C assignment. There's no need to check anything else.
6384 if (!S.getLangOpts().CPlusPlus) {
6385 assert(Initializer && "Initializer must be non-null");
6386 // If allowed, check whether this is an Objective-C writeback conversion.
6387 if (allowObjCWritebackConversion &&
6388 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
6389 return;
6390 }
6391
6392 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
6393 return;
6394
6395 // Handle initialization in C
6396 AddCAssignmentStep(DestType);
6397 MaybeProduceObjCObject(S, *this, Entity);
6398 return;
6399 }
6400
6401 assert(S.getLangOpts().CPlusPlus);
6402
6403 // - If the destination type is a (possibly cv-qualified) class type:
6404 if (DestType->isRecordType()) {
6405 // - If the initialization is direct-initialization, or if it is
6406 // copy-initialization where the cv-unqualified version of the
6407 // source type is the same class as, or a derived class of, the
6408 // class of the destination, constructors are considered. [...]
6409 if (Kind.getKind() == InitializationKind::IK_Direct ||
6410 (Kind.getKind() == InitializationKind::IK_Copy &&
6411 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
6412 (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
6413 SourceType, DestType))))) {
6414 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
6415 *this);
6416
6417 // We fall back to the "no matching constructor" path if the
6418 // failed candidate set has functions other than the three default
6419 // constructors. For example, conversion function.
6420 if (const auto *RD =
6421 dyn_cast<CXXRecordDecl>(DestType->getAs<RecordType>()->getDecl());
6422 // In general, we should call isCompleteType for RD to check its
6423 // completeness, we don't call it here as it was already called in the
6424 // above TryConstructorInitialization.
6425 S.getLangOpts().CPlusPlus20 && RD && RD->hasDefinition() &&
6426 RD->isAggregate() && Failed() &&
6428 // Do not attempt paren list initialization if overload resolution
6429 // resolves to a deleted function .
6430 //
6431 // We may reach this condition if we have a union wrapping a class with
6432 // a non-trivial copy or move constructor and we call one of those two
6433 // constructors. The union is an aggregate, but the matched constructor
6434 // is implicitly deleted, so we need to prevent aggregate initialization
6435 // (otherwise, it'll attempt aggregate initialization by initializing
6436 // the first element with a reference to the union).
6439 S, Kind.getLocation(), Best);
6441 // C++20 [dcl.init] 17.6.2.2:
6442 // - Otherwise, if no constructor is viable, the destination type is
6443 // an
6444 // aggregate class, and the initializer is a parenthesized
6445 // expression-list.
6446 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6447 /*VerifyOnly=*/true);
6448 }
6449 }
6450 } else {
6451 // - Otherwise (i.e., for the remaining copy-initialization cases),
6452 // user-defined conversion sequences that can convert from the
6453 // source type to the destination type or (when a conversion
6454 // function is used) to a derived class thereof are enumerated as
6455 // described in 13.3.1.4, and the best one is chosen through
6456 // overload resolution (13.3).
6457 assert(Initializer && "Initializer must be non-null");
6458 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6459 TopLevelOfInitList);
6460 }
6461 return;
6462 }
6463
6464 assert(Args.size() >= 1 && "Zero-argument case handled above");
6465
6466 // For HLSL ext vector types we allow list initialization behavior for C++
6467 // constructor syntax. This is accomplished by converting initialization
6468 // arguments an InitListExpr late.
6469 if (S.getLangOpts().HLSL && Args.size() > 1 && DestType->isExtVectorType() &&
6470 (SourceType.isNull() ||
6471 !Context.hasSameUnqualifiedType(SourceType, DestType))) {
6472
6474 for (auto *Arg : Args) {
6475 if (Arg->getType()->isExtVectorType()) {
6476 const auto *VTy = Arg->getType()->castAs<ExtVectorType>();
6477 unsigned Elm = VTy->getNumElements();
6478 for (unsigned Idx = 0; Idx < Elm; ++Idx) {
6479 InitArgs.emplace_back(new (Context) ArraySubscriptExpr(
6480 Arg,
6482 Context, llvm::APInt(Context.getIntWidth(Context.IntTy), Idx),
6483 Context.IntTy, SourceLocation()),
6484 VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(),
6485 SourceLocation()));
6486 }
6487 } else
6488 InitArgs.emplace_back(Arg);
6489 }
6490 InitListExpr *ILE = new (Context) InitListExpr(
6491 S.getASTContext(), SourceLocation(), InitArgs, SourceLocation());
6492 Args[0] = ILE;
6493 AddListInitializationStep(DestType);
6494 return;
6495 }
6496
6497 // The remaining cases all need a source type.
6498 if (Args.size() > 1) {
6500 return;
6501 } else if (isa<InitListExpr>(Args[0])) {
6503 return;
6504 }
6505
6506 // - Otherwise, if the source type is a (possibly cv-qualified) class
6507 // type, conversion functions are considered.
6508 if (!SourceType.isNull() && SourceType->isRecordType()) {
6509 assert(Initializer && "Initializer must be non-null");
6510 // For a conversion to _Atomic(T) from either T or a class type derived
6511 // from T, initialize the T object then convert to _Atomic type.
6512 bool NeedAtomicConversion = false;
6513 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
6514 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
6515 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
6516 Atomic->getValueType())) {
6517 DestType = Atomic->getValueType();
6518 NeedAtomicConversion = true;
6519 }
6520 }
6521
6522 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6523 TopLevelOfInitList);
6524 MaybeProduceObjCObject(S, *this, Entity);
6525 if (!Failed() && NeedAtomicConversion)
6527 return;
6528 }
6529
6530 // - Otherwise, if the initialization is direct-initialization, the source
6531 // type is std::nullptr_t, and the destination type is bool, the initial
6532 // value of the object being initialized is false.
6533 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
6534 DestType->isBooleanType() &&
6535 Kind.getKind() == InitializationKind::IK_Direct) {
6538 Initializer->isGLValue()),
6539 DestType);
6540 return;
6541 }
6542
6543 // - Otherwise, the initial value of the object being initialized is the
6544 // (possibly converted) value of the initializer expression. Standard
6545 // conversions (Clause 4) will be used, if necessary, to convert the
6546 // initializer expression to the cv-unqualified version of the
6547 // destination type; no user-defined conversions are considered.
6548
6550 = S.TryImplicitConversion(Initializer, DestType,
6551 /*SuppressUserConversions*/true,
6552 Sema::AllowedExplicit::None,
6553 /*InOverloadResolution*/ false,
6554 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
6555 allowObjCWritebackConversion);
6556
6557 if (ICS.isStandard() &&
6559 // Objective-C ARC writeback conversion.
6560
6561 // We should copy unless we're passing to an argument explicitly
6562 // marked 'out'.
6563 bool ShouldCopy = true;
6564 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6565 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6566
6567 // If there was an lvalue adjustment, add it as a separate conversion.
6568 if (ICS.Standard.First == ICK_Array_To_Pointer ||
6571 LvalueICS.setStandard();
6573 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
6574 LvalueICS.Standard.First = ICS.Standard.First;
6575 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
6576 }
6577
6578 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
6579 } else if (ICS.isBad()) {
6582 else if (DeclAccessPair Found;
6583 Initializer->getType() == Context.OverloadTy &&
6585 /*Complain=*/false, Found))
6587 else if (Initializer->getType()->isFunctionType() &&
6590 else
6592 } else {
6593 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6594
6595 MaybeProduceObjCObject(S, *this, Entity);
6596 }
6597}
6598
6600 for (auto &S : Steps)
6601 S.Destroy();
6602}
6603
6604//===----------------------------------------------------------------------===//
6605// Perform initialization
6606//===----------------------------------------------------------------------===//
6608getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
6609 switch(Entity.getKind()) {
6615 return Sema::AA_Initializing;
6616
6618 if (Entity.getDecl() &&
6619 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6620 return Sema::AA_Sending;
6621
6622 return Sema::AA_Passing;
6623
6625 if (Entity.getDecl() &&
6626 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6627 return Sema::AA_Sending;
6628
6629 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
6630
6632 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
6633 return Sema::AA_Returning;
6634
6637 // FIXME: Can we tell apart casting vs. converting?
6638 return Sema::AA_Casting;
6639
6641 // This is really initialization, but refer to it as conversion for
6642 // consistency with CheckConvertedConstantExpression.
6643 return Sema::AA_Converting;
6644
6655 return Sema::AA_Initializing;
6656 }
6657
6658 llvm_unreachable("Invalid EntityKind!");
6659}
6660
6661/// Whether we should bind a created object as a temporary when
6662/// initializing the given entity.
6663static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
6664 switch (Entity.getKind()) {
6682 return false;
6683
6689 return true;
6690 }
6691
6692 llvm_unreachable("missed an InitializedEntity kind?");
6693}
6694
6695/// Whether the given entity, when initialized with an object
6696/// created for that initialization, requires destruction.
6697static bool shouldDestroyEntity(const InitializedEntity &Entity) {
6698 switch (Entity.getKind()) {
6709 return false;
6710
6723 return true;
6724 }
6725
6726 llvm_unreachable("missed an InitializedEntity kind?");
6727}
6728
6729/// Get the location at which initialization diagnostics should appear.
6731 Expr *Initializer) {
6732 switch (Entity.getKind()) {
6735 return Entity.getReturnLoc();
6736
6738 return Entity.getThrowLoc();
6739
6742 return Entity.getDecl()->getLocation();
6743
6745 return Entity.getCaptureLoc();
6746
6763 return Initializer->getBeginLoc();
6764 }
6765 llvm_unreachable("missed an InitializedEntity kind?");
6766}
6767
6768/// Make a (potentially elidable) temporary copy of the object
6769/// provided by the given initializer by calling the appropriate copy
6770/// constructor.
6771///
6772/// \param S The Sema object used for type-checking.
6773///
6774/// \param T The type of the temporary object, which must either be
6775/// the type of the initializer expression or a superclass thereof.
6776///
6777/// \param Entity The entity being initialized.
6778///
6779/// \param CurInit The initializer expression.
6780///
6781/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
6782/// is permitted in C++03 (but not C++0x) when binding a reference to
6783/// an rvalue.
6784///
6785/// \returns An expression that copies the initializer expression into
6786/// a temporary object, or an error expression if a copy could not be
6787/// created.
6789 QualType T,
6790 const InitializedEntity &Entity,
6791 ExprResult CurInit,
6792 bool IsExtraneousCopy) {
6793 if (CurInit.isInvalid())
6794 return CurInit;
6795 // Determine which class type we're copying to.
6796 Expr *CurInitExpr = (Expr *)CurInit.get();
6797 CXXRecordDecl *Class = nullptr;
6798 if (const RecordType *Record = T->getAs<RecordType>())
6799 Class = cast<CXXRecordDecl>(Record->getDecl());
6800 if (!Class)
6801 return CurInit;
6802
6803 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
6804
6805 // Make sure that the type we are copying is complete.
6806 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
6807 return CurInit;
6808
6809 // Perform overload resolution using the class's constructors. Per
6810 // C++11 [dcl.init]p16, second bullet for class types, this initialization
6811 // is direct-initialization.
6814
6817 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
6818 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6819 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6820 /*RequireActualConstructor=*/false,
6821 /*SecondStepOfCopyInit=*/true)) {
6822 case OR_Success:
6823 break;
6824
6826 CandidateSet.NoteCandidates(
6828 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
6829 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
6830 : diag::err_temp_copy_no_viable)
6831 << (int)Entity.getKind() << CurInitExpr->getType()
6832 << CurInitExpr->getSourceRange()),
6833 S, OCD_AllCandidates, CurInitExpr);
6834 if (!IsExtraneousCopy || S.isSFINAEContext())
6835 return ExprError();
6836 return CurInit;
6837
6838 case OR_Ambiguous:
6839 CandidateSet.NoteCandidates(
6840 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
6841 << (int)Entity.getKind()
6842 << CurInitExpr->getType()
6843 << CurInitExpr->getSourceRange()),
6844 S, OCD_AmbiguousCandidates, CurInitExpr);
6845 return ExprError();
6846
6847 case OR_Deleted:
6848 S.Diag(Loc, diag::err_temp_copy_deleted)
6849 << (int)Entity.getKind() << CurInitExpr->getType()
6850 << CurInitExpr->getSourceRange();
6851 S.NoteDeletedFunction(Best->Function);
6852 return ExprError();
6853 }
6854
6855 bool HadMultipleCandidates = CandidateSet.size() > 1;
6856
6857 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
6858 SmallVector<Expr*, 8> ConstructorArgs;
6859 CurInit.get(); // Ownership transferred into MultiExprArg, below.
6860
6861 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
6862 IsExtraneousCopy);
6863
6864 if (IsExtraneousCopy) {
6865 // If this is a totally extraneous copy for C++03 reference
6866 // binding purposes, just return the original initialization
6867 // expression. We don't generate an (elided) copy operation here
6868 // because doing so would require us to pass down a flag to avoid
6869 // infinite recursion, where each step adds another extraneous,
6870 // elidable copy.
6871
6872 // Instantiate the default arguments of any extra parameters in
6873 // the selected copy constructor, as if we were going to create a
6874 // proper call to the copy constructor.
6875 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
6876 ParmVarDecl *Parm = Constructor->getParamDecl(I);
6877 if (S.RequireCompleteType(Loc, Parm->getType(),
6878 diag::err_call_incomplete_argument))
6879 break;
6880
6881 // Build the default argument expression; we don't actually care
6882 // if this succeeds or not, because this routine will complain
6883 // if there was a problem.
6884 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
6885 }
6886
6887 return CurInitExpr;
6888 }
6889
6890 // Determine the arguments required to actually perform the
6891 // constructor call (we might have derived-to-base conversions, or
6892 // the copy constructor may have default arguments).
6893 if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
6894 ConstructorArgs))
6895 return ExprError();
6896
6897 // C++0x [class.copy]p32:
6898 // When certain criteria are met, an implementation is allowed to
6899 // omit the copy/move construction of a class object, even if the
6900 // copy/move constructor and/or destructor for the object have
6901 // side effects. [...]
6902 // - when a temporary class object that has not been bound to a
6903 // reference (12.2) would be copied/moved to a class object
6904 // with the same cv-unqualified type, the copy/move operation
6905 // can be omitted by constructing the temporary object
6906 // directly into the target of the omitted copy/move
6907 //
6908 // Note that the other three bullets are handled elsewhere. Copy
6909 // elision for return statements and throw expressions are handled as part
6910 // of constructor initialization, while copy elision for exception handlers
6911 // is handled by the run-time.
6912 //
6913 // FIXME: If the function parameter is not the same type as the temporary, we
6914 // should still be able to elide the copy, but we don't have a way to
6915 // represent in the AST how much should be elided in this case.
6916 bool Elidable =
6917 CurInitExpr->isTemporaryObject(S.Context, Class) &&
6919 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
6920 CurInitExpr->getType());
6921
6922 // Actually perform the constructor call.
6923 CurInit = S.BuildCXXConstructExpr(
6924 Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,
6925 HadMultipleCandidates,
6926 /*ListInit*/ false,
6927 /*StdInitListInit*/ false,
6928 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
6929
6930 // If we're supposed to bind temporaries, do so.
6931 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
6932 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6933 return CurInit;
6934}
6935
6936/// Check whether elidable copy construction for binding a reference to
6937/// a temporary would have succeeded if we were building in C++98 mode, for
6938/// -Wc++98-compat.
6940 const InitializedEntity &Entity,
6941 Expr *CurInitExpr) {
6942 assert(S.getLangOpts().CPlusPlus11);
6943
6944 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
6945 if (!Record)
6946 return;
6947
6948 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
6949 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
6950 return;
6951
6952 // Find constructors which would have been considered.
6955 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
6956
6957 // Perform overload resolution.
6960 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
6961 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6962 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6963 /*RequireActualConstructor=*/false,
6964 /*SecondStepOfCopyInit=*/true);
6965
6966 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
6967 << OR << (int)Entity.getKind() << CurInitExpr->getType()
6968 << CurInitExpr->getSourceRange();
6969
6970 switch (OR) {
6971 case OR_Success:
6972 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
6973 Best->FoundDecl, Entity, Diag);
6974 // FIXME: Check default arguments as far as that's possible.
6975 break;
6976
6978 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6979 OCD_AllCandidates, CurInitExpr);
6980 break;
6981
6982 case OR_Ambiguous:
6983 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6984 OCD_AmbiguousCandidates, CurInitExpr);
6985 break;
6986
6987 case OR_Deleted:
6988 S.Diag(Loc, Diag);
6989 S.NoteDeletedFunction(Best->Function);
6990 break;
6991 }
6992}
6993
6994void InitializationSequence::PrintInitLocationNote(Sema &S,
6995 const InitializedEntity &Entity) {
6996 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
6997 if (Entity.getDecl()->getLocation().isInvalid())
6998 return;
6999
7000 if (Entity.getDecl()->getDeclName())
7001 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
7002 << Entity.getDecl()->getDeclName();
7003 else
7004 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
7005 }
7006 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
7007 Entity.getMethodDecl())
7008 S.Diag(Entity.getMethodDecl()->getLocation(),
7009 diag::note_method_return_type_change)
7010 << Entity.getMethodDecl()->getDeclName();
7011}
7012
7013/// Returns true if the parameters describe a constructor initialization of
7014/// an explicit temporary object, e.g. "Point(x, y)".
7015static bool isExplicitTemporary(const InitializedEntity &Entity,
7016 const InitializationKind &Kind,
7017 unsigned NumArgs) {
7018 switch (Entity.getKind()) {
7022 break;
7023 default:
7024 return false;
7025 }
7026
7027 switch (Kind.getKind()) {
7029 return true;
7030 // FIXME: Hack to work around cast weirdness.
7033 return NumArgs != 1;
7034 default:
7035 return false;
7036 }
7037}
7038
7039static ExprResult
7041 const InitializedEntity &Entity,
7042 const InitializationKind &Kind,
7043 MultiExprArg Args,
7044 const InitializationSequence::Step& Step,
7045 bool &ConstructorInitRequiresZeroInit,
7046 bool IsListInitialization,
7047 bool IsStdInitListInitialization,
7048 SourceLocation LBraceLoc,
7049 SourceLocation RBraceLoc) {
7050 unsigned NumArgs = Args.size();
7051 CXXConstructorDecl *Constructor
7052 = cast<CXXConstructorDecl>(Step.Function.Function);
7053 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7054
7055 // Build a call to the selected constructor.
7056 SmallVector<Expr*, 8> ConstructorArgs;
7057 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7058 ? Kind.getEqualLoc()
7059 : Kind.getLocation();
7060
7061 if (Kind.getKind() == InitializationKind::IK_Default) {
7062 // Force even a trivial, implicit default constructor to be
7063 // semantically checked. We do this explicitly because we don't build
7064 // the definition for completely trivial constructors.
7065 assert(Constructor->getParent() && "No parent class for constructor.");
7066 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7067 Constructor->isTrivial() && !Constructor->isUsed(false)) {
7069 S.DefineImplicitDefaultConstructor(Loc, Constructor);
7070 });
7071 }
7072 }
7073
7074 ExprResult CurInit((Expr *)nullptr);
7075
7076 // C++ [over.match.copy]p1:
7077 // - When initializing a temporary to be bound to the first parameter
7078 // of a constructor that takes a reference to possibly cv-qualified
7079 // T as its first argument, called with a single argument in the
7080 // context of direct-initialization, explicit conversion functions
7081 // are also considered.
7082 bool AllowExplicitConv =
7083 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7086
7087 // A smart pointer constructed from a nullable pointer is nullable.
7088 if (NumArgs == 1 && !Kind.isExplicitCast())
7090 Entity.getType(), Args.front()->getType(), Kind.getLocation());
7091
7092 // Determine the arguments required to actually perform the constructor
7093 // call.
7094 if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
7095 ConstructorArgs, AllowExplicitConv,
7096 IsListInitialization))
7097 return ExprError();
7098
7099 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7100 // An explicitly-constructed temporary, e.g., X(1, 2).
7102 return ExprError();
7103
7104 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7105 if (!TSInfo)
7106 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
7107 SourceRange ParenOrBraceRange =
7108 (Kind.getKind() == InitializationKind::IK_DirectList)
7109 ? SourceRange(LBraceLoc, RBraceLoc)
7110 : Kind.getParenOrBraceRange();
7111
7112 CXXConstructorDecl *CalleeDecl = Constructor;
7113 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7114 Step.Function.FoundDecl.getDecl())) {
7115 CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
7116 }
7117 S.MarkFunctionReferenced(Loc, CalleeDecl);
7118
7119 CurInit = S.CheckForImmediateInvocation(
7121 S.Context, CalleeDecl,
7122 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7123 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7124 IsListInitialization, IsStdInitListInitialization,
7125 ConstructorInitRequiresZeroInit),
7126 CalleeDecl);
7127 } else {
7129
7130 if (Entity.getKind() == InitializedEntity::EK_Base) {
7131 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7134 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7135 ConstructKind = CXXConstructionKind::Delegating;
7136 }
7137
7138 // Only get the parenthesis or brace range if it is a list initialization or
7139 // direct construction.
7140 SourceRange ParenOrBraceRange;
7141 if (IsListInitialization)
7142 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7143 else if (Kind.getKind() == InitializationKind::IK_Direct)
7144 ParenOrBraceRange = Kind.getParenOrBraceRange();
7145
7146 // If the entity allows NRVO, mark the construction as elidable
7147 // unconditionally.
7148 if (Entity.allowsNRVO())
7149 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7150 Step.Function.FoundDecl,
7151 Constructor, /*Elidable=*/true,
7152 ConstructorArgs,
7153 HadMultipleCandidates,
7154 IsListInitialization,
7155 IsStdInitListInitialization,
7156 ConstructorInitRequiresZeroInit,
7157 ConstructKind,
7158 ParenOrBraceRange);
7159 else
7160 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7161 Step.Function.FoundDecl,
7162 Constructor,
7163 ConstructorArgs,
7164 HadMultipleCandidates,
7165 IsListInitialization,
7166 IsStdInitListInitialization,
7167 ConstructorInitRequiresZeroInit,
7168 ConstructKind,
7169 ParenOrBraceRange);
7170 }
7171 if (CurInit.isInvalid())
7172 return ExprError();
7173
7174 // Only check access if all of that succeeded.
7175 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
7177 return ExprError();
7178
7179 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
7181 return ExprError();
7182
7183 if (shouldBindAsTemporary(Entity))
7184 CurInit = S.MaybeBindToTemporary(CurInit.get());
7185
7186 return CurInit;
7187}
7188
7189namespace {
7190enum LifetimeKind {
7191 /// The lifetime of a temporary bound to this entity ends at the end of the
7192 /// full-expression, and that's (probably) fine.
7193 LK_FullExpression,
7194
7195 /// The lifetime of a temporary bound to this entity is extended to the
7196 /// lifeitme of the entity itself.
7197 LK_Extended,
7198
7199 /// The lifetime of a temporary bound to this entity probably ends too soon,
7200 /// because the entity is allocated in a new-expression.
7201 LK_New,
7202
7203 /// The lifetime of a temporary bound to this entity ends too soon, because
7204 /// the entity is a return object.
7205 LK_Return,
7206
7207 /// The lifetime of a temporary bound to this entity ends too soon, because
7208 /// the entity is the result of a statement expression.
7209 LK_StmtExprResult,
7210
7211 /// This is a mem-initializer: if it would extend a temporary (other than via
7212 /// a default member initializer), the program is ill-formed.
7213 LK_MemInitializer,
7214};
7215using LifetimeResult =
7216 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
7217}
7218
7219/// Determine the declaration which an initialized entity ultimately refers to,
7220/// for the purpose of lifetime-extending a temporary bound to a reference in
7221/// the initialization of \p Entity.
7222static LifetimeResult getEntityLifetime(
7223 const InitializedEntity *Entity,
7224 const InitializedEntity *InitField = nullptr) {
7225 // C++11 [class.temporary]p5:
7226 switch (Entity->getKind()) {
7228 // The temporary [...] persists for the lifetime of the reference
7229 return {Entity, LK_Extended};
7230
7232 // For subobjects, we look at the complete object.
7233 if (Entity->getParent())
7234 return getEntityLifetime(Entity->getParent(), Entity);
7235
7236 // except:
7237 // C++17 [class.base.init]p8:
7238 // A temporary expression bound to a reference member in a
7239 // mem-initializer is ill-formed.
7240 // C++17 [class.base.init]p11:
7241 // A temporary expression bound to a reference member from a
7242 // default member initializer is ill-formed.
7243 //
7244 // The context of p11 and its example suggest that it's only the use of a
7245 // default member initializer from a constructor that makes the program
7246 // ill-formed, not its mere existence, and that it can even be used by
7247 // aggregate initialization.
7248 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
7249 : LK_MemInitializer};
7250
7252 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
7253 // type.
7254 return {Entity, LK_Extended};
7255
7258 // -- A temporary bound to a reference parameter in a function call
7259 // persists until the completion of the full-expression containing
7260 // the call.
7261 return {nullptr, LK_FullExpression};
7262
7264 // FIXME: This will always be ill-formed; should we eagerly diagnose it here?
7265 return {nullptr, LK_FullExpression};
7266
7268 // -- The lifetime of a temporary bound to the returned value in a
7269 // function return statement is not extended; the temporary is
7270 // destroyed at the end of the full-expression in the return statement.
7271 return {nullptr, LK_Return};
7272
7274 // FIXME: Should we lifetime-extend through the result of a statement
7275 // expression?
7276 return {nullptr, LK_StmtExprResult};
7277
7279 // -- A temporary bound to a reference in a new-initializer persists
7280 // until the completion of the full-expression containing the
7281 // new-initializer.
7282 return {nullptr, LK_New};
7283
7287 // We don't yet know the storage duration of the surrounding temporary.
7288 // Assume it's got full-expression duration for now, it will patch up our
7289 // storage duration if that's not correct.
7290 return {nullptr, LK_FullExpression};
7291
7293 // For subobjects, we look at the complete object.
7294 return getEntityLifetime(Entity->getParent(), InitField);
7295
7297 // For subobjects, we look at the complete object.
7298 if (Entity->getParent())
7299 return getEntityLifetime(Entity->getParent(), InitField);
7300 return {InitField, LK_MemInitializer};
7301
7303 // We can reach this case for aggregate initialization in a constructor:
7304 // struct A { int &&r; };
7305 // struct B : A { B() : A{0} {} };
7306 // In this case, use the outermost field decl as the context.
7307 return {InitField, LK_MemInitializer};
7308
7314 return {nullptr, LK_FullExpression};
7315
7317 // FIXME: Can we diagnose lifetime problems with exceptions?
7318 return {nullptr, LK_FullExpression};
7319
7321 // -- A temporary object bound to a reference element of an aggregate of
7322 // class type initialized from a parenthesized expression-list
7323 // [dcl.init, 9.3] persists until the completion of the full-expression
7324 // containing the expression-list.
7325 return {nullptr, LK_FullExpression};
7326 }
7327
7328 llvm_unreachable("unknown entity kind");
7329}
7330
7331namespace {
7332enum ReferenceKind {
7333 /// Lifetime would be extended by a reference binding to a temporary.
7334 RK_ReferenceBinding,
7335 /// Lifetime would be extended by a std::initializer_list object binding to
7336 /// its backing array.
7337 RK_StdInitializerList,
7338};
7339
7340/// A temporary or local variable. This will be one of:
7341/// * A MaterializeTemporaryExpr.
7342/// * A DeclRefExpr whose declaration is a local.
7343/// * An AddrLabelExpr.
7344/// * A BlockExpr for a block with captures.
7345using Local = Expr*;
7346
7347/// Expressions we stepped over when looking for the local state. Any steps
7348/// that would inhibit lifetime extension or take us out of subexpressions of
7349/// the initializer are included.
7350struct IndirectLocalPathEntry {
7351 enum EntryKind {
7352 DefaultInit,
7353 AddressOf,
7354 VarInit,
7355 LValToRVal,
7356 LifetimeBoundCall,
7357 TemporaryCopy,
7358 LambdaCaptureInit,
7359 GslReferenceInit,
7360 GslPointerInit
7361 } Kind;
7362 Expr *E;
7363 union {
7364 const Decl *D = nullptr;
7365 const LambdaCapture *Capture;
7366 };
7367 IndirectLocalPathEntry() {}
7368 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
7369 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
7370 : Kind(K), E(E), D(D) {}
7371 IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture)
7372 : Kind(K), E(E), Capture(Capture) {}
7373};
7374
7375using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
7376
7377struct RevertToOldSizeRAII {
7378 IndirectLocalPath &Path;
7379 unsigned OldSize = Path.size();
7380 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
7381 ~RevertToOldSizeRAII() { Path.resize(OldSize); }
7382};
7383
7384using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
7385 ReferenceKind RK)>;
7386}
7387
7388static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
7389 for (auto E : Path)
7390 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
7391 return true;
7392 return false;
7393}
7394
7395static bool pathContainsInit(IndirectLocalPath &Path) {
7396 return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
7397 return E.Kind == IndirectLocalPathEntry::DefaultInit ||
7398 E.Kind == IndirectLocalPathEntry::VarInit;
7399 });
7400}
7401
7402static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7403 Expr *Init, LocalVisitor Visit,
7404 bool RevisitSubinits,
7405 bool EnableLifetimeWarnings);
7406
7407static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7408 Expr *Init, ReferenceKind RK,
7409 LocalVisitor Visit,
7410 bool EnableLifetimeWarnings);
7411
7412template <typename T> static bool isRecordWithAttr(QualType Type) {
7413 if (auto *RD = Type->getAsCXXRecordDecl())
7414 return RD->hasAttr<T>();
7415 return false;
7416}
7417
7418// Decl::isInStdNamespace will return false for iterators in some STL
7419// implementations due to them being defined in a namespace outside of the std
7420// namespace.
7421static bool isInStlNamespace(const Decl *D) {
7422 const DeclContext *DC = D->getDeclContext();
7423 if (!DC)
7424 return false;
7425 if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
7426 if (const IdentifierInfo *II = ND->getIdentifier()) {
7427 StringRef Name = II->getName();
7428 if (Name.size() >= 2 && Name.front() == '_' &&
7429 (Name[1] == '_' || isUppercase(Name[1])))
7430 return true;
7431 }
7432
7433 return DC->isStdNamespace();
7434}
7435
7437 if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee))
7438 if (isRecordWithAttr<PointerAttr>(Conv->getConversionType()))
7439 return true;
7440 if (!isInStlNamespace(Callee->getParent()))
7441 return false;
7442 if (!isRecordWithAttr<PointerAttr>(
7443 Callee->getFunctionObjectParameterType()) &&
7444 !isRecordWithAttr<OwnerAttr>(Callee->getFunctionObjectParameterType()))
7445 return false;
7446 if (Callee->getReturnType()->isPointerType() ||
7447 isRecordWithAttr<PointerAttr>(Callee->getReturnType())) {
7448 if (!Callee->getIdentifier())
7449 return false;
7450 return llvm::StringSwitch<bool>(Callee->getName())
7451 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
7452 .Cases("end", "rend", "cend", "crend", true)
7453 .Cases("c_str", "data", "get", true)
7454 // Map and set types.
7455 .Cases("find", "equal_range", "lower_bound", "upper_bound", true)
7456 .Default(false);
7457 } else if (Callee->getReturnType()->isReferenceType()) {
7458 if (!Callee->getIdentifier()) {
7459 auto OO = Callee->getOverloadedOperator();
7460 return OO == OverloadedOperatorKind::OO_Subscript ||
7461 OO == OverloadedOperatorKind::OO_Star;
7462 }
7463 return llvm::StringSwitch<bool>(Callee->getName())
7464 .Cases("front", "back", "at", "top", "value", true)
7465 .Default(false);
7466 }
7467 return false;
7468}
7469
7471 if (!FD->getIdentifier() || FD->getNumParams() != 1)
7472 return false;
7473 const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl();
7474 if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace())
7475 return false;
7476 if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) &&
7477 !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0)))
7478 return false;
7479 if (FD->getReturnType()->isPointerType() ||
7480 isRecordWithAttr<PointerAttr>(FD->getReturnType())) {
7481 return llvm::StringSwitch<bool>(FD->getName())
7482 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
7483 .Cases("end", "rend", "cend", "crend", true)
7484 .Case("data", true)
7485 .Default(false);
7486 } else if (FD->getReturnType()->isReferenceType()) {
7487 return llvm::StringSwitch<bool>(FD->getName())
7488 .Cases("get", "any_cast", true)
7489 .Default(false);
7490 }
7491 return false;
7492}
7493
7494static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
7495 LocalVisitor Visit) {
7496 auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) {
7497 // We are not interested in the temporary base objects of gsl Pointers:
7498 // Temp().ptr; // Here ptr might not dangle.
7499 if (isa<MemberExpr>(Arg->IgnoreImpCasts()))
7500 return;
7501 // Once we initialized a value with a reference, it can no longer dangle.
7502 if (!Value) {
7503 for (const IndirectLocalPathEntry &PE : llvm::reverse(Path)) {
7504 if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit)
7505 continue;
7506 if (PE.Kind == IndirectLocalPathEntry::GslPointerInit)
7507 return;
7508 break;
7509 }
7510 }
7511 Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit
7512 : IndirectLocalPathEntry::GslReferenceInit,
7513 Arg, D});
7514 if (Arg->isGLValue())
7515 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
7516 Visit,
7517 /*EnableLifetimeWarnings=*/true);
7518 else
7519 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7520 /*EnableLifetimeWarnings=*/true);
7521 Path.pop_back();
7522 };
7523
7524 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
7525 const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee());
7526 if (MD && shouldTrackImplicitObjectArg(MD))
7527 VisitPointerArg(MD, MCE->getImplicitObjectArgument(),
7528 !MD->getReturnType()->isReferenceType());
7529 return;
7530 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) {
7531 FunctionDecl *Callee = OCE->getDirectCallee();
7532 if (Callee && Callee->isCXXInstanceMember() &&
7533 shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee)))
7534 VisitPointerArg(Callee, OCE->getArg(0),
7535 !Callee->getReturnType()->isReferenceType());
7536 return;
7537 } else if (auto *CE = dyn_cast<CallExpr>(Call)) {
7538 FunctionDecl *Callee = CE->getDirectCallee();
7539 if (Callee && shouldTrackFirstArgument(Callee))
7540 VisitPointerArg(Callee, CE->getArg(0),
7541 !Callee->getReturnType()->isReferenceType());
7542 return;
7543 }
7544
7545 if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) {
7546 const auto *Ctor = CCE->getConstructor();
7547 const CXXRecordDecl *RD = Ctor->getParent();
7548 if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>())
7549 VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true);
7550 }
7551}
7552
7554 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7555 if (!TSI)
7556 return false;
7557 // Don't declare this variable in the second operand of the for-statement;
7558 // GCC miscompiles that by ending its lifetime before evaluating the
7559 // third operand. See gcc.gnu.org/PR86769.
7561 for (TypeLoc TL = TSI->getTypeLoc();
7562 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7563 TL = ATL.getModifiedLoc()) {
7564 if (ATL.getAttrAs<LifetimeBoundAttr>())
7565 return true;
7566 }
7567
7568 // Assume that all assignment operators with a "normal" return type return
7569 // *this, that is, an lvalue reference that is the same type as the implicit
7570 // object parameter (or the LHS for a non-member operator$=).
7572 if (OO == OO_Equal || isCompoundAssignmentOperator(OO)) {
7573 QualType RetT = FD->getReturnType();
7574 if (RetT->isLValueReferenceType()) {
7575 ASTContext &Ctx = FD->getASTContext();
7576 QualType LHST;
7577 auto *MD = dyn_cast<CXXMethodDecl>(FD);
7578 if (MD && MD->isCXXInstanceMember())
7579 LHST = Ctx.getLValueReferenceType(MD->getFunctionObjectParameterType());
7580 else
7581 LHST = MD->getParamDecl(0)->getType();
7582 if (Ctx.hasSameType(RetT, LHST))
7583 return true;
7584 }
7585 }
7586
7587 return false;
7588}
7589
7590static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
7591 LocalVisitor Visit) {
7592 const FunctionDecl *Callee;
7593 ArrayRef<Expr*> Args;
7594
7595 if (auto *CE = dyn_cast<CallExpr>(Call)) {
7596 Callee = CE->getDirectCallee();
7597 Args = llvm::ArrayRef(CE->getArgs(), CE->getNumArgs());
7598 } else {
7599 auto *CCE = cast<CXXConstructExpr>(Call);
7600 Callee = CCE->getConstructor();
7601 Args = llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs());
7602 }
7603 if (!Callee)
7604 return;
7605
7606 Expr *ObjectArg = nullptr;
7607 if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
7608 ObjectArg = Args[0];
7609 Args = Args.slice(1);
7610 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
7611 ObjectArg = MCE->getImplicitObjectArgument();
7612 }
7613
7614 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
7615 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
7616 if (Arg->isGLValue())
7617 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
7618 Visit,
7619 /*EnableLifetimeWarnings=*/false);
7620 else
7621 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7622 /*EnableLifetimeWarnings=*/false);
7623 Path.pop_back();
7624 };
7625
7626 bool CheckCoroCall = false;
7627 if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
7628 CheckCoroCall = RD->hasAttr<CoroLifetimeBoundAttr>() &&
7629 RD->hasAttr<CoroReturnTypeAttr>() &&
7630 !Callee->hasAttr<CoroDisableLifetimeBoundAttr>();
7631 }
7632
7633 if (ObjectArg) {
7634 bool CheckCoroObjArg = CheckCoroCall;
7635 // Coroutine lambda objects with empty capture list are not lifetimebound.
7636 if (auto *LE = dyn_cast<LambdaExpr>(ObjectArg->IgnoreImplicit());
7637 LE && LE->captures().empty())
7638 CheckCoroObjArg = false;
7639 // Allow `get_return_object()` as the object param (__promise) is not
7640 // lifetimebound.
7641 if (Sema::CanBeGetReturnObject(Callee))
7642 CheckCoroObjArg = false;
7643 if (implicitObjectParamIsLifetimeBound(Callee) || CheckCoroObjArg)
7644 VisitLifetimeBoundArg(Callee, ObjectArg);
7645 }
7646
7647 for (unsigned I = 0,
7648 N = std::min<unsigned>(Callee->getNumParams(), Args.size());
7649 I != N; ++I) {
7650 if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
7651 VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
7652 }
7653}
7654
7655/// Visit the locals that would be reachable through a reference bound to the
7656/// glvalue expression \c Init.
7657static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7658 Expr *Init, ReferenceKind RK,
7659 LocalVisitor Visit,
7660 bool EnableLifetimeWarnings) {
7661 RevertToOldSizeRAII RAII(Path);
7662
7663 // Walk past any constructs which we can lifetime-extend across.
7664 Expr *Old;
7665 do {
7666 Old = Init;
7667
7668 if (auto *FE = dyn_cast<FullExpr>(Init))
7669 Init = FE->getSubExpr();
7670
7671 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7672 // If this is just redundant braces around an initializer, step over it.
7673 if (ILE->isTransparent())
7674 Init = ILE->getInit(0);
7675 }
7676
7677 // Step over any subobject adjustments; we may have a materialized
7678 // temporary inside them.
7679 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7680
7681 // Per current approach for DR1376, look through casts to reference type
7682 // when performing lifetime extension.
7683 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
7684 if (CE->getSubExpr()->isGLValue())
7685 Init = CE->getSubExpr();
7686
7687 // Per the current approach for DR1299, look through array element access
7688 // on array glvalues when performing lifetime extension.
7689 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
7690 Init = ASE->getBase();
7691 auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
7692 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
7693 Init = ICE->getSubExpr();
7694 else
7695 // We can't lifetime extend through this but we might still find some
7696 // retained temporaries.
7697 return visitLocalsRetainedByInitializer(Path, Init, Visit, true,
7698 EnableLifetimeWarnings);
7699 }
7700
7701 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7702 // constructor inherits one as an implicit mem-initializer.
7703 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7704 Path.push_back(
7705 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7706 Init = DIE->getExpr();
7707 }
7708 } while (Init != Old);
7709
7710 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
7711 if (Visit(Path, Local(MTE), RK))
7712 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true,
7713 EnableLifetimeWarnings);
7714 }
7715
7716 if (isa<CallExpr>(Init)) {
7717 if (EnableLifetimeWarnings)
7718 handleGslAnnotatedTypes(Path, Init, Visit);
7719 return visitLifetimeBoundArguments(Path, Init, Visit);
7720 }
7721
7722 switch (Init->getStmtClass()) {
7723 case Stmt::DeclRefExprClass: {
7724 // If we find the name of a local non-reference parameter, we could have a
7725 // lifetime problem.
7726 auto *DRE = cast<DeclRefExpr>(Init);
7727 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7728 if (VD && VD->hasLocalStorage() &&
7729 !DRE->refersToEnclosingVariableOrCapture()) {
7730 if (!VD->getType()->isReferenceType()) {
7731 Visit(Path, Local(DRE), RK);
7732 } else if (isa<ParmVarDecl>(DRE->getDecl())) {
7733 // The lifetime of a reference parameter is unknown; assume it's OK
7734 // for now.
7735 break;
7736 } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
7737 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7738 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
7739 RK_ReferenceBinding, Visit,
7740 EnableLifetimeWarnings);
7741 }
7742 }
7743 break;
7744 }
7745
7746 case Stmt::UnaryOperatorClass: {
7747 // The only unary operator that make sense to handle here
7748 // is Deref. All others don't resolve to a "name." This includes
7749 // handling all sorts of rvalues passed to a unary operator.
7750 const UnaryOperator *U = cast<UnaryOperator>(Init);
7751 if (U->getOpcode() == UO_Deref)
7752 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true,
7753 EnableLifetimeWarnings);
7754 break;
7755 }
7756
7757 case Stmt::ArraySectionExprClass: {
7759 cast<ArraySectionExpr>(Init)->getBase(),
7760 Visit, true, EnableLifetimeWarnings);
7761 break;
7762 }
7763
7764 case Stmt::ConditionalOperatorClass:
7765 case Stmt::BinaryConditionalOperatorClass: {
7766 auto *C = cast<AbstractConditionalOperator>(Init);
7767 if (!C->getTrueExpr()->getType()->isVoidType())
7768 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit,
7769 EnableLifetimeWarnings);
7770 if (!C->getFalseExpr()->getType()->isVoidType())
7771 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit,
7772 EnableLifetimeWarnings);
7773 break;
7774 }
7775
7776 case Stmt::CompoundLiteralExprClass: {
7777 if (auto *CLE = dyn_cast<CompoundLiteralExpr>(Init)) {
7778 if (!CLE->isFileScope())
7779 Visit(Path, Local(CLE), RK);
7780 }
7781 break;
7782 }
7783
7784 // FIXME: Visit the left-hand side of an -> or ->*.
7785
7786 default:
7787 break;
7788 }
7789}
7790
7791/// Visit the locals that would be reachable through an object initialized by
7792/// the prvalue expression \c Init.
7793static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7794 Expr *Init, LocalVisitor Visit,
7795 bool RevisitSubinits,
7796 bool EnableLifetimeWarnings) {
7797 RevertToOldSizeRAII RAII(Path);
7798
7799 Expr *Old;
7800 do {
7801 Old = Init;
7802
7803 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7804 // constructor inherits one as an implicit mem-initializer.
7805 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7806 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7807 Init = DIE->getExpr();
7808 }
7809
7810 if (auto *FE = dyn_cast<FullExpr>(Init))
7811 Init = FE->getSubExpr();
7812
7813 // Dig out the expression which constructs the extended temporary.
7814 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7815
7816 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
7817 Init = BTE->getSubExpr();
7818
7819 Init = Init->IgnoreParens();
7820
7821 // Step over value-preserving rvalue casts.
7822 if (auto *CE = dyn_cast<CastExpr>(Init)) {
7823 switch (CE->getCastKind()) {
7824 case CK_LValueToRValue:
7825 // If we can match the lvalue to a const object, we can look at its
7826 // initializer.
7827 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
7829 Path, Init, RK_ReferenceBinding,
7830 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
7831 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
7832 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7833 if (VD && VD->getType().isConstQualified() && VD->getInit() &&
7834 !isVarOnPath(Path, VD)) {
7835 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7836 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true,
7837 EnableLifetimeWarnings);
7838 }
7839 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
7840 if (MTE->getType().isConstQualified())
7841 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit,
7842 true, EnableLifetimeWarnings);
7843 }
7844 return false;
7845 }, EnableLifetimeWarnings);
7846
7847 // We assume that objects can be retained by pointers cast to integers,
7848 // but not if the integer is cast to floating-point type or to _Complex.
7849 // We assume that casts to 'bool' do not preserve enough information to
7850 // retain a local object.
7851 case CK_NoOp:
7852 case CK_BitCast:
7853 case CK_BaseToDerived:
7854 case CK_DerivedToBase:
7855 case CK_UncheckedDerivedToBase:
7856 case CK_Dynamic:
7857 case CK_ToUnion:
7858 case CK_UserDefinedConversion:
7859 case CK_ConstructorConversion:
7860 case CK_IntegralToPointer:
7861 case CK_PointerToIntegral:
7862 case CK_VectorSplat:
7863 case CK_IntegralCast:
7864 case CK_CPointerToObjCPointerCast:
7865 case CK_BlockPointerToObjCPointerCast:
7866 case CK_AnyPointerToBlockPointerCast:
7867 case CK_AddressSpaceConversion:
7868 break;
7869
7870 case CK_ArrayToPointerDecay:
7871 // Model array-to-pointer decay as taking the address of the array
7872 // lvalue.
7873 Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
7874 return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
7875 RK_ReferenceBinding, Visit,
7876 EnableLifetimeWarnings);
7877
7878 default:
7879 return;
7880 }
7881
7882 Init = CE->getSubExpr();
7883 }
7884 } while (Old != Init);
7885
7886 // C++17 [dcl.init.list]p6:
7887 // initializing an initializer_list object from the array extends the
7888 // lifetime of the array exactly like binding a reference to a temporary.
7889 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
7890 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
7891 RK_StdInitializerList, Visit,
7892 EnableLifetimeWarnings);
7893
7894 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7895 // We already visited the elements of this initializer list while
7896 // performing the initialization. Don't visit them again unless we've
7897 // changed the lifetime of the initialized entity.
7898 if (!RevisitSubinits)
7899 return;
7900
7901 if (ILE->isTransparent())
7902 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
7903 RevisitSubinits,
7904 EnableLifetimeWarnings);
7905
7906 if (ILE->getType()->isArrayType()) {
7907 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
7908 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
7909 RevisitSubinits,
7910 EnableLifetimeWarnings);
7911 return;
7912 }
7913
7914 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
7915 assert(RD->isAggregate() && "aggregate init on non-aggregate");
7916
7917 // If we lifetime-extend a braced initializer which is initializing an
7918 // aggregate, and that aggregate contains reference members which are
7919 // bound to temporaries, those temporaries are also lifetime-extended.
7920 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
7923 RK_ReferenceBinding, Visit,
7924 EnableLifetimeWarnings);
7925 else {
7926 unsigned Index = 0;
7927 for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
7928 visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
7929 RevisitSubinits,
7930 EnableLifetimeWarnings);
7931 for (const auto *I : RD->fields()) {
7932 if (Index >= ILE->getNumInits())
7933 break;
7934 if (I->isUnnamedBitField())
7935 continue;
7936 Expr *SubInit = ILE->getInit(Index);
7937 if (I->getType()->isReferenceType())
7939 RK_ReferenceBinding, Visit,
7940 EnableLifetimeWarnings);
7941 else
7942 // This might be either aggregate-initialization of a member or
7943 // initialization of a std::initializer_list object. Regardless,
7944 // we should recursively lifetime-extend that initializer.
7945 visitLocalsRetainedByInitializer(Path, SubInit, Visit,
7946 RevisitSubinits,
7947 EnableLifetimeWarnings);
7948 ++Index;
7949 }
7950 }
7951 }
7952 return;
7953 }
7954
7955 // The lifetime of an init-capture is that of the closure object constructed
7956 // by a lambda-expression.
7957 if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
7958 LambdaExpr::capture_iterator CapI = LE->capture_begin();
7959 for (Expr *E : LE->capture_inits()) {
7960 assert(CapI != LE->capture_end());
7961 const LambdaCapture &Cap = *CapI++;
7962 if (!E)
7963 continue;
7964 if (Cap.capturesVariable())
7965 Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap});
7966 if (E->isGLValue())
7967 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
7968 Visit, EnableLifetimeWarnings);
7969 else
7970 visitLocalsRetainedByInitializer(Path, E, Visit, true,
7971 EnableLifetimeWarnings);
7972 if (Cap.capturesVariable())
7973 Path.pop_back();
7974 }
7975 }
7976
7977 // Assume that a copy or move from a temporary references the same objects
7978 // that the temporary does.
7979 if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
7980 if (CCE->getConstructor()->isCopyOrMoveConstructor()) {
7981 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) {
7982 Expr *Arg = MTE->getSubExpr();
7983 Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg,
7984 CCE->getConstructor()});
7985 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7986 /*EnableLifetimeWarnings*/false);
7987 Path.pop_back();
7988 }
7989 }
7990 }
7991
7992 if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) {
7993 if (EnableLifetimeWarnings)
7994 handleGslAnnotatedTypes(Path, Init, Visit);
7995 return visitLifetimeBoundArguments(Path, Init, Visit);
7996 }
7997
7998 switch (Init->getStmtClass()) {
7999 case Stmt::UnaryOperatorClass: {
8000 auto *UO = cast<UnaryOperator>(Init);
8001 // If the initializer is the address of a local, we could have a lifetime
8002 // problem.
8003 if (UO->getOpcode() == UO_AddrOf) {
8004 // If this is &rvalue, then it's ill-formed and we have already diagnosed
8005 // it. Don't produce a redundant warning about the lifetime of the
8006 // temporary.
8007 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
8008 return;
8009
8010 Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
8011 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
8012 RK_ReferenceBinding, Visit,
8013 EnableLifetimeWarnings);
8014 }
8015 break;
8016 }
8017
8018 case Stmt::BinaryOperatorClass: {
8019 // Handle pointer arithmetic.
8020 auto *BO = cast<BinaryOperator>(Init);
8021 BinaryOperatorKind BOK = BO->getOpcode();
8022 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
8023 break;
8024
8025 if (BO->getLHS()->getType()->isPointerType())
8026 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true,
8027 EnableLifetimeWarnings);
8028 else if (BO->getRHS()->getType()->isPointerType())
8029 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true,
8030 EnableLifetimeWarnings);
8031 break;
8032 }
8033
8034 case Stmt::ConditionalOperatorClass:
8035 case Stmt::BinaryConditionalOperatorClass: {
8036 auto *C = cast<AbstractConditionalOperator>(Init);
8037 // In C++, we can have a throw-expression operand, which has 'void' type
8038 // and isn't interesting from a lifetime perspective.
8039 if (!C->getTrueExpr()->getType()->isVoidType())
8040 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true,
8041 EnableLifetimeWarnings);
8042 if (!C->getFalseExpr()->getType()->isVoidType())
8043 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true,
8044 EnableLifetimeWarnings);
8045 break;
8046 }
8047
8048 case Stmt::BlockExprClass:
8049 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
8050 // This is a local block, whose lifetime is that of the function.
8051 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
8052 }
8053 break;
8054
8055 case Stmt::AddrLabelExprClass:
8056 // We want to warn if the address of a label would escape the function.
8057 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
8058 break;
8059
8060 default:
8061 break;
8062 }
8063}
8064
8065/// Whether a path to an object supports lifetime extension.
8067 /// Lifetime-extend along this path.
8069 /// We should lifetime-extend, but we don't because (due to technical
8070 /// limitations) we can't. This happens for default member initializers,
8071 /// which we don't clone for every use, so we don't have a unique
8072 /// MaterializeTemporaryExpr to update.
8074 /// Do not lifetime extend along this path.
8075 NoExtend
8077
8078/// Determine whether this is an indirect path to a temporary that we are
8079/// supposed to lifetime-extend along.
8080static PathLifetimeKind
8081shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
8082 PathLifetimeKind Kind = PathLifetimeKind::Extend;
8083 for (auto Elem : Path) {
8084 if (Elem.Kind == IndirectLocalPathEntry::DefaultInit)
8085 Kind = PathLifetimeKind::ShouldExtend;
8086 else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit)
8087 return PathLifetimeKind::NoExtend;
8088 }
8089 return Kind;
8090}
8091
8092/// Find the range for the first interesting entry in the path at or after I.
8093static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
8094 Expr *E) {
8095 for (unsigned N = Path.size(); I != N; ++I) {
8096 switch (Path[I].Kind) {
8097 case IndirectLocalPathEntry::AddressOf:
8098 case IndirectLocalPathEntry::LValToRVal:
8099 case IndirectLocalPathEntry::LifetimeBoundCall:
8100 case IndirectLocalPathEntry::TemporaryCopy:
8101 case IndirectLocalPathEntry::GslReferenceInit:
8102 case IndirectLocalPathEntry::GslPointerInit:
8103 // These exist primarily to mark the path as not permitting or
8104 // supporting lifetime extension.
8105 break;
8106
8107 case IndirectLocalPathEntry::VarInit:
8108 if (cast<VarDecl>(Path[I].D)->isImplicit())
8109 return SourceRange();
8110 [[fallthrough]];
8111 case IndirectLocalPathEntry::DefaultInit:
8112 return Path[I].E->getSourceRange();
8113
8114 case IndirectLocalPathEntry::LambdaCaptureInit:
8115 if (!Path[I].Capture->capturesVariable())
8116 continue;
8117 return Path[I].E->getSourceRange();
8118 }
8119 }
8120 return E->getSourceRange();
8121}
8122
8123static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
8124 for (const auto &It : llvm::reverse(Path)) {
8125 if (It.Kind == IndirectLocalPathEntry::VarInit)
8126 continue;
8127 if (It.Kind == IndirectLocalPathEntry::AddressOf)
8128 continue;
8129 if (It.Kind == IndirectLocalPathEntry::LifetimeBoundCall)
8130 continue;
8131 return It.Kind == IndirectLocalPathEntry::GslPointerInit ||
8132 It.Kind == IndirectLocalPathEntry::GslReferenceInit;
8133 }
8134 return false;
8135}
8136
8138 Expr *Init) {
8139 LifetimeResult LR = getEntityLifetime(&Entity);
8140 LifetimeKind LK = LR.getInt();
8141 const InitializedEntity *ExtendingEntity = LR.getPointer();
8142
8143 // If this entity doesn't have an interesting lifetime, don't bother looking
8144 // for temporaries within its initializer.
8145 if (LK == LK_FullExpression)
8146 return;
8147
8148 auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
8149 ReferenceKind RK) -> bool {
8150 SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
8151 SourceLocation DiagLoc = DiagRange.getBegin();
8152
8153 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
8154
8155 bool IsGslPtrInitWithGslTempOwner = false;
8156 bool IsLocalGslOwner = false;
8158 if (isa<DeclRefExpr>(L)) {
8159 // We do not want to follow the references when returning a pointer originating
8160 // from a local owner to avoid the following false positive:
8161 // int &p = *localUniquePtr;
8162 // someContainer.add(std::move(localUniquePtr));
8163 // return p;
8164 IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType());
8165 if (pathContainsInit(Path) || !IsLocalGslOwner)
8166 return false;
8167 } else {
8168 IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
8169 isRecordWithAttr<OwnerAttr>(MTE->getType());
8170 // Skipping a chain of initializing gsl::Pointer annotated objects.
8171 // We are looking only for the final source to find out if it was
8172 // a local or temporary owner or the address of a local variable/param.
8173 if (!IsGslPtrInitWithGslTempOwner)
8174 return true;
8175 }
8176 }
8177
8178 switch (LK) {
8179 case LK_FullExpression:
8180 llvm_unreachable("already handled this");
8181
8182 case LK_Extended: {
8183 if (!MTE) {
8184 // The initialized entity has lifetime beyond the full-expression,
8185 // and the local entity does too, so don't warn.
8186 //
8187 // FIXME: We should consider warning if a static / thread storage
8188 // duration variable retains an automatic storage duration local.
8189 return false;
8190 }
8191
8192 if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
8193 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8194 return false;
8195 }
8196
8197 switch (shouldLifetimeExtendThroughPath(Path)) {
8198 case PathLifetimeKind::Extend:
8199 // Update the storage duration of the materialized temporary.
8200 // FIXME: Rebuild the expression instead of mutating it.
8201 MTE->setExtendingDecl(ExtendingEntity->getDecl(),
8202 ExtendingEntity->allocateManglingNumber());
8203 // Also visit the temporaries lifetime-extended by this initializer.
8204 return true;
8205
8206 case PathLifetimeKind::ShouldExtend:
8207 // We're supposed to lifetime-extend the temporary along this path (per
8208 // the resolution of DR1815), but we don't support that yet.
8209 //
8210 // FIXME: Properly handle this situation. Perhaps the easiest approach
8211 // would be to clone the initializer expression on each use that would
8212 // lifetime extend its temporaries.
8213 Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
8214 << RK << DiagRange;
8215 break;
8216
8217 case PathLifetimeKind::NoExtend:
8218 // If the path goes through the initialization of a variable or field,
8219 // it can't possibly reach a temporary created in this full-expression.
8220 // We will have already diagnosed any problems with the initializer.
8221 if (pathContainsInit(Path))
8222 return false;
8223
8224 Diag(DiagLoc, diag::warn_dangling_variable)
8225 << RK << !Entity.getParent()
8226 << ExtendingEntity->getDecl()->isImplicit()
8227 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
8228 break;
8229 }
8230 break;
8231 }
8232
8233 case LK_MemInitializer: {
8234 if (isa<MaterializeTemporaryExpr>(L)) {
8235 // Under C++ DR1696, if a mem-initializer (or a default member
8236 // initializer used by the absence of one) would lifetime-extend a
8237 // temporary, the program is ill-formed.
8238 if (auto *ExtendingDecl =
8239 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8240 if (IsGslPtrInitWithGslTempOwner) {
8241 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
8242 << ExtendingDecl << DiagRange;
8243 Diag(ExtendingDecl->getLocation(),
8244 diag::note_ref_or_ptr_member_declared_here)
8245 << true;
8246 return false;
8247 }
8248 bool IsSubobjectMember = ExtendingEntity != &Entity;
8249 Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) !=
8250 PathLifetimeKind::NoExtend
8251 ? diag::err_dangling_member
8252 : diag::warn_dangling_member)
8253 << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
8254 // Don't bother adding a note pointing to the field if we're inside
8255 // its default member initializer; our primary diagnostic points to
8256 // the same place in that case.
8257 if (Path.empty() ||
8258 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
8259 Diag(ExtendingDecl->getLocation(),
8260 diag::note_lifetime_extending_member_declared_here)
8261 << RK << IsSubobjectMember;
8262 }
8263 } else {
8264 // We have a mem-initializer but no particular field within it; this
8265 // is either a base class or a delegating initializer directly
8266 // initializing the base-class from something that doesn't live long
8267 // enough.
8268 //
8269 // FIXME: Warn on this.
8270 return false;
8271 }
8272 } else {
8273 // Paths via a default initializer can only occur during error recovery
8274 // (there's no other way that a default initializer can refer to a
8275 // local). Don't produce a bogus warning on those cases.
8276 if (pathContainsInit(Path))
8277 return false;
8278
8279 // Suppress false positives for code like the one below:
8280 // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {}
8281 if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
8282 return false;
8283
8284 auto *DRE = dyn_cast<DeclRefExpr>(L);
8285 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
8286 if (!VD) {
8287 // A member was initialized to a local block.
8288 // FIXME: Warn on this.
8289 return false;
8290 }
8291
8292 if (auto *Member =
8293 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8294 bool IsPointer = !Member->getType()->isReferenceType();
8295 Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
8296 : diag::warn_bind_ref_member_to_parameter)
8297 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
8298 Diag(Member->getLocation(),
8299 diag::note_ref_or_ptr_member_declared_here)
8300 << (unsigned)IsPointer;
8301 }
8302 }
8303 break;
8304 }
8305
8306 case LK_New:
8307 if (isa<MaterializeTemporaryExpr>(L)) {
8308 if (IsGslPtrInitWithGslTempOwner)
8309 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8310 else
8311 Diag(DiagLoc, RK == RK_ReferenceBinding
8312 ? diag::warn_new_dangling_reference
8313 : diag::warn_new_dangling_initializer_list)
8314 << !Entity.getParent() << DiagRange;
8315 } else {
8316 // We can't determine if the allocation outlives the local declaration.
8317 return false;
8318 }
8319 break;
8320
8321 case LK_Return:
8322 case LK_StmtExprResult:
8323 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
8324 // We can't determine if the local variable outlives the statement
8325 // expression.
8326 if (LK == LK_StmtExprResult)
8327 return false;
8328 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
8329 << Entity.getType()->isReferenceType() << DRE->getDecl()
8330 << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
8331 } else if (isa<BlockExpr>(L)) {
8332 Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
8333 } else if (isa<AddrLabelExpr>(L)) {
8334 // Don't warn when returning a label from a statement expression.
8335 // Leaving the scope doesn't end its lifetime.
8336 if (LK == LK_StmtExprResult)
8337 return false;
8338 Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
8339 } else if (auto *CLE = dyn_cast<CompoundLiteralExpr>(L)) {
8340 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
8341 << Entity.getType()->isReferenceType() << CLE->getInitializer() << 2
8342 << DiagRange;
8343 } else {
8344 // P2748R5: Disallow Binding a Returned Glvalue to a Temporary.
8345 // [stmt.return]/p6: In a function whose return type is a reference,
8346 // other than an invented function for std::is_convertible ([meta.rel]),
8347 // a return statement that binds the returned reference to a temporary
8348 // expression ([class.temporary]) is ill-formed.
8349 if (getLangOpts().CPlusPlus26 && Entity.getType()->isReferenceType())
8350 Diag(DiagLoc, diag::err_ret_local_temp_ref)
8351 << Entity.getType()->isReferenceType() << DiagRange;
8352 else
8353 Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
8354 << Entity.getType()->isReferenceType() << DiagRange;
8355 }
8356 break;
8357 }
8358
8359 for (unsigned I = 0; I != Path.size(); ++I) {
8360 auto Elem = Path[I];
8361
8362 switch (Elem.Kind) {
8363 case IndirectLocalPathEntry::AddressOf:
8364 case IndirectLocalPathEntry::LValToRVal:
8365 // These exist primarily to mark the path as not permitting or
8366 // supporting lifetime extension.
8367 break;
8368
8369 case IndirectLocalPathEntry::LifetimeBoundCall:
8370 case IndirectLocalPathEntry::TemporaryCopy:
8371 case IndirectLocalPathEntry::GslPointerInit:
8372 case IndirectLocalPathEntry::GslReferenceInit:
8373 // FIXME: Consider adding a note for these.
8374 break;
8375
8376 case IndirectLocalPathEntry::DefaultInit: {
8377 auto *FD = cast<FieldDecl>(Elem.D);
8378 Diag(FD->getLocation(), diag::note_init_with_default_member_initializer)
8379 << FD << nextPathEntryRange(Path, I + 1, L);
8380 break;
8381 }
8382
8383 case IndirectLocalPathEntry::VarInit: {
8384 const VarDecl *VD = cast<VarDecl>(Elem.D);
8385 Diag(VD->getLocation(), diag::note_local_var_initializer)
8386 << VD->getType()->isReferenceType()
8387 << VD->isImplicit() << VD->getDeclName()
8388 << nextPathEntryRange(Path, I + 1, L);
8389 break;
8390 }
8391
8392 case IndirectLocalPathEntry::LambdaCaptureInit:
8393 if (!Elem.Capture->capturesVariable())
8394 break;
8395 // FIXME: We can't easily tell apart an init-capture from a nested
8396 // capture of an init-capture.
8397 const ValueDecl *VD = Elem.Capture->getCapturedVar();
8398 Diag(Elem.Capture->getLocation(), diag::note_lambda_capture_initializer)
8399 << VD << VD->isInitCapture() << Elem.Capture->isExplicit()
8400 << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD
8401 << nextPathEntryRange(Path, I + 1, L);
8402 break;
8403 }
8404 }
8405
8406 // We didn't lifetime-extend, so don't go any further; we don't need more
8407 // warnings or errors on inner temporaries within this one's initializer.
8408 return false;
8409 };
8410
8411 bool EnableLifetimeWarnings = !getDiagnostics().isIgnored(
8412 diag::warn_dangling_lifetime_pointer, SourceLocation());
8414 if (Init->isGLValue())
8415 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
8416 TemporaryVisitor,
8417 EnableLifetimeWarnings);
8418 else
8419 visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false,
8420 EnableLifetimeWarnings);
8421}
8422
8423static void DiagnoseNarrowingInInitList(Sema &S,
8424 const ImplicitConversionSequence &ICS,
8425 QualType PreNarrowingType,
8426 QualType EntityType,
8427 const Expr *PostInit);
8428
8429static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
8430 QualType ToType, Expr *Init);
8431
8432/// Provide warnings when std::move is used on construction.
8433static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
8434 bool IsReturnStmt) {
8435 if (!InitExpr)
8436 return;
8437
8439 return;
8440
8441 QualType DestType = InitExpr->getType();
8442 if (!DestType->isRecordType())
8443 return;
8444
8445 unsigned DiagID = 0;
8446 if (IsReturnStmt) {
8447 const CXXConstructExpr *CCE =
8448 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
8449 if (!CCE || CCE->getNumArgs() != 1)
8450 return;
8451
8453 return;
8454
8455 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
8456 }
8457
8458 // Find the std::move call and get the argument.
8459 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
8460 if (!CE || !CE->isCallToStdMove())
8461 return;
8462
8463 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
8464
8465 if (IsReturnStmt) {
8466 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
8467 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
8468 return;
8469
8470 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
8471 if (!VD || !VD->hasLocalStorage())
8472 return;
8473
8474 // __block variables are not moved implicitly.
8475 if (VD->hasAttr<BlocksAttr>())
8476 return;
8477
8478 QualType SourceType = VD->getType();
8479 if (!SourceType->isRecordType())
8480 return;
8481
8482 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
8483 return;
8484 }
8485
8486 // If we're returning a function parameter, copy elision
8487 // is not possible.
8488 if (isa<ParmVarDecl>(VD))
8489 DiagID = diag::warn_redundant_move_on_return;
8490 else
8491 DiagID = diag::warn_pessimizing_move_on_return;
8492 } else {
8493 DiagID = diag::warn_pessimizing_move_on_initialization;
8494 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
8495 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
8496 return;
8497 }
8498
8499 S.Diag(CE->getBeginLoc(), DiagID);
8500
8501 // Get all the locations for a fix-it. Don't emit the fix-it if any location
8502 // is within a macro.
8503 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
8504 if (CallBegin.isMacroID())
8505 return;
8506 SourceLocation RParen = CE->getRParenLoc();
8507 if (RParen.isMacroID())
8508 return;
8509 SourceLocation LParen;
8510 SourceLocation ArgLoc = Arg->getBeginLoc();
8511
8512 // Special testing for the argument location. Since the fix-it needs the
8513 // location right before the argument, the argument location can be in a
8514 // macro only if it is at the beginning of the macro.
8515 while (ArgLoc.isMacroID() &&
8518 }
8519
8520 if (LParen.isMacroID())
8521 return;
8522
8523 LParen = ArgLoc.getLocWithOffset(-1);
8524
8525 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
8526 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
8527 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
8528}
8529
8530static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
8531 // Check to see if we are dereferencing a null pointer. If so, this is
8532 // undefined behavior, so warn about it. This only handles the pattern
8533 // "*null", which is a very syntactic check.
8534 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
8535 if (UO->getOpcode() == UO_Deref &&
8536 UO->getSubExpr()->IgnoreParenCasts()->
8537 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
8538 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
8539 S.PDiag(diag::warn_binding_null_to_reference)
8540 << UO->getSubExpr()->getSourceRange());
8541 }
8542}
8543
8546 bool BoundToLvalueReference) {
8547 auto MTE = new (Context)
8548 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
8549
8550 // Order an ExprWithCleanups for lifetime marks.
8551 //
8552 // TODO: It'll be good to have a single place to check the access of the
8553 // destructor and generate ExprWithCleanups for various uses. Currently these
8554 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
8555 // but there may be a chance to merge them.
8558 auto &Record = ExprEvalContexts.back();
8559 Record.ForRangeLifetimeExtendTemps.push_back(MTE);
8560 }
8561 return MTE;
8562}
8563
8565 // In C++98, we don't want to implicitly create an xvalue.
8566 // FIXME: This means that AST consumers need to deal with "prvalues" that
8567 // denote materialized temporaries. Maybe we should add another ValueKind
8568 // for "xvalue pretending to be a prvalue" for C++98 support.
8569 if (!E->isPRValue() || !getLangOpts().CPlusPlus11)
8570 return E;
8571
8572 // C++1z [conv.rval]/1: T shall be a complete type.
8573 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
8574 // If so, we should check for a non-abstract class type here too.
8575 QualType T = E->getType();
8576 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
8577 return ExprError();
8578
8579 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
8580}
8581
8583 ExprValueKind VK,
8585
8586 CastKind CK = CK_NoOp;
8587
8588 if (VK == VK_PRValue) {
8589 auto PointeeTy = Ty->getPointeeType();
8590 auto ExprPointeeTy = E->getType()->getPointeeType();
8591 if (!PointeeTy.isNull() &&
8592 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
8593 CK = CK_AddressSpaceConversion;
8594 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
8595 CK = CK_AddressSpaceConversion;
8596 }
8597
8598 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
8599}
8600
8602 const InitializedEntity &Entity,
8603 const InitializationKind &Kind,
8604 MultiExprArg Args,
8605 QualType *ResultType) {
8606 if (Failed()) {
8607 Diagnose(S, Entity, Kind, Args);
8608 return ExprError();
8609 }
8610 if (!ZeroInitializationFixit.empty()) {
8611 const Decl *D = Entity.getDecl();
8612 const auto *VD = dyn_cast_or_null<VarDecl>(D);
8613 QualType DestType = Entity.getType();
8614
8615 // The initialization would have succeeded with this fixit. Since the fixit
8616 // is on the error, we need to build a valid AST in this case, so this isn't
8617 // handled in the Failed() branch above.
8618 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
8619 // Use a more useful diagnostic for constexpr variables.
8620 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
8621 << VD
8622 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8623 ZeroInitializationFixit);
8624 } else {
8625 unsigned DiagID = diag::err_default_init_const;
8626 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
8627 DiagID = diag::ext_default_init_const;
8628
8629 S.Diag(Kind.getLocation(), DiagID)
8630 << DestType << (bool)DestType->getAs<RecordType>()
8631 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8632 ZeroInitializationFixit);
8633 }
8634 }
8635
8636 if (getKind() == DependentSequence) {
8637 // If the declaration is a non-dependent, incomplete array type
8638 // that has an initializer, then its type will be completed once
8639 // the initializer is instantiated.
8640 if (ResultType && !Entity.getType()->isDependentType() &&
8641 Args.size() == 1) {
8642 QualType DeclType = Entity.getType();
8643 if (const IncompleteArrayType *ArrayT
8644 = S.Context.getAsIncompleteArrayType(DeclType)) {
8645 // FIXME: We don't currently have the ability to accurately
8646 // compute the length of an initializer list without
8647 // performing full type-checking of the initializer list
8648 // (since we have to determine where braces are implicitly
8649 // introduced and such). So, we fall back to making the array
8650 // type a dependently-sized array type with no specified
8651 // bound.
8652 if (isa<InitListExpr>((Expr *)Args[0])) {
8653 SourceRange Brackets;
8654
8655 // Scavange the location of the brackets from the entity, if we can.
8656 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
8657 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
8658 TypeLoc TL = TInfo->getTypeLoc();
8659 if (IncompleteArrayTypeLoc ArrayLoc =
8661 Brackets = ArrayLoc.getBracketsRange();
8662 }
8663 }
8664
8665 *ResultType
8666 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
8667 /*NumElts=*/nullptr,
8668 ArrayT->getSizeModifier(),
8669 ArrayT->getIndexTypeCVRQualifiers(),
8670 Brackets);
8671 }
8672
8673 }
8674 }
8675 if (Kind.getKind() == InitializationKind::IK_Direct &&
8676 !Kind.isExplicitCast()) {
8677 // Rebuild the ParenListExpr.
8678 SourceRange ParenRange = Kind.getParenOrBraceRange();
8679 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
8680 Args);
8681 }
8682 assert(Kind.getKind() == InitializationKind::IK_Copy ||
8683 Kind.isExplicitCast() ||
8684 Kind.getKind() == InitializationKind::IK_DirectList);
8685 return ExprResult(Args[0]);
8686 }
8687
8688 // No steps means no initialization.
8689 if (Steps.empty())
8690 return ExprResult((Expr *)nullptr);
8691
8692 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
8693 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
8694 !Entity.isParamOrTemplateParamKind()) {
8695 // Produce a C++98 compatibility warning if we are initializing a reference
8696 // from an initializer list. For parameters, we produce a better warning
8697 // elsewhere.
8698 Expr *Init = Args[0];
8699 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
8700 << Init->getSourceRange();
8701 }
8702
8703 if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
8704 isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
8705 // Produce a Microsoft compatibility warning when initializing from a
8706 // predefined expression since MSVC treats predefined expressions as string
8707 // literals.
8708 Expr *Init = Args[0];
8709 S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
8710 }
8711
8712 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8713 QualType ETy = Entity.getType();
8714 bool HasGlobalAS = ETy.hasAddressSpace() &&
8716
8717 if (S.getLangOpts().OpenCLVersion >= 200 &&
8718 ETy->isAtomicType() && !HasGlobalAS &&
8719 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8720 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
8721 << 1
8722 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8723 return ExprError();
8724 }
8725
8726 QualType DestType = Entity.getType().getNonReferenceType();
8727 // FIXME: Ugly hack around the fact that Entity.getType() is not
8728 // the same as Entity.getDecl()->getType() in cases involving type merging,
8729 // and we want latter when it makes sense.
8730 if (ResultType)
8731 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8732 Entity.getType();
8733
8734 ExprResult CurInit((Expr *)nullptr);
8735 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8736
8737 // HLSL allows vector initialization to function like list initialization, but
8738 // use the syntax of a C++-like constructor.
8739 bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() &&
8740 isa<InitListExpr>(Args[0]);
8741 (void)IsHLSLVectorInit;
8742
8743 // For initialization steps that start with a single initializer,
8744 // grab the only argument out the Args and place it into the "current"
8745 // initializer.
8746 switch (Steps.front().Kind) {
8751 case SK_BindReference:
8753 case SK_FinalCopy:
8755 case SK_UserConversion:
8764 case SK_UnwrapInitList:
8765 case SK_RewrapInitList:
8766 case SK_CAssignment:
8767 case SK_StringInit:
8769 case SK_ArrayLoopIndex:
8770 case SK_ArrayLoopInit:
8771 case SK_ArrayInit:
8772 case SK_GNUArrayInit:
8778 case SK_OCLSamplerInit:
8779 case SK_OCLZeroOpaqueType: {
8780 assert(Args.size() == 1 || IsHLSLVectorInit);
8781 CurInit = Args[0];
8782 if (!CurInit.get()) return ExprError();
8783 break;
8784 }
8785
8791 break;
8792 }
8793
8794 // Promote from an unevaluated context to an unevaluated list context in
8795 // C++11 list-initialization; we need to instantiate entities usable in
8796 // constant expressions here in order to perform narrowing checks =(
8799 CurInit.get() && isa<InitListExpr>(CurInit.get()));
8800
8801 // C++ [class.abstract]p2:
8802 // no objects of an abstract class can be created except as subobjects
8803 // of a class derived from it
8804 auto checkAbstractType = [&](QualType T) -> bool {
8805 if (Entity.getKind() == InitializedEntity::EK_Base ||
8807 return false;
8808 return S.RequireNonAbstractType(Kind.getLocation(), T,
8809 diag::err_allocation_of_abstract_type);
8810 };
8811
8812 // Walk through the computed steps for the initialization sequence,
8813 // performing the specified conversions along the way.
8814 bool ConstructorInitRequiresZeroInit = false;
8815 for (step_iterator Step = step_begin(), StepEnd = step_end();
8816 Step != StepEnd; ++Step) {
8817 if (CurInit.isInvalid())
8818 return ExprError();
8819
8820 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8821
8822 switch (Step->Kind) {
8824 // Overload resolution determined which function invoke; update the
8825 // initializer to reflect that choice.
8827 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
8828 return ExprError();
8829 CurInit = S.FixOverloadedFunctionReference(CurInit,
8832 // We might get back another placeholder expression if we resolved to a
8833 // builtin.
8834 if (!CurInit.isInvalid())
8835 CurInit = S.CheckPlaceholderExpr(CurInit.get());
8836 break;
8837
8841 // We have a derived-to-base cast that produces either an rvalue or an
8842 // lvalue. Perform that cast.
8843
8844 CXXCastPath BasePath;
8845
8846 // Casts to inaccessible base classes are allowed with C-style casts.
8847 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8849 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8850 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8851 return ExprError();
8852
8853 ExprValueKind VK =
8855 ? VK_LValue
8857 : VK_PRValue);
8859 CK_DerivedToBase, CurInit.get(),
8860 &BasePath, VK, FPOptionsOverride());
8861 break;
8862 }
8863
8864 case SK_BindReference:
8865 // Reference binding does not have any corresponding ASTs.
8866
8867 // Check exception specifications
8868 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8869 return ExprError();
8870
8871 // We don't check for e.g. function pointers here, since address
8872 // availability checks should only occur when the function first decays
8873 // into a pointer or reference.
8874 if (CurInit.get()->getType()->isFunctionProtoType()) {
8875 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8876 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8877 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8878 DRE->getBeginLoc()))
8879 return ExprError();
8880 }
8881 }
8882 }
8883
8884 CheckForNullPointerDereference(S, CurInit.get());
8885 break;
8886
8888 // Make sure the "temporary" is actually an rvalue.
8889 assert(CurInit.get()->isPRValue() && "not a temporary");
8890
8891 // Check exception specifications
8892 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8893 return ExprError();
8894
8895 QualType MTETy = Step->Type;
8896
8897 // When this is an incomplete array type (such as when this is
8898 // initializing an array of unknown bounds from an init list), use THAT
8899 // type instead so that we propagate the array bounds.
8900 if (MTETy->isIncompleteArrayType() &&
8901 !CurInit.get()->getType()->isIncompleteArrayType() &&
8904 CurInit.get()->getType()->getPointeeOrArrayElementType()))
8905 MTETy = CurInit.get()->getType();
8906
8907 // Materialize the temporary into memory.
8909 MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8910 CurInit = MTE;
8911
8912 // If we're extending this temporary to automatic storage duration -- we
8913 // need to register its cleanup during the full-expression's cleanups.
8914 if (MTE->getStorageDuration() == SD_Automatic &&
8915 MTE->getType().isDestructedType())
8917 break;
8918 }
8919
8920 case SK_FinalCopy:
8921 if (checkAbstractType(Step->Type))
8922 return ExprError();
8923
8924 // If the overall initialization is initializing a temporary, we already
8925 // bound our argument if it was necessary to do so. If not (if we're
8926 // ultimately initializing a non-temporary), our argument needs to be
8927 // bound since it's initializing a function parameter.
8928 // FIXME: This is a mess. Rationalize temporary destruction.
8929 if (!shouldBindAsTemporary(Entity))
8930 CurInit = S.MaybeBindToTemporary(CurInit.get());
8931 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8932 /*IsExtraneousCopy=*/false);
8933 break;
8934
8936 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8937 /*IsExtraneousCopy=*/true);
8938 break;
8939
8940 case SK_UserConversion: {
8941 // We have a user-defined conversion that invokes either a constructor
8942 // or a conversion function.
8946 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8947 bool CreatedObject = false;
8948 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8949 // Build a call to the selected constructor.
8950 SmallVector<Expr*, 8> ConstructorArgs;
8951 SourceLocation Loc = CurInit.get()->getBeginLoc();
8952
8953 // Determine the arguments required to actually perform the constructor
8954 // call.
8955 Expr *Arg = CurInit.get();
8956 if (S.CompleteConstructorCall(Constructor, Step->Type,
8957 MultiExprArg(&Arg, 1), Loc,
8958 ConstructorArgs))
8959 return ExprError();
8960
8961 // Build an expression that constructs a temporary.
8962 CurInit = S.BuildCXXConstructExpr(
8963 Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
8964 HadMultipleCandidates,
8965 /*ListInit*/ false,
8966 /*StdInitListInit*/ false,
8967 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
8968 if (CurInit.isInvalid())
8969 return ExprError();
8970
8971 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8972 Entity);
8973 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8974 return ExprError();
8975
8976 CastKind = CK_ConstructorConversion;
8977 CreatedObject = true;
8978 } else {
8979 // Build a call to the conversion function.
8980 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
8981 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8982 FoundFn);
8983 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8984 return ExprError();
8985
8986 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8987 HadMultipleCandidates);
8988 if (CurInit.isInvalid())
8989 return ExprError();
8990
8991 CastKind = CK_UserDefinedConversion;
8992 CreatedObject = Conversion->getReturnType()->isRecordType();
8993 }
8994
8995 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8996 return ExprError();
8997
8998 CurInit = ImplicitCastExpr::Create(
8999 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
9000 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
9001
9002 if (shouldBindAsTemporary(Entity))
9003 // The overall entity is temporary, so this expression should be
9004 // destroyed at the end of its full-expression.
9005 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
9006 else if (CreatedObject && shouldDestroyEntity(Entity)) {
9007 // The object outlasts the full-expression, but we need to prepare for
9008 // a destructor being run on it.
9009 // FIXME: It makes no sense to do this here. This should happen
9010 // regardless of how we initialized the entity.
9011 QualType T = CurInit.get()->getType();
9012 if (const RecordType *Record = T->getAs<RecordType>()) {
9014 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
9016 S.PDiag(diag::err_access_dtor_temp) << T);
9018 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
9019 return ExprError();
9020 }
9021 }
9022 break;
9023 }
9024
9028 // Perform a qualification conversion; these can never go wrong.
9029 ExprValueKind VK =
9031 ? VK_LValue
9033 : VK_PRValue);
9034 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
9035 break;
9036 }
9037
9039 assert(CurInit.get()->isLValue() &&
9040 "function reference should be lvalue");
9041 CurInit =
9042 S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
9043 break;
9044
9045 case SK_AtomicConversion: {
9046 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
9047 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9048 CK_NonAtomicToAtomic, VK_PRValue);
9049 break;
9050 }
9051
9054 if (const auto *FromPtrType =
9055 CurInit.get()->getType()->getAs<PointerType>()) {
9056 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
9057 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9058 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9059 // Do not check static casts here because they are checked earlier
9060 // in Sema::ActOnCXXNamedCast()
9061 if (!Kind.isStaticCast()) {
9062 S.Diag(CurInit.get()->getExprLoc(),
9063 diag::warn_noderef_to_dereferenceable_pointer)
9064 << CurInit.get()->getSourceRange();
9065 }
9066 }
9067 }
9068 }
9069
9071 Kind.isCStyleCast() ? CheckedConversionKind::CStyleCast
9072 : Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast
9073 : Kind.isExplicitCast() ? CheckedConversionKind::OtherCast
9075 ExprResult CurInitExprRes =
9076 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
9077 getAssignmentAction(Entity), CCK);
9078 if (CurInitExprRes.isInvalid())
9079 return ExprError();
9080
9082
9083 CurInit = CurInitExprRes;
9084
9086 S.getLangOpts().CPlusPlus)
9087 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
9088 CurInit.get());
9089
9090 break;
9091 }
9092
9093 case SK_ListInitialization: {
9094 if (checkAbstractType(Step->Type))
9095 return ExprError();
9096
9097 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
9098 // If we're not initializing the top-level entity, we need to create an
9099 // InitializeTemporary entity for our target type.
9100 QualType Ty = Step->Type;
9101 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
9103 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
9104 InitListChecker PerformInitList(S, InitEntity,
9105 InitList, Ty, /*VerifyOnly=*/false,
9106 /*TreatUnavailableAsInvalid=*/false);
9107 if (PerformInitList.HadError())
9108 return ExprError();
9109
9110 // Hack: We must update *ResultType if available in order to set the
9111 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
9112 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
9113 if (ResultType &&
9114 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
9115 if ((*ResultType)->isRValueReferenceType())
9117 else if ((*ResultType)->isLValueReferenceType())
9119 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
9120 *ResultType = Ty;
9121 }
9122
9123 InitListExpr *StructuredInitList =
9124 PerformInitList.getFullyStructuredList();
9125 CurInit.get();
9126 CurInit = shouldBindAsTemporary(InitEntity)
9127 ? S.MaybeBindToTemporary(StructuredInitList)
9128 : StructuredInitList;
9129 break;
9130 }
9131
9133 if (checkAbstractType(Step->Type))
9134 return ExprError();
9135
9136 // When an initializer list is passed for a parameter of type "reference
9137 // to object", we don't get an EK_Temporary entity, but instead an
9138 // EK_Parameter entity with reference type.
9139 // FIXME: This is a hack. What we really should do is create a user
9140 // conversion step for this case, but this makes it considerably more
9141 // complicated. For now, this will do.
9143 Entity.getType().getNonReferenceType());
9144 bool UseTemporary = Entity.getType()->isReferenceType();
9145 assert(Args.size() == 1 && "expected a single argument for list init");
9146 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9147 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
9148 << InitList->getSourceRange();
9149 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
9150 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
9151 Entity,
9152 Kind, Arg, *Step,
9153 ConstructorInitRequiresZeroInit,
9154 /*IsListInitialization*/true,
9155 /*IsStdInitListInit*/false,
9156 InitList->getLBraceLoc(),
9157 InitList->getRBraceLoc());
9158 break;
9159 }
9160
9161 case SK_UnwrapInitList:
9162 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
9163 break;
9164
9165 case SK_RewrapInitList: {
9166 Expr *E = CurInit.get();
9168 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
9169 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
9170 ILE->setSyntacticForm(Syntactic);
9171 ILE->setType(E->getType());
9172 ILE->setValueKind(E->getValueKind());
9173 CurInit = ILE;
9174 break;
9175 }
9176
9179 if (checkAbstractType(Step->Type))
9180 return ExprError();
9181
9182 // When an initializer list is passed for a parameter of type "reference
9183 // to object", we don't get an EK_Temporary entity, but instead an
9184 // EK_Parameter entity with reference type.
9185 // FIXME: This is a hack. What we really should do is create a user
9186 // conversion step for this case, but this makes it considerably more
9187 // complicated. For now, this will do.
9189 Entity.getType().getNonReferenceType());
9190 bool UseTemporary = Entity.getType()->isReferenceType();
9191 bool IsStdInitListInit =
9193 Expr *Source = CurInit.get();
9194 SourceRange Range = Kind.hasParenOrBraceRange()
9195 ? Kind.getParenOrBraceRange()
9196 : SourceRange();
9198 S, UseTemporary ? TempEntity : Entity, Kind,
9199 Source ? MultiExprArg(Source) : Args, *Step,
9200 ConstructorInitRequiresZeroInit,
9201 /*IsListInitialization*/ IsStdInitListInit,
9202 /*IsStdInitListInitialization*/ IsStdInitListInit,
9203 /*LBraceLoc*/ Range.getBegin(),
9204 /*RBraceLoc*/ Range.getEnd());
9205 break;
9206 }
9207
9208 case SK_ZeroInitialization: {
9209 step_iterator NextStep = Step;
9210 ++NextStep;
9211 if (NextStep != StepEnd &&
9212 (NextStep->Kind == SK_ConstructorInitialization ||
9213 NextStep->Kind == SK_ConstructorInitializationFromList)) {
9214 // The need for zero-initialization is recorded directly into
9215 // the call to the object's constructor within the next step.
9216 ConstructorInitRequiresZeroInit = true;
9217 } else if (Kind.getKind() == InitializationKind::IK_Value &&
9218 S.getLangOpts().CPlusPlus &&
9219 !Kind.isImplicitValueInit()) {
9220 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
9221 if (!TSInfo)
9223 Kind.getRange().getBegin());
9224
9225 CurInit = new (S.Context) CXXScalarValueInitExpr(
9226 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
9227 Kind.getRange().getEnd());
9228 } else {
9229 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
9230 }
9231 break;
9232 }
9233
9234 case SK_CAssignment: {
9235 QualType SourceType = CurInit.get()->getType();
9236
9237 // Save off the initial CurInit in case we need to emit a diagnostic
9238 ExprResult InitialCurInit = CurInit;
9239 ExprResult Result = CurInit;
9243 if (Result.isInvalid())
9244 return ExprError();
9245 CurInit = Result;
9246
9247 // If this is a call, allow conversion to a transparent union.
9248 ExprResult CurInitExprRes = CurInit;
9249 if (ConvTy != Sema::Compatible &&
9250 Entity.isParameterKind() &&
9253 ConvTy = Sema::Compatible;
9254 if (CurInitExprRes.isInvalid())
9255 return ExprError();
9256 CurInit = CurInitExprRes;
9257
9258 if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) {
9259 CheckC23ConstexprInitConversion(S, SourceType, Entity.getType(),
9260 CurInit.get());
9261
9262 // C23 6.7.1p6: If an object or subobject declared with storage-class
9263 // specifier constexpr has pointer, integer, or arithmetic type, any
9264 // explicit initializer value for it shall be null, an integer
9265 // constant expression, or an arithmetic constant expression,
9266 // respectively.
9268 if (Entity.getType()->getAs<PointerType>() &&
9269 CurInit.get()->EvaluateAsRValue(ER, S.Context) &&
9270 !ER.Val.isNullPointer()) {
9271 S.Diag(Kind.getLocation(), diag::err_c23_constexpr_pointer_not_null);
9272 }
9273 }
9274
9275 bool Complained;
9276 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
9277 Step->Type, SourceType,
9278 InitialCurInit.get(),
9279 getAssignmentAction(Entity, true),
9280 &Complained)) {
9281 PrintInitLocationNote(S, Entity);
9282 return ExprError();
9283 } else if (Complained)
9284 PrintInitLocationNote(S, Entity);
9285 break;
9286 }
9287
9288 case SK_StringInit: {
9289 QualType Ty = Step->Type;
9290 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
9291 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
9292 S.Context.getAsArrayType(Ty), S,
9293 S.getLangOpts().C23 &&
9295 break;
9296 }
9297
9299 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9300 CK_ObjCObjectLValueCast,
9301 CurInit.get()->getValueKind());
9302 break;
9303
9304 case SK_ArrayLoopIndex: {
9305 Expr *Cur = CurInit.get();
9306 Expr *BaseExpr = new (S.Context)
9307 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
9308 Cur->getValueKind(), Cur->getObjectKind(), Cur);
9309 Expr *IndexExpr =
9312 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
9313 ArrayLoopCommonExprs.push_back(BaseExpr);
9314 break;
9315 }
9316
9317 case SK_ArrayLoopInit: {
9318 assert(!ArrayLoopCommonExprs.empty() &&
9319 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
9320 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
9321 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
9322 CurInit.get());
9323 break;
9324 }
9325
9326 case SK_GNUArrayInit:
9327 // Okay: we checked everything before creating this step. Note that
9328 // this is a GNU extension.
9329 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
9330 << Step->Type << CurInit.get()->getType()
9331 << CurInit.get()->getSourceRange();
9333 [[fallthrough]];
9334 case SK_ArrayInit:
9335 // If the destination type is an incomplete array type, update the
9336 // type accordingly.
9337 if (ResultType) {
9338 if (const IncompleteArrayType *IncompleteDest
9340 if (const ConstantArrayType *ConstantSource
9341 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
9342 *ResultType = S.Context.getConstantArrayType(
9343 IncompleteDest->getElementType(), ConstantSource->getSize(),
9344 ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
9345 }
9346 }
9347 }
9348 break;
9349
9351 // Okay: we checked everything before creating this step. Note that
9352 // this is a GNU extension.
9353 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
9354 << CurInit.get()->getSourceRange();
9355 break;
9356
9359 checkIndirectCopyRestoreSource(S, CurInit.get());
9360 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
9361 CurInit.get(), Step->Type,
9363 break;
9364
9366 CurInit = ImplicitCastExpr::Create(
9367 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
9369 break;
9370
9371 case SK_StdInitializerList: {
9372 S.Diag(CurInit.get()->getExprLoc(),
9373 diag::warn_cxx98_compat_initializer_list_init)
9374 << CurInit.get()->getSourceRange();
9375
9376 // Materialize the temporary into memory.
9378 CurInit.get()->getType(), CurInit.get(),
9379 /*BoundToLvalueReference=*/false);
9380
9381 // Wrap it in a construction of a std::initializer_list<T>.
9382 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
9383
9384 // Bind the result, in case the library has given initializer_list a
9385 // non-trivial destructor.
9386 if (shouldBindAsTemporary(Entity))
9387 CurInit = S.MaybeBindToTemporary(CurInit.get());
9388 break;
9389 }
9390
9391 case SK_OCLSamplerInit: {
9392 // Sampler initialization have 5 cases:
9393 // 1. function argument passing
9394 // 1a. argument is a file-scope variable
9395 // 1b. argument is a function-scope variable
9396 // 1c. argument is one of caller function's parameters
9397 // 2. variable initialization
9398 // 2a. initializing a file-scope variable
9399 // 2b. initializing a function-scope variable
9400 //
9401 // For file-scope variables, since they cannot be initialized by function
9402 // call of __translate_sampler_initializer in LLVM IR, their references
9403 // need to be replaced by a cast from their literal initializers to
9404 // sampler type. Since sampler variables can only be used in function
9405 // calls as arguments, we only need to replace them when handling the
9406 // argument passing.
9407 assert(Step->Type->isSamplerT() &&
9408 "Sampler initialization on non-sampler type.");
9409 Expr *Init = CurInit.get()->IgnoreParens();
9410 QualType SourceType = Init->getType();
9411 // Case 1
9412 if (Entity.isParameterKind()) {
9413 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
9414 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
9415 << SourceType;
9416 break;
9417 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
9418 auto Var = cast<VarDecl>(DRE->getDecl());
9419 // Case 1b and 1c
9420 // No cast from integer to sampler is needed.
9421 if (!Var->hasGlobalStorage()) {
9422 CurInit = ImplicitCastExpr::Create(
9423 S.Context, Step->Type, CK_LValueToRValue, Init,
9424 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
9425 break;
9426 }
9427 // Case 1a
9428 // For function call with a file-scope sampler variable as argument,
9429 // get the integer literal.
9430 // Do not diagnose if the file-scope variable does not have initializer
9431 // since this has already been diagnosed when parsing the variable
9432 // declaration.
9433 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
9434 break;
9435 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
9436 Var->getInit()))->getSubExpr();
9437 SourceType = Init->getType();
9438 }
9439 } else {
9440 // Case 2
9441 // Check initializer is 32 bit integer constant.
9442 // If the initializer is taken from global variable, do not diagnose since
9443 // this has already been done when parsing the variable declaration.
9444 if (!Init->isConstantInitializer(S.Context, false))
9445 break;
9446
9447 if (!SourceType->isIntegerType() ||
9448 32 != S.Context.getIntWidth(SourceType)) {
9449 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
9450 << SourceType;
9451 break;
9452 }
9453
9454 Expr::EvalResult EVResult;
9455 Init->EvaluateAsInt(EVResult, S.Context);
9456 llvm::APSInt Result = EVResult.Val.getInt();
9457 const uint64_t SamplerValue = Result.getLimitedValue();
9458 // 32-bit value of sampler's initializer is interpreted as
9459 // bit-field with the following structure:
9460 // |unspecified|Filter|Addressing Mode| Normalized Coords|
9461 // |31 6|5 4|3 1| 0|
9462 // This structure corresponds to enum values of sampler properties
9463 // defined in SPIR spec v1.2 and also opencl-c.h
9464 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
9465 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
9466 if (FilterMode != 1 && FilterMode != 2 &&
9468 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
9469 S.Diag(Kind.getLocation(),
9470 diag::warn_sampler_initializer_invalid_bits)
9471 << "Filter Mode";
9472 if (AddressingMode > 4)
9473 S.Diag(Kind.getLocation(),
9474 diag::warn_sampler_initializer_invalid_bits)
9475 << "Addressing Mode";
9476 }
9477
9478 // Cases 1a, 2a and 2b
9479 // Insert cast from integer to sampler.
9481 CK_IntToOCLSampler);
9482 break;
9483 }
9484 case SK_OCLZeroOpaqueType: {
9485 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
9487 "Wrong type for initialization of OpenCL opaque type.");
9488
9489 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9490 CK_ZeroToOCLOpaqueType,
9491 CurInit.get()->getValueKind());
9492 break;
9493 }
9495 CurInit = nullptr;
9496 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9497 /*VerifyOnly=*/false, &CurInit);
9498 if (CurInit.get() && ResultType)
9499 *ResultType = CurInit.get()->getType();
9500 if (shouldBindAsTemporary(Entity))
9501 CurInit = S.MaybeBindToTemporary(CurInit.get());
9502 break;
9503 }
9504 }
9505 }
9506
9507 Expr *Init = CurInit.get();
9508 if (!Init)
9509 return ExprError();
9510
9511 // Check whether the initializer has a shorter lifetime than the initialized
9512 // entity, and if not, either lifetime-extend or warn as appropriate.
9513 S.checkInitializerLifetime(Entity, Init);
9514
9515 // Diagnose non-fatal problems with the completed initialization.
9516 if (InitializedEntity::EntityKind EK = Entity.getKind();
9519 cast<FieldDecl>(Entity.getDecl())->isBitField())
9520 S.CheckBitFieldInitialization(Kind.getLocation(),
9521 cast<FieldDecl>(Entity.getDecl()), Init);
9522
9523 // Check for std::move on construction.
9526
9527 return Init;
9528}
9529
9530/// Somewhere within T there is an uninitialized reference subobject.
9531/// Dig it out and diagnose it.
9533 QualType T) {
9534 if (T->isReferenceType()) {
9535 S.Diag(Loc, diag::err_reference_without_init)
9536 << T.getNonReferenceType();
9537 return true;
9538 }
9539
9541 if (!RD || !RD->hasUninitializedReferenceMember())
9542 return false;
9543
9544 for (const auto *FI : RD->fields()) {
9545 if (FI->isUnnamedBitField())
9546 continue;
9547
9548 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
9549 S.Diag(Loc, diag::note_value_initialization_here) << RD;
9550 return true;
9551 }
9552 }
9553
9554 for (const auto &BI : RD->bases()) {
9555 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
9556 S.Diag(Loc, diag::note_value_initialization_here) << RD;
9557 return true;
9558 }
9559 }
9560
9561 return false;
9562}
9563
9564
9565//===----------------------------------------------------------------------===//
9566// Diagnose initialization failures
9567//===----------------------------------------------------------------------===//
9568
9569/// Emit notes associated with an initialization that failed due to a
9570/// "simple" conversion failure.
9571static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
9572 Expr *op) {
9573 QualType destType = entity.getType();
9574 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
9576
9577 // Emit a possible note about the conversion failing because the
9578 // operand is a message send with a related result type.
9580
9581 // Emit a possible note about a return failing because we're
9582 // expecting a related result type.
9583 if (entity.getKind() == InitializedEntity::EK_Result)
9585 }
9586 QualType fromType = op->getType();
9587 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
9588 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
9589 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
9590 auto *destDecl = destType->getPointeeCXXRecordDecl();
9591 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
9592 destDecl->getDeclKind() == Decl::CXXRecord &&
9593 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
9594 !fromDecl->hasDefinition() &&
9595 destPointeeType.getQualifiers().compatiblyIncludes(
9596 fromPointeeType.getQualifiers()))
9597 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
9598 << S.getASTContext().getTagDeclType(fromDecl)
9599 << S.getASTContext().getTagDeclType(destDecl);
9600}
9601
9602static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
9603 InitListExpr *InitList) {
9604 QualType DestType = Entity.getType();
9605
9606 QualType E;
9607 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
9609 E.withConst(),
9610 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
9611 InitList->getNumInits()),
9613 InitializedEntity HiddenArray =
9615 return diagnoseListInit(S, HiddenArray, InitList);
9616 }
9617
9618 if (DestType->isReferenceType()) {
9619 // A list-initialization failure for a reference means that we tried to
9620 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
9621 // inner initialization failed.
9622 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
9624 SourceLocation Loc = InitList->getBeginLoc();
9625 if (auto *D = Entity.getDecl())
9626 Loc = D->getLocation();
9627 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
9628 return;
9629 }
9630
9631 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
9632 /*VerifyOnly=*/false,
9633 /*TreatUnavailableAsInvalid=*/false);
9634 assert(DiagnoseInitList.HadError() &&
9635 "Inconsistent init list check result.");
9636}
9637
9639 const InitializedEntity &Entity,
9640 const InitializationKind &Kind,
9641 ArrayRef<Expr *> Args) {
9642 if (!Failed())
9643 return false;
9644
9645 QualType DestType = Entity.getType();
9646
9647 // When we want to diagnose only one element of a braced-init-list,
9648 // we need to factor it out.
9649 Expr *OnlyArg;
9650 if (Args.size() == 1) {
9651 auto *List = dyn_cast<InitListExpr>(Args[0]);
9652 if (List && List->getNumInits() == 1)
9653 OnlyArg = List->getInit(0);
9654 else
9655 OnlyArg = Args[0];
9656
9657 if (OnlyArg->getType() == S.Context.OverloadTy) {
9658 DeclAccessPair Found;
9660 OnlyArg, DestType.getNonReferenceType(), /*Complain=*/false,
9661 Found)) {
9662 if (Expr *Resolved =
9663 S.FixOverloadedFunctionReference(OnlyArg, Found, FD).get())
9664 OnlyArg = Resolved;
9665 }
9666 }
9667 }
9668 else
9669 OnlyArg = nullptr;
9670
9671 switch (Failure) {
9673 // FIXME: Customize for the initialized entity?
9674 if (Args.empty()) {
9675 // Dig out the reference subobject which is uninitialized and diagnose it.
9676 // If this is value-initialization, this could be nested some way within
9677 // the target type.
9678 assert(Kind.getKind() == InitializationKind::IK_Value ||
9679 DestType->isReferenceType());
9680 bool Diagnosed =
9681 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
9682 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
9683 (void)Diagnosed;
9684 } else // FIXME: diagnostic below could be better!
9685 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
9686 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9687 break;
9689 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9690 << 1 << Entity.getType() << Args[0]->getSourceRange();
9691 break;
9692
9694 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
9695 break;
9697 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
9698 break;
9700 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
9701 break;
9703 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
9704 break;
9706 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
9707 break;
9709 S.Diag(Kind.getLocation(),
9710 diag::err_array_init_incompat_wide_string_into_wchar);
9711 break;
9713 S.Diag(Kind.getLocation(),
9714 diag::err_array_init_plain_string_into_char8_t);
9715 S.Diag(Args.front()->getBeginLoc(),
9716 diag::note_array_init_plain_string_into_char8_t)
9717 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
9718 break;
9720 S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
9721 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9722 break;
9725 S.Diag(Kind.getLocation(),
9726 (Failure == FK_ArrayTypeMismatch
9727 ? diag::err_array_init_different_type
9728 : diag::err_array_init_non_constant_array))
9729 << DestType.getNonReferenceType()
9730 << OnlyArg->getType()
9731 << Args[0]->getSourceRange();
9732 break;
9733
9735 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
9736 << Args[0]->getSourceRange();
9737 break;
9738
9740 DeclAccessPair Found;
9742 DestType.getNonReferenceType(),
9743 true,
9744 Found);
9745 break;
9746 }
9747
9749 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
9750 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9751 OnlyArg->getBeginLoc());
9752 break;
9753 }
9754
9757 switch (FailedOverloadResult) {
9758 case OR_Ambiguous:
9759
9760 FailedCandidateSet.NoteCandidates(
9762 Kind.getLocation(),
9764 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
9765 << OnlyArg->getType() << DestType
9766 << Args[0]->getSourceRange())
9767 : (S.PDiag(diag::err_ref_init_ambiguous)
9768 << DestType << OnlyArg->getType()
9769 << Args[0]->getSourceRange())),
9770 S, OCD_AmbiguousCandidates, Args);
9771 break;
9772
9773 case OR_No_Viable_Function: {
9774 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
9775 if (!S.RequireCompleteType(Kind.getLocation(),
9776 DestType.getNonReferenceType(),
9777 diag::err_typecheck_nonviable_condition_incomplete,
9778 OnlyArg->getType(), Args[0]->getSourceRange()))
9779 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9780 << (Entity.getKind() == InitializedEntity::EK_Result)
9781 << OnlyArg->getType() << Args[0]->getSourceRange()
9782 << DestType.getNonReferenceType();
9783
9784 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9785 break;
9786 }
9787 case OR_Deleted: {
9790 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9791
9792 StringLiteral *Msg = Best->Function->getDeletedMessage();
9793 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9794 << OnlyArg->getType() << DestType.getNonReferenceType()
9795 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
9796 << Args[0]->getSourceRange();
9797 if (Ovl == OR_Deleted) {
9798 S.NoteDeletedFunction(Best->Function);
9799 } else {
9800 llvm_unreachable("Inconsistent overload resolution?");
9801 }
9802 break;
9803 }
9804
9805 case OR_Success:
9806 llvm_unreachable("Conversion did not fail!");
9807 }
9808 break;
9809
9811 if (isa<InitListExpr>(Args[0])) {
9812 S.Diag(Kind.getLocation(),
9813 diag::err_lvalue_reference_bind_to_initlist)
9815 << DestType.getNonReferenceType()
9816 << Args[0]->getSourceRange();
9817 break;
9818 }
9819 [[fallthrough]];
9820
9822 S.Diag(Kind.getLocation(),
9824 ? diag::err_lvalue_reference_bind_to_temporary
9825 : diag::err_lvalue_reference_bind_to_unrelated)
9827 << DestType.getNonReferenceType()
9828 << OnlyArg->getType()
9829 << Args[0]->getSourceRange();
9830 break;
9831
9833 // We don't necessarily have an unambiguous source bit-field.
9834 FieldDecl *BitField = Args[0]->getSourceBitField();
9835 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9836 << DestType.isVolatileQualified()
9837 << (BitField ? BitField->getDeclName() : DeclarationName())
9838 << (BitField != nullptr)
9839 << Args[0]->getSourceRange();
9840 if (BitField)
9841 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9842 break;
9843 }
9844
9846 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9847 << DestType.isVolatileQualified()
9848 << Args[0]->getSourceRange();
9849 break;
9850
9852 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9853 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9854 break;
9855
9857 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9858 << DestType.getNonReferenceType() << OnlyArg->getType()
9859 << Args[0]->getSourceRange();
9860 break;
9861
9863 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9864 << DestType << Args[0]->getSourceRange();
9865 break;
9866
9868 QualType SourceType = OnlyArg->getType();
9869 QualType NonRefType = DestType.getNonReferenceType();
9870 Qualifiers DroppedQualifiers =
9871 SourceType.getQualifiers() - NonRefType.getQualifiers();
9872
9873 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9874 SourceType.getQualifiers()))
9875 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9876 << NonRefType << SourceType << 1 /*addr space*/
9877 << Args[0]->getSourceRange();
9878 else if (DroppedQualifiers.hasQualifiers())
9879 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9880 << NonRefType << SourceType << 0 /*cv quals*/
9881 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9882 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9883 else
9884 // FIXME: Consider decomposing the type and explaining which qualifiers
9885 // were dropped where, or on which level a 'const' is missing, etc.
9886 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9887 << NonRefType << SourceType << 2 /*incompatible quals*/
9888 << Args[0]->getSourceRange();
9889 break;
9890 }
9891
9893 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9894 << DestType.getNonReferenceType()
9895 << DestType.getNonReferenceType()->isIncompleteType()
9896 << OnlyArg->isLValue()
9897 << OnlyArg->getType()
9898 << Args[0]->getSourceRange();
9899 emitBadConversionNotes(S, Entity, Args[0]);
9900 break;
9901
9902 case FK_ConversionFailed: {
9903 QualType FromType = OnlyArg->getType();
9904 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9905 << (int)Entity.getKind()
9906 << DestType
9907 << OnlyArg->isLValue()
9908 << FromType
9909 << Args[0]->getSourceRange();
9910 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9911 S.Diag(Kind.getLocation(), PDiag);
9912 emitBadConversionNotes(S, Entity, Args[0]);
9913 break;
9914 }
9915
9917 // No-op. This error has already been reported.
9918 break;
9919
9921 SourceRange R;
9922
9923 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9924 if (InitList && InitList->getNumInits() >= 1) {
9925 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9926 } else {
9927 assert(Args.size() > 1 && "Expected multiple initializers!");
9928 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9929 }
9930
9932 if (Kind.isCStyleOrFunctionalCast())
9933 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9934 << R;
9935 else
9936 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9937 << /*scalar=*/2 << R;
9938 break;
9939 }
9940
9942 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9943 << 0 << Entity.getType() << Args[0]->getSourceRange();
9944 break;
9945
9947 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9948 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9949 break;
9950
9952 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9953 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9954 break;
9955
9958 SourceRange ArgsRange;
9959 if (Args.size())
9960 ArgsRange =
9961 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9962
9963 if (Failure == FK_ListConstructorOverloadFailed) {
9964 assert(Args.size() == 1 &&
9965 "List construction from other than 1 argument.");
9966 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9967 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9968 }
9969
9970 // FIXME: Using "DestType" for the entity we're printing is probably
9971 // bad.
9972 switch (FailedOverloadResult) {
9973 case OR_Ambiguous:
9974 FailedCandidateSet.NoteCandidates(
9975 PartialDiagnosticAt(Kind.getLocation(),
9976 S.PDiag(diag::err_ovl_ambiguous_init)
9977 << DestType << ArgsRange),
9978 S, OCD_AmbiguousCandidates, Args);
9979 break;
9980
9982 if (Kind.getKind() == InitializationKind::IK_Default &&
9983 (Entity.getKind() == InitializedEntity::EK_Base ||
9986 isa<CXXConstructorDecl>(S.CurContext)) {
9987 // This is implicit default initialization of a member or
9988 // base within a constructor. If no viable function was
9989 // found, notify the user that they need to explicitly
9990 // initialize this base/member.
9991 CXXConstructorDecl *Constructor
9992 = cast<CXXConstructorDecl>(S.CurContext);
9993 const CXXRecordDecl *InheritedFrom = nullptr;
9994 if (auto Inherited = Constructor->getInheritedConstructor())
9995 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9996 if (Entity.getKind() == InitializedEntity::EK_Base) {
9997 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9998 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9999 << S.Context.getTypeDeclType(Constructor->getParent())
10000 << /*base=*/0
10001 << Entity.getType()
10002 << InheritedFrom;
10003
10004 RecordDecl *BaseDecl
10005 = Entity.getBaseSpecifier()->getType()->castAs<RecordType>()
10006 ->getDecl();
10007 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
10008 << S.Context.getTagDeclType(BaseDecl);
10009 } else {
10010 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
10011 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
10012 << S.Context.getTypeDeclType(Constructor->getParent())
10013 << /*member=*/1
10014 << Entity.getName()
10015 << InheritedFrom;
10016 S.Diag(Entity.getDecl()->getLocation(),
10017 diag::note_member_declared_at);
10018
10019 if (const RecordType *Record
10020 = Entity.getType()->getAs<RecordType>())
10021 S.Diag(Record->getDecl()->getLocation(),
10022 diag::note_previous_decl)
10023 << S.Context.getTagDeclType(Record->getDecl());
10024 }
10025 break;
10026 }
10027
10028 FailedCandidateSet.NoteCandidates(
10030 Kind.getLocation(),
10031 S.PDiag(diag::err_ovl_no_viable_function_in_init)
10032 << DestType << ArgsRange),
10033 S, OCD_AllCandidates, Args);
10034 break;
10035
10036 case OR_Deleted: {
10039 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
10040 if (Ovl != OR_Deleted) {
10041 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
10042 << DestType << ArgsRange;
10043 llvm_unreachable("Inconsistent overload resolution?");
10044 break;
10045 }
10046
10047 // If this is a defaulted or implicitly-declared function, then
10048 // it was implicitly deleted. Make it clear that the deletion was
10049 // implicit.
10050 if (S.isImplicitlyDeleted(Best->Function))
10051 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
10052 << llvm::to_underlying(
10053 S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)))
10054 << DestType << ArgsRange;
10055 else {
10056 StringLiteral *Msg = Best->Function->getDeletedMessage();
10057 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
10058 << DestType << (Msg != nullptr)
10059 << (Msg ? Msg->getString() : StringRef()) << ArgsRange;
10060 }
10061
10062 S.NoteDeletedFunction(Best->Function);
10063 break;
10064 }
10065
10066 case OR_Success:
10067 llvm_unreachable("Conversion did not fail!");
10068 }
10069 }
10070 break;
10071
10073 if (Entity.getKind() == InitializedEntity::EK_Member &&
10074 isa<CXXConstructorDecl>(S.CurContext)) {
10075 // This is implicit default-initialization of a const member in
10076 // a constructor. Complain that it needs to be explicitly
10077 // initialized.
10078 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
10079 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
10080 << (Constructor->getInheritedConstructor() ? 2 :
10081 Constructor->isImplicit() ? 1 : 0)
10082 << S.Context.getTypeDeclType(Constructor->getParent())
10083 << /*const=*/1
10084 << Entity.getName();
10085 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
10086 << Entity.getName();
10087 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
10088 VD && VD->isConstexpr()) {
10089 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
10090 << VD;
10091 } else {
10092 S.Diag(Kind.getLocation(), diag::err_default_init_const)
10093 << DestType << (bool)DestType->getAs<RecordType>();
10094 }
10095 break;
10096
10097 case FK_Incomplete:
10098 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
10099 diag::err_init_incomplete_type);
10100 break;
10101
10103 // Run the init list checker again to emit diagnostics.
10104 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
10105 diagnoseListInit(S, Entity, InitList);
10106 break;
10107 }
10108
10109 case FK_PlaceholderType: {
10110 // FIXME: Already diagnosed!
10111 break;
10112 }
10113
10115 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
10116 << Args[0]->getSourceRange();
10119 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
10120 (void)Ovl;
10121 assert(Ovl == OR_Success && "Inconsistent overload resolution");
10122 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
10123 S.Diag(CtorDecl->getLocation(),
10124 diag::note_explicit_ctor_deduction_guide_here) << false;
10125 break;
10126 }
10127
10129 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
10130 /*VerifyOnly=*/false);
10131 break;
10132
10134 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
10135 S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
10136 << Entity.getType() << InitList->getSourceRange();
10137 break;
10138 }
10139
10140 PrintInitLocationNote(S, Entity);
10141 return true;
10142}
10143
10144void InitializationSequence::dump(raw_ostream &OS) const {
10145 switch (SequenceKind) {
10146 case FailedSequence: {
10147 OS << "Failed sequence: ";
10148 switch (Failure) {
10150 OS << "too many initializers for reference";
10151 break;
10152
10154 OS << "parenthesized list init for reference";
10155 break;
10156
10158 OS << "array requires initializer list";
10159 break;
10160
10162 OS << "address of unaddressable function was taken";
10163 break;
10164
10166 OS << "array requires initializer list or string literal";
10167 break;
10168
10170 OS << "array requires initializer list or wide string literal";
10171 break;
10172
10174 OS << "narrow string into wide char array";
10175 break;
10176
10178 OS << "wide string into char array";
10179 break;
10180
10182 OS << "incompatible wide string into wide char array";
10183 break;
10184
10186 OS << "plain string literal into char8_t array";
10187 break;
10188
10190 OS << "u8 string literal into char array";
10191 break;
10192
10194 OS << "array type mismatch";
10195 break;
10196
10198 OS << "non-constant array initializer";
10199 break;
10200
10202 OS << "address of overloaded function failed";
10203 break;
10204
10206 OS << "overload resolution for reference initialization failed";
10207 break;
10208
10210 OS << "non-const lvalue reference bound to temporary";
10211 break;
10212
10214 OS << "non-const lvalue reference bound to bit-field";
10215 break;
10216
10218 OS << "non-const lvalue reference bound to vector element";
10219 break;
10220
10222 OS << "non-const lvalue reference bound to matrix element";
10223 break;
10224
10226 OS << "non-const lvalue reference bound to unrelated type";
10227 break;
10228
10230 OS << "rvalue reference bound to an lvalue";
10231 break;
10232
10234 OS << "reference initialization drops qualifiers";
10235 break;
10236
10238 OS << "reference with mismatching address space bound to temporary";
10239 break;
10240
10242 OS << "reference initialization failed";
10243 break;
10244
10246 OS << "conversion failed";
10247 break;
10248
10250 OS << "conversion from property failed";
10251 break;
10252
10254 OS << "too many initializers for scalar";
10255 break;
10256
10258 OS << "parenthesized list init for reference";
10259 break;
10260
10262 OS << "referencing binding to initializer list";
10263 break;
10264
10266 OS << "initializer list for non-aggregate, non-scalar type";
10267 break;
10268
10270 OS << "overloading failed for user-defined conversion";
10271 break;
10272
10274 OS << "constructor overloading failed";
10275 break;
10276
10278 OS << "default initialization of a const variable";
10279 break;
10280
10281 case FK_Incomplete:
10282 OS << "initialization of incomplete type";
10283 break;
10284
10286 OS << "list initialization checker failure";
10287 break;
10288
10290 OS << "variable length array has an initializer";
10291 break;
10292
10293 case FK_PlaceholderType:
10294 OS << "initializer expression isn't contextually valid";
10295 break;
10296
10298 OS << "list constructor overloading failed";
10299 break;
10300
10302 OS << "list copy initialization chose explicit constructor";
10303 break;
10304
10306 OS << "parenthesized list initialization failed";
10307 break;
10308
10310 OS << "designated initializer for non-aggregate type";
10311 break;
10312 }
10313 OS << '\n';
10314 return;
10315 }
10316
10317 case DependentSequence:
10318 OS << "Dependent sequence\n";
10319 return;
10320
10321 case NormalSequence:
10322 OS << "Normal sequence: ";
10323 break;
10324 }
10325
10326 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
10327 if (S != step_begin()) {
10328 OS << " -> ";
10329 }
10330
10331 switch (S->Kind) {
10333 OS << "resolve address of overloaded function";
10334 break;
10335
10337 OS << "derived-to-base (prvalue)";
10338 break;
10339
10341 OS << "derived-to-base (xvalue)";
10342 break;
10343
10345 OS << "derived-to-base (lvalue)";
10346 break;
10347
10348 case SK_BindReference:
10349 OS << "bind reference to lvalue";
10350 break;
10351
10353 OS << "bind reference to a temporary";
10354 break;
10355
10356 case SK_FinalCopy:
10357 OS << "final copy in class direct-initialization";
10358 break;
10359
10361 OS << "extraneous C++03 copy to temporary";
10362 break;
10363
10364 case SK_UserConversion:
10365 OS << "user-defined conversion via " << *S->Function.Function;
10366 break;
10367
10369 OS << "qualification conversion (prvalue)";
10370 break;
10371
10373 OS << "qualification conversion (xvalue)";
10374 break;
10375
10377 OS << "qualification conversion (lvalue)";
10378 break;
10379
10381 OS << "function reference conversion";
10382 break;
10383
10385 OS << "non-atomic-to-atomic conversion";
10386 break;
10387
10389 OS << "implicit conversion sequence (";
10390 S->ICS->dump(); // FIXME: use OS
10391 OS << ")";
10392 break;
10393
10395 OS << "implicit conversion sequence with narrowing prohibited (";
10396 S->ICS->dump(); // FIXME: use OS
10397 OS << ")";
10398 break;
10399
10401 OS << "list aggregate initialization";
10402 break;
10403
10404 case SK_UnwrapInitList:
10405 OS << "unwrap reference initializer list";
10406 break;
10407
10408 case SK_RewrapInitList:
10409 OS << "rewrap reference initializer list";
10410 break;
10411
10413 OS << "constructor initialization";
10414 break;
10415
10417 OS << "list initialization via constructor";
10418 break;
10419
10421 OS << "zero initialization";
10422 break;
10423
10424 case SK_CAssignment:
10425 OS << "C assignment";
10426 break;
10427
10428 case SK_StringInit:
10429 OS << "string initialization";
10430 break;
10431
10433 OS << "Objective-C object conversion";
10434 break;
10435
10436 case SK_ArrayLoopIndex:
10437 OS << "indexing for array initialization loop";
10438 break;
10439
10440 case SK_ArrayLoopInit:
10441 OS << "array initialization loop";
10442 break;
10443
10444 case SK_ArrayInit:
10445 OS << "array initialization";
10446 break;
10447
10448 case SK_GNUArrayInit:
10449 OS << "array initialization (GNU extension)";
10450 break;
10451
10453 OS << "parenthesized array initialization";
10454 break;
10455
10457 OS << "pass by indirect copy and restore";
10458 break;
10459
10461 OS << "pass by indirect restore";
10462 break;
10463
10465 OS << "Objective-C object retension";
10466 break;
10467
10469 OS << "std::initializer_list from initializer list";
10470 break;
10471
10473 OS << "list initialization from std::initializer_list";
10474 break;
10475
10476 case SK_OCLSamplerInit:
10477 OS << "OpenCL sampler_t from integer constant";
10478 break;
10479
10481 OS << "OpenCL opaque type from zero";
10482 break;
10484 OS << "initialization from a parenthesized list of values";
10485 break;
10486 }
10487
10488 OS << " [" << S->Type << ']';
10489 }
10490
10491 OS << '\n';
10492}
10493
10495 dump(llvm::errs());
10496}
10497
10499 const ImplicitConversionSequence &ICS,
10500 QualType PreNarrowingType,
10501 QualType EntityType,
10502 const Expr *PostInit) {
10503 const StandardConversionSequence *SCS = nullptr;
10504 switch (ICS.getKind()) {
10506 SCS = &ICS.Standard;
10507 break;
10509 SCS = &ICS.UserDefined.After;
10510 break;
10515 return;
10516 }
10517
10518 auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
10519 unsigned ConstRefDiagID, unsigned WarnDiagID) {
10520 unsigned DiagID;
10521 auto &L = S.getLangOpts();
10522 if (L.CPlusPlus11 &&
10523 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))
10524 DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
10525 else
10526 DiagID = WarnDiagID;
10527 return S.Diag(PostInit->getBeginLoc(), DiagID)
10528 << PostInit->getSourceRange();
10529 };
10530
10531 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
10532 APValue ConstantValue;
10533 QualType ConstantType;
10534 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
10535 ConstantType)) {
10536 case NK_Not_Narrowing:
10538 // No narrowing occurred.
10539 return;
10540
10541 case NK_Type_Narrowing: {
10542 // This was a floating-to-integer conversion, which is always considered a
10543 // narrowing conversion even if the value is a constant and can be
10544 // represented exactly as an integer.
10545 QualType T = EntityType.getNonReferenceType();
10546 MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
10547 diag::ext_init_list_type_narrowing_const_reference,
10548 diag::warn_init_list_type_narrowing)
10549 << PreNarrowingType.getLocalUnqualifiedType()
10550 << T.getLocalUnqualifiedType();
10551 break;
10552 }
10553
10554 case NK_Constant_Narrowing: {
10555 // A constant value was narrowed.
10556 MakeDiag(EntityType.getNonReferenceType() != EntityType,
10557 diag::ext_init_list_constant_narrowing,
10558 diag::ext_init_list_constant_narrowing_const_reference,
10559 diag::warn_init_list_constant_narrowing)
10560 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
10562 break;
10563 }
10564
10565 case NK_Variable_Narrowing: {
10566 // A variable's value may have been narrowed.
10567 MakeDiag(EntityType.getNonReferenceType() != EntityType,
10568 diag::ext_init_list_variable_narrowing,
10569 diag::ext_init_list_variable_narrowing_const_reference,
10570 diag::warn_init_list_variable_narrowing)
10571 << PreNarrowingType.getLocalUnqualifiedType()
10573 break;
10574 }
10575 }
10576
10577 SmallString<128> StaticCast;
10578 llvm::raw_svector_ostream OS(StaticCast);
10579 OS << "static_cast<";
10580 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
10581 // It's important to use the typedef's name if there is one so that the
10582 // fixit doesn't break code using types like int64_t.
10583 //
10584 // FIXME: This will break if the typedef requires qualification. But
10585 // getQualifiedNameAsString() includes non-machine-parsable components.
10586 OS << *TT->getDecl();
10587 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
10588 OS << BT->getName(S.getLangOpts());
10589 else {
10590 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
10591 // with a broken cast.
10592 return;
10593 }
10594 OS << ">(";
10595 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
10596 << PostInit->getSourceRange()
10597 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
10599 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
10600}
10601
10603 QualType ToType, Expr *Init) {
10604 assert(S.getLangOpts().C23);
10606 Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
10607 Sema::AllowedExplicit::None,
10608 /*InOverloadResolution*/ false,
10609 /*CStyle*/ false,
10610 /*AllowObjCWritebackConversion=*/false);
10611
10612 if (!ICS.isStandard())
10613 return;
10614
10615 APValue Value;
10616 QualType PreNarrowingType;
10617 // Reuse C++ narrowing check.
10618 switch (ICS.Standard.getNarrowingKind(
10619 S.Context, Init, Value, PreNarrowingType,
10620 /*IgnoreFloatToIntegralConversion*/ false)) {
10621 // The value doesn't fit.
10623 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
10624 << Value.getAsString(S.Context, PreNarrowingType) << ToType;
10625 return;
10626
10627 // Conversion to a narrower type.
10628 case NK_Type_Narrowing:
10629 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
10630 << ToType << FromType;
10631 return;
10632
10633 // Since we only reuse narrowing check for C23 constexpr variables here, we're
10634 // not really interested in these cases.
10637 case NK_Not_Narrowing:
10638 return;
10639 }
10640 llvm_unreachable("unhandled case in switch");
10641}
10642
10644 Sema &SemaRef, QualType &TT) {
10645 assert(SemaRef.getLangOpts().C23);
10646 // character that string literal contains fits into TT - target type.
10647 const ArrayType *AT = SemaRef.Context.getAsArrayType(TT);
10648 QualType CharType = AT->getElementType();
10649 uint32_t BitWidth = SemaRef.Context.getTypeSize(CharType);
10650 bool isUnsigned = CharType->isUnsignedIntegerType();
10651 llvm::APSInt Value(BitWidth, isUnsigned);
10652 for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
10653 int64_t C = SE->getCodeUnitS(I, SemaRef.Context.getCharWidth());
10654 Value = C;
10655 if (Value != C) {
10656 SemaRef.Diag(SemaRef.getLocationOfStringLiteralByte(SE, I),
10657 diag::err_c23_constexpr_init_not_representable)
10658 << C << CharType;
10659 return;
10660 }
10661 }
10662 return;
10663}
10664
10665//===----------------------------------------------------------------------===//
10666// Initialization helper functions
10667//===----------------------------------------------------------------------===//
10668bool
10670 ExprResult Init) {
10671 if (Init.isInvalid())
10672 return false;
10673
10674 Expr *InitE = Init.get();
10675 assert(InitE && "No initialization expression");
10676
10677 InitializationKind Kind =
10679 InitializationSequence Seq(*this, Entity, Kind, InitE);
10680 return !Seq.Failed();
10681}
10682
10685 SourceLocation EqualLoc,
10687 bool TopLevelOfInitList,
10688 bool AllowExplicit) {
10689 if (Init.isInvalid())
10690 return ExprError();
10691
10692 Expr *InitE = Init.get();
10693 assert(InitE && "No initialization expression?");
10694
10695 if (EqualLoc.isInvalid())
10696 EqualLoc = InitE->getBeginLoc();
10697
10699 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
10700 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10701
10702 // Prevent infinite recursion when performing parameter copy-initialization.
10703 const bool ShouldTrackCopy =
10704 Entity.isParameterKind() && Seq.isConstructorInitialization();
10705 if (ShouldTrackCopy) {
10706 if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
10707 Seq.SetOverloadFailure(
10710
10711 // Try to give a meaningful diagnostic note for the problematic
10712 // constructor.
10713 const auto LastStep = Seq.step_end() - 1;
10714 assert(LastStep->Kind ==
10716 const FunctionDecl *Function = LastStep->Function.Function;
10717 auto Candidate =
10718 llvm::find_if(Seq.getFailedCandidateSet(),
10719 [Function](const OverloadCandidate &Candidate) -> bool {
10720 return Candidate.Viable &&
10721 Candidate.Function == Function &&
10722 Candidate.Conversions.size() > 0;
10723 });
10724 if (Candidate != Seq.getFailedCandidateSet().end() &&
10725 Function->getNumParams() > 0) {
10726 Candidate->Viable = false;
10729 InitE,
10730 Function->getParamDecl(0)->getType());
10731 }
10732 }
10733 CurrentParameterCopyTypes.push_back(Entity.getType());
10734 }
10735
10736 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
10737
10738 if (ShouldTrackCopy)
10739 CurrentParameterCopyTypes.pop_back();
10740
10741 return Result;
10742}
10743
10744/// Determine whether RD is, or is derived from, a specialization of CTD.
10746 ClassTemplateDecl *CTD) {
10747 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10748 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
10749 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
10750 };
10751 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
10752}
10753
10755 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10756 const InitializationKind &Kind, MultiExprArg Inits) {
10757 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10758 TSInfo->getType()->getContainedDeducedType());
10759 assert(DeducedTST && "not a deduced template specialization type");
10760
10761 auto TemplateName = DeducedTST->getTemplateName();
10763 return SubstAutoTypeDependent(TSInfo->getType());
10764
10765 // We can only perform deduction for class templates or alias templates.
10766 auto *Template =
10767 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10768 TemplateDecl *LookupTemplateDecl = Template;
10769 if (!Template) {
10770 if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
10772 Diag(Kind.getLocation(),
10773 diag::warn_cxx17_compat_ctad_for_alias_templates);
10774 LookupTemplateDecl = AliasTemplate;
10775 auto UnderlyingType = AliasTemplate->getTemplatedDecl()
10776 ->getUnderlyingType()
10777 .getCanonicalType();
10778 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
10779 // of the form
10780 // [typename] [nested-name-specifier] [template] simple-template-id
10781 if (const auto *TST =
10782 UnderlyingType->getAs<TemplateSpecializationType>()) {
10783 Template = dyn_cast_or_null<ClassTemplateDecl>(
10784 TST->getTemplateName().getAsTemplateDecl());
10785 } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
10786 // Cases where template arguments in the RHS of the alias are not
10787 // dependent. e.g.
10788 // using AliasFoo = Foo<bool>;
10789 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(
10790 RT->getAsCXXRecordDecl()))
10791 Template = CTSD->getSpecializedTemplate();
10792 }
10793 }
10794 }
10795 if (!Template) {
10796 Diag(Kind.getLocation(),
10797 diag::err_deduced_non_class_or_alias_template_specialization_type)
10799 if (auto *TD = TemplateName.getAsTemplateDecl())
10801 return QualType();
10802 }
10803
10804 // Can't deduce from dependent arguments.
10806 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10807 diag::warn_cxx14_compat_class_template_argument_deduction)
10808 << TSInfo->getTypeLoc().getSourceRange() << 0;
10809 return SubstAutoTypeDependent(TSInfo->getType());
10810 }
10811
10812 // FIXME: Perform "exact type" matching first, per CWG discussion?
10813 // Or implement this via an implied 'T(T) -> T' deduction guide?
10814
10815 // Look up deduction guides, including those synthesized from constructors.
10816 //
10817 // C++1z [over.match.class.deduct]p1:
10818 // A set of functions and function templates is formed comprising:
10819 // - For each constructor of the class template designated by the
10820 // template-name, a function template [...]
10821 // - For each deduction-guide, a function or function template [...]
10822 DeclarationNameInfo NameInfo(
10824 TSInfo->getTypeLoc().getEndLoc());
10825 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10826 LookupQualifiedName(Guides, LookupTemplateDecl->getDeclContext());
10827
10828 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10829 // clear on this, but they're not found by name so access does not apply.
10830 Guides.suppressDiagnostics();
10831
10832 // Figure out if this is list-initialization.
10834 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10835 ? dyn_cast<InitListExpr>(Inits[0])
10836 : nullptr;
10837
10838 // C++1z [over.match.class.deduct]p1:
10839 // Initialization and overload resolution are performed as described in
10840 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10841 // (as appropriate for the type of initialization performed) for an object
10842 // of a hypothetical class type, where the selected functions and function
10843 // templates are considered to be the constructors of that class type
10844 //
10845 // Since we know we're initializing a class type of a type unrelated to that
10846 // of the initializer, this reduces to something fairly reasonable.
10847 OverloadCandidateSet Candidates(Kind.getLocation(),
10850
10851 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10852
10853 // Return true if the candidate is added successfully, false otherwise.
10854 auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10856 DeclAccessPair FoundDecl,
10857 bool OnlyListConstructors,
10858 bool AllowAggregateDeductionCandidate) {
10859 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10860 // For copy-initialization, the candidate functions are all the
10861 // converting constructors (12.3.1) of that class.
10862 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10863 // The converting constructors of T are candidate functions.
10864 if (!AllowExplicit) {
10865 // Overload resolution checks whether the deduction guide is declared
10866 // explicit for us.
10867
10868 // When looking for a converting constructor, deduction guides that
10869 // could never be called with one argument are not interesting to
10870 // check or note.
10871 if (GD->getMinRequiredArguments() > 1 ||
10872 (GD->getNumParams() == 0 && !GD->isVariadic()))
10873 return;
10874 }
10875
10876 // C++ [over.match.list]p1.1: (first phase list initialization)
10877 // Initially, the candidate functions are the initializer-list
10878 // constructors of the class T
10879 if (OnlyListConstructors && !isInitListConstructor(GD))
10880 return;
10881
10882 if (!AllowAggregateDeductionCandidate &&
10883 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10884 return;
10885
10886 // C++ [over.match.list]p1.2: (second phase list initialization)
10887 // the candidate functions are all the constructors of the class T
10888 // C++ [over.match.ctor]p1: (all other cases)
10889 // the candidate functions are all the constructors of the class of
10890 // the object being initialized
10891
10892 // C++ [over.best.ics]p4:
10893 // When [...] the constructor [...] is a candidate by
10894 // - [over.match.copy] (in all cases)
10895 // FIXME: The "second phase of [over.match.list] case can also
10896 // theoretically happen here, but it's not clear whether we can
10897 // ever have a parameter of the right type.
10898 bool SuppressUserConversions = Kind.isCopyInit();
10899
10900 if (TD) {
10901 SmallVector<Expr *, 8> TmpInits;
10902 for (Expr *E : Inits)
10903 if (auto *DI = dyn_cast<DesignatedInitExpr>(E))
10904 TmpInits.push_back(DI->getInit());
10905 else
10906 TmpInits.push_back(E);
10908 TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
10909 SuppressUserConversions,
10910 /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
10911 /*PO=*/{}, AllowAggregateDeductionCandidate);
10912 } else {
10913 AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
10914 SuppressUserConversions,
10915 /*PartialOverloading=*/false, AllowExplicit);
10916 }
10917 };
10918
10919 bool FoundDeductionGuide = false;
10920
10921 auto TryToResolveOverload =
10922 [&](bool OnlyListConstructors) -> OverloadingResult {
10924 bool HasAnyDeductionGuide = false;
10925
10926 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10927 auto *Pattern = Template;
10928 while (Pattern->getInstantiatedFromMemberTemplate()) {
10929 if (Pattern->isMemberSpecialization())
10930 break;
10931 Pattern = Pattern->getInstantiatedFromMemberTemplate();
10932 }
10933
10934 auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());
10935 if (!(RD->getDefinition() && RD->isAggregate()))
10936 return;
10938 SmallVector<QualType, 8> ElementTypes;
10939
10940 InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10941 if (!CheckInitList.HadError()) {
10942 // C++ [over.match.class.deduct]p1.8:
10943 // if e_i is of array type and x_i is a braced-init-list, T_i is an
10944 // rvalue reference to the declared type of e_i and
10945 // C++ [over.match.class.deduct]p1.9:
10946 // if e_i is of array type and x_i is a bstring-literal, T_i is an
10947 // lvalue reference to the const-qualified declared type of e_i and
10948 // C++ [over.match.class.deduct]p1.10:
10949 // otherwise, T_i is the declared type of e_i
10950 for (int I = 0, E = ListInit->getNumInits();
10951 I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
10952 if (ElementTypes[I]->isArrayType()) {
10953 if (isa<InitListExpr>(ListInit->getInit(I)))
10954 ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);
10955 else if (isa<StringLiteral>(
10956 ListInit->getInit(I)->IgnoreParenImpCasts()))
10957 ElementTypes[I] =
10958 Context.getLValueReferenceType(ElementTypes[I].withConst());
10959 }
10960
10961 if (FunctionTemplateDecl *TD =
10963 LookupTemplateDecl, ElementTypes,
10964 TSInfo->getTypeLoc().getEndLoc())) {
10965 auto *GD = cast<CXXDeductionGuideDecl>(TD->getTemplatedDecl());
10966 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10967 OnlyListConstructors,
10968 /*AllowAggregateDeductionCandidate=*/true);
10969 HasAnyDeductionGuide = true;
10970 }
10971 }
10972 };
10973
10974 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10975 NamedDecl *D = (*I)->getUnderlyingDecl();
10976 if (D->isInvalidDecl())
10977 continue;
10978
10979 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10980 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10981 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10982 if (!GD)
10983 continue;
10984
10985 if (!GD->isImplicit())
10986 HasAnyDeductionGuide = true;
10987
10988 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10989 /*AllowAggregateDeductionCandidate=*/false);
10990 }
10991
10992 // C++ [over.match.class.deduct]p1.4:
10993 // if C is defined and its definition satisfies the conditions for an
10994 // aggregate class ([dcl.init.aggr]) with the assumption that any
10995 // dependent base class has no virtual functions and no virtual base
10996 // classes, and the initializer is a non-empty braced-init-list or
10997 // parenthesized expression-list, and there are no deduction-guides for
10998 // C, the set contains an additional function template, called the
10999 // aggregate deduction candidate, defined as follows.
11000 if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
11001 if (ListInit && ListInit->getNumInits()) {
11002 SynthesizeAggrGuide(ListInit);
11003 } else if (Inits.size()) { // parenthesized expression-list
11004 // Inits are expressions inside the parentheses. We don't have
11005 // the parentheses source locations, use the begin/end of Inits as the
11006 // best heuristic.
11007 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
11008 Inits, Inits.back()->getEndLoc());
11009 SynthesizeAggrGuide(&TempListInit);
11010 }
11011 }
11012
11013 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
11014
11015 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
11016 };
11017
11019
11020 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
11021 // try initializer-list constructors.
11022 if (ListInit) {
11023 bool TryListConstructors = true;
11024
11025 // Try list constructors unless the list is empty and the class has one or
11026 // more default constructors, in which case those constructors win.
11027 if (!ListInit->getNumInits()) {
11028 for (NamedDecl *D : Guides) {
11029 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
11030 if (FD && FD->getMinRequiredArguments() == 0) {
11031 TryListConstructors = false;
11032 break;
11033 }
11034 }
11035 } else if (ListInit->getNumInits() == 1) {
11036 // C++ [over.match.class.deduct]:
11037 // As an exception, the first phase in [over.match.list] (considering
11038 // initializer-list constructors) is omitted if the initializer list
11039 // consists of a single expression of type cv U, where U is a
11040 // specialization of C or a class derived from a specialization of C.
11041 Expr *E = ListInit->getInit(0);
11042 auto *RD = E->getType()->getAsCXXRecordDecl();
11043 if (!isa<InitListExpr>(E) && RD &&
11044 isCompleteType(Kind.getLocation(), E->getType()) &&
11046 TryListConstructors = false;
11047 }
11048
11049 if (TryListConstructors)
11050 Result = TryToResolveOverload(/*OnlyListConstructor*/true);
11051 // Then unwrap the initializer list and try again considering all
11052 // constructors.
11053 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
11054 }
11055
11056 // If list-initialization fails, or if we're doing any other kind of
11057 // initialization, we (eventually) consider constructors.
11059 Result = TryToResolveOverload(/*OnlyListConstructor*/false);
11060
11061 switch (Result) {
11062 case OR_Ambiguous:
11063 // FIXME: For list-initialization candidates, it'd usually be better to
11064 // list why they were not viable when given the initializer list itself as
11065 // an argument.
11066 Candidates.NoteCandidates(
11068 Kind.getLocation(),
11069 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
11070 << TemplateName),
11071 *this, OCD_AmbiguousCandidates, Inits);
11072 return QualType();
11073
11074 case OR_No_Viable_Function: {
11075 CXXRecordDecl *Primary =
11076 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
11077 bool Complete =
11078 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
11079 Candidates.NoteCandidates(
11081 Kind.getLocation(),
11082 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
11083 : diag::err_deduced_class_template_incomplete)
11084 << TemplateName << !Guides.empty()),
11085 *this, OCD_AllCandidates, Inits);
11086 return QualType();
11087 }
11088
11089 case OR_Deleted: {
11090 // FIXME: There are no tests for this diagnostic, and it doesn't seem
11091 // like we ever get here; attempts to trigger this seem to yield a
11092 // generic c'all to deleted function' diagnostic instead.
11093 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
11094 << TemplateName;
11095 NoteDeletedFunction(Best->Function);
11096 return QualType();
11097 }
11098
11099 case OR_Success:
11100 // C++ [over.match.list]p1:
11101 // In copy-list-initialization, if an explicit constructor is chosen, the
11102 // initialization is ill-formed.
11103 if (Kind.isCopyInit() && ListInit &&
11104 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
11105 bool IsDeductionGuide = !Best->Function->isImplicit();
11106 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
11107 << TemplateName << IsDeductionGuide;
11108 Diag(Best->Function->getLocation(),
11109 diag::note_explicit_ctor_deduction_guide_here)
11110 << IsDeductionGuide;
11111 return QualType();
11112 }
11113
11114 // Make sure we didn't select an unusable deduction guide, and mark it
11115 // as referenced.
11116 DiagnoseUseOfDecl(Best->FoundDecl, Kind.getLocation());
11117 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
11118 break;
11119 }
11120
11121 // C++ [dcl.type.class.deduct]p1:
11122 // The placeholder is replaced by the return type of the function selected
11123 // by overload resolution for class template deduction.
11125 SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
11126 Diag(TSInfo->getTypeLoc().getBeginLoc(),
11127 diag::warn_cxx14_compat_class_template_argument_deduction)
11128 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
11129
11130 // Warn if CTAD was used on a type that does not have any user-defined
11131 // deduction guides.
11132 if (!FoundDeductionGuide) {
11133 Diag(TSInfo->getTypeLoc().getBeginLoc(),
11134 diag::warn_ctad_maybe_unsupported)
11135 << TemplateName;
11136 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
11137 }
11138
11139 return DeducedType;
11140}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
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:570
static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD)
Definition: SemaInit.cpp:7553
static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E)
Tries to get a FunctionDecl out of E.
Definition: SemaInit.cpp:6125
static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee)
Definition: SemaInit.cpp:7436
static void updateStringLiteralType(Expr *E, QualType Ty)
Update the type of a string literal, including any surrounding parentheses, to match the type of the ...
Definition: SemaInit.cpp:174
static void updateGNUCompoundLiteralRValue(Expr *E)
Fix a compound literal initializing an array so it's correctly marked as an rvalue.
Definition: SemaInit.cpp:186
static bool initializingConstexprVariable(const InitializedEntity &Entity)
Definition: SemaInit.cpp:195
static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call, LocalVisitor Visit)
Definition: SemaInit.cpp:7590
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:1172
static bool shouldDestroyEntity(const InitializedEntity &Entity)
Whether the given entity, when initialized with an object created for that initialization,...
Definition: SemaInit.cpp:6697
static SourceLocation getInitializationLoc(const InitializedEntity &Entity, Expr *Initializer)
Get the location at which initialization diagnostics should appear.
Definition: SemaInit.cpp:6730
static bool hasAnyDesignatedInits(const InitListExpr *IL)
Definition: SemaInit.cpp:975
static bool tryObjCWritebackConversion(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity, Expr *Initializer)
Definition: SemaInit.cpp:6007
static DesignatedInitExpr * CloneDesignatedInitExpr(Sema &SemaRef, DesignatedInitExpr *DIE)
Definition: SemaInit.cpp:2500
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:6788
static Sema::AssignmentAction getAssignmentAction(const InitializedEntity &Entity, bool Diagnose=false)
Definition: SemaInit.cpp:6608
static void TryOrBuildParenListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args, InitializationSequence &Sequence, bool VerifyOnly, ExprResult *Result=nullptr)
Definition: SemaInit.cpp:5452
static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, bool IsReturnStmt)
Provide warnings when std::move is used on construction.
Definition: SemaInit.cpp:8433
static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE, Sema &SemaRef, QualType &TT)
Definition: SemaInit.cpp:10643
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:6939
static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, ClassTemplateDecl *CTD)
Determine whether RD is, or is derived from, a specialization of CTD.
Definition: SemaInit.cpp:10745
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:4073
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:74
StringInitFailureKind
Definition: SemaInit.cpp:60
@ SIF_None
Definition: SemaInit.cpp:61
@ SIF_PlainStringIntoUTF8Char
Definition: SemaInit.cpp:66
@ SIF_IncompatWideStringIntoWideChar
Definition: SemaInit.cpp:64
@ SIF_UTF8StringIntoPlainChar
Definition: SemaInit.cpp:65
@ SIF_NarrowStringIntoWideChar
Definition: SemaInit.cpp:62
@ SIF_Other
Definition: SemaInit.cpp:67
@ SIF_WideStringIntoChar
Definition: SemaInit.cpp:63
static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call, LocalVisitor Visit)
Definition: SemaInit.cpp:7494
static void TryDefaultInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence)
Attempt default initialization (C++ [dcl.init]p6).
Definition: SemaInit.cpp:5414
static bool TryOCLSamplerInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
Definition: SemaInit.cpp:6054
static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path)
Definition: SemaInit.cpp:8123
static bool isInStlNamespace(const Decl *D)
Definition: SemaInit.cpp:7421
static bool maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
Tries to add a zero initializer. Returns true if that worked.
Definition: SemaInit.cpp:4013
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:3352
static bool canPerformArrayCopy(const InitializedEntity &Entity)
Determine whether we can perform an elementwise array copy for this kind of entity.
Definition: SemaInit.cpp:6136
static bool IsZeroInitializer(Expr *Initializer, Sema &S)
Definition: SemaInit.cpp:6067
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:5003
static PathLifetimeKind shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path)
Determine whether this is an indirect path to a temporary that we are supposed to lifetime-extend alo...
Definition: SemaInit.cpp:8081
static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType, QualType ToType, Expr *Init)
Definition: SemaInit.cpp:10602
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:2472
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:5336
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:5704
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:4121
static LifetimeResult getEntityLifetime(const InitializedEntity *Entity, const InitializedEntity *InitField=nullptr)
Determine the declaration which an initialized entity ultimately refers to, for the purpose of lifeti...
Definition: SemaInit.cpp:7222
static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD)
Definition: SemaInit.cpp:7388
static bool shouldTrackFirstArgument(const FunctionDecl *FD)
Definition: SemaInit.cpp:7470
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:4563
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:5327
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:1927
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:4965
static void DiagnoseNarrowingInInitList(Sema &S, const ImplicitConversionSequence &ICS, QualType PreNarrowingType, QualType EntityType, const Expr *PostInit)
Definition: SemaInit.cpp:10498
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:5991
static bool pathContainsInit(IndirectLocalPath &Path)
Definition: SemaInit.cpp:7395
static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, Sema &S, bool CheckC23ConstexprInit=false)
Definition: SemaInit.cpp:213
static bool isRecordWithAttr(QualType Type)
Definition: SemaInit.cpp:7412
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:7015
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:4994
PathLifetimeKind
Whether a path to an object supports lifetime extension.
Definition: SemaInit.cpp:8066
@ ShouldExtend
We should lifetime-extend, but we don't because (due to technical limitations) we can't.
Definition: SemaInit.cpp:8073
@ NoExtend
Do not lifetime extend along this path.
Definition: SemaInit.cpp:8075
@ Extend
Lifetime-extend along this path.
Definition: SemaInit.cpp:8068
static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
Definition: SemaInit.cpp:6072
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:50
static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, InitListExpr *InitList)
Definition: SemaInit.cpp:9602
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:4780
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:4235
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:9571
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:1049
static void MaybeProduceObjCObject(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
Definition: SemaInit.cpp:4033
static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I, Expr *E)
Find the range for the first interesting entry in the path at or after I.
Definition: SemaInit.cpp:8093
static void checkIndirectCopyRestoreSource(Sema &S, Expr *src)
Check whether the given expression is a valid operand for an indirect copy/restore.
Definition: SemaInit.cpp:5973
static bool shouldBindAsTemporary(const InitializedEntity &Entity)
Whether we should bind a created object as a temporary when initializing the given entity.
Definition: SemaInit.cpp:6663
static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, Expr *Init, ReferenceKind RK, LocalVisitor Visit, bool EnableLifetimeWarnings)
Visit the locals that would be reachable through a reference bound to the glvalue expression Init.
Definition: SemaInit.cpp:7657
static bool ResolveOverloadedFunctionForReferenceBinding(Sema &S, Expr *Initializer, QualType &SourceType, QualType &UnqualifiedSourceType, QualType UnqualifiedTargetType, InitializationSequence &Sequence)
Definition: SemaInit.cpp:4415
static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, Expr *Init, LocalVisitor Visit, bool RevisitSubinits, bool EnableLifetimeWarnings)
Visit the locals that would be reachable through an object initialized by the prvalue expression Init...
Definition: SemaInit.cpp:7793
InvalidICRKind
The non-zero enum values here are indexes into diagnostic alternatives.
Definition: SemaInit.cpp:5903
@ IIK_okay
Definition: SemaInit.cpp:5903
@ IIK_nonlocal
Definition: SemaInit.cpp:5903
@ IIK_nonscalar
Definition: SemaInit.cpp:5903
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:7040
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:4460
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:5891
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:4108
static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, QualType T)
Somewhere within T there is an uninitialized reference subobject.
Definition: SemaInit.cpp:9532
static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, bool isAddressOf, bool &isWeakAccess)
Determines whether this expression is an acceptable ICR source.
Definition: SemaInit.cpp:5906
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for Objective-C.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TypeLoc interface and its subclasses.
__device__ int
__device__ __2f16 float __ockl_bool s
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APSInt & getInt()
Definition: APValue.h:423
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
bool isNullPointer() const
Definition: APValue.cpp:1010
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2768
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:648
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.
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true)
Form a pack expansion type with the given pattern.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2575
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2591
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:1098
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:2774
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:1591
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:775
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:1100
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2157
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
CanQualType OverloadTy
Definition: ASTContext.h:1119
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:2618
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:2341
CanQualType OCLSamplerTy
Definition: ASTContext.h:1128
CanQualType VoidTy
Definition: ASTContext.h:1091
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:2771
CanQualType Char32Ty
Definition: ASTContext.h:1099
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:757
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:1794
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2345
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:5564
Represents a loop initializing the elements of an array.
Definition: Expr.h:5511
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2664
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3518
QualType getElementType() const
Definition: Type.h:3530
Type source information for an attributed type.
Definition: TypeLoc.h:875
const T * getAttrAs()
Definition: TypeLoc.h:905
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:889
This class is used for builtin types like 'int'.
Definition: Type.h:2981
Kind getKind() const
Definition: Type.h:3023
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 binding an expression to a temporary.
Definition: ExprCXX.h:1487
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1542
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1685
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1605
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1682
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2777
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2614
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition: DeclCXX.cpp:2773
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2902
Represents a C++ deduction guide declaration.
Definition: DeclCXX.h:1952
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition: ExprCXX.cpp:1885
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:1162
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition: DeclCXX.h:1392
base_class_range bases()
Definition: DeclCXX.h:619
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition: DeclCXX.cpp:1833
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:613
llvm::iterator_range< base_class_iterator > base_class_range
Definition: DeclCXX.h:615
llvm::iterator_range< base_class_const_iterator > base_class_const_range
Definition: DeclCXX.h:617
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 a value-initialized rvalue of type T, which is a non-class type.
Definition: ExprCXX.h:2177
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:1076
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3011
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1638
bool isCallToStdMove() const
Definition: Expr.cpp:3510
Expr * getCallee()
Definition: Expr.h:2970
SourceLocation getRParenLoc() const
Definition: Expr.h:3130
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:3483
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:3086
QualType getElementType() const
Definition: Type.h:3096
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4179
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3556
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:218
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3632
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:1369
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:2279
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2342
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
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:1975
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1802
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1938
bool isStdNamespace() const
Definition: DeclBase.cpp:1266
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1458
ValueDecl * getDecl()
Definition: Expr.h:1328
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isInStdNamespace() const
Definition: DeclBase.cpp:403
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:441
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
bool isInvalidDecl() const
Definition: DeclBase.h:594
SourceLocation getLocation() const
Definition: DeclBase.h:445
DeclContext * getDeclContext()
Definition: DeclBase.h:454
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
bool hasAttr() const
Definition: DeclBase.h:583
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
The name of a declaration.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5947
Represents a single C99 designator.
Definition: Expr.h:5135
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:5297
void setFieldDecl(FieldDecl *FD)
Definition: Expr.h:5233
FieldDecl * getFieldDecl() const
Definition: Expr.h:5226
SourceLocation getFieldLoc() const
Definition: Expr.h:5243
const IdentifierInfo * getFieldName() const
Definition: Expr.cpp:4545
SourceLocation getDotLoc() const
Definition: Expr.h:5238
SourceLocation getLBracketLoc() const
Definition: Expr.h:5279
Represents a C99 designated initializer expression.
Definition: Expr.h:5092
bool isDirectInit() const
Whether this designated initializer should result in direct-initialization of the designated subobjec...
Definition: Expr.h:5352
Expr * getArrayRangeEnd(const Designator &D) const
Definition: Expr.cpp:4654
void setInit(Expr *init)
Definition: Expr.h:5364
Expr * getSubExpr(unsigned Idx) const
Definition: Expr.h:5374
llvm::MutableArrayRef< Designator > designators()
Definition: Expr.h:5325
bool usesGNUSyntax() const
Determines whether this designated initializer used the deprecated GNU syntax for designated initiali...
Definition: Expr.h:5356
Expr * getArrayRangeStart(const Designator &D) const
Definition: Expr.cpp:4649
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:4661
static DesignatedInitExpr * Create(const ASTContext &C, llvm::ArrayRef< Designator > Designators, ArrayRef< Expr * > IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
Definition: Expr.cpp:4587
Expr * getArrayIndex(const Designator &D) const
Definition: Expr.cpp:4644
Designator * getDesignator(unsigned Idx)
Definition: Expr.h:5333
Expr * getInit() const
Retrieve the initializer value.
Definition: Expr.h:5360
unsigned size() const
Returns the number of designators in this initializer.
Definition: Expr.h:5322
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:4623
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:4640
SourceLocation getEqualOrColonLoc() const
Retrieve the location of the '=' that precedes the initializer value itself, if present.
Definition: Expr.h:5347
unsigned getNumSubExprs() const
Retrieve the total number of subexpressions in this designated initializer expression,...
Definition: Expr.h:5372
InitListExpr * getUpdater() const
Definition: Expr.h:5479
Designation - Represent a full designation, which is a sequence of designators.
Definition: Designator.h:208
const Designator & getDesignator(unsigned Idx) const
Definition: Designator.h:219
unsigned getNumDesignators() const
Definition: Designator.h:218
Designator - A designator in a C99 designated initializer.
Definition: Designator.h:38
SourceLocation getFieldLoc() const
Definition: Designator.h:133
SourceLocation getDotLoc() const
Definition: Designator.h:128
Expr * getArrayRangeStart() const
Definition: Designator.h:181
bool isArrayDesignator() const
Definition: Designator.h:108
SourceLocation getLBracketLoc() const
Definition: Designator.h:154
bool isArrayRangeDesignator() const
Definition: Designator.h:109
bool isFieldDesignator() const
Definition: Designator.h:107
SourceLocation getRBracketLoc() const
Definition: Designator.h:161
SourceLocation getEllipsisLoc() const
Definition: Designator.h:191
Expr * getArrayRangeEnd() const
Definition: Designator.h:186
const IdentifierInfo * getFieldDecl() const
Definition: Designator.h:123
Expr * getArrayIndex() const
Definition: Designator.h:149
static Designator CreateFieldDesignator(const IdentifierInfo *FieldName, SourceLocation DotLoc, SourceLocation FieldLoc)
Creates a field designator.
Definition: Designator.h:115
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
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:5575
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
bool isGLValue() const
Definition: Expr.h:280
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3064
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:4138
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:3059
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3047
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3055
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:3279
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:821
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:825
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:3556
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3039
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:3193
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:3923
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:4061
Represents difference between two FPOptions values.
Definition: LangOptions.h:915
Represents a member of a struct/union/class.
Definition: Decl.h:3057
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3218
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4644
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4666
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:3151
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
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:97
Represents a function declaration or definition.
Definition: Decl.h:1971
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2706
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3713
QualType getReturnType() const
Definition: Decl.h:2754
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2502
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2347
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3692
Declaration of a template function.
Definition: DeclTemplate.h:957
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:2074
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:543
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition: Overload.h:594
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:598
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:742
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5600
Represents a C array with an unspecified size.
Definition: Type.h:3703
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3341
chain_iterator chain_end() const
Definition: Decl.h:3367
chain_iterator chain_begin() const
Definition: Decl.h:3366
ArrayRef< NamedDecl * >::const_iterator chain_iterator
Definition: Decl.h:3361
Describes an C or C++ initializer list.
Definition: Expr.h:4847
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition: Expr.h:4951
void setSyntacticForm(InitListExpr *Init)
Definition: Expr.h:5017
void markError()
Mark the semantic form of the InitListExpr as error when the semantic analysis fails.
Definition: Expr.h:4913
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition: Expr.h:4954
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition: Expr.cpp:2432
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition: Expr.cpp:2392
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition: Expr.h:4966
unsigned getNumInits() const
Definition: Expr.h:4877
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:2466
void setInit(unsigned Init, Expr *expr)
Definition: Expr.h:4903
SourceLocation getLBraceLoc() const
Definition: Expr.h:5001
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:2396
void setArrayFiller(Expr *filler)
Definition: Expr.cpp:2408
InitListExpr * getSyntacticForm() const
Definition: Expr.h:5013
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition: Expr.h:4941
SourceLocation getRBraceLoc() const
Definition: Expr.h:5003
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4893
bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const
Is this the zero initializer {0} in a language which considers it idiomatic?
Definition: Expr.cpp:2455
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:2484
void setInitializedFieldInUnion(FieldDecl *FD)
Definition: Expr.h:4972
bool isSyntacticForm() const
Definition: Expr.h:5010
void setRBraceLoc(SourceLocation Loc)
Definition: Expr.h:5004
void sawArrayRangeDesignator(bool ARD=true)
Definition: Expr.h:5027
Expr ** getInits()
Retrieve the set of initializers.
Definition: Expr.h:4880
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:3867
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:8601
void AddStringInitStep(QualType T)
Add a string init step.
Definition: SemaInit.cpp:3902
void AddStdInitializerListConstructionStep(QualType T)
Add a step to construct a std::initializer_list object from an initializer list.
Definition: SemaInit.cpp:3957
void AddConstructorInitializationStep(DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, bool HadMultipleCandidates, bool FromInitList, bool AsInitList)
Add a constructor-initialization step.
Definition: SemaInit.cpp:3874
@ 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:3810
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:6114
void AddQualificationConversionStep(QualType Ty, ExprValueKind Category)
Add a new step that performs a qualification conversion to the given type.
Definition: SemaInit.cpp:3823
void AddFunctionReferenceConversionStep(QualType Ty)
Add a new step that performs a function reference conversion to the given type.
Definition: SemaInit.cpp:3842
void AddDerivedToBaseCastStep(QualType BaseType, ExprValueKind Category)
Add a new step in the initialization that performs a derived-to- base cast.
Definition: SemaInit.cpp:3773
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:6170
void AddParenthesizedListInitStep(QualType T)
Definition: SemaInit.cpp:3978
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:3701
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:3971
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:3795
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:3909
void SetOverloadFailure(FailureKind Failure, OverloadingResult Result)
Note that this initialization sequence failed due to failed overload resolution.
Definition: SemaInit.cpp:4000
step_iterator step_end() const
void AddParenthesizedArrayInitStep(QualType T)
Add a parenthesized array initialization step.
Definition: SemaInit.cpp:3934
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:3802
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:3964
void AddCAssignmentStep(QualType T)
Add a C assignment step.
Definition: SemaInit.cpp:3895
void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy)
Add a step to pass an object by indirect copy-restore.
Definition: SemaInit.cpp:3941
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:3985
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
Definition: SemaInit.cpp:9638
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:3849
void dump() const
Dump a representation of this initialization sequence to standard error, for debugging purposes.
Definition: SemaInit.cpp:10494
void AddConversionSequenceStep(const ImplicitConversionSequence &ICS, QualType T, bool TopLevelOfInitList=false)
Add a new step that applies an implicit conversion sequence.
Definition: SemaInit.cpp:3856
void AddZeroInitializationStep(QualType T)
Add a zero-initialization step.
Definition: SemaInit.cpp:3888
void AddProduceObjCObjectStep(QualType T)
Add a step to "produce" an Objective-C object (by retaining it).
Definition: SemaInit.cpp:3950
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:3787
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:3690
void AddArrayInitLoopStep(QualType T, QualType EltTy)
Add an array initialization loop step.
Definition: SemaInit.cpp:3923
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:3761
void AddArrayInitStep(QualType T, bool IsGNUExtension)
Add an array initialization step.
Definition: SemaInit.cpp:3916
bool isConstructorInitialization() const
Determine whether this initialization is direct call to a constructor.
Definition: SemaInit.cpp:3755
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:3471
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:3483
unsigned allocateManglingNumber() const
QualType getType() const
Retrieve type being initialized.
ValueDecl * getDecl() const
Retrieve the variable, parameter, or field being initialized.
Definition: SemaInit.cpp:3521
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:3555
void dump() const
Dump a representation of the initialized entity to standard error, for debugging purposes.
Definition: SemaInit.cpp:3636
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.
bool isDefaultMemberInitializer() const
Is this the default member initializer of a member (specified inside the class definition)?
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:6221
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:977
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3424
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
bool capturesVariable() const
Determine whether this capture handles a variable.
Definition: LambdaCapture.h:88
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:4710
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:4735
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
Represent a C++ namespace.
Definition: Decl.h:547
Represents a place-holder for an object not to be initialized by anything.
Definition: Expr.h:5420
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:410
QualType getEncodedType() const
Definition: ExprObjC.h:429
ObjCIndirectCopyRestoreExpr - Represents the passing of a function argument by indirect copy-restore ...
Definition: ExprObjC.h:1575
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
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:980
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void setDestAS(LangAS AS)
Definition: Overload.h:1215
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition: Overload.h:1001
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition: Overload.h:996
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
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:1761
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3139
A (possibly-)qualified type.
Definition: Type.h:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7443
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7448
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3469
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:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7359
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7485
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7399
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1432
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:7560
QualType getCanonicalType() const
Definition: Type.h:7411
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7453
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7432
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7480
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1530
The collection of all-type qualifiers we support.
Definition: Type.h:318
unsigned getCVRQualifiers() const
Definition: Type.h:474
void addAddressSpace(LangAS space)
Definition: Type.h:583
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:350
bool hasConst() const
Definition: Type.h:443
bool hasQualifiers() const
Return true if the set contains any qualifiers.
Definition: Type.h:632
bool hasAddressSpace() const
Definition: Type.h:556
Qualifiers withoutAddressSpace() const
Definition: Type.h:524
void removeAddressSpace()
Definition: Type.h:582
static Qualifiers fromCVRMask(unsigned CVR)
Definition: Type.h:421
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:694
bool hasVolatile() const
Definition: Type.h:453
bool hasObjCLifetime() const
Definition: Type.h:530
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:731
LangAS getAddressSpace() const
Definition: Type.h:557
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3442
Represents a struct/union/class.
Definition: Decl.h:4168
bool hasFlexibleArrayMember() const
Definition: Decl.h:4201
field_iterator field_end() const
Definition: Decl.h:4377
field_range fields() const
Definition: Decl.h:4374
bool isRandomized() const
Definition: Decl.h:4318
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4359
specific_decl_iterator< FieldDecl > field_iterator
Definition: Decl.h:4371
bool field_empty() const
Definition: Decl.h:4382
field_iterator field_begin() const
Definition: Decl.cpp:5069
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5549
RecordDecl * getDecl() const
Definition: Type.h:5559
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3380
bool isSpelledAsLValue() const
Definition: Type.h:3393
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
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:1314
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:451
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:4599
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7289
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7297
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition: SemaInit.cpp:168
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
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:8061
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:8064
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:8070
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:8068
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...
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:17081
ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init)
Definition: SemaInit.cpp:3369
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1422
ASTContext & Context
Definition: Sema.h:848
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:582
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:514
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:1003
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:5724
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:764
ASTContext & getASTContext() const
Definition: Sema.h:517
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9673
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:645
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:7999
llvm::SmallVector< QualType, 4 > CurrentParameterCopyTypes
Stack of types that correspond to the parameter entities that are currently being copy-initialized.
Definition: Sema.h:6972
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:65
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
const LangOptions & getLangOpts() const
Definition: Sema.h:510
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:8582
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:17418
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:8564
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:72
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:5149
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:9725
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:10754
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:6221
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:986
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:8545
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:6020
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6022
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:6101
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1311
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20849
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:10402
SourceManager & getSourceManager() const
Definition: Sema.h:515
AssignmentAction
Definition: Sema.h:5157
@ AA_Returning
Definition: Sema.h:5160
@ AA_Passing_CFAudited
Definition: Sema.h:5165
@ AA_Initializing
Definition: Sema.h:5162
@ AA_Converting
Definition: Sema.h:5161
@ AA_Passing
Definition: Sema.h:5159
@ AA_Casting
Definition: Sema.h:5164
@ AA_Sending
Definition: Sema.h:5163
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:20127
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5569
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=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
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:228
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11584
@ CTK_ErrorRecovery
Definition: Sema.h:7529
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3335
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:5211
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:8831
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...
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
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:8137
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6364
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
Definition: SemaType.cpp:8772
SourceManager & SourceMgr
Definition: Sema.h:851
DiagnosticsEngine & Diags
Definition: Sema.h:850
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:511
static bool CanBeGetReturnObject(const FunctionDecl *FD)
Definition: SemaDecl.cpp:15983
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10684
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5643
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:520
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:16748
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:17983
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:10669
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
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:267
void setFromType(QualType T)
Definition: Overload.h:357
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:278
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:272
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:359
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:364
QualType getToType(unsigned Idx) const
Definition: Overload.h:374
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
unsigned getLength() const
Definition: Expr.h:1890
StringLiteralKind getKind() const
Definition: Expr.h:1893
int64_t getCodeUnitS(size_t I, uint64_t BitWidth) const
Definition: Expr.h:1879
StringRef getString() const
Definition: Expr.h:1850
bool isUnion() const
Definition: Decl.h:3790
bool isBigEndian() const
Definition: TargetInfo.h:1650
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() 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:6089
const Type * getTypeForDecl() const
Definition: Decl.h:3414
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
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2684
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7330
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:7341
The base class of the type hierarchy.
Definition: Type.h:1813
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1871
bool isVoidType() const
Definition: Type.h:7905
bool isBooleanType() const
Definition: Type.h:8033
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8083
bool isIncompleteArrayType() const
Definition: Type.h:7686
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2135
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2060
bool isRValueReferenceType() const
Definition: Type.h:7632
bool isConstantArrayType() const
Definition: Type.h:7682
bool isArrayType() const
Definition: Type.h:7678
bool isCharType() const
Definition: Type.cpp:2078
bool isPointerType() const
Definition: Type.h:7612
bool isArrayParameterType() const
Definition: Type.h:7694
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7945
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8193
bool isReferenceType() const
Definition: Type.h:7624
bool isScalarType() const
Definition: Type.h:8004
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:1856
bool isChar8Type() const
Definition: Type.cpp:2094
bool isSizelessBuiltinType() const
Definition: Type.cpp:2422
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:695
bool isExtVectorType() const
Definition: Type.h:7722
bool isOCLIntelSubgroupAVCType() const
Definition: Type.h:7850
bool isLValueReferenceType() const
Definition: Type.h:7628
bool isOpenCLSpecificType() const
Definition: Type.h:7865
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2653
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2327
bool isAnyComplexType() const
Definition: Type.h:7714
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2000
bool isQueueT() const
Definition: Type.h:7821
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8076
bool isAtomicType() const
Definition: Type.h:7757
bool isFunctionProtoType() const
Definition: Type.h:2494
bool isObjCObjectType() const
Definition: Type.h:7748
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8179
bool isEventT() const
Definition: Type.h:7813
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2351
bool isFunctionType() const
Definition: Type.h:7608
bool isObjCObjectPointerType() const
Definition: Type.h:7744
bool isVectorType() const
Definition: Type.h:7718
bool isFloatingType() const
Definition: Type.cpp:2238
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:2185
bool isSamplerT() const
Definition: Type.h:7809
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8126
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:605
bool isNullPtrType() const
Definition: Type.h:7938
bool isRecordType() const
Definition: Type.h:7706
bool isObjCRetainableType() const
Definition: Type.cpp:4878
bool isUnionType() const
Definition: Type.cpp:661
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:2183
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
QualType getType() const
Definition: Decl.h:717
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5371
Represents a variable declaration or definition.
Definition: Decl.h:918
const Expr * getInit() const
Definition: Decl.h:1355
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1171
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3747
Represents a GCC generic vector type.
Definition: Type.h:3969
unsigned getNumElements() const
Definition: Type.h:3984
VectorKind getVectorKind() const
Definition: Type.h:3989
QualType getElementType() const
Definition: Type.h:3983
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:1873
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.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus26
Definition: LangStandard.h:61
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
bool isCompoundAssignmentOperator(OverloadedOperatorKind Kind)
Determine if this is a compound assignment operator.
Definition: OperatorKinds.h:53
@ ovl_fail_bad_conversion
Definition: Overload.h:777
@ 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:1534
LLVM_READONLY bool isUppercase(unsigned char c)
Return true if this character is an uppercase ASCII letter: [A-Z].
Definition: CharInfo.h:127
@ LCK_ByRef
Capturing by reference.
Definition: Lambda.h:37
BinaryOperatorKind
@ SD_Automatic
Automatic storage duration (most local variables).
Definition: Specifiers.h:326
@ 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.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
Expr * IgnoreParensSingleStep(Expr *E)
Definition: IgnoreExpr.h:150
const FunctionProtoType * T
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:245
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:251
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:259
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:248
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:255
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition: Overload.h:1241
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Braces
New-expression has a C++11 list-initializer.
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:436
@ Implicit
An implicit conversion.
@ CStyleCast
A C-style cast.
@ OtherCast
A cast other than a C-style cast.
@ FunctionalCast
A functional-style cast.
@ AS_public
Definition: Specifiers.h:121
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
unsigned long uint64_t
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
#define bool
Definition: stdbool.h:24
CXXConstructorDecl * Constructor
Definition: Overload.h:1233
DeclAccessPair FoundDecl
Definition: Overload.h:1232
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:848
bool Viable
Viable - True to indicate that this overload candidate is viable.
Definition: Overload.h:877
unsigned char FailureKind
FailureKind - The reason why this candidate is not viable.
Definition: Overload.h:911
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition: Overload.h:871
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:8078
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:427