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 "llvm/ADT/APInt.h"
32#include "llvm/ADT/FoldingSet.h"
33#include "llvm/ADT/PointerIntPair.h"
34#include "llvm/ADT/SmallString.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/StringExtras.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/raw_ostream.h"
39
40using namespace clang;
41
42//===----------------------------------------------------------------------===//
43// Sema Initialization Checking
44//===----------------------------------------------------------------------===//
45
46/// Check whether T is compatible with a wide character type (wchar_t,
47/// char16_t or char32_t).
48static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
49 if (Context.typesAreCompatible(Context.getWideCharType(), T))
50 return true;
51 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
52 return Context.typesAreCompatible(Context.Char16Ty, T) ||
53 Context.typesAreCompatible(Context.Char32Ty, T);
54 }
55 return false;
56}
57
66};
67
68/// Check whether the array of type AT can be initialized by the Init
69/// expression by means of string initialization. Returns SIF_None if so,
70/// otherwise returns a StringInitFailureKind that describes why the
71/// initialization would not work.
73 ASTContext &Context) {
74 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
75 return SIF_Other;
76
77 // See if this is a string literal or @encode.
78 Init = Init->IgnoreParens();
79
80 // Handle @encode, which is a narrow string.
81 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
82 return SIF_None;
83
84 // Otherwise we can only handle string literals.
85 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
86 if (!SL)
87 return SIF_Other;
88
89 const QualType ElemTy =
91
92 auto IsCharOrUnsignedChar = [](const QualType &T) {
93 const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
94 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
95 };
96
97 switch (SL->getKind()) {
98 case StringLiteralKind::UTF8:
99 // char8_t array can be initialized with a UTF-8 string.
100 // - C++20 [dcl.init.string] (DR)
101 // Additionally, an array of char or unsigned char may be initialized
102 // by a UTF-8 string literal.
103 if (ElemTy->isChar8Type() ||
104 (Context.getLangOpts().Char8 &&
105 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
106 return SIF_None;
107 [[fallthrough]];
108 case StringLiteralKind::Ordinary:
109 // char array can be initialized with a narrow string.
110 // Only allow char x[] = "foo"; not char x[] = L"foo";
111 if (ElemTy->isCharType())
112 return (SL->getKind() == StringLiteralKind::UTF8 &&
113 Context.getLangOpts().Char8)
115 : SIF_None;
116 if (ElemTy->isChar8Type())
118 if (IsWideCharCompatible(ElemTy, Context))
120 return SIF_Other;
121 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
122 // "An array with element type compatible with a qualified or unqualified
123 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
124 // string literal with the corresponding encoding prefix (L, u, or U,
125 // respectively), optionally enclosed in braces.
126 case StringLiteralKind::UTF16:
127 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
128 return SIF_None;
129 if (ElemTy->isCharType() || ElemTy->isChar8Type())
131 if (IsWideCharCompatible(ElemTy, Context))
133 return SIF_Other;
134 case StringLiteralKind::UTF32:
135 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
136 return SIF_None;
137 if (ElemTy->isCharType() || ElemTy->isChar8Type())
139 if (IsWideCharCompatible(ElemTy, Context))
141 return SIF_Other;
142 case StringLiteralKind::Wide:
143 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
144 return SIF_None;
145 if (ElemTy->isCharType() || ElemTy->isChar8Type())
147 if (IsWideCharCompatible(ElemTy, Context))
149 return SIF_Other;
150 case StringLiteralKind::Unevaluated:
151 assert(false && "Unevaluated string literal in initialization");
152 break;
153 }
154
155 llvm_unreachable("missed a StringLiteral kind?");
156}
157
159 ASTContext &Context) {
160 const ArrayType *arrayType = Context.getAsArrayType(declType);
161 if (!arrayType)
162 return SIF_Other;
163 return IsStringInit(init, arrayType, Context);
164}
165
167 return ::IsStringInit(Init, AT, Context) == SIF_None;
168}
169
170/// Update the type of a string literal, including any surrounding parentheses,
171/// to match the type of the object which it is initializing.
173 while (true) {
174 E->setType(Ty);
176 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
177 break;
179 }
180}
181
182/// Fix a compound literal initializing an array so it's correctly marked
183/// as an rvalue.
185 while (true) {
187 if (isa<CompoundLiteralExpr>(E))
188 break;
190 }
191}
192
194 Decl *D = Entity.getDecl();
195 const InitializedEntity *Parent = &Entity;
196
197 while (Parent) {
198 D = Parent->getDecl();
199 Parent = Parent->getParent();
200 }
201
202 if (const auto *VD = dyn_cast_if_present<VarDecl>(D); VD && VD->isConstexpr())
203 return true;
204
205 return false;
206}
207
209 Sema &SemaRef, QualType &TT);
210
211static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
212 Sema &S, bool CheckC23ConstexprInit = false) {
213 // Get the length of the string as parsed.
214 auto *ConstantArrayTy =
215 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
216 uint64_t StrLength = ConstantArrayTy->getZExtSize();
217
218 if (CheckC23ConstexprInit)
219 if (const StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens()))
221
222 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
223 // C99 6.7.8p14. We have an array of character type with unknown size
224 // being initialized to a string literal.
225 llvm::APInt ConstVal(32, StrLength);
226 // Return a new array type (C99 6.7.8p22).
228 IAT->getElementType(), ConstVal, nullptr, ArraySizeModifier::Normal, 0);
229 updateStringLiteralType(Str, DeclT);
230 return;
231 }
232
233 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
234
235 // We have an array of character type with known size. However,
236 // the size may be smaller or larger than the string we are initializing.
237 // FIXME: Avoid truncation for 64-bit length strings.
238 if (S.getLangOpts().CPlusPlus) {
239 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
240 // For Pascal strings it's OK to strip off the terminating null character,
241 // so the example below is valid:
242 //
243 // unsigned char a[2] = "\pa";
244 if (SL->isPascal())
245 StrLength--;
246 }
247
248 // [dcl.init.string]p2
249 if (StrLength > CAT->getZExtSize())
250 S.Diag(Str->getBeginLoc(),
251 diag::err_initializer_string_for_char_array_too_long)
252 << CAT->getZExtSize() << StrLength << Str->getSourceRange();
253 } else {
254 // C99 6.7.8p14.
255 if (StrLength - 1 > CAT->getZExtSize())
256 S.Diag(Str->getBeginLoc(),
257 diag::ext_initializer_string_for_char_array_too_long)
258 << Str->getSourceRange();
259 }
260
261 // Set the type to the actual size that we are initializing. If we have
262 // something like:
263 // char x[1] = "foo";
264 // then this will set the string literal's type to char[1].
265 updateStringLiteralType(Str, DeclT);
266}
267
268//===----------------------------------------------------------------------===//
269// Semantic checking for initializer lists.
270//===----------------------------------------------------------------------===//
271
272namespace {
273
274/// Semantic checking for initializer lists.
275///
276/// The InitListChecker class contains a set of routines that each
277/// handle the initialization of a certain kind of entity, e.g.,
278/// arrays, vectors, struct/union types, scalars, etc. The
279/// InitListChecker itself performs a recursive walk of the subobject
280/// structure of the type to be initialized, while stepping through
281/// the initializer list one element at a time. The IList and Index
282/// parameters to each of the Check* routines contain the active
283/// (syntactic) initializer list and the index into that initializer
284/// list that represents the current initializer. Each routine is
285/// responsible for moving that Index forward as it consumes elements.
286///
287/// Each Check* routine also has a StructuredList/StructuredIndex
288/// arguments, which contains the current "structured" (semantic)
289/// initializer list and the index into that initializer list where we
290/// are copying initializers as we map them over to the semantic
291/// list. Once we have completed our recursive walk of the subobject
292/// structure, we will have constructed a full semantic initializer
293/// list.
294///
295/// C99 designators cause changes in the initializer list traversal,
296/// because they make the initialization "jump" into a specific
297/// subobject and then continue the initialization from that
298/// point. CheckDesignatedInitializer() recursively steps into the
299/// designated subobject and manages backing out the recursion to
300/// initialize the subobjects after the one designated.
301///
302/// If an initializer list contains any designators, we build a placeholder
303/// structured list even in 'verify only' mode, so that we can track which
304/// elements need 'empty' initializtion.
305class InitListChecker {
306 Sema &SemaRef;
307 bool hadError = false;
308 bool VerifyOnly; // No diagnostics.
309 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
310 bool InOverloadResolution;
311 InitListExpr *FullyStructuredList = nullptr;
312 NoInitExpr *DummyExpr = nullptr;
313 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;
314
315 NoInitExpr *getDummyInit() {
316 if (!DummyExpr)
317 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
318 return DummyExpr;
319 }
320
321 void CheckImplicitInitList(const InitializedEntity &Entity,
322 InitListExpr *ParentIList, QualType T,
323 unsigned &Index, InitListExpr *StructuredList,
324 unsigned &StructuredIndex);
325 void CheckExplicitInitList(const InitializedEntity &Entity,
326 InitListExpr *IList, QualType &T,
327 InitListExpr *StructuredList,
328 bool TopLevelObject = false);
329 void CheckListElementTypes(const InitializedEntity &Entity,
330 InitListExpr *IList, QualType &DeclType,
331 bool SubobjectIsDesignatorContext,
332 unsigned &Index,
333 InitListExpr *StructuredList,
334 unsigned &StructuredIndex,
335 bool TopLevelObject = false);
336 void CheckSubElementType(const InitializedEntity &Entity,
337 InitListExpr *IList, QualType ElemType,
338 unsigned &Index,
339 InitListExpr *StructuredList,
340 unsigned &StructuredIndex,
341 bool DirectlyDesignated = false);
342 void CheckComplexType(const InitializedEntity &Entity,
343 InitListExpr *IList, QualType DeclType,
344 unsigned &Index,
345 InitListExpr *StructuredList,
346 unsigned &StructuredIndex);
347 void CheckScalarType(const InitializedEntity &Entity,
348 InitListExpr *IList, QualType DeclType,
349 unsigned &Index,
350 InitListExpr *StructuredList,
351 unsigned &StructuredIndex);
352 void CheckReferenceType(const InitializedEntity &Entity,
353 InitListExpr *IList, QualType DeclType,
354 unsigned &Index,
355 InitListExpr *StructuredList,
356 unsigned &StructuredIndex);
357 void CheckVectorType(const InitializedEntity &Entity,
358 InitListExpr *IList, QualType DeclType, unsigned &Index,
359 InitListExpr *StructuredList,
360 unsigned &StructuredIndex);
361 void CheckStructUnionTypes(const InitializedEntity &Entity,
362 InitListExpr *IList, QualType DeclType,
365 bool SubobjectIsDesignatorContext, unsigned &Index,
366 InitListExpr *StructuredList,
367 unsigned &StructuredIndex,
368 bool TopLevelObject = false);
369 void CheckArrayType(const InitializedEntity &Entity,
370 InitListExpr *IList, QualType &DeclType,
371 llvm::APSInt elementIndex,
372 bool SubobjectIsDesignatorContext, unsigned &Index,
373 InitListExpr *StructuredList,
374 unsigned &StructuredIndex);
375 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
376 InitListExpr *IList, DesignatedInitExpr *DIE,
377 unsigned DesigIdx,
378 QualType &CurrentObjectType,
380 llvm::APSInt *NextElementIndex,
381 unsigned &Index,
382 InitListExpr *StructuredList,
383 unsigned &StructuredIndex,
384 bool FinishSubobjectInit,
385 bool TopLevelObject);
386 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
387 QualType CurrentObjectType,
388 InitListExpr *StructuredList,
389 unsigned StructuredIndex,
390 SourceRange InitRange,
391 bool IsFullyOverwritten = false);
392 void UpdateStructuredListElement(InitListExpr *StructuredList,
393 unsigned &StructuredIndex,
394 Expr *expr);
395 InitListExpr *createInitListExpr(QualType CurrentObjectType,
396 SourceRange InitRange,
397 unsigned ExpectedNumInits);
398 int numArrayElements(QualType DeclType);
399 int numStructUnionElements(QualType DeclType);
400 static RecordDecl *getRecordDecl(QualType DeclType);
401
402 ExprResult PerformEmptyInit(SourceLocation Loc,
403 const InitializedEntity &Entity);
404
405 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
406 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
407 bool UnionOverride = false,
408 bool FullyOverwritten = true) {
409 // Overriding an initializer via a designator is valid with C99 designated
410 // initializers, but ill-formed with C++20 designated initializers.
411 unsigned DiagID =
412 SemaRef.getLangOpts().CPlusPlus
413 ? (UnionOverride ? diag::ext_initializer_union_overrides
414 : diag::ext_initializer_overrides)
415 : diag::warn_initializer_overrides;
416
417 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
418 // In overload resolution, we have to strictly enforce the rules, and so
419 // don't allow any overriding of prior initializers. This matters for a
420 // case such as:
421 //
422 // union U { int a, b; };
423 // struct S { int a, b; };
424 // void f(U), f(S);
425 //
426 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
427 // consistency, we disallow all overriding of prior initializers in
428 // overload resolution, not only overriding of union members.
429 hadError = true;
430 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
431 // If we'll be keeping around the old initializer but overwriting part of
432 // the object it initialized, and that object is not trivially
433 // destructible, this can leak. Don't allow that, not even as an
434 // extension.
435 //
436 // FIXME: It might be reasonable to allow this in cases where the part of
437 // the initializer that we're overriding has trivial destruction.
438 DiagID = diag::err_initializer_overrides_destructed;
439 } else if (!OldInit->getSourceRange().isValid()) {
440 // We need to check on source range validity because the previous
441 // initializer does not have to be an explicit initializer. e.g.,
442 //
443 // struct P { int a, b; };
444 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
445 //
446 // There is an overwrite taking place because the first braced initializer
447 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
448 //
449 // Such overwrites are harmless, so we don't diagnose them. (Note that in
450 // C++, this cannot be reached unless we've already seen and diagnosed a
451 // different conformance issue, such as a mixture of designated and
452 // non-designated initializers or a multi-level designator.)
453 return;
454 }
455
456 if (!VerifyOnly) {
457 SemaRef.Diag(NewInitRange.getBegin(), DiagID)
458 << NewInitRange << FullyOverwritten << OldInit->getType();
459 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
460 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
461 << OldInit->getSourceRange();
462 }
463 }
464
465 // Explanation on the "FillWithNoInit" mode:
466 //
467 // Assume we have the following definitions (Case#1):
468 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
469 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
470 //
471 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
472 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
473 //
474 // But if we have (Case#2):
475 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
476 //
477 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
478 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
479 //
480 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
481 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
482 // initializers but with special "NoInitExpr" place holders, which tells the
483 // CodeGen not to generate any initializers for these parts.
484 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
485 const InitializedEntity &ParentEntity,
486 InitListExpr *ILE, bool &RequiresSecondPass,
487 bool FillWithNoInit);
488 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
489 const InitializedEntity &ParentEntity,
490 InitListExpr *ILE, bool &RequiresSecondPass,
491 bool FillWithNoInit = false);
492 void FillInEmptyInitializations(const InitializedEntity &Entity,
493 InitListExpr *ILE, bool &RequiresSecondPass,
494 InitListExpr *OuterILE, unsigned OuterIndex,
495 bool FillWithNoInit = false);
496 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
497 Expr *InitExpr, FieldDecl *Field,
498 bool TopLevelObject);
499 void CheckEmptyInitializable(const InitializedEntity &Entity,
500 SourceLocation Loc);
501
502public:
503 InitListChecker(
504 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
505 bool VerifyOnly, bool TreatUnavailableAsInvalid,
506 bool InOverloadResolution = false,
507 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);
508 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
509 QualType &T,
510 SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)
511 : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,
512 /*TreatUnavailableAsInvalid=*/false,
513 /*InOverloadResolution=*/false,
514 &AggrDeductionCandidateParamTypes){};
515
516 bool HadError() { return hadError; }
517
518 // Retrieves the fully-structured initializer list used for
519 // semantic analysis and code generation.
520 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
521};
522
523} // end anonymous namespace
524
525ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
526 const InitializedEntity &Entity) {
528 true);
529 MultiExprArg SubInit;
530 Expr *InitExpr;
531 InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc);
532
533 // C++ [dcl.init.aggr]p7:
534 // If there are fewer initializer-clauses in the list than there are
535 // members in the aggregate, then each member not explicitly initialized
536 // ...
537 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
539 if (EmptyInitList) {
540 // C++1y / DR1070:
541 // shall be initialized [...] from an empty initializer list.
542 //
543 // We apply the resolution of this DR to C++11 but not C++98, since C++98
544 // does not have useful semantics for initialization from an init list.
545 // We treat this as copy-initialization, because aggregate initialization
546 // always performs copy-initialization on its elements.
547 //
548 // Only do this if we're initializing a class type, to avoid filling in
549 // the initializer list where possible.
550 InitExpr = VerifyOnly
551 ? &DummyInitList
552 : new (SemaRef.Context)
553 InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc);
554 InitExpr->setType(SemaRef.Context.VoidTy);
555 SubInit = InitExpr;
557 } else {
558 // C++03:
559 // shall be value-initialized.
560 }
561
562 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
563 // libstdc++4.6 marks the vector default constructor as explicit in
564 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
565 // stlport does so too. Look for std::__debug for libstdc++, and for
566 // std:: for stlport. This is effectively a compiler-side implementation of
567 // LWG2193.
568 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
572 InitSeq.getFailedCandidateSet()
573 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
574 (void)O;
575 assert(O == OR_Success && "Inconsistent overload resolution");
576 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
577 CXXRecordDecl *R = CtorDecl->getParent();
578
579 if (CtorDecl->getMinRequiredArguments() == 0 &&
580 CtorDecl->isExplicit() && R->getDeclName() &&
581 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
582 bool IsInStd = false;
583 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
584 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
586 IsInStd = true;
587 }
588
589 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
590 .Cases("basic_string", "deque", "forward_list", true)
591 .Cases("list", "map", "multimap", "multiset", true)
592 .Cases("priority_queue", "queue", "set", "stack", true)
593 .Cases("unordered_map", "unordered_set", "vector", true)
594 .Default(false)) {
595 InitSeq.InitializeFrom(
596 SemaRef, Entity,
597 InitializationKind::CreateValue(Loc, Loc, Loc, true),
598 MultiExprArg(), /*TopLevelOfInitList=*/false,
599 TreatUnavailableAsInvalid);
600 // Emit a warning for this. System header warnings aren't shown
601 // by default, but people working on system headers should see it.
602 if (!VerifyOnly) {
603 SemaRef.Diag(CtorDecl->getLocation(),
604 diag::warn_invalid_initializer_from_system_header);
606 SemaRef.Diag(Entity.getDecl()->getLocation(),
607 diag::note_used_in_initialization_here);
608 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
609 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
610 }
611 }
612 }
613 }
614 if (!InitSeq) {
615 if (!VerifyOnly) {
616 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
618 SemaRef.Diag(Entity.getDecl()->getLocation(),
619 diag::note_in_omitted_aggregate_initializer)
620 << /*field*/1 << Entity.getDecl();
621 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
622 bool IsTrailingArrayNewMember =
623 Entity.getParent() &&
625 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
626 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
627 << Entity.getElementIndex();
628 }
629 }
630 hadError = true;
631 return ExprError();
632 }
633
634 return VerifyOnly ? ExprResult()
635 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
636}
637
638void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
639 SourceLocation Loc) {
640 // If we're building a fully-structured list, we'll check this at the end
641 // once we know which elements are actually initialized. Otherwise, we know
642 // that there are no designators so we can just check now.
643 if (FullyStructuredList)
644 return;
645 PerformEmptyInit(Loc, Entity);
646}
647
648void InitListChecker::FillInEmptyInitForBase(
649 unsigned Init, const CXXBaseSpecifier &Base,
650 const InitializedEntity &ParentEntity, InitListExpr *ILE,
651 bool &RequiresSecondPass, bool FillWithNoInit) {
653 SemaRef.Context, &Base, false, &ParentEntity);
654
655 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
656 ExprResult BaseInit = FillWithNoInit
657 ? new (SemaRef.Context) NoInitExpr(Base.getType())
658 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
659 if (BaseInit.isInvalid()) {
660 hadError = true;
661 return;
662 }
663
664 if (!VerifyOnly) {
665 assert(Init < ILE->getNumInits() && "should have been expanded");
666 ILE->setInit(Init, BaseInit.getAs<Expr>());
667 }
668 } else if (InitListExpr *InnerILE =
669 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
670 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
671 ILE, Init, FillWithNoInit);
672 } else if (DesignatedInitUpdateExpr *InnerDIUE =
673 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
674 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
675 RequiresSecondPass, ILE, Init,
676 /*FillWithNoInit =*/true);
677 }
678}
679
680void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
681 const InitializedEntity &ParentEntity,
682 InitListExpr *ILE,
683 bool &RequiresSecondPass,
684 bool FillWithNoInit) {
685 SourceLocation Loc = ILE->getEndLoc();
686 unsigned NumInits = ILE->getNumInits();
687 InitializedEntity MemberEntity
688 = InitializedEntity::InitializeMember(Field, &ParentEntity);
689
690 if (Init >= NumInits || !ILE->getInit(Init)) {
691 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
692 if (!RType->getDecl()->isUnion())
693 assert((Init < NumInits || VerifyOnly) &&
694 "This ILE should have been expanded");
695
696 if (FillWithNoInit) {
697 assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
698 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
699 if (Init < NumInits)
700 ILE->setInit(Init, Filler);
701 else
702 ILE->updateInit(SemaRef.Context, Init, Filler);
703 return;
704 }
705 // C++1y [dcl.init.aggr]p7:
706 // If there are fewer initializer-clauses in the list than there are
707 // members in the aggregate, then each member not explicitly initialized
708 // shall be initialized from its brace-or-equal-initializer [...]
709 if (Field->hasInClassInitializer()) {
710 if (VerifyOnly)
711 return;
712
713 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
714 if (DIE.isInvalid()) {
715 hadError = true;
716 return;
717 }
718 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
719 if (Init < NumInits)
720 ILE->setInit(Init, DIE.get());
721 else {
722 ILE->updateInit(SemaRef.Context, Init, DIE.get());
723 RequiresSecondPass = true;
724 }
725 return;
726 }
727
728 if (Field->getType()->isReferenceType()) {
729 if (!VerifyOnly) {
730 // C++ [dcl.init.aggr]p9:
731 // If an incomplete or empty initializer-list leaves a
732 // member of reference type uninitialized, the program is
733 // ill-formed.
734 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
735 << Field->getType()
736 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
737 ->getSourceRange();
738 SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
739 }
740 hadError = true;
741 return;
742 }
743
744 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
745 if (MemberInit.isInvalid()) {
746 hadError = true;
747 return;
748 }
749
750 if (hadError || VerifyOnly) {
751 // Do nothing
752 } else if (Init < NumInits) {
753 ILE->setInit(Init, MemberInit.getAs<Expr>());
754 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
755 // Empty initialization requires a constructor call, so
756 // extend the initializer list to include the constructor
757 // call and make a note that we'll need to take another pass
758 // through the initializer list.
759 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
760 RequiresSecondPass = true;
761 }
762 } else if (InitListExpr *InnerILE
763 = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
764 FillInEmptyInitializations(MemberEntity, InnerILE,
765 RequiresSecondPass, ILE, Init, FillWithNoInit);
766 } else if (DesignatedInitUpdateExpr *InnerDIUE =
767 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
768 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
769 RequiresSecondPass, ILE, Init,
770 /*FillWithNoInit =*/true);
771 }
772}
773
774/// Recursively replaces NULL values within the given initializer list
775/// with expressions that perform value-initialization of the
776/// appropriate type, and finish off the InitListExpr formation.
777void
778InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
779 InitListExpr *ILE,
780 bool &RequiresSecondPass,
781 InitListExpr *OuterILE,
782 unsigned OuterIndex,
783 bool FillWithNoInit) {
784 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
785 "Should not have void type");
786
787 // We don't need to do any checks when just filling NoInitExprs; that can't
788 // fail.
789 if (FillWithNoInit && VerifyOnly)
790 return;
791
792 // If this is a nested initializer list, we might have changed its contents
793 // (and therefore some of its properties, such as instantiation-dependence)
794 // while filling it in. Inform the outer initializer list so that its state
795 // can be updated to match.
796 // FIXME: We should fully build the inner initializers before constructing
797 // the outer InitListExpr instead of mutating AST nodes after they have
798 // been used as subexpressions of other nodes.
799 struct UpdateOuterILEWithUpdatedInit {
800 InitListExpr *Outer;
801 unsigned OuterIndex;
802 ~UpdateOuterILEWithUpdatedInit() {
803 if (Outer)
804 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
805 }
806 } UpdateOuterRAII = {OuterILE, OuterIndex};
807
808 // A transparent ILE is not performing aggregate initialization and should
809 // not be filled in.
810 if (ILE->isTransparent())
811 return;
812
813 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
814 const RecordDecl *RDecl = RType->getDecl();
815 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
816 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
817 Entity, ILE, RequiresSecondPass, FillWithNoInit);
818 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
819 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
820 for (auto *Field : RDecl->fields()) {
821 if (Field->hasInClassInitializer()) {
822 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
823 FillWithNoInit);
824 break;
825 }
826 }
827 } else {
828 // The fields beyond ILE->getNumInits() are default initialized, so in
829 // order to leave them uninitialized, the ILE is expanded and the extra
830 // fields are then filled with NoInitExpr.
831 unsigned NumElems = numStructUnionElements(ILE->getType());
832 if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
833 ++NumElems;
834 if (!VerifyOnly && ILE->getNumInits() < NumElems)
835 ILE->resizeInits(SemaRef.Context, NumElems);
836
837 unsigned Init = 0;
838
839 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
840 for (auto &Base : CXXRD->bases()) {
841 if (hadError)
842 return;
843
844 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
845 FillWithNoInit);
846 ++Init;
847 }
848 }
849
850 for (auto *Field : RDecl->fields()) {
851 if (Field->isUnnamedBitfield())
852 continue;
853
854 if (hadError)
855 return;
856
857 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
858 FillWithNoInit);
859 if (hadError)
860 return;
861
862 ++Init;
863
864 // Only look at the first initialization of a union.
865 if (RDecl->isUnion())
866 break;
867 }
868 }
869
870 return;
871 }
872
873 QualType ElementType;
874
875 InitializedEntity ElementEntity = Entity;
876 unsigned NumInits = ILE->getNumInits();
877 unsigned NumElements = NumInits;
878 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
879 ElementType = AType->getElementType();
880 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
881 NumElements = CAType->getZExtSize();
882 // For an array new with an unknown bound, ask for one additional element
883 // in order to populate the array filler.
884 if (Entity.isVariableLengthArrayNew())
885 ++NumElements;
886 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
887 0, Entity);
888 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
889 ElementType = VType->getElementType();
890 NumElements = VType->getNumElements();
891 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
892 0, Entity);
893 } else
894 ElementType = ILE->getType();
895
896 bool SkipEmptyInitChecks = false;
897 for (unsigned Init = 0; Init != NumElements; ++Init) {
898 if (hadError)
899 return;
900
901 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
903 ElementEntity.setElementIndex(Init);
904
905 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
906 return;
907
908 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
909 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
910 ILE->setInit(Init, ILE->getArrayFiller());
911 else if (!InitExpr && !ILE->hasArrayFiller()) {
912 // In VerifyOnly mode, there's no point performing empty initialization
913 // more than once.
914 if (SkipEmptyInitChecks)
915 continue;
916
917 Expr *Filler = nullptr;
918
919 if (FillWithNoInit)
920 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
921 else {
922 ExprResult ElementInit =
923 PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
924 if (ElementInit.isInvalid()) {
925 hadError = true;
926 return;
927 }
928
929 Filler = ElementInit.getAs<Expr>();
930 }
931
932 if (hadError) {
933 // Do nothing
934 } else if (VerifyOnly) {
935 SkipEmptyInitChecks = true;
936 } else if (Init < NumInits) {
937 // For arrays, just set the expression used for value-initialization
938 // of the "holes" in the array.
939 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
940 ILE->setArrayFiller(Filler);
941 else
942 ILE->setInit(Init, Filler);
943 } else {
944 // For arrays, just set the expression used for value-initialization
945 // of the rest of elements and exit.
946 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
947 ILE->setArrayFiller(Filler);
948 return;
949 }
950
951 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
952 // Empty initialization requires a constructor call, so
953 // extend the initializer list to include the constructor
954 // call and make a note that we'll need to take another pass
955 // through the initializer list.
956 ILE->updateInit(SemaRef.Context, Init, Filler);
957 RequiresSecondPass = true;
958 }
959 }
960 } else if (InitListExpr *InnerILE
961 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
962 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
963 ILE, Init, FillWithNoInit);
964 } else if (DesignatedInitUpdateExpr *InnerDIUE =
965 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
966 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
967 RequiresSecondPass, ILE, Init,
968 /*FillWithNoInit =*/true);
969 }
970 }
971}
972
973static bool hasAnyDesignatedInits(const InitListExpr *IL) {
974 for (const Stmt *Init : *IL)
975 if (isa_and_nonnull<DesignatedInitExpr>(Init))
976 return true;
977 return false;
978}
979
980InitListChecker::InitListChecker(
981 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
982 bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,
983 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)
984 : SemaRef(S), VerifyOnly(VerifyOnly),
985 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
986 InOverloadResolution(InOverloadResolution),
987 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
988 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
989 FullyStructuredList =
990 createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
991
992 // FIXME: Check that IL isn't already the semantic form of some other
993 // InitListExpr. If it is, we'd create a broken AST.
994 if (!VerifyOnly)
995 FullyStructuredList->setSyntacticForm(IL);
996 }
997
998 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
999 /*TopLevelObject=*/true);
1000
1001 if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
1002 bool RequiresSecondPass = false;
1003 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
1004 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
1005 if (RequiresSecondPass && !hadError)
1006 FillInEmptyInitializations(Entity, FullyStructuredList,
1007 RequiresSecondPass, nullptr, 0);
1008 }
1009 if (hadError && FullyStructuredList)
1010 FullyStructuredList->markError();
1011}
1012
1013int InitListChecker::numArrayElements(QualType DeclType) {
1014 // FIXME: use a proper constant
1015 int maxElements = 0x7FFFFFFF;
1016 if (const ConstantArrayType *CAT =
1017 SemaRef.Context.getAsConstantArrayType(DeclType)) {
1018 maxElements = static_cast<int>(CAT->getZExtSize());
1019 }
1020 return maxElements;
1021}
1022
1023int InitListChecker::numStructUnionElements(QualType DeclType) {
1024 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
1025 int InitializableMembers = 0;
1026 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1027 InitializableMembers += CXXRD->getNumBases();
1028 for (const auto *Field : structDecl->fields())
1029 if (!Field->isUnnamedBitfield())
1030 ++InitializableMembers;
1031
1032 if (structDecl->isUnion())
1033 return std::min(InitializableMembers, 1);
1034 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1035}
1036
1037RecordDecl *InitListChecker::getRecordDecl(QualType DeclType) {
1038 if (const auto *RT = DeclType->getAs<RecordType>())
1039 return RT->getDecl();
1040 if (const auto *Inject = DeclType->getAs<InjectedClassNameType>())
1041 return Inject->getDecl();
1042 return nullptr;
1043}
1044
1045/// Determine whether Entity is an entity for which it is idiomatic to elide
1046/// the braces in aggregate initialization.
1048 // Recursive initialization of the one and only field within an aggregate
1049 // class is considered idiomatic. This case arises in particular for
1050 // initialization of std::array, where the C++ standard suggests the idiom of
1051 //
1052 // std::array<T, N> arr = {1, 2, 3};
1053 //
1054 // (where std::array is an aggregate struct containing a single array field.
1055
1056 if (!Entity.getParent())
1057 return false;
1058
1059 // Allows elide brace initialization for aggregates with empty base.
1060 if (Entity.getKind() == InitializedEntity::EK_Base) {
1061 auto *ParentRD =
1062 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1063 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1064 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1065 }
1066
1067 // Allow brace elision if the only subobject is a field.
1068 if (Entity.getKind() == InitializedEntity::EK_Member) {
1069 auto *ParentRD =
1070 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1071 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1072 if (CXXRD->getNumBases()) {
1073 return false;
1074 }
1075 }
1076 auto FieldIt = ParentRD->field_begin();
1077 assert(FieldIt != ParentRD->field_end() &&
1078 "no fields but have initializer for member?");
1079 return ++FieldIt == ParentRD->field_end();
1080 }
1081
1082 return false;
1083}
1084
1085/// Check whether the range of the initializer \p ParentIList from element
1086/// \p Index onwards can be used to initialize an object of type \p T. Update
1087/// \p Index to indicate how many elements of the list were consumed.
1088///
1089/// This also fills in \p StructuredList, from element \p StructuredIndex
1090/// onwards, with the fully-braced, desugared form of the initialization.
1091void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1092 InitListExpr *ParentIList,
1093 QualType T, unsigned &Index,
1094 InitListExpr *StructuredList,
1095 unsigned &StructuredIndex) {
1096 int maxElements = 0;
1097
1098 if (T->isArrayType())
1099 maxElements = numArrayElements(T);
1100 else if (T->isRecordType())
1101 maxElements = numStructUnionElements(T);
1102 else if (T->isVectorType())
1103 maxElements = T->castAs<VectorType>()->getNumElements();
1104 else
1105 llvm_unreachable("CheckImplicitInitList(): Illegal type");
1106
1107 if (maxElements == 0) {
1108 if (!VerifyOnly)
1109 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1110 diag::err_implicit_empty_initializer);
1111 ++Index;
1112 hadError = true;
1113 return;
1114 }
1115
1116 // Build a structured initializer list corresponding to this subobject.
1117 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1118 ParentIList, Index, T, StructuredList, StructuredIndex,
1119 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1120 ParentIList->getSourceRange().getEnd()));
1121 unsigned StructuredSubobjectInitIndex = 0;
1122
1123 // Check the element types and build the structural subobject.
1124 unsigned StartIndex = Index;
1125 CheckListElementTypes(Entity, ParentIList, T,
1126 /*SubobjectIsDesignatorContext=*/false, Index,
1127 StructuredSubobjectInitList,
1128 StructuredSubobjectInitIndex);
1129
1130 if (StructuredSubobjectInitList) {
1131 StructuredSubobjectInitList->setType(T);
1132
1133 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1134 // Update the structured sub-object initializer so that it's ending
1135 // range corresponds with the end of the last initializer it used.
1136 if (EndIndex < ParentIList->getNumInits() &&
1137 ParentIList->getInit(EndIndex)) {
1138 SourceLocation EndLoc
1139 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1140 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1141 }
1142
1143 // Complain about missing braces.
1144 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1145 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1147 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1148 diag::warn_missing_braces)
1149 << StructuredSubobjectInitList->getSourceRange()
1151 StructuredSubobjectInitList->getBeginLoc(), "{")
1153 SemaRef.getLocForEndOfToken(
1154 StructuredSubobjectInitList->getEndLoc()),
1155 "}");
1156 }
1157
1158 // Warn if this type won't be an aggregate in future versions of C++.
1159 auto *CXXRD = T->getAsCXXRecordDecl();
1160 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1161 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1162 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1163 << StructuredSubobjectInitList->getSourceRange() << T;
1164 }
1165 }
1166}
1167
1168/// Warn that \p Entity was of scalar type and was initialized by a
1169/// single-element braced initializer list.
1170static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1172 // Don't warn during template instantiation. If the initialization was
1173 // non-dependent, we warned during the initial parse; otherwise, the
1174 // type might not be scalar in some uses of the template.
1176 return;
1177
1178 unsigned DiagID = 0;
1179
1180 switch (Entity.getKind()) {
1189 // Extra braces here are suspicious.
1190 DiagID = diag::warn_braces_around_init;
1191 break;
1192
1194 // Warn on aggregate initialization but not on ctor init list or
1195 // default member initializer.
1196 if (Entity.getParent())
1197 DiagID = diag::warn_braces_around_init;
1198 break;
1199
1202 // No warning, might be direct-list-initialization.
1203 // FIXME: Should we warn for copy-list-initialization in these cases?
1204 break;
1205
1209 // No warning, braces are part of the syntax of the underlying construct.
1210 break;
1211
1213 // No warning, we already warned when initializing the result.
1214 break;
1215
1223 llvm_unreachable("unexpected braced scalar init");
1224 }
1225
1226 if (DiagID) {
1227 S.Diag(Braces.getBegin(), DiagID)
1228 << Entity.getType()->isSizelessBuiltinType() << Braces
1229 << FixItHint::CreateRemoval(Braces.getBegin())
1230 << FixItHint::CreateRemoval(Braces.getEnd());
1231 }
1232}
1233
1234/// Check whether the initializer \p IList (that was written with explicit
1235/// braces) can be used to initialize an object of type \p T.
1236///
1237/// This also fills in \p StructuredList with the fully-braced, desugared
1238/// form of the initialization.
1239void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1240 InitListExpr *IList, QualType &T,
1241 InitListExpr *StructuredList,
1242 bool TopLevelObject) {
1243 unsigned Index = 0, StructuredIndex = 0;
1244 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1245 Index, StructuredList, StructuredIndex, TopLevelObject);
1246 if (StructuredList) {
1247 QualType ExprTy = T;
1248 if (!ExprTy->isArrayType())
1249 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1250 if (!VerifyOnly)
1251 IList->setType(ExprTy);
1252 StructuredList->setType(ExprTy);
1253 }
1254 if (hadError)
1255 return;
1256
1257 // Don't complain for incomplete types, since we'll get an error elsewhere.
1258 if (Index < IList->getNumInits() && !T->isIncompleteType()) {
1259 // We have leftover initializers
1260 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1261 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1262 hadError = ExtraInitsIsError;
1263 if (VerifyOnly) {
1264 return;
1265 } else if (StructuredIndex == 1 &&
1266 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1267 SIF_None) {
1268 unsigned DK =
1269 ExtraInitsIsError
1270 ? diag::err_excess_initializers_in_char_array_initializer
1271 : diag::ext_excess_initializers_in_char_array_initializer;
1272 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1273 << IList->getInit(Index)->getSourceRange();
1274 } else if (T->isSizelessBuiltinType()) {
1275 unsigned DK = ExtraInitsIsError
1276 ? diag::err_excess_initializers_for_sizeless_type
1277 : diag::ext_excess_initializers_for_sizeless_type;
1278 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1279 << T << IList->getInit(Index)->getSourceRange();
1280 } else {
1281 int initKind = T->isArrayType() ? 0 :
1282 T->isVectorType() ? 1 :
1283 T->isScalarType() ? 2 :
1284 T->isUnionType() ? 3 :
1285 4;
1286
1287 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1288 : diag::ext_excess_initializers;
1289 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1290 << initKind << IList->getInit(Index)->getSourceRange();
1291 }
1292 }
1293
1294 if (!VerifyOnly) {
1295 if (T->isScalarType() && IList->getNumInits() == 1 &&
1296 !isa<InitListExpr>(IList->getInit(0)))
1297 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1298
1299 // Warn if this is a class type that won't be an aggregate in future
1300 // versions of C++.
1301 auto *CXXRD = T->getAsCXXRecordDecl();
1302 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1303 // Don't warn if there's an equivalent default constructor that would be
1304 // used instead.
1305 bool HasEquivCtor = false;
1306 if (IList->getNumInits() == 0) {
1307 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1308 HasEquivCtor = CD && !CD->isDeleted();
1309 }
1310
1311 if (!HasEquivCtor) {
1312 SemaRef.Diag(IList->getBeginLoc(),
1313 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1314 << IList->getSourceRange() << T;
1315 }
1316 }
1317 }
1318}
1319
1320void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1321 InitListExpr *IList,
1322 QualType &DeclType,
1323 bool SubobjectIsDesignatorContext,
1324 unsigned &Index,
1325 InitListExpr *StructuredList,
1326 unsigned &StructuredIndex,
1327 bool TopLevelObject) {
1328 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1329 // Explicitly braced initializer for complex type can be real+imaginary
1330 // parts.
1331 CheckComplexType(Entity, IList, DeclType, Index,
1332 StructuredList, StructuredIndex);
1333 } else if (DeclType->isScalarType()) {
1334 CheckScalarType(Entity, IList, DeclType, Index,
1335 StructuredList, StructuredIndex);
1336 } else if (DeclType->isVectorType()) {
1337 CheckVectorType(Entity, IList, DeclType, Index,
1338 StructuredList, StructuredIndex);
1339 } else if (const RecordDecl *RD = getRecordDecl(DeclType)) {
1340 auto Bases =
1343 if (DeclType->isRecordType()) {
1344 assert(DeclType->isAggregateType() &&
1345 "non-aggregate records should be handed in CheckSubElementType");
1346 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1347 Bases = CXXRD->bases();
1348 } else {
1349 Bases = cast<CXXRecordDecl>(RD)->bases();
1350 }
1351 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1352 SubobjectIsDesignatorContext, Index, StructuredList,
1353 StructuredIndex, TopLevelObject);
1354 } else if (DeclType->isArrayType()) {
1355 llvm::APSInt Zero(
1356 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1357 false);
1358 CheckArrayType(Entity, IList, DeclType, Zero,
1359 SubobjectIsDesignatorContext, Index,
1360 StructuredList, StructuredIndex);
1361 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1362 // This type is invalid, issue a diagnostic.
1363 ++Index;
1364 if (!VerifyOnly)
1365 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1366 << DeclType;
1367 hadError = true;
1368 } else if (DeclType->isReferenceType()) {
1369 CheckReferenceType(Entity, IList, DeclType, Index,
1370 StructuredList, StructuredIndex);
1371 } else if (DeclType->isObjCObjectType()) {
1372 if (!VerifyOnly)
1373 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1374 hadError = true;
1375 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1376 DeclType->isSizelessBuiltinType()) {
1377 // Checks for scalar type are sufficient for these types too.
1378 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1379 StructuredIndex);
1380 } else if (DeclType->isDependentType()) {
1381 // C++ [over.match.class.deduct]p1.5:
1382 // brace elision is not considered for any aggregate element that has a
1383 // dependent non-array type or an array type with a value-dependent bound
1384 ++Index;
1385 assert(AggrDeductionCandidateParamTypes);
1386 AggrDeductionCandidateParamTypes->push_back(DeclType);
1387 } else {
1388 if (!VerifyOnly)
1389 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1390 << DeclType;
1391 hadError = true;
1392 }
1393}
1394
1395void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1396 InitListExpr *IList,
1397 QualType ElemType,
1398 unsigned &Index,
1399 InitListExpr *StructuredList,
1400 unsigned &StructuredIndex,
1401 bool DirectlyDesignated) {
1402 Expr *expr = IList->getInit(Index);
1403
1404 if (ElemType->isReferenceType())
1405 return CheckReferenceType(Entity, IList, ElemType, Index,
1406 StructuredList, StructuredIndex);
1407
1408 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1409 if (SubInitList->getNumInits() == 1 &&
1410 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1411 SIF_None) {
1412 // FIXME: It would be more faithful and no less correct to include an
1413 // InitListExpr in the semantic form of the initializer list in this case.
1414 expr = SubInitList->getInit(0);
1415 }
1416 // Nested aggregate initialization and C++ initialization are handled later.
1417 } else if (isa<ImplicitValueInitExpr>(expr)) {
1418 // This happens during template instantiation when we see an InitListExpr
1419 // that we've already checked once.
1420 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1421 "found implicit initialization for the wrong type");
1422 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1423 ++Index;
1424 return;
1425 }
1426
1427 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1428 // C++ [dcl.init.aggr]p2:
1429 // Each member is copy-initialized from the corresponding
1430 // initializer-clause.
1431
1432 // FIXME: Better EqualLoc?
1435
1436 // Vector elements can be initialized from other vectors in which case
1437 // we need initialization entity with a type of a vector (and not a vector
1438 // element!) initializing multiple vector elements.
1439 auto TmpEntity =
1440 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1442 : Entity;
1443
1444 if (TmpEntity.getType()->isDependentType()) {
1445 // C++ [over.match.class.deduct]p1.5:
1446 // brace elision is not considered for any aggregate element that has a
1447 // dependent non-array type or an array type with a value-dependent
1448 // bound
1449 assert(AggrDeductionCandidateParamTypes);
1450 if (!isa_and_nonnull<ConstantArrayType>(
1451 SemaRef.Context.getAsArrayType(ElemType))) {
1452 ++Index;
1453 AggrDeductionCandidateParamTypes->push_back(ElemType);
1454 return;
1455 }
1456 } else {
1457 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1458 /*TopLevelOfInitList*/ true);
1459 // C++14 [dcl.init.aggr]p13:
1460 // If the assignment-expression can initialize a member, the member is
1461 // initialized. Otherwise [...] brace elision is assumed
1462 //
1463 // Brace elision is never performed if the element is not an
1464 // assignment-expression.
1465 if (Seq || isa<InitListExpr>(expr)) {
1466 if (!VerifyOnly) {
1467 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1468 if (Result.isInvalid())
1469 hadError = true;
1470
1471 UpdateStructuredListElement(StructuredList, StructuredIndex,
1472 Result.getAs<Expr>());
1473 } else if (!Seq) {
1474 hadError = true;
1475 } else if (StructuredList) {
1476 UpdateStructuredListElement(StructuredList, StructuredIndex,
1477 getDummyInit());
1478 }
1479 ++Index;
1480 if (AggrDeductionCandidateParamTypes)
1481 AggrDeductionCandidateParamTypes->push_back(ElemType);
1482 return;
1483 }
1484 }
1485
1486 // Fall through for subaggregate initialization
1487 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1488 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1489 return CheckScalarType(Entity, IList, ElemType, Index,
1490 StructuredList, StructuredIndex);
1491 } else if (const ArrayType *arrayType =
1492 SemaRef.Context.getAsArrayType(ElemType)) {
1493 // arrayType can be incomplete if we're initializing a flexible
1494 // array member. There's nothing we can do with the completed
1495 // type here, though.
1496
1497 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1498 // FIXME: Should we do this checking in verify-only mode?
1499 if (!VerifyOnly)
1500 CheckStringInit(expr, ElemType, arrayType, SemaRef,
1501 SemaRef.getLangOpts().C23 &&
1503 if (StructuredList)
1504 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1505 ++Index;
1506 return;
1507 }
1508
1509 // Fall through for subaggregate initialization.
1510
1511 } else {
1512 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1513 ElemType->isOpenCLSpecificType()) && "Unexpected type");
1514
1515 // C99 6.7.8p13:
1516 //
1517 // The initializer for a structure or union object that has
1518 // automatic storage duration shall be either an initializer
1519 // list as described below, or a single expression that has
1520 // compatible structure or union type. In the latter case, the
1521 // initial value of the object, including unnamed members, is
1522 // that of the expression.
1523 ExprResult ExprRes = expr;
1525 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1526 if (ExprRes.isInvalid())
1527 hadError = true;
1528 else {
1529 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1530 if (ExprRes.isInvalid())
1531 hadError = true;
1532 }
1533 UpdateStructuredListElement(StructuredList, StructuredIndex,
1534 ExprRes.getAs<Expr>());
1535 ++Index;
1536 return;
1537 }
1538 ExprRes.get();
1539 // Fall through for subaggregate initialization
1540 }
1541
1542 // C++ [dcl.init.aggr]p12:
1543 //
1544 // [...] Otherwise, if the member is itself a non-empty
1545 // subaggregate, brace elision is assumed and the initializer is
1546 // considered for the initialization of the first member of
1547 // the subaggregate.
1548 // OpenCL vector initializer is handled elsewhere.
1549 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1550 ElemType->isAggregateType()) {
1551 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1552 StructuredIndex);
1553 ++StructuredIndex;
1554
1555 // In C++20, brace elision is not permitted for a designated initializer.
1556 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1557 if (InOverloadResolution)
1558 hadError = true;
1559 if (!VerifyOnly) {
1560 SemaRef.Diag(expr->getBeginLoc(),
1561 diag::ext_designated_init_brace_elision)
1562 << expr->getSourceRange()
1563 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1565 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1566 }
1567 }
1568 } else {
1569 if (!VerifyOnly) {
1570 // We cannot initialize this element, so let PerformCopyInitialization
1571 // produce the appropriate diagnostic. We already checked that this
1572 // initialization will fail.
1575 /*TopLevelOfInitList=*/true);
1576 (void)Copy;
1577 assert(Copy.isInvalid() &&
1578 "expected non-aggregate initialization to fail");
1579 }
1580 hadError = true;
1581 ++Index;
1582 ++StructuredIndex;
1583 }
1584}
1585
1586void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1587 InitListExpr *IList, QualType DeclType,
1588 unsigned &Index,
1589 InitListExpr *StructuredList,
1590 unsigned &StructuredIndex) {
1591 assert(Index == 0 && "Index in explicit init list must be zero");
1592
1593 // As an extension, clang supports complex initializers, which initialize
1594 // a complex number component-wise. When an explicit initializer list for
1595 // a complex number contains two initializers, this extension kicks in:
1596 // it expects the initializer list to contain two elements convertible to
1597 // the element type of the complex type. The first element initializes
1598 // the real part, and the second element intitializes the imaginary part.
1599
1600 if (IList->getNumInits() < 2)
1601 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1602 StructuredIndex);
1603
1604 // This is an extension in C. (The builtin _Complex type does not exist
1605 // in the C++ standard.)
1606 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1607 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1608 << IList->getSourceRange();
1609
1610 // Initialize the complex number.
1611 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1612 InitializedEntity ElementEntity =
1614
1615 for (unsigned i = 0; i < 2; ++i) {
1616 ElementEntity.setElementIndex(Index);
1617 CheckSubElementType(ElementEntity, IList, elementType, Index,
1618 StructuredList, StructuredIndex);
1619 }
1620}
1621
1622void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1623 InitListExpr *IList, QualType DeclType,
1624 unsigned &Index,
1625 InitListExpr *StructuredList,
1626 unsigned &StructuredIndex) {
1627 if (Index >= IList->getNumInits()) {
1628 if (!VerifyOnly) {
1629 if (SemaRef.getLangOpts().CPlusPlus) {
1630 if (DeclType->isSizelessBuiltinType())
1631 SemaRef.Diag(IList->getBeginLoc(),
1632 SemaRef.getLangOpts().CPlusPlus11
1633 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1634 : diag::err_empty_sizeless_initializer)
1635 << DeclType << IList->getSourceRange();
1636 else
1637 SemaRef.Diag(IList->getBeginLoc(),
1638 SemaRef.getLangOpts().CPlusPlus11
1639 ? diag::warn_cxx98_compat_empty_scalar_initializer
1640 : diag::err_empty_scalar_initializer)
1641 << IList->getSourceRange();
1642 }
1643 }
1644 hadError =
1645 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1646 ++Index;
1647 ++StructuredIndex;
1648 return;
1649 }
1650
1651 Expr *expr = IList->getInit(Index);
1652 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1653 // FIXME: This is invalid, and accepting it causes overload resolution
1654 // to pick the wrong overload in some corner cases.
1655 if (!VerifyOnly)
1656 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1657 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1658
1659 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1660 StructuredIndex);
1661 return;
1662 } else if (isa<DesignatedInitExpr>(expr)) {
1663 if (!VerifyOnly)
1664 SemaRef.Diag(expr->getBeginLoc(),
1665 diag::err_designator_for_scalar_or_sizeless_init)
1666 << DeclType->isSizelessBuiltinType() << DeclType
1667 << expr->getSourceRange();
1668 hadError = true;
1669 ++Index;
1670 ++StructuredIndex;
1671 return;
1672 }
1673
1674 ExprResult Result;
1675 if (VerifyOnly) {
1676 if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1677 Result = getDummyInit();
1678 else
1679 Result = ExprError();
1680 } else {
1681 Result =
1682 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1683 /*TopLevelOfInitList=*/true);
1684 }
1685
1686 Expr *ResultExpr = nullptr;
1687
1688 if (Result.isInvalid())
1689 hadError = true; // types weren't compatible.
1690 else {
1691 ResultExpr = Result.getAs<Expr>();
1692
1693 if (ResultExpr != expr && !VerifyOnly) {
1694 // The type was promoted, update initializer list.
1695 // FIXME: Why are we updating the syntactic init list?
1696 IList->setInit(Index, ResultExpr);
1697 }
1698 }
1699 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1700 ++Index;
1701 if (AggrDeductionCandidateParamTypes)
1702 AggrDeductionCandidateParamTypes->push_back(DeclType);
1703}
1704
1705void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1706 InitListExpr *IList, QualType DeclType,
1707 unsigned &Index,
1708 InitListExpr *StructuredList,
1709 unsigned &StructuredIndex) {
1710 if (Index >= IList->getNumInits()) {
1711 // FIXME: It would be wonderful if we could point at the actual member. In
1712 // general, it would be useful to pass location information down the stack,
1713 // so that we know the location (or decl) of the "current object" being
1714 // initialized.
1715 if (!VerifyOnly)
1716 SemaRef.Diag(IList->getBeginLoc(),
1717 diag::err_init_reference_member_uninitialized)
1718 << DeclType << IList->getSourceRange();
1719 hadError = true;
1720 ++Index;
1721 ++StructuredIndex;
1722 return;
1723 }
1724
1725 Expr *expr = IList->getInit(Index);
1726 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1727 if (!VerifyOnly)
1728 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1729 << DeclType << IList->getSourceRange();
1730 hadError = true;
1731 ++Index;
1732 ++StructuredIndex;
1733 return;
1734 }
1735
1736 ExprResult Result;
1737 if (VerifyOnly) {
1738 if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1739 Result = getDummyInit();
1740 else
1741 Result = ExprError();
1742 } else {
1743 Result =
1744 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1745 /*TopLevelOfInitList=*/true);
1746 }
1747
1748 if (Result.isInvalid())
1749 hadError = true;
1750
1751 expr = Result.getAs<Expr>();
1752 // FIXME: Why are we updating the syntactic init list?
1753 if (!VerifyOnly && expr)
1754 IList->setInit(Index, expr);
1755
1756 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1757 ++Index;
1758 if (AggrDeductionCandidateParamTypes)
1759 AggrDeductionCandidateParamTypes->push_back(DeclType);
1760}
1761
1762void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1763 InitListExpr *IList, QualType DeclType,
1764 unsigned &Index,
1765 InitListExpr *StructuredList,
1766 unsigned &StructuredIndex) {
1767 const VectorType *VT = DeclType->castAs<VectorType>();
1768 unsigned maxElements = VT->getNumElements();
1769 unsigned numEltsInit = 0;
1770 QualType elementType = VT->getElementType();
1771
1772 if (Index >= IList->getNumInits()) {
1773 // Make sure the element type can be value-initialized.
1774 CheckEmptyInitializable(
1776 IList->getEndLoc());
1777 return;
1778 }
1779
1780 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1781 // If the initializing element is a vector, try to copy-initialize
1782 // instead of breaking it apart (which is doomed to failure anyway).
1783 Expr *Init = IList->getInit(Index);
1784 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1785 ExprResult Result;
1786 if (VerifyOnly) {
1787 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1788 Result = getDummyInit();
1789 else
1790 Result = ExprError();
1791 } else {
1792 Result =
1793 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1794 /*TopLevelOfInitList=*/true);
1795 }
1796
1797 Expr *ResultExpr = nullptr;
1798 if (Result.isInvalid())
1799 hadError = true; // types weren't compatible.
1800 else {
1801 ResultExpr = Result.getAs<Expr>();
1802
1803 if (ResultExpr != Init && !VerifyOnly) {
1804 // The type was promoted, update initializer list.
1805 // FIXME: Why are we updating the syntactic init list?
1806 IList->setInit(Index, ResultExpr);
1807 }
1808 }
1809 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1810 ++Index;
1811 if (AggrDeductionCandidateParamTypes)
1812 AggrDeductionCandidateParamTypes->push_back(elementType);
1813 return;
1814 }
1815
1816 InitializedEntity ElementEntity =
1818
1819 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1820 // Don't attempt to go past the end of the init list
1821 if (Index >= IList->getNumInits()) {
1822 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1823 break;
1824 }
1825
1826 ElementEntity.setElementIndex(Index);
1827 CheckSubElementType(ElementEntity, IList, elementType, Index,
1828 StructuredList, StructuredIndex);
1829 }
1830
1831 if (VerifyOnly)
1832 return;
1833
1834 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1835 const VectorType *T = Entity.getType()->castAs<VectorType>();
1836 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
1837 T->getVectorKind() == VectorKind::NeonPoly)) {
1838 // The ability to use vector initializer lists is a GNU vector extension
1839 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1840 // endian machines it works fine, however on big endian machines it
1841 // exhibits surprising behaviour:
1842 //
1843 // uint32x2_t x = {42, 64};
1844 // return vget_lane_u32(x, 0); // Will return 64.
1845 //
1846 // Because of this, explicitly call out that it is non-portable.
1847 //
1848 SemaRef.Diag(IList->getBeginLoc(),
1849 diag::warn_neon_vector_initializer_non_portable);
1850
1851 const char *typeCode;
1852 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1853
1854 if (elementType->isFloatingType())
1855 typeCode = "f";
1856 else if (elementType->isSignedIntegerType())
1857 typeCode = "s";
1858 else if (elementType->isUnsignedIntegerType())
1859 typeCode = "u";
1860 else
1861 llvm_unreachable("Invalid element type!");
1862
1863 SemaRef.Diag(IList->getBeginLoc(),
1864 SemaRef.Context.getTypeSize(VT) > 64
1865 ? diag::note_neon_vector_initializer_non_portable_q
1866 : diag::note_neon_vector_initializer_non_portable)
1867 << typeCode << typeSize;
1868 }
1869
1870 return;
1871 }
1872
1873 InitializedEntity ElementEntity =
1875
1876 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
1877 for (unsigned i = 0; i < maxElements; ++i) {
1878 // Don't attempt to go past the end of the init list
1879 if (Index >= IList->getNumInits())
1880 break;
1881
1882 ElementEntity.setElementIndex(Index);
1883
1884 QualType IType = IList->getInit(Index)->getType();
1885 if (!IType->isVectorType()) {
1886 CheckSubElementType(ElementEntity, IList, elementType, Index,
1887 StructuredList, StructuredIndex);
1888 ++numEltsInit;
1889 } else {
1890 QualType VecType;
1891 const VectorType *IVT = IType->castAs<VectorType>();
1892 unsigned numIElts = IVT->getNumElements();
1893
1894 if (IType->isExtVectorType())
1895 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1896 else
1897 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1898 IVT->getVectorKind());
1899 CheckSubElementType(ElementEntity, IList, VecType, Index,
1900 StructuredList, StructuredIndex);
1901 numEltsInit += numIElts;
1902 }
1903 }
1904
1905 // OpenCL and HLSL require all elements to be initialized.
1906 if (numEltsInit != maxElements) {
1907 if (!VerifyOnly)
1908 SemaRef.Diag(IList->getBeginLoc(),
1909 diag::err_vector_incorrect_num_initializers)
1910 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1911 hadError = true;
1912 }
1913}
1914
1915/// Check if the type of a class element has an accessible destructor, and marks
1916/// it referenced. Returns true if we shouldn't form a reference to the
1917/// destructor.
1918///
1919/// Aggregate initialization requires a class element's destructor be
1920/// accessible per 11.6.1 [dcl.init.aggr]:
1921///
1922/// The destructor for each element of class type is potentially invoked
1923/// (15.4 [class.dtor]) from the context where the aggregate initialization
1924/// occurs.
1926 Sema &SemaRef) {
1927 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1928 if (!CXXRD)
1929 return false;
1930
1931 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1932 SemaRef.CheckDestructorAccess(Loc, Destructor,
1933 SemaRef.PDiag(diag::err_access_dtor_temp)
1934 << ElementType);
1935 SemaRef.MarkFunctionReferenced(Loc, Destructor);
1936 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1937}
1938
1939void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1940 InitListExpr *IList, QualType &DeclType,
1941 llvm::APSInt elementIndex,
1942 bool SubobjectIsDesignatorContext,
1943 unsigned &Index,
1944 InitListExpr *StructuredList,
1945 unsigned &StructuredIndex) {
1946 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1947
1948 if (!VerifyOnly) {
1949 if (checkDestructorReference(arrayType->getElementType(),
1950 IList->getEndLoc(), SemaRef)) {
1951 hadError = true;
1952 return;
1953 }
1954 }
1955
1956 // Check for the special-case of initializing an array with a string.
1957 if (Index < IList->getNumInits()) {
1958 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1959 SIF_None) {
1960 // We place the string literal directly into the resulting
1961 // initializer list. This is the only place where the structure
1962 // of the structured initializer list doesn't match exactly,
1963 // because doing so would involve allocating one character
1964 // constant for each string.
1965 // FIXME: Should we do these checks in verify-only mode too?
1966 if (!VerifyOnly)
1967 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef,
1968 SemaRef.getLangOpts().C23 &&
1970 if (StructuredList) {
1971 UpdateStructuredListElement(StructuredList, StructuredIndex,
1972 IList->getInit(Index));
1973 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1974 }
1975 ++Index;
1976 if (AggrDeductionCandidateParamTypes)
1977 AggrDeductionCandidateParamTypes->push_back(DeclType);
1978 return;
1979 }
1980 }
1981 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1982 // Check for VLAs; in standard C it would be possible to check this
1983 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1984 // them in all sorts of strange places).
1985 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
1986 if (!VerifyOnly) {
1987 // C23 6.7.10p4: An entity of variable length array type shall not be
1988 // initialized except by an empty initializer.
1989 //
1990 // The C extension warnings are issued from ParseBraceInitializer() and
1991 // do not need to be issued here. However, we continue to issue an error
1992 // in the case there are initializers or we are compiling C++. We allow
1993 // use of VLAs in C++, but it's not clear we want to allow {} to zero
1994 // init a VLA in C++ in all cases (such as with non-trivial constructors).
1995 // FIXME: should we allow this construct in C++ when it makes sense to do
1996 // so?
1997 if (HasErr)
1998 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1999 diag::err_variable_object_no_init)
2000 << VAT->getSizeExpr()->getSourceRange();
2001 }
2002 hadError = HasErr;
2003 ++Index;
2004 ++StructuredIndex;
2005 return;
2006 }
2007
2008 // We might know the maximum number of elements in advance.
2009 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2010 elementIndex.isUnsigned());
2011 bool maxElementsKnown = false;
2012 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
2013 maxElements = CAT->getSize();
2014 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
2015 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2016 maxElementsKnown = true;
2017 }
2018
2019 QualType elementType = arrayType->getElementType();
2020 while (Index < IList->getNumInits()) {
2021 Expr *Init = IList->getInit(Index);
2022 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2023 // If we're not the subobject that matches up with the '{' for
2024 // the designator, we shouldn't be handling the
2025 // designator. Return immediately.
2026 if (!SubobjectIsDesignatorContext)
2027 return;
2028
2029 // Handle this designated initializer. elementIndex will be
2030 // updated to be the next array element we'll initialize.
2031 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2032 DeclType, nullptr, &elementIndex, Index,
2033 StructuredList, StructuredIndex, true,
2034 false)) {
2035 hadError = true;
2036 continue;
2037 }
2038
2039 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2040 maxElements = maxElements.extend(elementIndex.getBitWidth());
2041 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2042 elementIndex = elementIndex.extend(maxElements.getBitWidth());
2043 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2044
2045 // If the array is of incomplete type, keep track of the number of
2046 // elements in the initializer.
2047 if (!maxElementsKnown && elementIndex > maxElements)
2048 maxElements = elementIndex;
2049
2050 continue;
2051 }
2052
2053 // If we know the maximum number of elements, and we've already
2054 // hit it, stop consuming elements in the initializer list.
2055 if (maxElementsKnown && elementIndex == maxElements)
2056 break;
2057
2058 InitializedEntity ElementEntity =
2059 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
2060 Entity);
2061 // Check this element.
2062 CheckSubElementType(ElementEntity, IList, elementType, Index,
2063 StructuredList, StructuredIndex);
2064 ++elementIndex;
2065
2066 // If the array is of incomplete type, keep track of the number of
2067 // elements in the initializer.
2068 if (!maxElementsKnown && elementIndex > maxElements)
2069 maxElements = elementIndex;
2070 }
2071 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2072 // If this is an incomplete array type, the actual type needs to
2073 // be calculated here.
2074 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2075 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2076 // Sizing an array implicitly to zero is not allowed by ISO C,
2077 // but is supported by GNU.
2078 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2079 }
2080
2081 DeclType = SemaRef.Context.getConstantArrayType(
2082 elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2083 }
2084 if (!hadError) {
2085 // If there are any members of the array that get value-initialized, check
2086 // that is possible. That happens if we know the bound and don't have
2087 // enough elements, or if we're performing an array new with an unknown
2088 // bound.
2089 if ((maxElementsKnown && elementIndex < maxElements) ||
2090 Entity.isVariableLengthArrayNew())
2091 CheckEmptyInitializable(
2093 IList->getEndLoc());
2094 }
2095}
2096
2097bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2098 Expr *InitExpr,
2099 FieldDecl *Field,
2100 bool TopLevelObject) {
2101 // Handle GNU flexible array initializers.
2102 unsigned FlexArrayDiag;
2103 if (isa<InitListExpr>(InitExpr) &&
2104 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2105 // Empty flexible array init always allowed as an extension
2106 FlexArrayDiag = diag::ext_flexible_array_init;
2107 } else if (!TopLevelObject) {
2108 // Disallow flexible array init on non-top-level object
2109 FlexArrayDiag = diag::err_flexible_array_init;
2110 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2111 // Disallow flexible array init on anything which is not a variable.
2112 FlexArrayDiag = diag::err_flexible_array_init;
2113 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2114 // Disallow flexible array init on local variables.
2115 FlexArrayDiag = diag::err_flexible_array_init;
2116 } else {
2117 // Allow other cases.
2118 FlexArrayDiag = diag::ext_flexible_array_init;
2119 }
2120
2121 if (!VerifyOnly) {
2122 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2123 << InitExpr->getBeginLoc();
2124 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2125 << Field;
2126 }
2127
2128 return FlexArrayDiag != diag::ext_flexible_array_init;
2129}
2130
2131void InitListChecker::CheckStructUnionTypes(
2132 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2134 bool SubobjectIsDesignatorContext, unsigned &Index,
2135 InitListExpr *StructuredList, unsigned &StructuredIndex,
2136 bool TopLevelObject) {
2137 const RecordDecl *RD = getRecordDecl(DeclType);
2138
2139 // If the record is invalid, some of it's members are invalid. To avoid
2140 // confusion, we forgo checking the initializer for the entire record.
2141 if (RD->isInvalidDecl()) {
2142 // Assume it was supposed to consume a single initializer.
2143 ++Index;
2144 hadError = true;
2145 return;
2146 }
2147
2148 if (RD->isUnion() && IList->getNumInits() == 0) {
2149 if (!VerifyOnly)
2150 for (FieldDecl *FD : RD->fields()) {
2151 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2152 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2153 hadError = true;
2154 return;
2155 }
2156 }
2157
2158 // If there's a default initializer, use it.
2159 if (isa<CXXRecordDecl>(RD) &&
2160 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2161 if (!StructuredList)
2162 return;
2163 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2164 Field != FieldEnd; ++Field) {
2165 if (Field->hasInClassInitializer()) {
2166 StructuredList->setInitializedFieldInUnion(*Field);
2167 // FIXME: Actually build a CXXDefaultInitExpr?
2168 return;
2169 }
2170 }
2171 }
2172
2173 // Value-initialize the first member of the union that isn't an unnamed
2174 // bitfield.
2175 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2176 Field != FieldEnd; ++Field) {
2177 if (!Field->isUnnamedBitfield()) {
2178 CheckEmptyInitializable(
2179 InitializedEntity::InitializeMember(*Field, &Entity),
2180 IList->getEndLoc());
2181 if (StructuredList)
2182 StructuredList->setInitializedFieldInUnion(*Field);
2183 break;
2184 }
2185 }
2186 return;
2187 }
2188
2189 bool InitializedSomething = false;
2190
2191 // If we have any base classes, they are initialized prior to the fields.
2192 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2193 auto &Base = *I;
2194 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2195
2196 // Designated inits always initialize fields, so if we see one, all
2197 // remaining base classes have no explicit initializer.
2198 if (Init && isa<DesignatedInitExpr>(Init))
2199 Init = nullptr;
2200
2201 // C++ [over.match.class.deduct]p1.6:
2202 // each non-trailing aggregate element that is a pack expansion is assumed
2203 // to correspond to no elements of the initializer list, and (1.7) a
2204 // trailing aggregate element that is a pack expansion is assumed to
2205 // correspond to all remaining elements of the initializer list (if any).
2206
2207 // C++ [over.match.class.deduct]p1.9:
2208 // ... except that additional parameter packs of the form P_j... are
2209 // inserted into the parameter list in their original aggregate element
2210 // position corresponding to each non-trailing aggregate element of
2211 // type P_j that was skipped because it was a parameter pack, and the
2212 // trailing sequence of parameters corresponding to a trailing
2213 // aggregate element that is a pack expansion (if any) is replaced
2214 // by a single parameter of the form T_n....
2215 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2216 AggrDeductionCandidateParamTypes->push_back(
2217 SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2218
2219 // Trailing pack expansion
2220 if (I + 1 == E && RD->field_empty()) {
2221 if (Index < IList->getNumInits())
2222 Index = IList->getNumInits();
2223 return;
2224 }
2225
2226 continue;
2227 }
2228
2229 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2231 SemaRef.Context, &Base, false, &Entity);
2232 if (Init) {
2233 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2234 StructuredList, StructuredIndex);
2235 InitializedSomething = true;
2236 } else {
2237 CheckEmptyInitializable(BaseEntity, InitLoc);
2238 }
2239
2240 if (!VerifyOnly)
2241 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2242 hadError = true;
2243 return;
2244 }
2245 }
2246
2247 // If structDecl is a forward declaration, this loop won't do
2248 // anything except look at designated initializers; That's okay,
2249 // because an error should get printed out elsewhere. It might be
2250 // worthwhile to skip over the rest of the initializer, though.
2251 RecordDecl::field_iterator FieldEnd = RD->field_end();
2252 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2253 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2254 });
2255 bool HasDesignatedInit = false;
2256
2257 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2258
2259 while (Index < IList->getNumInits()) {
2260 Expr *Init = IList->getInit(Index);
2261 SourceLocation InitLoc = Init->getBeginLoc();
2262
2263 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2264 // If we're not the subobject that matches up with the '{' for
2265 // the designator, we shouldn't be handling the
2266 // designator. Return immediately.
2267 if (!SubobjectIsDesignatorContext)
2268 return;
2269
2270 HasDesignatedInit = true;
2271
2272 // Handle this designated initializer. Field will be updated to
2273 // the next field that we'll be initializing.
2274 bool DesignatedInitFailed = CheckDesignatedInitializer(
2275 Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2276 StructuredList, StructuredIndex, true, TopLevelObject);
2277 if (DesignatedInitFailed)
2278 hadError = true;
2279
2280 // Find the field named by the designated initializer.
2281 DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2282 if (!VerifyOnly && D->isFieldDesignator()) {
2283 FieldDecl *F = D->getFieldDecl();
2284 InitializedFields.insert(F);
2285 if (!DesignatedInitFailed) {
2286 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2287 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2288 hadError = true;
2289 return;
2290 }
2291 }
2292 }
2293
2294 InitializedSomething = true;
2295 continue;
2296 }
2297
2298 // Check if this is an initializer of forms:
2299 //
2300 // struct foo f = {};
2301 // struct foo g = {0};
2302 //
2303 // These are okay for randomized structures. [C99 6.7.8p19]
2304 //
2305 // Also, if there is only one element in the structure, we allow something
2306 // like this, because it's really not randomized in the traditional sense.
2307 //
2308 // struct foo h = {bar};
2309 auto IsZeroInitializer = [&](const Expr *I) {
2310 if (IList->getNumInits() == 1) {
2311 if (NumRecordDecls == 1)
2312 return true;
2313 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2314 return IL->getValue().isZero();
2315 }
2316 return false;
2317 };
2318
2319 // Don't allow non-designated initializers on randomized structures.
2320 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2321 if (!VerifyOnly)
2322 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2323 hadError = true;
2324 break;
2325 }
2326
2327 if (Field == FieldEnd) {
2328 // We've run out of fields. We're done.
2329 break;
2330 }
2331
2332 // We've already initialized a member of a union. We're done.
2333 if (InitializedSomething && RD->isUnion())
2334 break;
2335
2336 // If we've hit the flexible array member at the end, we're done.
2337 if (Field->getType()->isIncompleteArrayType())
2338 break;
2339
2340 if (Field->isUnnamedBitfield()) {
2341 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2342 ++Field;
2343 continue;
2344 }
2345
2346 // Make sure we can use this declaration.
2347 bool InvalidUse;
2348 if (VerifyOnly)
2349 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2350 else
2351 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2352 *Field, IList->getInit(Index)->getBeginLoc());
2353 if (InvalidUse) {
2354 ++Index;
2355 ++Field;
2356 hadError = true;
2357 continue;
2358 }
2359
2360 if (!VerifyOnly) {
2361 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2362 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2363 hadError = true;
2364 return;
2365 }
2366 }
2367
2368 InitializedEntity MemberEntity =
2369 InitializedEntity::InitializeMember(*Field, &Entity);
2370 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2371 StructuredList, StructuredIndex);
2372 InitializedSomething = true;
2373 InitializedFields.insert(*Field);
2374
2375 if (RD->isUnion() && StructuredList) {
2376 // Initialize the first field within the union.
2377 StructuredList->setInitializedFieldInUnion(*Field);
2378 }
2379
2380 ++Field;
2381 }
2382
2383 // Emit warnings for missing struct field initializers.
2384 // This check is disabled for designated initializers in C.
2385 // This matches gcc behaviour.
2386 bool IsCDesignatedInitializer =
2387 HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2388 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2389 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
2390 !IsCDesignatedInitializer) {
2391 // It is possible we have one or more unnamed bitfields remaining.
2392 // Find first (if any) named field and emit warning.
2393 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2394 : Field,
2395 end = RD->field_end();
2396 it != end; ++it) {
2397 if (HasDesignatedInit && InitializedFields.count(*it))
2398 continue;
2399
2400 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer() &&
2401 !it->getType()->isIncompleteArrayType()) {
2402 auto Diag = HasDesignatedInit
2403 ? diag::warn_missing_designated_field_initializers
2404 : diag::warn_missing_field_initializers;
2405 SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;
2406 break;
2407 }
2408 }
2409 }
2410
2411 // Check that any remaining fields can be value-initialized if we're not
2412 // building a structured list. (If we are, we'll check this later.)
2413 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2414 !Field->getType()->isIncompleteArrayType()) {
2415 for (; Field != FieldEnd && !hadError; ++Field) {
2416 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
2417 CheckEmptyInitializable(
2418 InitializedEntity::InitializeMember(*Field, &Entity),
2419 IList->getEndLoc());
2420 }
2421 }
2422
2423 // Check that the types of the remaining fields have accessible destructors.
2424 if (!VerifyOnly) {
2425 // If the initializer expression has a designated initializer, check the
2426 // elements for which a designated initializer is not provided too.
2427 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2428 : Field;
2429 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2430 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2431 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2432 hadError = true;
2433 return;
2434 }
2435 }
2436 }
2437
2438 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2439 Index >= IList->getNumInits())
2440 return;
2441
2442 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2443 TopLevelObject)) {
2444 hadError = true;
2445 ++Index;
2446 return;
2447 }
2448
2449 InitializedEntity MemberEntity =
2450 InitializedEntity::InitializeMember(*Field, &Entity);
2451
2452 if (isa<InitListExpr>(IList->getInit(Index)) ||
2453 AggrDeductionCandidateParamTypes)
2454 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2455 StructuredList, StructuredIndex);
2456 else
2457 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2458 StructuredList, StructuredIndex);
2459}
2460
2461/// Expand a field designator that refers to a member of an
2462/// anonymous struct or union into a series of field designators that
2463/// refers to the field within the appropriate subobject.
2464///
2466 DesignatedInitExpr *DIE,
2467 unsigned DesigIdx,
2468 IndirectFieldDecl *IndirectField) {
2470
2471 // Build the replacement designators.
2472 SmallVector<Designator, 4> Replacements;
2473 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2474 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2475 if (PI + 1 == PE)
2476 Replacements.push_back(Designator::CreateFieldDesignator(
2477 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2478 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2479 else
2480 Replacements.push_back(Designator::CreateFieldDesignator(
2481 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2482 assert(isa<FieldDecl>(*PI));
2483 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2484 }
2485
2486 // Expand the current designator into the set of replacement
2487 // designators, so we have a full subobject path down to where the
2488 // member of the anonymous struct/union is actually stored.
2489 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2490 &Replacements[0] + Replacements.size());
2491}
2492
2494 DesignatedInitExpr *DIE) {
2495 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2496 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2497 for (unsigned I = 0; I < NumIndexExprs; ++I)
2498 IndexExprs[I] = DIE->getSubExpr(I + 1);
2499 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2500 IndexExprs,
2501 DIE->getEqualOrColonLoc(),
2502 DIE->usesGNUSyntax(), DIE->getInit());
2503}
2504
2505namespace {
2506
2507// Callback to only accept typo corrections that are for field members of
2508// the given struct or union.
2509class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2510 public:
2511 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2512 : Record(RD) {}
2513
2514 bool ValidateCandidate(const TypoCorrection &candidate) override {
2515 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2516 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2517 }
2518
2519 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2520 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2521 }
2522
2523 private:
2524 const RecordDecl *Record;
2525};
2526
2527} // end anonymous namespace
2528
2529/// Check the well-formedness of a C99 designated initializer.
2530///
2531/// Determines whether the designated initializer @p DIE, which
2532/// resides at the given @p Index within the initializer list @p
2533/// IList, is well-formed for a current object of type @p DeclType
2534/// (C99 6.7.8). The actual subobject that this designator refers to
2535/// within the current subobject is returned in either
2536/// @p NextField or @p NextElementIndex (whichever is appropriate).
2537///
2538/// @param IList The initializer list in which this designated
2539/// initializer occurs.
2540///
2541/// @param DIE The designated initializer expression.
2542///
2543/// @param DesigIdx The index of the current designator.
2544///
2545/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2546/// into which the designation in @p DIE should refer.
2547///
2548/// @param NextField If non-NULL and the first designator in @p DIE is
2549/// a field, this will be set to the field declaration corresponding
2550/// to the field named by the designator. On input, this is expected to be
2551/// the next field that would be initialized in the absence of designation,
2552/// if the complete object being initialized is a struct.
2553///
2554/// @param NextElementIndex If non-NULL and the first designator in @p
2555/// DIE is an array designator or GNU array-range designator, this
2556/// will be set to the last index initialized by this designator.
2557///
2558/// @param Index Index into @p IList where the designated initializer
2559/// @p DIE occurs.
2560///
2561/// @param StructuredList The initializer list expression that
2562/// describes all of the subobject initializers in the order they'll
2563/// actually be initialized.
2564///
2565/// @returns true if there was an error, false otherwise.
2566bool
2567InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2568 InitListExpr *IList,
2569 DesignatedInitExpr *DIE,
2570 unsigned DesigIdx,
2571 QualType &CurrentObjectType,
2572 RecordDecl::field_iterator *NextField,
2573 llvm::APSInt *NextElementIndex,
2574 unsigned &Index,
2575 InitListExpr *StructuredList,
2576 unsigned &StructuredIndex,
2577 bool FinishSubobjectInit,
2578 bool TopLevelObject) {
2579 if (DesigIdx == DIE->size()) {
2580 // C++20 designated initialization can result in direct-list-initialization
2581 // of the designated subobject. This is the only way that we can end up
2582 // performing direct initialization as part of aggregate initialization, so
2583 // it needs special handling.
2584 if (DIE->isDirectInit()) {
2585 Expr *Init = DIE->getInit();
2586 assert(isa<InitListExpr>(Init) &&
2587 "designator result in direct non-list initialization?");
2589 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2590 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2591 /*TopLevelOfInitList*/ true);
2592 if (StructuredList) {
2593 ExprResult Result = VerifyOnly
2594 ? getDummyInit()
2595 : Seq.Perform(SemaRef, Entity, Kind, Init);
2596 UpdateStructuredListElement(StructuredList, StructuredIndex,
2597 Result.get());
2598 }
2599 ++Index;
2600 if (AggrDeductionCandidateParamTypes)
2601 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2602 return !Seq;
2603 }
2604
2605 // Check the actual initialization for the designated object type.
2606 bool prevHadError = hadError;
2607
2608 // Temporarily remove the designator expression from the
2609 // initializer list that the child calls see, so that we don't try
2610 // to re-process the designator.
2611 unsigned OldIndex = Index;
2612 IList->setInit(OldIndex, DIE->getInit());
2613
2614 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2615 StructuredIndex, /*DirectlyDesignated=*/true);
2616
2617 // Restore the designated initializer expression in the syntactic
2618 // form of the initializer list.
2619 if (IList->getInit(OldIndex) != DIE->getInit())
2620 DIE->setInit(IList->getInit(OldIndex));
2621 IList->setInit(OldIndex, DIE);
2622
2623 return hadError && !prevHadError;
2624 }
2625
2627 bool IsFirstDesignator = (DesigIdx == 0);
2628 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2629 // Determine the structural initializer list that corresponds to the
2630 // current subobject.
2631 if (IsFirstDesignator)
2632 StructuredList = FullyStructuredList;
2633 else {
2634 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2635 StructuredList->getInit(StructuredIndex) : nullptr;
2636 if (!ExistingInit && StructuredList->hasArrayFiller())
2637 ExistingInit = StructuredList->getArrayFiller();
2638
2639 if (!ExistingInit)
2640 StructuredList = getStructuredSubobjectInit(
2641 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2642 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2643 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2644 StructuredList = Result;
2645 else {
2646 // We are creating an initializer list that initializes the
2647 // subobjects of the current object, but there was already an
2648 // initialization that completely initialized the current
2649 // subobject, e.g., by a compound literal:
2650 //
2651 // struct X { int a, b; };
2652 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2653 //
2654 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2655 // designated initializer re-initializes only its current object
2656 // subobject [0].b.
2657 diagnoseInitOverride(ExistingInit,
2658 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2659 /*UnionOverride=*/false,
2660 /*FullyOverwritten=*/false);
2661
2662 if (!VerifyOnly) {
2664 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2665 StructuredList = E->getUpdater();
2666 else {
2667 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2669 ExistingInit, DIE->getEndLoc());
2670 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2671 StructuredList = DIUE->getUpdater();
2672 }
2673 } else {
2674 // We don't need to track the structured representation of a
2675 // designated init update of an already-fully-initialized object in
2676 // verify-only mode. The only reason we would need the structure is
2677 // to determine where the uninitialized "holes" are, and in this
2678 // case, we know there aren't any and we can't introduce any.
2679 StructuredList = nullptr;
2680 }
2681 }
2682 }
2683 }
2684
2685 if (D->isFieldDesignator()) {
2686 // C99 6.7.8p7:
2687 //
2688 // If a designator has the form
2689 //
2690 // . identifier
2691 //
2692 // then the current object (defined below) shall have
2693 // structure or union type and the identifier shall be the
2694 // name of a member of that type.
2695 RecordDecl *RD = getRecordDecl(CurrentObjectType);
2696 if (!RD) {
2697 SourceLocation Loc = D->getDotLoc();
2698 if (Loc.isInvalid())
2699 Loc = D->getFieldLoc();
2700 if (!VerifyOnly)
2701 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2702 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2703 ++Index;
2704 return true;
2705 }
2706
2707 FieldDecl *KnownField = D->getFieldDecl();
2708 if (!KnownField) {
2709 const IdentifierInfo *FieldName = D->getFieldName();
2710 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2711 if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2712 KnownField = FD;
2713 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2714 // In verify mode, don't modify the original.
2715 if (VerifyOnly)
2716 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2717 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2718 D = DIE->getDesignator(DesigIdx);
2719 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2720 }
2721 if (!KnownField) {
2722 if (VerifyOnly) {
2723 ++Index;
2724 return true; // No typo correction when just trying this out.
2725 }
2726
2727 // We found a placeholder variable
2728 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2729 FieldName)) {
2730 ++Index;
2731 return true;
2732 }
2733 // Name lookup found something, but it wasn't a field.
2734 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2735 !Lookup.empty()) {
2736 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2737 << FieldName;
2738 SemaRef.Diag(Lookup.front()->getLocation(),
2739 diag::note_field_designator_found);
2740 ++Index;
2741 return true;
2742 }
2743
2744 // Name lookup didn't find anything.
2745 // Determine whether this was a typo for another field name.
2746 FieldInitializerValidatorCCC CCC(RD);
2747 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2748 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2749 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2751 SemaRef.diagnoseTypo(
2752 Corrected,
2753 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2754 << FieldName << CurrentObjectType);
2755 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2756 hadError = true;
2757 } else {
2758 // Typo correction didn't find anything.
2759 SourceLocation Loc = D->getFieldLoc();
2760
2761 // The loc can be invalid with a "null" designator (i.e. an anonymous
2762 // union/struct). Do our best to approximate the location.
2763 if (Loc.isInvalid())
2764 Loc = IList->getBeginLoc();
2765
2766 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
2767 << FieldName << CurrentObjectType << DIE->getSourceRange();
2768 ++Index;
2769 return true;
2770 }
2771 }
2772 }
2773
2774 unsigned NumBases = 0;
2775 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2776 NumBases = CXXRD->getNumBases();
2777
2778 unsigned FieldIndex = NumBases;
2779
2780 for (auto *FI : RD->fields()) {
2781 if (FI->isUnnamedBitfield())
2782 continue;
2783 if (declaresSameEntity(KnownField, FI)) {
2784 KnownField = FI;
2785 break;
2786 }
2787 ++FieldIndex;
2788 }
2789
2792
2793 // All of the fields of a union are located at the same place in
2794 // the initializer list.
2795 if (RD->isUnion()) {
2796 FieldIndex = 0;
2797 if (StructuredList) {
2798 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2799 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2800 assert(StructuredList->getNumInits() == 1
2801 && "A union should never have more than one initializer!");
2802
2803 Expr *ExistingInit = StructuredList->getInit(0);
2804 if (ExistingInit) {
2805 // We're about to throw away an initializer, emit warning.
2806 diagnoseInitOverride(
2807 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2808 /*UnionOverride=*/true,
2809 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
2810 : true);
2811 }
2812
2813 // remove existing initializer
2814 StructuredList->resizeInits(SemaRef.Context, 0);
2815 StructuredList->setInitializedFieldInUnion(nullptr);
2816 }
2817
2818 StructuredList->setInitializedFieldInUnion(*Field);
2819 }
2820 }
2821
2822 // Make sure we can use this declaration.
2823 bool InvalidUse;
2824 if (VerifyOnly)
2825 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2826 else
2827 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2828 if (InvalidUse) {
2829 ++Index;
2830 return true;
2831 }
2832
2833 // C++20 [dcl.init.list]p3:
2834 // The ordered identifiers in the designators of the designated-
2835 // initializer-list shall form a subsequence of the ordered identifiers
2836 // in the direct non-static data members of T.
2837 //
2838 // Note that this is not a condition on forming the aggregate
2839 // initialization, only on actually performing initialization,
2840 // so it is not checked in VerifyOnly mode.
2841 //
2842 // FIXME: This is the only reordering diagnostic we produce, and it only
2843 // catches cases where we have a top-level field designator that jumps
2844 // backwards. This is the only such case that is reachable in an
2845 // otherwise-valid C++20 program, so is the only case that's required for
2846 // conformance, but for consistency, we should diagnose all the other
2847 // cases where a designator takes us backwards too.
2848 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
2849 NextField &&
2850 (*NextField == RD->field_end() ||
2851 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
2852 // Find the field that we just initialized.
2853 FieldDecl *PrevField = nullptr;
2854 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
2855 if (FI->isUnnamedBitfield())
2856 continue;
2857 if (*NextField != RD->field_end() &&
2858 declaresSameEntity(*FI, **NextField))
2859 break;
2860 PrevField = *FI;
2861 }
2862
2863 if (PrevField &&
2864 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2865 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2866 diag::ext_designated_init_reordered)
2867 << KnownField << PrevField << DIE->getSourceRange();
2868
2869 unsigned OldIndex = StructuredIndex - 1;
2870 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
2871 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
2872 SemaRef.Diag(PrevInit->getBeginLoc(),
2873 diag::note_previous_field_init)
2874 << PrevField << PrevInit->getSourceRange();
2875 }
2876 }
2877 }
2878 }
2879
2880
2881 // Update the designator with the field declaration.
2882 if (!VerifyOnly)
2883 D->setFieldDecl(*Field);
2884
2885 // Make sure that our non-designated initializer list has space
2886 // for a subobject corresponding to this field.
2887 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
2888 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2889
2890 // This designator names a flexible array member.
2891 if (Field->getType()->isIncompleteArrayType()) {
2892 bool Invalid = false;
2893 if ((DesigIdx + 1) != DIE->size()) {
2894 // We can't designate an object within the flexible array
2895 // member (because GCC doesn't allow it).
2896 if (!VerifyOnly) {
2898 = DIE->getDesignator(DesigIdx + 1);
2899 SemaRef.Diag(NextD->getBeginLoc(),
2900 diag::err_designator_into_flexible_array_member)
2901 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2902 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2903 << *Field;
2904 }
2905 Invalid = true;
2906 }
2907
2908 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2909 !isa<StringLiteral>(DIE->getInit())) {
2910 // The initializer is not an initializer list.
2911 if (!VerifyOnly) {
2912 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2913 diag::err_flexible_array_init_needs_braces)
2914 << DIE->getInit()->getSourceRange();
2915 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2916 << *Field;
2917 }
2918 Invalid = true;
2919 }
2920
2921 // Check GNU flexible array initializer.
2922 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2923 TopLevelObject))
2924 Invalid = true;
2925
2926 if (Invalid) {
2927 ++Index;
2928 return true;
2929 }
2930
2931 // Initialize the array.
2932 bool prevHadError = hadError;
2933 unsigned newStructuredIndex = FieldIndex;
2934 unsigned OldIndex = Index;
2935 IList->setInit(Index, DIE->getInit());
2936
2937 InitializedEntity MemberEntity =
2938 InitializedEntity::InitializeMember(*Field, &Entity);
2939 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2940 StructuredList, newStructuredIndex);
2941
2942 IList->setInit(OldIndex, DIE);
2943 if (hadError && !prevHadError) {
2944 ++Field;
2945 ++FieldIndex;
2946 if (NextField)
2947 *NextField = Field;
2948 StructuredIndex = FieldIndex;
2949 return true;
2950 }
2951 } else {
2952 // Recurse to check later designated subobjects.
2953 QualType FieldType = Field->getType();
2954 unsigned newStructuredIndex = FieldIndex;
2955
2956 InitializedEntity MemberEntity =
2957 InitializedEntity::InitializeMember(*Field, &Entity);
2958 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2959 FieldType, nullptr, nullptr, Index,
2960 StructuredList, newStructuredIndex,
2961 FinishSubobjectInit, false))
2962 return true;
2963 }
2964
2965 // Find the position of the next field to be initialized in this
2966 // subobject.
2967 ++Field;
2968 ++FieldIndex;
2969
2970 // If this the first designator, our caller will continue checking
2971 // the rest of this struct/class/union subobject.
2972 if (IsFirstDesignator) {
2973 if (Field != RD->field_end() && Field->isUnnamedBitfield())
2974 ++Field;
2975
2976 if (NextField)
2977 *NextField = Field;
2978
2979 StructuredIndex = FieldIndex;
2980 return false;
2981 }
2982
2983 if (!FinishSubobjectInit)
2984 return false;
2985
2986 // We've already initialized something in the union; we're done.
2987 if (RD->isUnion())
2988 return hadError;
2989
2990 // Check the remaining fields within this class/struct/union subobject.
2991 bool prevHadError = hadError;
2992
2993 auto NoBases =
2996 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2997 false, Index, StructuredList, FieldIndex);
2998 return hadError && !prevHadError;
2999 }
3000
3001 // C99 6.7.8p6:
3002 //
3003 // If a designator has the form
3004 //
3005 // [ constant-expression ]
3006 //
3007 // then the current object (defined below) shall have array
3008 // type and the expression shall be an integer constant
3009 // expression. If the array is of unknown size, any
3010 // nonnegative value is valid.
3011 //
3012 // Additionally, cope with the GNU extension that permits
3013 // designators of the form
3014 //
3015 // [ constant-expression ... constant-expression ]
3016 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
3017 if (!AT) {
3018 if (!VerifyOnly)
3019 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3020 << CurrentObjectType;
3021 ++Index;
3022 return true;
3023 }
3024
3025 Expr *IndexExpr = nullptr;
3026 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3027 if (D->isArrayDesignator()) {
3028 IndexExpr = DIE->getArrayIndex(*D);
3029 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3030 DesignatedEndIndex = DesignatedStartIndex;
3031 } else {
3032 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3033
3034 DesignatedStartIndex =
3036 DesignatedEndIndex =
3038 IndexExpr = DIE->getArrayRangeEnd(*D);
3039
3040 // Codegen can't handle evaluating array range designators that have side
3041 // effects, because we replicate the AST value for each initialized element.
3042 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3043 // elements with something that has a side effect, so codegen can emit an
3044 // "error unsupported" error instead of miscompiling the app.
3045 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3046 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3047 FullyStructuredList->sawArrayRangeDesignator();
3048 }
3049
3050 if (isa<ConstantArrayType>(AT)) {
3051 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3052 DesignatedStartIndex
3053 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3054 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3055 DesignatedEndIndex
3056 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3057 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3058 if (DesignatedEndIndex >= MaxElements) {
3059 if (!VerifyOnly)
3060 SemaRef.Diag(IndexExpr->getBeginLoc(),
3061 diag::err_array_designator_too_large)
3062 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3063 << IndexExpr->getSourceRange();
3064 ++Index;
3065 return true;
3066 }
3067 } else {
3068 unsigned DesignatedIndexBitWidth =
3070 DesignatedStartIndex =
3071 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3072 DesignatedEndIndex =
3073 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3074 DesignatedStartIndex.setIsUnsigned(true);
3075 DesignatedEndIndex.setIsUnsigned(true);
3076 }
3077
3078 bool IsStringLiteralInitUpdate =
3079 StructuredList && StructuredList->isStringLiteralInit();
3080 if (IsStringLiteralInitUpdate && VerifyOnly) {
3081 // We're just verifying an update to a string literal init. We don't need
3082 // to split the string up into individual characters to do that.
3083 StructuredList = nullptr;
3084 } else if (IsStringLiteralInitUpdate) {
3085 // We're modifying a string literal init; we have to decompose the string
3086 // so we can modify the individual characters.
3087 ASTContext &Context = SemaRef.Context;
3088 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3089
3090 // Compute the character type
3091 QualType CharTy = AT->getElementType();
3092
3093 // Compute the type of the integer literals.
3094 QualType PromotedCharTy = CharTy;
3095 if (Context.isPromotableIntegerType(CharTy))
3096 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3097 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3098
3099 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3100 // Get the length of the string.
3101 uint64_t StrLen = SL->getLength();
3102 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3103 StrLen = cast<ConstantArrayType>(AT)->getZExtSize();
3104 StructuredList->resizeInits(Context, StrLen);
3105
3106 // Build a literal for each character in the string, and put them into
3107 // the init list.
3108 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3109 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3110 Expr *Init = new (Context) IntegerLiteral(
3111 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3112 if (CharTy != PromotedCharTy)
3113 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3114 Init, nullptr, VK_PRValue,
3116 StructuredList->updateInit(Context, i, Init);
3117 }
3118 } else {
3119 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3120 std::string Str;
3121 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3122
3123 // Get the length of the string.
3124 uint64_t StrLen = Str.size();
3125 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3126 StrLen = cast<ConstantArrayType>(AT)->getZExtSize();
3127 StructuredList->resizeInits(Context, StrLen);
3128
3129 // Build a literal for each character in the string, and put them into
3130 // the init list.
3131 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3132 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3133 Expr *Init = new (Context) IntegerLiteral(
3134 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3135 if (CharTy != PromotedCharTy)
3136 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3137 Init, nullptr, VK_PRValue,
3139 StructuredList->updateInit(Context, i, Init);
3140 }
3141 }
3142 }
3143
3144 // Make sure that our non-designated initializer list has space
3145 // for a subobject corresponding to this array element.
3146 if (StructuredList &&
3147 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3148 StructuredList->resizeInits(SemaRef.Context,
3149 DesignatedEndIndex.getZExtValue() + 1);
3150
3151 // Repeatedly perform subobject initializations in the range
3152 // [DesignatedStartIndex, DesignatedEndIndex].
3153
3154 // Move to the next designator
3155 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3156 unsigned OldIndex = Index;
3157
3158 InitializedEntity ElementEntity =
3160
3161 while (DesignatedStartIndex <= DesignatedEndIndex) {
3162 // Recurse to check later designated subobjects.
3163 QualType ElementType = AT->getElementType();
3164 Index = OldIndex;
3165
3166 ElementEntity.setElementIndex(ElementIndex);
3167 if (CheckDesignatedInitializer(
3168 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3169 nullptr, Index, StructuredList, ElementIndex,
3170 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3171 false))
3172 return true;
3173
3174 // Move to the next index in the array that we'll be initializing.
3175 ++DesignatedStartIndex;
3176 ElementIndex = DesignatedStartIndex.getZExtValue();
3177 }
3178
3179 // If this the first designator, our caller will continue checking
3180 // the rest of this array subobject.
3181 if (IsFirstDesignator) {
3182 if (NextElementIndex)
3183 *NextElementIndex = DesignatedStartIndex;
3184 StructuredIndex = ElementIndex;
3185 return false;
3186 }
3187
3188 if (!FinishSubobjectInit)
3189 return false;
3190
3191 // Check the remaining elements within this array subobject.
3192 bool prevHadError = hadError;
3193 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3194 /*SubobjectIsDesignatorContext=*/false, Index,
3195 StructuredList, ElementIndex);
3196 return hadError && !prevHadError;
3197}
3198
3199// Get the structured initializer list for a subobject of type
3200// @p CurrentObjectType.
3202InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3203 QualType CurrentObjectType,
3204 InitListExpr *StructuredList,
3205 unsigned StructuredIndex,
3206 SourceRange InitRange,
3207 bool IsFullyOverwritten) {
3208 if (!StructuredList)
3209 return nullptr;
3210
3211 Expr *ExistingInit = nullptr;
3212 if (StructuredIndex < StructuredList->getNumInits())
3213 ExistingInit = StructuredList->getInit(StructuredIndex);
3214
3215 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3216 // There might have already been initializers for subobjects of the current
3217 // object, but a subsequent initializer list will overwrite the entirety
3218 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3219 //
3220 // struct P { char x[6]; };
3221 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3222 //
3223 // The first designated initializer is ignored, and l.x is just "f".
3224 if (!IsFullyOverwritten)
3225 return Result;
3226
3227 if (ExistingInit) {
3228 // We are creating an initializer list that initializes the
3229 // subobjects of the current object, but there was already an
3230 // initialization that completely initialized the current
3231 // subobject:
3232 //
3233 // struct X { int a, b; };
3234 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3235 //
3236 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3237 // designated initializer overwrites the [0].b initializer
3238 // from the prior initialization.
3239 //
3240 // When the existing initializer is an expression rather than an
3241 // initializer list, we cannot decompose and update it in this way.
3242 // For example:
3243 //
3244 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3245 //
3246 // This case is handled by CheckDesignatedInitializer.
3247 diagnoseInitOverride(ExistingInit, InitRange);
3248 }
3249
3250 unsigned ExpectedNumInits = 0;
3251 if (Index < IList->getNumInits()) {
3252 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3253 ExpectedNumInits = Init->getNumInits();
3254 else
3255 ExpectedNumInits = IList->getNumInits() - Index;
3256 }
3257
3258 InitListExpr *Result =
3259 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3260
3261 // Link this new initializer list into the structured initializer
3262 // lists.
3263 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3264 return Result;
3265}
3266
3268InitListChecker::createInitListExpr(QualType CurrentObjectType,
3269 SourceRange InitRange,
3270 unsigned ExpectedNumInits) {
3271 InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3272 SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd());
3273
3274 QualType ResultType = CurrentObjectType;
3275 if (!ResultType->isArrayType())
3276 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3277 Result->setType(ResultType);
3278
3279 // Pre-allocate storage for the structured initializer list.
3280 unsigned NumElements = 0;
3281
3282 if (const ArrayType *AType
3283 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3284 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3285 NumElements = CAType->getZExtSize();
3286 // Simple heuristic so that we don't allocate a very large
3287 // initializer with many empty entries at the end.
3288 if (NumElements > ExpectedNumInits)
3289 NumElements = 0;
3290 }
3291 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3292 NumElements = VType->getNumElements();
3293 } else if (CurrentObjectType->isRecordType()) {
3294 NumElements = numStructUnionElements(CurrentObjectType);
3295 } else if (CurrentObjectType->isDependentType()) {
3296 NumElements = 1;
3297 }
3298
3299 Result->reserveInits(SemaRef.Context, NumElements);
3300
3301 return Result;
3302}
3303
3304/// Update the initializer at index @p StructuredIndex within the
3305/// structured initializer list to the value @p expr.
3306void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3307 unsigned &StructuredIndex,
3308 Expr *expr) {
3309 // No structured initializer list to update
3310 if (!StructuredList)
3311 return;
3312
3313 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3314 StructuredIndex, expr)) {
3315 // This initializer overwrites a previous initializer.
3316 // No need to diagnose when `expr` is nullptr because a more relevant
3317 // diagnostic has already been issued and this diagnostic is potentially
3318 // noise.
3319 if (expr)
3320 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3321 }
3322
3323 ++StructuredIndex;
3324}
3325
3326/// Determine whether we can perform aggregate initialization for the purposes
3327/// of overload resolution.
3329 const InitializedEntity &Entity, InitListExpr *From) {
3330 QualType Type = Entity.getType();
3331 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3332 /*TreatUnavailableAsInvalid=*/false,
3333 /*InOverloadResolution=*/true);
3334 return !Check.HadError();
3335}
3336
3337/// Check that the given Index expression is a valid array designator
3338/// value. This is essentially just a wrapper around
3339/// VerifyIntegerConstantExpression that also checks for negative values
3340/// and produces a reasonable diagnostic if there is a
3341/// failure. Returns the index expression, possibly with an implicit cast
3342/// added, on success. If everything went okay, Value will receive the
3343/// value of the constant expression.
3344static ExprResult
3345CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3346 SourceLocation Loc = Index->getBeginLoc();
3347
3348 // Make sure this is an integer constant expression.
3351 if (Result.isInvalid())
3352 return Result;
3353
3354 if (Value.isSigned() && Value.isNegative())
3355 return S.Diag(Loc, diag::err_array_designator_negative)
3356 << toString(Value, 10) << Index->getSourceRange();
3357
3358 Value.setIsUnsigned(true);
3359 return Result;
3360}
3361
3363 SourceLocation EqualOrColonLoc,
3364 bool GNUSyntax,
3365 ExprResult Init) {
3366 typedef DesignatedInitExpr::Designator ASTDesignator;
3367
3368 bool Invalid = false;
3370 SmallVector<Expr *, 32> InitExpressions;
3371
3372 // Build designators and check array designator expressions.
3373 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3374 const Designator &D = Desig.getDesignator(Idx);
3375
3376 if (D.isFieldDesignator()) {
3377 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3378 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3379 } else if (D.isArrayDesignator()) {
3380 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3381 llvm::APSInt IndexValue;
3382 if (!Index->isTypeDependent() && !Index->isValueDependent())
3383 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3384 if (!Index)
3385 Invalid = true;
3386 else {
3387 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3388 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3389 InitExpressions.push_back(Index);
3390 }
3391 } else if (D.isArrayRangeDesignator()) {
3392 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3393 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3394 llvm::APSInt StartValue;
3395 llvm::APSInt EndValue;
3396 bool StartDependent = StartIndex->isTypeDependent() ||
3397 StartIndex->isValueDependent();
3398 bool EndDependent = EndIndex->isTypeDependent() ||
3399 EndIndex->isValueDependent();
3400 if (!StartDependent)
3401 StartIndex =
3402 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3403 if (!EndDependent)
3404 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3405
3406 if (!StartIndex || !EndIndex)
3407 Invalid = true;
3408 else {
3409 // Make sure we're comparing values with the same bit width.
3410 if (StartDependent || EndDependent) {
3411 // Nothing to compute.
3412 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3413 EndValue = EndValue.extend(StartValue.getBitWidth());
3414 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3415 StartValue = StartValue.extend(EndValue.getBitWidth());
3416
3417 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3418 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3419 << toString(StartValue, 10) << toString(EndValue, 10)
3420 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3421 Invalid = true;
3422 } else {
3423 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3424 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3425 D.getRBracketLoc()));
3426 InitExpressions.push_back(StartIndex);
3427 InitExpressions.push_back(EndIndex);
3428 }
3429 }
3430 }
3431 }
3432
3433 if (Invalid || Init.isInvalid())
3434 return ExprError();
3435
3436 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3437 EqualOrColonLoc, GNUSyntax,
3438 Init.getAs<Expr>());
3439}
3440
3441//===----------------------------------------------------------------------===//
3442// Initialization entity
3443//===----------------------------------------------------------------------===//
3444
3445InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3447 : Parent(&Parent), Index(Index)
3448{
3449 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3450 Kind = EK_ArrayElement;
3451 Type = AT->getElementType();
3452 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3453 Kind = EK_VectorElement;
3454 Type = VT->getElementType();
3455 } else {
3456 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3457 assert(CT && "Unexpected type");
3458 Kind = EK_ComplexElement;
3459 Type = CT->getElementType();
3460 }
3461}
3462
3465 const CXXBaseSpecifier *Base,
3466 bool IsInheritedVirtualBase,
3467 const InitializedEntity *Parent) {
3469 Result.Kind = EK_Base;
3470 Result.Parent = Parent;
3471 Result.Base = {Base, IsInheritedVirtualBase};
3472 Result.Type = Base->getType();
3473 return Result;
3474}
3475
3477 switch (getKind()) {
3478 case EK_Parameter:
3480 ParmVarDecl *D = Parameter.getPointer();
3481 return (D ? D->getDeclName() : DeclarationName());
3482 }
3483
3484 case EK_Variable:
3485 case EK_Member:
3487 case EK_Binding:
3489 return Variable.VariableOrMember->getDeclName();
3490
3491 case EK_LambdaCapture:
3492 return DeclarationName(Capture.VarID);
3493
3494 case EK_Result:
3495 case EK_StmtExprResult:
3496 case EK_Exception:
3497 case EK_New:
3498 case EK_Temporary:
3499 case EK_Base:
3500 case EK_Delegating:
3501 case EK_ArrayElement:
3502 case EK_VectorElement:
3503 case EK_ComplexElement:
3504 case EK_BlockElement:
3507 case EK_RelatedResult:
3508 return DeclarationName();
3509 }
3510
3511 llvm_unreachable("Invalid EntityKind!");
3512}
3513
3515 switch (getKind()) {
3516 case EK_Variable:
3517 case EK_Member:
3519 case EK_Binding:
3521 return Variable.VariableOrMember;
3522
3523 case EK_Parameter:
3525 return Parameter.getPointer();
3526
3527 case EK_Result:
3528 case EK_StmtExprResult:
3529 case EK_Exception:
3530 case EK_New:
3531 case EK_Temporary:
3532 case EK_Base:
3533 case EK_Delegating:
3534 case EK_ArrayElement:
3535 case EK_VectorElement:
3536 case EK_ComplexElement:
3537 case EK_BlockElement:
3539 case EK_LambdaCapture:
3541 case EK_RelatedResult:
3542 return nullptr;
3543 }
3544
3545 llvm_unreachable("Invalid EntityKind!");
3546}
3547
3549 switch (getKind()) {
3550 case EK_Result:
3551 case EK_Exception:
3552 return LocAndNRVO.NRVO;
3553
3554 case EK_StmtExprResult:
3555 case EK_Variable:
3556 case EK_Parameter:
3559 case EK_Member:
3561 case EK_Binding:
3562 case EK_New:
3563 case EK_Temporary:
3565 case EK_Base:
3566 case EK_Delegating:
3567 case EK_ArrayElement:
3568 case EK_VectorElement:
3569 case EK_ComplexElement:
3570 case EK_BlockElement:
3572 case EK_LambdaCapture:
3573 case EK_RelatedResult:
3574 break;
3575 }
3576
3577 return false;
3578}
3579
3580unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3581 assert(getParent() != this);
3582 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3583 for (unsigned I = 0; I != Depth; ++I)
3584 OS << "`-";
3585
3586 switch (getKind()) {
3587 case EK_Variable: OS << "Variable"; break;
3588 case EK_Parameter: OS << "Parameter"; break;
3589 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3590 break;
3591 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3592 case EK_Result: OS << "Result"; break;
3593 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3594 case EK_Exception: OS << "Exception"; break;
3595 case EK_Member:
3597 OS << "Member";
3598 break;
3599 case EK_Binding: OS << "Binding"; break;
3600 case EK_New: OS << "New"; break;
3601 case EK_Temporary: OS << "Temporary"; break;
3602 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3603 case EK_RelatedResult: OS << "RelatedResult"; break;
3604 case EK_Base: OS << "Base"; break;
3605 case EK_Delegating: OS << "Delegating"; break;
3606 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3607 case EK_VectorElement: OS << "VectorElement " << Index; break;
3608 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3609 case EK_BlockElement: OS << "Block"; break;
3611 OS << "Block (lambda)";
3612 break;
3613 case EK_LambdaCapture:
3614 OS << "LambdaCapture ";
3615 OS << DeclarationName(Capture.VarID);
3616 break;
3617 }
3618
3619 if (auto *D = getDecl()) {
3620 OS << " ";
3621 D->printQualifiedName(OS);
3622 }
3623
3624 OS << " '" << getType() << "'\n";
3625
3626 return Depth + 1;
3627}
3628
3629LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3630 dumpImpl(llvm::errs());
3631}
3632
3633//===----------------------------------------------------------------------===//
3634// Initialization sequence
3635//===----------------------------------------------------------------------===//
3636
3638 switch (Kind) {
3643 case SK_BindReference:
3645 case SK_FinalCopy:
3647 case SK_UserConversion:
3654 case SK_UnwrapInitList:
3655 case SK_RewrapInitList:
3659 case SK_CAssignment:
3660 case SK_StringInit:
3662 case SK_ArrayLoopIndex:
3663 case SK_ArrayLoopInit:
3664 case SK_ArrayInit:
3665 case SK_GNUArrayInit:
3672 case SK_OCLSamplerInit:
3675 break;
3676
3679 delete ICS;
3680 }
3681}
3682
3684 // There can be some lvalue adjustments after the SK_BindReference step.
3685 for (const Step &S : llvm::reverse(Steps)) {
3686 if (S.Kind == SK_BindReference)
3687 return true;
3688 if (S.Kind == SK_BindReferenceToTemporary)
3689 return false;
3690 }
3691 return false;
3692}
3693
3695 if (!Failed())
3696 return false;
3697
3698 switch (getFailureKind()) {
3709 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3726 case FK_Incomplete:
3731 case FK_PlaceholderType:
3736 return false;
3737
3742 return FailedOverloadResult == OR_Ambiguous;
3743 }
3744
3745 llvm_unreachable("Invalid EntityKind!");
3746}
3747
3749 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3750}
3751
3752void
3753InitializationSequence
3754::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3755 DeclAccessPair Found,
3756 bool HadMultipleCandidates) {
3757 Step S;
3759 S.Type = Function->getType();
3760 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3761 S.Function.Function = Function;
3762 S.Function.FoundDecl = Found;
3763 Steps.push_back(S);
3764}
3765
3767 ExprValueKind VK) {
3768 Step S;
3769 switch (VK) {
3770 case VK_PRValue:
3772 break;
3773 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3774 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3775 }
3776 S.Type = BaseType;
3777 Steps.push_back(S);
3778}
3779
3781 bool BindingTemporary) {
3782 Step S;
3783 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3784 S.Type = T;
3785 Steps.push_back(S);
3786}
3787
3789 Step S;
3790 S.Kind = SK_FinalCopy;
3791 S.Type = T;
3792 Steps.push_back(S);
3793}
3794
3796 Step S;
3798 S.Type = T;
3799 Steps.push_back(S);
3800}
3801
3802void
3804 DeclAccessPair FoundDecl,
3805 QualType T,
3806 bool HadMultipleCandidates) {
3807 Step S;
3808 S.Kind = SK_UserConversion;
3809 S.Type = T;
3810 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3811 S.Function.Function = Function;
3812 S.Function.FoundDecl = FoundDecl;
3813 Steps.push_back(S);
3814}
3815
3817 ExprValueKind VK) {
3818 Step S;
3819 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
3820 switch (VK) {
3821 case VK_PRValue:
3823 break;
3824 case VK_XValue:
3826 break;
3827 case VK_LValue:
3829 break;
3830 }
3831 S.Type = Ty;
3832 Steps.push_back(S);
3833}
3834
3836 Step S;
3838 S.Type = Ty;
3839 Steps.push_back(S);
3840}
3841
3843 Step S;
3844 S.Kind = SK_AtomicConversion;
3845 S.Type = Ty;
3846 Steps.push_back(S);
3847}
3848
3851 bool TopLevelOfInitList) {
3852 Step S;
3853 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3855 S.Type = T;
3856 S.ICS = new ImplicitConversionSequence(ICS);
3857 Steps.push_back(S);
3858}
3859
3861 Step S;
3862 S.Kind = SK_ListInitialization;
3863 S.Type = T;
3864 Steps.push_back(S);
3865}
3866
3868 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3869 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3870 Step S;
3871 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3874 S.Type = T;
3875 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3876 S.Function.Function = Constructor;
3877 S.Function.FoundDecl = FoundDecl;
3878 Steps.push_back(S);
3879}
3880
3882 Step S;
3883 S.Kind = SK_ZeroInitialization;
3884 S.Type = T;
3885 Steps.push_back(S);
3886}
3887
3889 Step S;
3890 S.Kind = SK_CAssignment;
3891 S.Type = T;
3892 Steps.push_back(S);
3893}
3894
3896 Step S;
3897 S.Kind = SK_StringInit;
3898 S.Type = T;
3899 Steps.push_back(S);
3900}
3901
3903 Step S;
3904 S.Kind = SK_ObjCObjectConversion;
3905 S.Type = T;
3906 Steps.push_back(S);
3907}
3908
3910 Step S;
3911 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3912 S.Type = T;
3913 Steps.push_back(S);
3914}
3915
3917 Step S;
3918 S.Kind = SK_ArrayLoopIndex;
3919 S.Type = EltT;
3920 Steps.insert(Steps.begin(), S);
3921
3922 S.Kind = SK_ArrayLoopInit;
3923 S.Type = T;
3924 Steps.push_back(S);
3925}
3926
3928 Step S;
3930 S.Type = T;
3931 Steps.push_back(S);
3932}
3933
3935 bool shouldCopy) {
3936 Step s;
3937 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3939 s.Type = type;
3940 Steps.push_back(s);
3941}
3942
3944 Step S;
3945 S.Kind = SK_ProduceObjCObject;
3946 S.Type = T;
3947 Steps.push_back(S);
3948}
3949
3951 Step S;
3952 S.Kind = SK_StdInitializerList;
3953 S.Type = T;
3954 Steps.push_back(S);
3955}
3956
3958 Step S;
3959 S.Kind = SK_OCLSamplerInit;
3960 S.Type = T;
3961 Steps.push_back(S);
3962}
3963
3965 Step S;
3966 S.Kind = SK_OCLZeroOpaqueType;
3967 S.Type = T;
3968 Steps.push_back(S);
3969}
3970
3972 Step S;
3973 S.Kind = SK_ParenthesizedListInit;
3974 S.Type = T;
3975 Steps.push_back(S);
3976}
3977
3979 InitListExpr *Syntactic) {
3980 assert(Syntactic->getNumInits() == 1 &&
3981 "Can only rewrap trivial init lists.");
3982 Step S;
3983 S.Kind = SK_UnwrapInitList;
3984 S.Type = Syntactic->getInit(0)->getType();
3985 Steps.insert(Steps.begin(), S);
3986
3987 S.Kind = SK_RewrapInitList;
3988 S.Type = T;
3989 S.WrappingSyntacticList = Syntactic;
3990 Steps.push_back(S);
3991}
3992
3996 this->Failure = Failure;
3997 this->FailedOverloadResult = Result;
3998}
3999
4000//===----------------------------------------------------------------------===//
4001// Attempt initialization
4002//===----------------------------------------------------------------------===//
4003
4004/// Tries to add a zero initializer. Returns true if that worked.
4005static bool
4007 const InitializedEntity &Entity) {
4009 return false;
4010
4011 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
4012 if (VD->getInit() || VD->getEndLoc().isMacroID())
4013 return false;
4014
4015 QualType VariableTy = VD->getType().getCanonicalType();
4017 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
4018 if (!Init.empty()) {
4019 Sequence.AddZeroInitializationStep(Entity.getType());
4020 Sequence.SetZeroInitializationFixit(Init, Loc);
4021 return true;
4022 }
4023 return false;
4024}
4025
4027 InitializationSequence &Sequence,
4028 const InitializedEntity &Entity) {
4029 if (!S.getLangOpts().ObjCAutoRefCount) return;
4030
4031 /// When initializing a parameter, produce the value if it's marked
4032 /// __attribute__((ns_consumed)).
4033 if (Entity.isParameterKind()) {
4034 if (!Entity.isParameterConsumed())
4035 return;
4036
4037 assert(Entity.getType()->isObjCRetainableType() &&
4038 "consuming an object of unretainable type?");
4039 Sequence.AddProduceObjCObjectStep(Entity.getType());
4040
4041 /// When initializing a return value, if the return type is a
4042 /// retainable type, then returns need to immediately retain the
4043 /// object. If an autorelease is required, it will be done at the
4044 /// last instant.
4045 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4047 if (!Entity.getType()->isObjCRetainableType())
4048 return;
4049
4050 Sequence.AddProduceObjCObjectStep(Entity.getType());
4051 }
4052}
4053
4054static void TryListInitialization(Sema &S,
4055 const InitializedEntity &Entity,
4056 const InitializationKind &Kind,
4057 InitListExpr *InitList,
4058 InitializationSequence &Sequence,
4059 bool TreatUnavailableAsInvalid);
4060
4061/// When initializing from init list via constructor, handle
4062/// initialization of an object of type std::initializer_list<T>.
4063///
4064/// \return true if we have handled initialization of an object of type
4065/// std::initializer_list<T>, false otherwise.
4067 InitListExpr *List,
4068 QualType DestType,
4069 InitializationSequence &Sequence,
4070 bool TreatUnavailableAsInvalid) {
4071 QualType E;
4072 if (!S.isStdInitializerList(DestType, &E))
4073 return false;
4074
4075 if (!S.isCompleteType(List->getExprLoc(), E)) {
4076 Sequence.setIncompleteTypeFailure(E);
4077 return true;
4078 }
4079
4080 // Try initializing a temporary array from the init list.
4082 E.withConst(),
4083 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4084 List->getNumInits()),
4086 InitializedEntity HiddenArray =
4089 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4090 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4091 TreatUnavailableAsInvalid);
4092 if (Sequence)
4093 Sequence.AddStdInitializerListConstructionStep(DestType);
4094 return true;
4095}
4096
4097/// Determine if the constructor has the signature of a copy or move
4098/// constructor for the type T of the class in which it was found. That is,
4099/// determine if its first parameter is of type T or reference to (possibly
4100/// cv-qualified) T.
4102 const ConstructorInfo &Info) {
4103 if (Info.Constructor->getNumParams() == 0)
4104 return false;
4105
4106 QualType ParmT =
4108 QualType ClassT =
4109 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
4110
4111 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4112}
4113
4115 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4116 OverloadCandidateSet &CandidateSet, QualType DestType,
4118 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4119 bool IsListInit, bool RequireActualConstructor,
4120 bool SecondStepOfCopyInit = false) {
4122 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4123
4124 for (NamedDecl *D : Ctors) {
4125 auto Info = getConstructorInfo(D);
4126 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4127 continue;
4128
4129 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4130 continue;
4131
4132 // C++11 [over.best.ics]p4:
4133 // ... and the constructor or user-defined conversion function is a
4134 // candidate by
4135 // - 13.3.1.3, when the argument is the temporary in the second step
4136 // of a class copy-initialization, or
4137 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4138 // - the second phase of 13.3.1.7 when the initializer list has exactly
4139 // one element that is itself an initializer list, and the target is
4140 // the first parameter of a constructor of class X, and the conversion
4141 // is to X or reference to (possibly cv-qualified X),
4142 // user-defined conversion sequences are not considered.
4143 bool SuppressUserConversions =
4144 SecondStepOfCopyInit ||
4145 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4147
4148 if (Info.ConstructorTmpl)
4150 Info.ConstructorTmpl, Info.FoundDecl,
4151 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4152 /*PartialOverloading=*/false, AllowExplicit);
4153 else {
4154 // C++ [over.match.copy]p1:
4155 // - When initializing a temporary to be bound to the first parameter
4156 // of a constructor [for type T] that takes a reference to possibly
4157 // cv-qualified T as its first argument, called with a single
4158 // argument in the context of direct-initialization, explicit
4159 // conversion functions are also considered.
4160 // FIXME: What if a constructor template instantiates to such a signature?
4161 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4162 Args.size() == 1 &&
4164 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4165 CandidateSet, SuppressUserConversions,
4166 /*PartialOverloading=*/false, AllowExplicit,
4167 AllowExplicitConv);
4168 }
4169 }
4170
4171 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4172 //
4173 // When initializing an object of class type T by constructor
4174 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4175 // from a single expression of class type U, conversion functions of
4176 // U that convert to the non-reference type cv T are candidates.
4177 // Explicit conversion functions are only candidates during
4178 // direct-initialization.
4179 //
4180 // Note: SecondStepOfCopyInit is only ever true in this case when
4181 // evaluating whether to produce a C++98 compatibility warning.
4182 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4183 !RequireActualConstructor && !SecondStepOfCopyInit) {
4184 Expr *Initializer = Args[0];
4185 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4186 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4187 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4188 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4189 NamedDecl *D = *I;
4190 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4191 D = D->getUnderlyingDecl();
4192
4193 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4194 CXXConversionDecl *Conv;
4195 if (ConvTemplate)
4196 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4197 else
4198 Conv = cast<CXXConversionDecl>(D);
4199
4200 if (ConvTemplate)
4202 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4203 CandidateSet, AllowExplicit, AllowExplicit,
4204 /*AllowResultConversion*/ false);
4205 else
4206 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4207 DestType, CandidateSet, AllowExplicit,
4208 AllowExplicit,
4209 /*AllowResultConversion*/ false);
4210 }
4211 }
4212 }
4213
4214 // Perform overload resolution and return the result.
4215 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4216}
4217
4218/// Attempt initialization by constructor (C++ [dcl.init]), which
4219/// enumerates the constructors of the initialized entity and performs overload
4220/// resolution to select the best.
4221/// \param DestType The destination class type.
4222/// \param DestArrayType The destination type, which is either DestType or
4223/// a (possibly multidimensional) array of DestType.
4224/// \param IsListInit Is this list-initialization?
4225/// \param IsInitListCopy Is this non-list-initialization resulting from a
4226/// list-initialization from {x} where x is the same
4227/// type as the entity?
4229 const InitializedEntity &Entity,
4230 const InitializationKind &Kind,
4231 MultiExprArg Args, QualType DestType,
4232 QualType DestArrayType,
4233 InitializationSequence &Sequence,
4234 bool IsListInit = false,
4235 bool IsInitListCopy = false) {
4236 assert(((!IsListInit && !IsInitListCopy) ||
4237 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4238 "IsListInit/IsInitListCopy must come with a single initializer list "
4239 "argument.");
4240 InitListExpr *ILE =
4241 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4242 MultiExprArg UnwrappedArgs =
4243 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4244
4245 // The type we're constructing needs to be complete.
4246 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4247 Sequence.setIncompleteTypeFailure(DestType);
4248 return;
4249 }
4250
4251 bool RequireActualConstructor =
4252 !(Entity.getKind() != InitializedEntity::EK_Base &&
4254 Entity.getKind() !=
4256
4257 // C++17 [dcl.init]p17:
4258 // - If the initializer expression is a prvalue and the cv-unqualified
4259 // version of the source type is the same class as the class of the
4260 // destination, the initializer expression is used to initialize the
4261 // destination object.
4262 // Per DR (no number yet), this does not apply when initializing a base
4263 // class or delegating to another constructor from a mem-initializer.
4264 // ObjC++: Lambda captured by the block in the lambda to block conversion
4265 // should avoid copy elision.
4266 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4267 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4268 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4269 // Convert qualifications if necessary.
4270 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4271 if (ILE)
4272 Sequence.RewrapReferenceInitList(DestType, ILE);
4273 return;
4274 }
4275
4276 const RecordType *DestRecordType = DestType->getAs<RecordType>();
4277 assert(DestRecordType && "Constructor initialization requires record type");
4278 CXXRecordDecl *DestRecordDecl
4279 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4280
4281 // Build the candidate set directly in the initialization sequence
4282 // structure, so that it will persist if we fail.
4283 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4284
4285 // Determine whether we are allowed to call explicit constructors or
4286 // explicit conversion operators.
4287 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4288 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4289
4290 // - Otherwise, if T is a class type, constructors are considered. The
4291 // applicable constructors are enumerated, and the best one is chosen
4292 // through overload resolution.
4293 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4294
4297 bool AsInitializerList = false;
4298
4299 // C++11 [over.match.list]p1, per DR1467:
4300 // When objects of non-aggregate type T are list-initialized, such that
4301 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4302 // according to the rules in this section, overload resolution selects
4303 // the constructor in two phases:
4304 //
4305 // - Initially, the candidate functions are the initializer-list
4306 // constructors of the class T and the argument list consists of the
4307 // initializer list as a single argument.
4308 if (IsListInit) {
4309 AsInitializerList = true;
4310
4311 // If the initializer list has no elements and T has a default constructor,
4312 // the first phase is omitted.
4313 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4315 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4316 CopyInitialization, AllowExplicit,
4317 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4318 }
4319
4320 // C++11 [over.match.list]p1:
4321 // - If no viable initializer-list constructor is found, overload resolution
4322 // is performed again, where the candidate functions are all the
4323 // constructors of the class T and the argument list consists of the
4324 // elements of the initializer list.
4326 AsInitializerList = false;
4328 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4329 Best, CopyInitialization, AllowExplicit,
4330 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4331 }
4332 if (Result) {
4333 Sequence.SetOverloadFailure(
4336 Result);
4337
4338 if (Result != OR_Deleted)
4339 return;
4340 }
4341
4342 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4343
4344 // In C++17, ResolveConstructorOverload can select a conversion function
4345 // instead of a constructor.
4346 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4347 // Add the user-defined conversion step that calls the conversion function.
4348 QualType ConvType = CD->getConversionType();
4349 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4350 "should not have selected this conversion function");
4351 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4352 HadMultipleCandidates);
4353 if (!S.Context.hasSameType(ConvType, DestType))
4354 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4355 if (IsListInit)
4356 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4357 return;
4358 }
4359
4360 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4361 if (Result != OR_Deleted) {
4362 // C++11 [dcl.init]p6:
4363 // If a program calls for the default initialization of an object
4364 // of a const-qualified type T, T shall be a class type with a
4365 // user-provided default constructor.
4366 // C++ core issue 253 proposal:
4367 // If the implicit default constructor initializes all subobjects, no
4368 // initializer should be required.
4369 // The 253 proposal is for example needed to process libstdc++ headers
4370 // in 5.x.
4371 if (Kind.getKind() == InitializationKind::IK_Default &&
4372 Entity.getType().isConstQualified()) {
4373 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4374 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4376 return;
4377 }
4378 }
4379
4380 // C++11 [over.match.list]p1:
4381 // In copy-list-initialization, if an explicit constructor is chosen, the
4382 // initializer is ill-formed.
4383 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4385 return;
4386 }
4387 }
4388
4389 // [class.copy.elision]p3:
4390 // In some copy-initialization contexts, a two-stage overload resolution
4391 // is performed.
4392 // If the first overload resolution selects a deleted function, we also
4393 // need the initialization sequence to decide whether to perform the second
4394 // overload resolution.
4395 // For deleted functions in other contexts, there is no need to get the
4396 // initialization sequence.
4397 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4398 return;
4399
4400 // Add the constructor initialization step. Any cv-qualification conversion is
4401 // subsumed by the initialization.
4403 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4404 IsListInit | IsInitListCopy, AsInitializerList);
4405}
4406
4407static bool
4410 QualType &SourceType,
4411 QualType &UnqualifiedSourceType,
4412 QualType UnqualifiedTargetType,
4413 InitializationSequence &Sequence) {
4414 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4415 S.Context.OverloadTy) {
4416 DeclAccessPair Found;
4417 bool HadMultipleCandidates = false;
4418 if (FunctionDecl *Fn
4420 UnqualifiedTargetType,
4421 false, Found,
4422 &HadMultipleCandidates)) {
4423 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4424 HadMultipleCandidates);
4425 SourceType = Fn->getType();
4426 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4427 } else if (!UnqualifiedTargetType->isRecordType()) {
4429 return true;
4430 }
4431 }
4432 return false;
4433}
4434
4436 const InitializedEntity &Entity,
4437 const InitializationKind &Kind,
4439 QualType cv1T1, QualType T1,
4440 Qualifiers T1Quals,
4441 QualType cv2T2, QualType T2,
4442 Qualifiers T2Quals,
4443 InitializationSequence &Sequence,
4444 bool TopLevelOfInitList);
4445
4446static void TryValueInitialization(Sema &S,
4447 const InitializedEntity &Entity,
4448 const InitializationKind &Kind,
4449 InitializationSequence &Sequence,
4450 InitListExpr *InitList = nullptr);
4451
4452/// Attempt list initialization of a reference.
4454 const InitializedEntity &Entity,
4455 const InitializationKind &Kind,
4456 InitListExpr *InitList,
4457 InitializationSequence &Sequence,
4458 bool TreatUnavailableAsInvalid) {
4459 // First, catch C++03 where this isn't possible.
4460 if (!S.getLangOpts().CPlusPlus11) {
4462 return;
4463 }
4464 // Can't reference initialize a compound literal.
4467 return;
4468 }
4469
4470 QualType DestType = Entity.getType();
4471 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4472 Qualifiers T1Quals;
4473 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4474
4475 // Reference initialization via an initializer list works thus:
4476 // If the initializer list consists of a single element that is
4477 // reference-related to the referenced type, bind directly to that element
4478 // (possibly creating temporaries).
4479 // Otherwise, initialize a temporary with the initializer list and
4480 // bind to that.
4481 if (InitList->getNumInits() == 1) {
4482 Expr *Initializer = InitList->getInit(0);
4484 Qualifiers T2Quals;
4485 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4486
4487 // If this fails, creating a temporary wouldn't work either.
4489 T1, Sequence))
4490 return;
4491
4492 SourceLocation DeclLoc = Initializer->getBeginLoc();
4493 Sema::ReferenceCompareResult RefRelationship
4494 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4495 if (RefRelationship >= Sema::Ref_Related) {
4496 // Try to bind the reference here.
4497 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4498 T1Quals, cv2T2, T2, T2Quals, Sequence,
4499 /*TopLevelOfInitList=*/true);
4500 if (Sequence)
4501 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4502 return;
4503 }
4504
4505 // Update the initializer if we've resolved an overloaded function.
4506 if (Sequence.step_begin() != Sequence.step_end())
4507 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4508 }
4509 // Perform address space compatibility check.
4510 QualType cv1T1IgnoreAS = cv1T1;
4511 if (T1Quals.hasAddressSpace()) {
4512 Qualifiers T2Quals;
4513 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4514 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4515 Sequence.SetFailed(
4517 return;
4518 }
4519 // Ignore address space of reference type at this point and perform address
4520 // space conversion after the reference binding step.
4521 cv1T1IgnoreAS =
4523 }
4524 // Not reference-related. Create a temporary and bind to that.
4525 InitializedEntity TempEntity =
4527
4528 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4529 TreatUnavailableAsInvalid);
4530 if (Sequence) {
4531 if (DestType->isRValueReferenceType() ||
4532 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4533 if (S.getLangOpts().CPlusPlus20 &&
4534 isa<IncompleteArrayType>(T1->getUnqualifiedDesugaredType()) &&
4535 DestType->isRValueReferenceType()) {
4536 // C++20 [dcl.init.list]p3.10:
4537 // List-initialization of an object or reference of type T is defined as
4538 // follows:
4539 // ..., unless T is “reference to array of unknown bound of U”, in which
4540 // case the type of the prvalue is the type of x in the declaration U
4541 // x[] H, where H is the initializer list.
4543 }
4544 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4545 /*BindingTemporary=*/true);
4546 if (T1Quals.hasAddressSpace())
4548 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4549 } else
4550 Sequence.SetFailed(
4552 }
4553}
4554
4555/// Attempt list initialization (C++0x [dcl.init.list])
4557 const InitializedEntity &Entity,
4558 const InitializationKind &Kind,
4559 InitListExpr *InitList,
4560 InitializationSequence &Sequence,
4561 bool TreatUnavailableAsInvalid) {
4562 QualType DestType = Entity.getType();
4563
4564 // C++ doesn't allow scalar initialization with more than one argument.
4565 // But C99 complex numbers are scalars and it makes sense there.
4566 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4567 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4569 return;
4570 }
4571 if (DestType->isReferenceType()) {
4572 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4573 TreatUnavailableAsInvalid);
4574 return;
4575 }
4576
4577 if (DestType->isRecordType() &&
4578 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4579 Sequence.setIncompleteTypeFailure(DestType);
4580 return;
4581 }
4582
4583 // C++20 [dcl.init.list]p3:
4584 // - If the braced-init-list contains a designated-initializer-list, T shall
4585 // be an aggregate class. [...] Aggregate initialization is performed.
4586 //
4587 // We allow arrays here too in order to support array designators.
4588 //
4589 // FIXME: This check should precede the handling of reference initialization.
4590 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4591 // as a tentative DR resolution.
4592 bool IsDesignatedInit = InitList->hasDesignatedInit();
4593 if (!DestType->isAggregateType() && IsDesignatedInit) {
4594 Sequence.SetFailed(
4596 return;
4597 }
4598
4599 // C++11 [dcl.init.list]p3, per DR1467:
4600 // - If T is a class type and the initializer list has a single element of
4601 // type cv U, where U is T or a class derived from T, the object is
4602 // initialized from that element (by copy-initialization for
4603 // copy-list-initialization, or by direct-initialization for
4604 // direct-list-initialization).
4605 // - Otherwise, if T is a character array and the initializer list has a
4606 // single element that is an appropriately-typed string literal
4607 // (8.5.2 [dcl.init.string]), initialization is performed as described
4608 // in that section.
4609 // - Otherwise, if T is an aggregate, [...] (continue below).
4610 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
4611 !IsDesignatedInit) {
4612 if (DestType->isRecordType()) {
4613 QualType InitType = InitList->getInit(0)->getType();
4614 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4615 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4616 Expr *InitListAsExpr = InitList;
4617 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4618 DestType, Sequence,
4619 /*InitListSyntax*/false,
4620 /*IsInitListCopy*/true);
4621 return;
4622 }
4623 }
4624 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4625 Expr *SubInit[1] = {InitList->getInit(0)};
4626 if (!isa<VariableArrayType>(DestAT) &&
4627 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4628 InitializationKind SubKind =
4629 Kind.getKind() == InitializationKind::IK_DirectList
4630 ? InitializationKind::CreateDirect(Kind.getLocation(),
4631 InitList->getLBraceLoc(),
4632 InitList->getRBraceLoc())
4633 : Kind;
4634 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4635 /*TopLevelOfInitList*/ true,
4636 TreatUnavailableAsInvalid);
4637
4638 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4639 // the element is not an appropriately-typed string literal, in which
4640 // case we should proceed as in C++11 (below).
4641 if (Sequence) {
4642 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4643 return;
4644 }
4645 }
4646 }
4647 }
4648
4649 // C++11 [dcl.init.list]p3:
4650 // - If T is an aggregate, aggregate initialization is performed.
4651 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4652 (S.getLangOpts().CPlusPlus11 &&
4653 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
4654 if (S.getLangOpts().CPlusPlus11) {
4655 // - Otherwise, if the initializer list has no elements and T is a
4656 // class type with a default constructor, the object is
4657 // value-initialized.
4658 if (InitList->getNumInits() == 0) {
4659 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4660 if (S.LookupDefaultConstructor(RD)) {
4661 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4662 return;
4663 }
4664 }
4665
4666 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4667 // an initializer_list object constructed [...]
4668 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4669 TreatUnavailableAsInvalid))
4670 return;
4671
4672 // - Otherwise, if T is a class type, constructors are considered.
4673 Expr *InitListAsExpr = InitList;
4674 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4675 DestType, Sequence, /*InitListSyntax*/true);
4676 } else
4678 return;
4679 }
4680
4681 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4682 InitList->getNumInits() == 1) {
4683 Expr *E = InitList->getInit(0);
4684
4685 // - Otherwise, if T is an enumeration with a fixed underlying type,
4686 // the initializer-list has a single element v, and the initialization
4687 // is direct-list-initialization, the object is initialized with the
4688 // value T(v); if a narrowing conversion is required to convert v to
4689 // the underlying type of T, the program is ill-formed.
4690 auto *ET = DestType->getAs<EnumType>();
4691 if (S.getLangOpts().CPlusPlus17 &&
4692 Kind.getKind() == InitializationKind::IK_DirectList &&
4693 ET && ET->getDecl()->isFixed() &&
4694 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4696 E->getType()->isFloatingType())) {
4697 // There are two ways that T(v) can work when T is an enumeration type.
4698 // If there is either an implicit conversion sequence from v to T or
4699 // a conversion function that can convert from v to T, then we use that.
4700 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4701 // type, it is converted to the enumeration type via its underlying type.
4702 // There is no overlap possible between these two cases (except when the
4703 // source value is already of the destination type), and the first
4704 // case is handled by the general case for single-element lists below.
4706 ICS.setStandard();
4708 if (!E->isPRValue())
4710 // If E is of a floating-point type, then the conversion is ill-formed
4711 // due to narrowing, but go through the motions in order to produce the
4712 // right diagnostic.
4716 ICS.Standard.setFromType(E->getType());
4717 ICS.Standard.setToType(0, E->getType());
4718 ICS.Standard.setToType(1, DestType);
4719 ICS.Standard.setToType(2, DestType);
4720 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4721 /*TopLevelOfInitList*/true);
4722 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4723 return;
4724 }
4725
4726 // - Otherwise, if the initializer list has a single element of type E
4727 // [...references are handled above...], the object or reference is
4728 // initialized from that element (by copy-initialization for
4729 // copy-list-initialization, or by direct-initialization for
4730 // direct-list-initialization); if a narrowing conversion is required
4731 // to convert the element to T, the program is ill-formed.
4732 //
4733 // Per core-24034, this is direct-initialization if we were performing
4734 // direct-list-initialization and copy-initialization otherwise.
4735 // We can't use InitListChecker for this, because it always performs
4736 // copy-initialization. This only matters if we might use an 'explicit'
4737 // conversion operator, or for the special case conversion of nullptr_t to
4738 // bool, so we only need to handle those cases.
4739 //
4740 // FIXME: Why not do this in all cases?
4741 Expr *Init = InitList->getInit(0);
4742 if (Init->getType()->isRecordType() ||
4743 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
4744 InitializationKind SubKind =
4745 Kind.getKind() == InitializationKind::IK_DirectList
4746 ? InitializationKind::CreateDirect(Kind.getLocation(),
4747 InitList->getLBraceLoc(),
4748 InitList->getRBraceLoc())
4749 : Kind;
4750 Expr *SubInit[1] = { Init };
4751 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4752 /*TopLevelOfInitList*/true,
4753 TreatUnavailableAsInvalid);
4754 if (Sequence)
4755 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4756 return;
4757 }
4758 }
4759
4760 InitListChecker CheckInitList(S, Entity, InitList,
4761 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4762 if (CheckInitList.HadError()) {
4764 return;
4765 }
4766
4767 // Add the list initialization step with the built init list.
4768 Sequence.AddListInitializationStep(DestType);
4769}
4770
4771/// Try a reference initialization that involves calling a conversion
4772/// function.
4774 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4775 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4776 InitializationSequence &Sequence) {
4777 QualType DestType = Entity.getType();
4778 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4779 QualType T1 = cv1T1.getUnqualifiedType();
4780 QualType cv2T2 = Initializer->getType();
4781 QualType T2 = cv2T2.getUnqualifiedType();
4782
4783 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
4784 "Must have incompatible references when binding via conversion");
4785
4786 // Build the candidate set directly in the initialization sequence
4787 // structure, so that it will persist if we fail.
4788 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4790
4791 // Determine whether we are allowed to call explicit conversion operators.
4792 // Note that none of [over.match.copy], [over.match.conv], nor
4793 // [over.match.ref] permit an explicit constructor to be chosen when
4794 // initializing a reference, not even for direct-initialization.
4795 bool AllowExplicitCtors = false;
4796 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4797
4798 const RecordType *T1RecordType = nullptr;
4799 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4800 S.isCompleteType(Kind.getLocation(), T1)) {
4801 // The type we're converting to is a class type. Enumerate its constructors
4802 // to see if there is a suitable conversion.
4803 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4804
4805 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4806 auto Info = getConstructorInfo(D);
4807 if (!Info.Constructor)
4808 continue;
4809
4810 if (!Info.Constructor->isInvalidDecl() &&
4811 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
4812 if (Info.ConstructorTmpl)
4814 Info.ConstructorTmpl, Info.FoundDecl,
4815 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4816 /*SuppressUserConversions=*/true,
4817 /*PartialOverloading*/ false, AllowExplicitCtors);
4818 else
4820 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4821 /*SuppressUserConversions=*/true,
4822 /*PartialOverloading*/ false, AllowExplicitCtors);
4823 }
4824 }
4825 }
4826 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4827 return OR_No_Viable_Function;
4828
4829 const RecordType *T2RecordType = nullptr;
4830 if ((T2RecordType = T2->getAs<RecordType>()) &&
4831 S.isCompleteType(Kind.getLocation(), T2)) {
4832 // The type we're converting from is a class type, enumerate its conversion
4833 // functions.
4834 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4835
4836 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4837 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4838 NamedDecl *D = *I;
4839 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4840 if (isa<UsingShadowDecl>(D))
4841 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4842
4843 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4844 CXXConversionDecl *Conv;
4845 if (ConvTemplate)
4846 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4847 else
4848 Conv = cast<CXXConversionDecl>(D);
4849
4850 // If the conversion function doesn't return a reference type,
4851 // it can't be considered for this conversion unless we're allowed to
4852 // consider rvalues.
4853 // FIXME: Do we need to make sure that we only consider conversion
4854 // candidates with reference-compatible results? That might be needed to
4855 // break recursion.
4856 if ((AllowRValues ||
4858 if (ConvTemplate)
4860 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4861 CandidateSet,
4862 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4863 else
4865 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4866 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4867 }
4868 }
4869 }
4870 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4871 return OR_No_Viable_Function;
4872
4873 SourceLocation DeclLoc = Initializer->getBeginLoc();
4874
4875 // Perform overload resolution. If it fails, return the failed result.
4878 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4879 return Result;
4880
4881 FunctionDecl *Function = Best->Function;
4882 // This is the overload that will be used for this initialization step if we
4883 // use this initialization. Mark it as referenced.
4884 Function->setReferenced();
4885
4886 // Compute the returned type and value kind of the conversion.
4887 QualType cv3T3;
4888 if (isa<CXXConversionDecl>(Function))
4889 cv3T3 = Function->getReturnType();
4890 else
4891 cv3T3 = T1;
4892
4894 if (cv3T3->isLValueReferenceType())
4895 VK = VK_LValue;
4896 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4897 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4898 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4899
4900 // Add the user-defined conversion step.
4901 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4902 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4903 HadMultipleCandidates);
4904
4905 // Determine whether we'll need to perform derived-to-base adjustments or
4906 // other conversions.
4908 Sema::ReferenceCompareResult NewRefRelationship =
4909 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
4910
4911 // Add the final conversion sequence, if necessary.
4912 if (NewRefRelationship == Sema::Ref_Incompatible) {
4913 assert(!isa<CXXConstructorDecl>(Function) &&
4914 "should not have conversion after constructor");
4915
4917 ICS.setStandard();
4918 ICS.Standard = Best->FinalConversion;
4919 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4920
4921 // Every implicit conversion results in a prvalue, except for a glvalue
4922 // derived-to-base conversion, which we handle below.
4923 cv3T3 = ICS.Standard.getToType(2);
4924 VK = VK_PRValue;
4925 }
4926
4927 // If the converted initializer is a prvalue, its type T4 is adjusted to
4928 // type "cv1 T4" and the temporary materialization conversion is applied.
4929 //
4930 // We adjust the cv-qualifications to match the reference regardless of
4931 // whether we have a prvalue so that the AST records the change. In this
4932 // case, T4 is "cv3 T3".
4933 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4934 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4935 Sequence.AddQualificationConversionStep(cv1T4, VK);
4936 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
4937 VK = IsLValueRef ? VK_LValue : VK_XValue;
4938
4939 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4940 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4941 else if (RefConv & Sema::ReferenceConversions::ObjC)
4942 Sequence.AddObjCObjectConversionStep(cv1T1);
4943 else if (RefConv & Sema::ReferenceConversions::Function)
4944 Sequence.AddFunctionReferenceConversionStep(cv1T1);
4945 else if (RefConv & Sema::ReferenceConversions::Qualification) {
4946 if (!S.Context.hasSameType(cv1T4, cv1T1))
4947 Sequence.AddQualificationConversionStep(cv1T1, VK);
4948 }
4949
4950 return OR_Success;
4951}
4952
4954 const InitializedEntity &Entity,
4955 Expr *CurInitExpr);
4956
4957/// Attempt reference initialization (C++0x [dcl.init.ref])
4959 const InitializationKind &Kind,
4961 InitializationSequence &Sequence,
4962 bool TopLevelOfInitList) {
4963 QualType DestType = Entity.getType();
4964 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4965 Qualifiers T1Quals;
4966 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4968 Qualifiers T2Quals;
4969 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4970
4971 // If the initializer is the address of an overloaded function, try
4972 // to resolve the overloaded function. If all goes well, T2 is the
4973 // type of the resulting function.
4975 T1, Sequence))
4976 return;
4977
4978 // Delegate everything else to a subfunction.
4979 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4980 T1Quals, cv2T2, T2, T2Quals, Sequence,
4981 TopLevelOfInitList);
4982}
4983
4984/// Determine whether an expression is a non-referenceable glvalue (one to
4985/// which a reference can never bind). Attempting to bind a reference to
4986/// such a glvalue will always create a temporary.
4988 return E->refersToBitField() || E->refersToVectorElement() ||
4990}
4991
4992/// Reference initialization without resolving overloaded functions.
4993///
4994/// We also can get here in C if we call a builtin which is declared as
4995/// a function with a parameter of reference type (such as __builtin_va_end()).
4997 const InitializedEntity &Entity,
4998 const InitializationKind &Kind,
5000 QualType cv1T1, QualType T1,
5001 Qualifiers T1Quals,
5002 QualType cv2T2, QualType T2,
5003 Qualifiers T2Quals,
5004 InitializationSequence &Sequence,
5005 bool TopLevelOfInitList) {
5006 QualType DestType = Entity.getType();
5007 SourceLocation DeclLoc = Initializer->getBeginLoc();
5008
5009 // Compute some basic properties of the types and the initializer.
5010 bool isLValueRef = DestType->isLValueReferenceType();
5011 bool isRValueRef = !isLValueRef;
5012 Expr::Classification InitCategory = Initializer->Classify(S.Context);
5013
5015 Sema::ReferenceCompareResult RefRelationship =
5016 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
5017
5018 // C++0x [dcl.init.ref]p5:
5019 // A reference to type "cv1 T1" is initialized by an expression of type
5020 // "cv2 T2" as follows:
5021 //
5022 // - If the reference is an lvalue reference and the initializer
5023 // expression
5024 // Note the analogous bullet points for rvalue refs to functions. Because
5025 // there are no function rvalues in C++, rvalue refs to functions are treated
5026 // like lvalue refs.
5027 OverloadingResult ConvOvlResult = OR_Success;
5028 bool T1Function = T1->isFunctionType();
5029 if (isLValueRef || T1Function) {
5030 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
5031 (RefRelationship == Sema::Ref_Compatible ||
5032 (Kind.isCStyleOrFunctionalCast() &&
5033 RefRelationship == Sema::Ref_Related))) {
5034 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5035 // reference-compatible with "cv2 T2," or
5036 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5037 Sema::ReferenceConversions::ObjC)) {
5038 // If we're converting the pointee, add any qualifiers first;
5039 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5040 if (RefConv & (Sema::ReferenceConversions::Qualification))
5042 S.Context.getQualifiedType(T2, T1Quals),
5043 Initializer->getValueKind());
5044 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5045 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
5046 else
5047 Sequence.AddObjCObjectConversionStep(cv1T1);
5048 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5049 // Perform a (possibly multi-level) qualification conversion.
5050 Sequence.AddQualificationConversionStep(cv1T1,
5051 Initializer->getValueKind());
5052 } else if (RefConv & Sema::ReferenceConversions::Function) {
5053 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5054 }
5055
5056 // We only create a temporary here when binding a reference to a
5057 // bit-field or vector element. Those cases are't supposed to be
5058 // handled by this bullet, but the outcome is the same either way.
5059 Sequence.AddReferenceBindingStep(cv1T1, false);
5060 return;
5061 }
5062
5063 // - has a class type (i.e., T2 is a class type), where T1 is not
5064 // reference-related to T2, and can be implicitly converted to an
5065 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5066 // with "cv3 T3" (this conversion is selected by enumerating the
5067 // applicable conversion functions (13.3.1.6) and choosing the best
5068 // one through overload resolution (13.3)),
5069 // If we have an rvalue ref to function type here, the rhs must be
5070 // an rvalue. DR1287 removed the "implicitly" here.
5071 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5072 (isLValueRef || InitCategory.isRValue())) {
5073 if (S.getLangOpts().CPlusPlus) {
5074 // Try conversion functions only for C++.
5075 ConvOvlResult = TryRefInitWithConversionFunction(
5076 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5077 /*IsLValueRef*/ isLValueRef, Sequence);
5078 if (ConvOvlResult == OR_Success)
5079 return;
5080 if (ConvOvlResult != OR_No_Viable_Function)
5081 Sequence.SetOverloadFailure(
5083 ConvOvlResult);
5084 } else {
5085 ConvOvlResult = OR_No_Viable_Function;
5086 }
5087 }
5088 }
5089
5090 // - Otherwise, the reference shall be an lvalue reference to a
5091 // non-volatile const type (i.e., cv1 shall be const), or the reference
5092 // shall be an rvalue reference.
5093 // For address spaces, we interpret this to mean that an addr space
5094 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5095 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5096 T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5099 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5100 Sequence.SetOverloadFailure(
5102 ConvOvlResult);
5103 else if (!InitCategory.isLValue())
5104 Sequence.SetFailed(
5105 T1Quals.isAddressSpaceSupersetOf(T2Quals)
5109 else {
5111 switch (RefRelationship) {
5113 if (Initializer->refersToBitField())
5116 else if (Initializer->refersToVectorElement())
5119 else if (Initializer->refersToMatrixElement())
5122 else
5123 llvm_unreachable("unexpected kind of compatible initializer");
5124 break;
5125 case Sema::Ref_Related:
5127 break;
5131 break;
5132 }
5133 Sequence.SetFailed(FK);
5134 }
5135 return;
5136 }
5137
5138 // - If the initializer expression
5139 // - is an
5140 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5141 // [1z] rvalue (but not a bit-field) or
5142 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5143 //
5144 // Note: functions are handled above and below rather than here...
5145 if (!T1Function &&
5146 (RefRelationship == Sema::Ref_Compatible ||
5147 (Kind.isCStyleOrFunctionalCast() &&
5148 RefRelationship == Sema::Ref_Related)) &&
5149 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5150 (InitCategory.isPRValue() &&
5151 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5152 T2->isArrayType())))) {
5153 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5154 if (InitCategory.isPRValue() && T2->isRecordType()) {
5155 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5156 // compiler the freedom to perform a copy here or bind to the
5157 // object, while C++0x requires that we bind directly to the
5158 // object. Hence, we always bind to the object without making an
5159 // extra copy. However, in C++03 requires that we check for the
5160 // presence of a suitable copy constructor:
5161 //
5162 // The constructor that would be used to make the copy shall
5163 // be callable whether or not the copy is actually done.
5164 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5165 Sequence.AddExtraneousCopyToTemporary(cv2T2);
5166 else if (S.getLangOpts().CPlusPlus11)
5168 }
5169
5170 // C++1z [dcl.init.ref]/5.2.1.2:
5171 // If the converted initializer is a prvalue, its type T4 is adjusted
5172 // to type "cv1 T4" and the temporary materialization conversion is
5173 // applied.
5174 // Postpone address space conversions to after the temporary materialization
5175 // conversion to allow creating temporaries in the alloca address space.
5176 auto T1QualsIgnoreAS = T1Quals;
5177 auto T2QualsIgnoreAS = T2Quals;
5178 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5179 T1QualsIgnoreAS.removeAddressSpace();
5180 T2QualsIgnoreAS.removeAddressSpace();
5181 }
5182 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
5183 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5184 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5185 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5186 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5187 // Add addr space conversion if required.
5188 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5189 auto T4Quals = cv1T4.getQualifiers();
5190 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5191 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5192 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5193 cv1T4 = cv1T4WithAS;
5194 }
5195
5196 // In any case, the reference is bound to the resulting glvalue (or to
5197 // an appropriate base class subobject).
5198 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5199 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5200 else if (RefConv & Sema::ReferenceConversions::ObjC)
5201 Sequence.AddObjCObjectConversionStep(cv1T1);
5202 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5203 if (!S.Context.hasSameType(cv1T4, cv1T1))
5204 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5205 }
5206 return;
5207 }
5208
5209 // - has a class type (i.e., T2 is a class type), where T1 is not
5210 // reference-related to T2, and can be implicitly converted to an
5211 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5212 // where "cv1 T1" is reference-compatible with "cv3 T3",
5213 //
5214 // DR1287 removes the "implicitly" here.
5215 if (T2->isRecordType()) {
5216 if (RefRelationship == Sema::Ref_Incompatible) {
5217 ConvOvlResult = TryRefInitWithConversionFunction(
5218 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5219 /*IsLValueRef*/ isLValueRef, Sequence);
5220 if (ConvOvlResult)
5221 Sequence.SetOverloadFailure(
5223 ConvOvlResult);
5224
5225 return;
5226 }
5227
5228 if (RefRelationship == Sema::Ref_Compatible &&
5229 isRValueRef && InitCategory.isLValue()) {
5230 Sequence.SetFailed(
5232 return;
5233 }
5234
5236 return;
5237 }
5238
5239 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5240 // from the initializer expression using the rules for a non-reference
5241 // copy-initialization (8.5). The reference is then bound to the
5242 // temporary. [...]
5243
5244 // Ignore address space of reference type at this point and perform address
5245 // space conversion after the reference binding step.
5246 QualType cv1T1IgnoreAS =
5247 T1Quals.hasAddressSpace()
5249 : cv1T1;
5250
5251 InitializedEntity TempEntity =
5253
5254 // FIXME: Why do we use an implicit conversion here rather than trying
5255 // copy-initialization?
5257 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5258 /*SuppressUserConversions=*/false,
5259 Sema::AllowedExplicit::None,
5260 /*FIXME:InOverloadResolution=*/false,
5261 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5262 /*AllowObjCWritebackConversion=*/false);
5263
5264 if (ICS.isBad()) {
5265 // FIXME: Use the conversion function set stored in ICS to turn
5266 // this into an overloading ambiguity diagnostic. However, we need
5267 // to keep that set as an OverloadCandidateSet rather than as some
5268 // other kind of set.
5269 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5270 Sequence.SetOverloadFailure(
5272 ConvOvlResult);
5273 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5275 else
5277 return;
5278 } else {
5279 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType(),
5280 TopLevelOfInitList);
5281 }
5282
5283 // [...] If T1 is reference-related to T2, cv1 must be the
5284 // same cv-qualification as, or greater cv-qualification
5285 // than, cv2; otherwise, the program is ill-formed.
5286 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5287 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5288 if (RefRelationship == Sema::Ref_Related &&
5289 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5290 !T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5292 return;
5293 }
5294
5295 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5296 // reference, the initializer expression shall not be an lvalue.
5297 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5298 InitCategory.isLValue()) {
5299 Sequence.SetFailed(
5301 return;
5302 }
5303
5304 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5305
5306 if (T1Quals.hasAddressSpace()) {
5308 LangAS::Default)) {
5309 Sequence.SetFailed(
5311 return;
5312 }
5313 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5314 : VK_XValue);
5315 }
5316}
5317
5318/// Attempt character array initialization from a string literal
5319/// (C++ [dcl.init.string], C99 6.7.8).
5321 const InitializedEntity &Entity,
5322 const InitializationKind &Kind,
5324 InitializationSequence &Sequence) {
5325 Sequence.AddStringInitStep(Entity.getType());
5326}
5327
5328/// Attempt value initialization (C++ [dcl.init]p7).
5330 const InitializedEntity &Entity,
5331 const InitializationKind &Kind,
5332 InitializationSequence &Sequence,
5333 InitListExpr *InitList) {
5334 assert((!InitList || InitList->getNumInits() == 0) &&
5335 "Shouldn't use value-init for non-empty init lists");
5336
5337 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5338 //
5339 // To value-initialize an object of type T means:
5340 QualType T = Entity.getType();
5341
5342 // -- if T is an array type, then each element is value-initialized;
5343 T = S.Context.getBaseElementType(T);
5344
5345 if (const RecordType *RT = T->getAs<RecordType>()) {
5346 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5347 bool NeedZeroInitialization = true;
5348 // C++98:
5349 // -- if T is a class type (clause 9) with a user-declared constructor
5350 // (12.1), then the default constructor for T is called (and the
5351 // initialization is ill-formed if T has no accessible default
5352 // constructor);
5353 // C++11:
5354 // -- if T is a class type (clause 9) with either no default constructor
5355 // (12.1 [class.ctor]) or a default constructor that is user-provided
5356 // or deleted, then the object is default-initialized;
5357 //
5358 // Note that the C++11 rule is the same as the C++98 rule if there are no
5359 // defaulted or deleted constructors, so we just use it unconditionally.
5361 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5362 NeedZeroInitialization = false;
5363
5364 // -- if T is a (possibly cv-qualified) non-union class type without a
5365 // user-provided or deleted default constructor, then the object is
5366 // zero-initialized and, if T has a non-trivial default constructor,
5367 // default-initialized;
5368 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5369 // constructor' part was removed by DR1507.
5370 if (NeedZeroInitialization)
5371 Sequence.AddZeroInitializationStep(Entity.getType());
5372
5373 // C++03:
5374 // -- if T is a non-union class type without a user-declared constructor,
5375 // then every non-static data member and base class component of T is
5376 // value-initialized;
5377 // [...] A program that calls for [...] value-initialization of an
5378 // entity of reference type is ill-formed.
5379 //
5380 // C++11 doesn't need this handling, because value-initialization does not
5381 // occur recursively there, and the implicit default constructor is
5382 // defined as deleted in the problematic cases.
5383 if (!S.getLangOpts().CPlusPlus11 &&
5384 ClassDecl->hasUninitializedReferenceMember()) {
5386 return;
5387 }
5388
5389 // If this is list-value-initialization, pass the empty init list on when
5390 // building the constructor call. This affects the semantics of a few
5391 // things (such as whether an explicit default constructor can be called).
5392 Expr *InitListAsExpr = InitList;
5393 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5394 bool InitListSyntax = InitList;
5395
5396 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5397 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5399 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5400 }
5401 }
5402
5403 Sequence.AddZeroInitializationStep(Entity.getType());
5404}
5405
5406/// Attempt default initialization (C++ [dcl.init]p6).
5408 const InitializedEntity &Entity,
5409 const InitializationKind &Kind,
5410 InitializationSequence &Sequence) {
5411 assert(Kind.getKind() == InitializationKind::IK_Default);
5412
5413 // C++ [dcl.init]p6:
5414 // To default-initialize an object of type T means:
5415 // - if T is an array type, each element is default-initialized;
5416 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5417
5418 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5419 // constructor for T is called (and the initialization is ill-formed if
5420 // T has no accessible default constructor);
5421 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5422 TryConstructorInitialization(S, Entity, Kind, std::nullopt, DestType,
5423 Entity.getType(), Sequence);
5424 return;
5425 }
5426
5427 // - otherwise, no initialization is performed.
5428
5429 // If a program calls for the default initialization of an object of
5430 // a const-qualified type T, T shall be a class type with a user-provided
5431 // default constructor.
5432 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5433 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5435 return;
5436 }
5437
5438 // If the destination type has a lifetime property, zero-initialize it.
5439 if (DestType.getQualifiers().hasObjCLifetime()) {
5440 Sequence.AddZeroInitializationStep(Entity.getType());
5441 return;
5442 }
5443}
5444
5446 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5447 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5448 ExprResult *Result = nullptr) {
5449 unsigned EntityIndexToProcess = 0;
5450 SmallVector<Expr *, 4> InitExprs;
5451 QualType ResultType;
5452 Expr *ArrayFiller = nullptr;
5453 FieldDecl *InitializedFieldInUnion = nullptr;
5454
5455 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5456 const InitializationKind &SubKind,
5457 Expr *Arg, Expr **InitExpr = nullptr) {
5459 S, SubEntity, SubKind, Arg ? MultiExprArg(Arg) : std::nullopt);
5460
5461 if (IS.Failed()) {
5462 if (!VerifyOnly) {
5463 IS.Diagnose(S, SubEntity, SubKind, Arg ? ArrayRef(Arg) : std::nullopt);
5464 } else {
5465 Sequence.SetFailed(
5467 }
5468
5469 return false;
5470 }
5471 if (!VerifyOnly) {
5472 ExprResult ER;
5473 ER = IS.Perform(S, SubEntity, SubKind,
5474 Arg ? MultiExprArg(Arg) : std::nullopt);
5475 if (InitExpr)
5476 *InitExpr = ER.get();
5477 else
5478 InitExprs.push_back(ER.get());
5479 }
5480 return true;
5481 };
5482
5483 if (const ArrayType *AT =
5484 S.getASTContext().getAsArrayType(Entity.getType())) {
5485 SmallVector<InitializedEntity, 4> ElementEntities;
5486 uint64_t ArrayLength;
5487 // C++ [dcl.init]p16.5
5488 // if the destination type is an array, the object is initialized as
5489 // follows. Let x1, . . . , xk be the elements of the expression-list. If
5490 // the destination type is an array of unknown bound, it is defined as
5491 // having k elements.
5492 if (const ConstantArrayType *CAT =
5494 ArrayLength = CAT->getZExtSize();
5495 ResultType = Entity.getType();
5496 } else if (const VariableArrayType *VAT =
5498 // Braced-initialization of variable array types is not allowed, even if
5499 // the size is greater than or equal to the number of args, so we don't
5500 // allow them to be initialized via parenthesized aggregate initialization
5501 // either.
5502 const Expr *SE = VAT->getSizeExpr();
5503 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
5504 << SE->getSourceRange();
5505 return;
5506 } else {
5507 assert(isa<IncompleteArrayType>(Entity.getType()));
5508 ArrayLength = Args.size();
5509 }
5510 EntityIndexToProcess = ArrayLength;
5511
5512 // ...the ith array element is copy-initialized with xi for each
5513 // 1 <= i <= k
5514 for (Expr *E : Args) {
5516 S.getASTContext(), EntityIndexToProcess, Entity);
5518 E->getExprLoc(), /*isDirectInit=*/false, E);
5519 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5520 return;
5521 }
5522 // ...and value-initialized for each k < i <= n;
5523 if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {
5525 S.getASTContext(), Args.size(), Entity);
5527 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5528 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
5529 return;
5530 }
5531
5532 if (ResultType.isNull()) {
5533 ResultType = S.Context.getConstantArrayType(
5534 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
5535 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 0);
5536 }
5537 } else if (auto *RT = Entity.getType()->getAs<RecordType>()) {
5538 bool IsUnion = RT->isUnionType();
5539 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5540 if (RD->isInvalidDecl()) {
5541 // Exit early to avoid confusion when processing members.
5542 // We do the same for braced list initialization in
5543 // `CheckStructUnionTypes`.
5544 Sequence.SetFailed(
5546 return;
5547 }
5548
5549 if (!IsUnion) {
5550 for (const CXXBaseSpecifier &Base : RD->bases()) {
5552 S.getASTContext(), &Base, false, &Entity);
5553 if (EntityIndexToProcess < Args.size()) {
5554 // C++ [dcl.init]p16.6.2.2.
5555 // ...the object is initialized is follows. Let e1, ..., en be the
5556 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
5557 // the elements of the expression-list...The element ei is
5558 // copy-initialized with xi for 1 <= i <= k.
5559 Expr *E = Args[EntityIndexToProcess];
5561 E->getExprLoc(), /*isDirectInit=*/false, E);
5562 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5563 return;
5564 } else {
5565 // We've processed all of the args, but there are still base classes
5566 // that have to be initialized.
5567 // C++ [dcl.init]p17.6.2.2
5568 // The remaining elements...otherwise are value initialzed
5570 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
5571 /*IsImplicit=*/true);
5572 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5573 return;
5574 }
5575 EntityIndexToProcess++;
5576 }
5577 }
5578
5579 for (FieldDecl *FD : RD->fields()) {
5580 // Unnamed bitfields should not be initialized at all, either with an arg
5581 // or by default.
5582 if (FD->isUnnamedBitfield())
5583 continue;
5584
5585 InitializedEntity SubEntity =
5587
5588 if (EntityIndexToProcess < Args.size()) {
5589 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
5590 Expr *E = Args[EntityIndexToProcess];
5591
5592 // Incomplete array types indicate flexible array members. Do not allow
5593 // paren list initializations of structs with these members, as GCC
5594 // doesn't either.
5595 if (FD->getType()->isIncompleteArrayType()) {
5596 if (!VerifyOnly) {
5597 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
5598 << SourceRange(E->getBeginLoc(), E->getEndLoc());
5599 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
5600 }
5601 Sequence.SetFailed(
5603 return;
5604 }
5605
5607 E->getExprLoc(), /*isDirectInit=*/false, E);
5608 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5609 return;
5610
5611 // Unions should have only one initializer expression, so we bail out
5612 // after processing the first field. If there are more initializers then
5613 // it will be caught when we later check whether EntityIndexToProcess is
5614 // less than Args.size();
5615 if (IsUnion) {
5616 InitializedFieldInUnion = FD;
5617 EntityIndexToProcess = 1;
5618 break;
5619 }
5620 } else {
5621 // We've processed all of the args, but there are still members that
5622 // have to be initialized.
5623 if (FD->hasInClassInitializer()) {
5624 if (!VerifyOnly) {
5625 // C++ [dcl.init]p16.6.2.2
5626 // The remaining elements are initialized with their default
5627 // member initializers, if any
5629 Kind.getParenOrBraceRange().getEnd(), FD);
5630 if (DIE.isInvalid())
5631 return;
5632 S.checkInitializerLifetime(SubEntity, DIE.get());
5633 InitExprs.push_back(DIE.get());
5634 }
5635 } else {
5636 // C++ [dcl.init]p17.6.2.2
5637 // The remaining elements...otherwise are value initialzed
5638 if (FD->getType()->isReferenceType()) {
5639 Sequence.SetFailed(
5641 if (!VerifyOnly) {
5642 SourceRange SR = Kind.getParenOrBraceRange();
5643 S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
5644 << FD->getType() << SR;
5645 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
5646 }
5647 return;
5648 }
5650 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5651 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5652 return;
5653 }
5654 }
5655 EntityIndexToProcess++;
5656 }
5657 ResultType = Entity.getType();
5658 }
5659
5660 // Not all of the args have been processed, so there must've been more args
5661 // than were required to initialize the element.
5662 if (EntityIndexToProcess < Args.size()) {
5664 if (!VerifyOnly) {
5665 QualType T = Entity.getType();
5666 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4;
5667 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
5668 Args.back()->getEndLoc());
5669 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5670 << InitKind << ExcessInitSR;
5671 }
5672 return;
5673 }
5674
5675 if (VerifyOnly) {
5677 Sequence.AddParenthesizedListInitStep(Entity.getType());
5678 } else if (Result) {
5679 SourceRange SR = Kind.getParenOrBraceRange();
5680 auto *CPLIE = CXXParenListInitExpr::Create(
5681 S.getASTContext(), InitExprs, ResultType, Args.size(),
5682 Kind.getLocation(), SR.getBegin(), SR.getEnd());
5683 if (ArrayFiller)
5684 CPLIE->setArrayFiller(ArrayFiller);
5685 if (InitializedFieldInUnion)
5686 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
5687 *Result = CPLIE;
5688 S.Diag(Kind.getLocation(),
5689 diag::warn_cxx17_compat_aggregate_init_paren_list)
5690 << Kind.getLocation() << SR << ResultType;
5691 }
5692}
5693
5694/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
5695/// which enumerates all conversion functions and performs overload resolution
5696/// to select the best.
5698 QualType DestType,
5699 const InitializationKind &Kind,
5701 InitializationSequence &Sequence,
5702 bool TopLevelOfInitList) {
5703 assert(!DestType->isReferenceType() && "References are handled elsewhere");
5704 QualType SourceType = Initializer->getType();
5705 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
5706 "Must have a class type to perform a user-defined conversion");
5707
5708 // Build the candidate set directly in the initialization sequence
5709 // structure, so that it will persist if we fail.
5710 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5712 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
5713
5714 // Determine whether we are allowed to call explicit constructors or
5715 // explicit conversion operators.
5716 bool AllowExplicit = Kind.AllowExplicit();
5717
5718 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5719 // The type we're converting to is a class type. Enumerate its constructors
5720 // to see if there is a suitable conversion.
5721 CXXRecordDecl *DestRecordDecl
5722 = cast<CXXRecordDecl>(DestRecordType->getDecl());
5723
5724 // Try to complete the type we're converting to.
5725 if (S.isCompleteType(Kind.getLocation(), DestType)) {
5726 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
5727 auto Info = getConstructorInfo(D);
5728 if (!Info.Constructor)
5729 continue;
5730
5731 if (!Info.Constructor->isInvalidDecl() &&
5732 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5733 if (Info.ConstructorTmpl)
5735 Info.ConstructorTmpl, Info.FoundDecl,
5736 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5737 /*SuppressUserConversions=*/true,
5738 /*PartialOverloading*/ false, AllowExplicit);
5739 else
5740 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
5741 Initializer, CandidateSet,
5742 /*SuppressUserConversions=*/true,
5743 /*PartialOverloading*/ false, AllowExplicit);
5744 }
5745 }
5746 }
5747 }
5748
5749 SourceLocation DeclLoc = Initializer->getBeginLoc();
5750
5751 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5752 // The type we're converting from is a class type, enumerate its conversion
5753 // functions.
5754
5755 // We can only enumerate the conversion functions for a complete type; if
5756 // the type isn't complete, simply skip this step.
5757 if (S.isCompleteType(DeclLoc, SourceType)) {
5758 CXXRecordDecl *SourceRecordDecl
5759 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
5760
5761 const auto &Conversions =
5762 SourceRecordDecl->getVisibleConversionFunctions();
5763 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5764 NamedDecl *D = *I;
5765 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5766 if (isa<UsingShadowDecl>(D))
5767 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5768
5769 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5770 CXXConversionDecl *Conv;
5771 if (ConvTemplate)
5772 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5773 else
5774 Conv = cast<CXXConversionDecl>(D);
5775
5776 if (ConvTemplate)
5778 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5779 CandidateSet, AllowExplicit, AllowExplicit);
5780 else
5781 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
5782 DestType, CandidateSet, AllowExplicit,
5783 AllowExplicit);
5784 }
5785 }
5786 }
5787
5788 // Perform overload resolution. If it fails, return the failed result.
5791 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5792 Sequence.SetOverloadFailure(
5794
5795 // [class.copy.elision]p3:
5796 // In some copy-initialization contexts, a two-stage overload resolution
5797 // is performed.
5798 // If the first overload resolution selects a deleted function, we also
5799 // need the initialization sequence to decide whether to perform the second
5800 // overload resolution.
5801 if (!(Result == OR_Deleted &&
5802 Kind.getKind() == InitializationKind::IK_Copy))
5803 return;
5804 }
5805
5806 FunctionDecl *Function = Best->Function;
5807 Function->setReferenced();
5808 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5809
5810 if (isa<CXXConstructorDecl>(Function)) {
5811 // Add the user-defined conversion step. Any cv-qualification conversion is
5812 // subsumed by the initialization. Per DR5, the created temporary is of the
5813 // cv-unqualified type of the destination.
5814 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5815 DestType.getUnqualifiedType(),
5816 HadMultipleCandidates);
5817
5818 // C++14 and before:
5819 // - if the function is a constructor, the call initializes a temporary
5820 // of the cv-unqualified version of the destination type. The [...]
5821 // temporary [...] is then used to direct-initialize, according to the
5822 // rules above, the object that is the destination of the
5823 // copy-initialization.
5824 // Note that this just performs a simple object copy from the temporary.
5825 //
5826 // C++17:
5827 // - if the function is a constructor, the call is a prvalue of the
5828 // cv-unqualified version of the destination type whose return object
5829 // is initialized by the constructor. The call is used to
5830 // direct-initialize, according to the rules above, the object that
5831 // is the destination of the copy-initialization.
5832 // Therefore we need to do nothing further.
5833 //
5834 // FIXME: Mark this copy as extraneous.
5835 if (!S.getLangOpts().CPlusPlus17)
5836 Sequence.AddFinalCopy(DestType);
5837 else if (DestType.hasQualifiers())
5838 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5839 return;
5840 }
5841
5842 // Add the user-defined conversion step that calls the conversion function.
5843 QualType ConvType = Function->getCallResultType();
5844 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5845 HadMultipleCandidates);
5846
5847 if (ConvType->getAs<RecordType>()) {
5848 // The call is used to direct-initialize [...] the object that is the
5849 // destination of the copy-initialization.
5850 //
5851 // In C++17, this does not call a constructor if we enter /17.6.1:
5852 // - If the initializer expression is a prvalue and the cv-unqualified
5853 // version of the source type is the same as the class of the
5854 // destination [... do not make an extra copy]
5855 //
5856 // FIXME: Mark this copy as extraneous.
5857 if (!S.getLangOpts().CPlusPlus17 ||
5858 Function->getReturnType()->isReferenceType() ||
5859 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5860 Sequence.AddFinalCopy(DestType);
5861 else if (!S.Context.hasSameType(ConvType, DestType))
5862 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5863 return;
5864 }
5865
5866 // If the conversion following the call to the conversion function
5867 // is interesting, add it as a separate step.
5868 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5869 Best->FinalConversion.Third) {
5871 ICS.setStandard();
5872 ICS.Standard = Best->FinalConversion;
5873 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5874 }
5875}
5876
5877/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5878/// a function with a pointer return type contains a 'return false;' statement.
5879/// In C++11, 'false' is not a null pointer, so this breaks the build of any
5880/// code using that header.
5881///
5882/// Work around this by treating 'return false;' as zero-initializing the result
5883/// if it's used in a pointer-returning function in a system header.
5885 const InitializedEntity &Entity,
5886 const Expr *Init) {
5887 return S.getLangOpts().CPlusPlus11 &&
5889 Entity.getType()->isPointerType() &&
5890 isa<CXXBoolLiteralExpr>(Init) &&
5891 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5892 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5893}
5894
5895/// The non-zero enum values here are indexes into diagnostic alternatives.
5897
5898/// Determines whether this expression is an acceptable ICR source.
5900 bool isAddressOf, bool &isWeakAccess) {
5901 // Skip parens.
5902 e = e->IgnoreParens();
5903
5904 // Skip address-of nodes.
5905 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5906 if (op->getOpcode() == UO_AddrOf)
5907 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5908 isWeakAccess);
5909
5910 // Skip certain casts.
5911 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5912 switch (ce->getCastKind()) {
5913 case CK_Dependent:
5914 case CK_BitCast:
5915 case CK_LValueBitCast:
5916 case CK_NoOp:
5917 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
5918
5919 case CK_ArrayToPointerDecay:
5920 return IIK_nonscalar;
5921
5922 case CK_NullToPointer:
5923 return IIK_okay;
5924
5925 default:
5926 break;
5927 }
5928
5929 // If we have a declaration reference, it had better be a local variable.
5930 } else if (isa<DeclRefExpr>(e)) {
5931 // set isWeakAccess to true, to mean that there will be an implicit
5932 // load which requires a cleanup.
5934 isWeakAccess = true;
5935
5936 if (!isAddressOf) return IIK_nonlocal;
5937
5938 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5939 if (!var) return IIK_nonlocal;
5940
5941 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5942
5943 // If we have a conditional operator, check both sides.
5944 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5945 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5946 isWeakAccess))
5947 return iik;
5948
5949 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5950
5951 // These are never scalar.
5952 } else if (isa<ArraySubscriptExpr>(e)) {
5953 return IIK_nonscalar;
5954
5955 // Otherwise, it needs to be a null pointer constant.
5956 } else {
5959 }
5960
5961 return IIK_nonlocal;
5962}
5963
5964/// Check whether the given expression is a valid operand for an
5965/// indirect copy/restore.
5967 assert(src->isPRValue());
5968 bool isWeakAccess = false;
5969 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5970 // If isWeakAccess to true, there will be an implicit
5971 // load which requires a cleanup.
5972 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5974
5975 if (iik == IIK_okay) return;
5976
5977 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5978 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5979 << src->getSourceRange();
5980}
5981
5982/// Determine whether we have compatible array types for the
5983/// purposes of GNU by-copy array initialization.
5984static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5985 const ArrayType *Source) {
5986 // If the source and destination array types are equivalent, we're
5987 // done.
5988 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5989 return true;
5990
5991 // Make sure that the element types are the same.
5992 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5993 return false;
5994
5995 // The only mismatch we allow is when the destination is an
5996 // incomplete array type and the source is a constant array type.
5997 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5998}
5999
6001 InitializationSequence &Sequence,
6002 const InitializedEntity &Entity,
6003 Expr *Initializer) {
6004 bool ArrayDecay = false;
6005 QualType ArgType = Initializer->getType();
6006 QualType ArgPointee;
6007 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
6008 ArrayDecay = true;
6009 ArgPointee = ArgArrayType->getElementType();
6010 ArgType = S.Context.getPointerType(ArgPointee);
6011 }
6012
6013 // Handle write-back conversion.
6014 QualType ConvertedArgType;
6015 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
6016 ConvertedArgType))
6017 return false;
6018
6019 // We should copy unless we're passing to an argument explicitly
6020 // marked 'out'.
6021 bool ShouldCopy = true;
6022 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6023 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6024
6025 // Do we need an lvalue conversion?
6026 if (ArrayDecay || Initializer->isGLValue()) {
6028 ICS.setStandard();
6030
6031 QualType ResultType;
6032 if (ArrayDecay) {
6034 ResultType = S.Context.getPointerType(ArgPointee);
6035 } else {
6037 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
6038 }
6039
6040 Sequence.AddConversionSequenceStep(ICS, ResultType);
6041 }
6042
6043 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
6044 return true;
6045}
6046
6048 InitializationSequence &Sequence,
6049 QualType DestType,
6050 Expr *Initializer) {
6051 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6052 (!Initializer->isIntegerConstantExpr(S.Context) &&
6053 !Initializer->getType()->isSamplerT()))
6054 return false;
6055
6056 Sequence.AddOCLSamplerInitStep(DestType);
6057 return true;
6058}
6059
6061 return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
6062 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
6063}
6064
6066 InitializationSequence &Sequence,
6067 QualType DestType,
6068 Expr *Initializer) {
6069 if (!S.getLangOpts().OpenCL)
6070 return false;
6071
6072 //
6073 // OpenCL 1.2 spec, s6.12.10
6074 //
6075 // The event argument can also be used to associate the
6076 // async_work_group_copy with a previous async copy allowing
6077 // an event to be shared by multiple async copies; otherwise
6078 // event should be zero.
6079 //
6080 if (DestType->isEventT() || DestType->isQueueT()) {
6082 return false;
6083
6084 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6085 return true;
6086 }
6087
6088 // We should allow zero initialization for all types defined in the
6089 // cl_intel_device_side_avc_motion_estimation extension, except
6090 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6092 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
6093 DestType->isOCLIntelSubgroupAVCType()) {
6094 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6095 DestType->isOCLIntelSubgroupAVCMceResultType())
6096 return false;
6098 return false;
6099
6100 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6101 return true;
6102 }
6103
6104 return false;
6105}
6106
6108 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6109 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6110 : FailedOverloadResult(OR_Success),
6111 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6112 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6113 TreatUnavailableAsInvalid);
6114}
6115
6116/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6117/// address of that function, this returns true. Otherwise, it returns false.
6118static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6119 auto *DRE = dyn_cast<DeclRefExpr>(E);
6120 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6121 return false;
6122
6124 cast<FunctionDecl>(DRE->getDecl()));
6125}
6126
6127/// Determine whether we can perform an elementwise array copy for this kind
6128/// of entity.
6129static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6130 switch (Entity.getKind()) {
6132 // C++ [expr.prim.lambda]p24:
6133 // For array members, the array elements are direct-initialized in
6134 // increasing subscript order.
6135 return true;
6136
6138 // C++ [dcl.decomp]p1:
6139 // [...] each element is copy-initialized or direct-initialized from the
6140 // corresponding element of the assignment-expression [...]
6141 return isa<DecompositionDecl>(Entity.getDecl());
6142
6144 // C++ [class.copy.ctor]p14:
6145 // - if the member is an array, each element is direct-initialized with
6146 // the corresponding subobject of x
6147 return Entity.isImplicitMemberInitializer();
6148
6150 // All the above cases are intended to apply recursively, even though none
6151 // of them actually say that.
6152 if (auto *E = Entity.getParent())
6153 return canPerformArrayCopy(*E);
6154 break;
6155
6156 default:
6157 break;
6158 }
6159
6160 return false;
6161}
6162
6164 const InitializedEntity &Entity,
6165 const InitializationKind &Kind,
6166 MultiExprArg Args,
6167 bool TopLevelOfInitList,
6168 bool TreatUnavailableAsInvalid) {
6169 ASTContext &Context = S.Context;
6170
6171 // Eliminate non-overload placeholder types in the arguments. We
6172 // need to do this before checking whether types are dependent
6173 // because lowering a pseudo-object expression might well give us
6174 // something of dependent type.
6175 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6176 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6177 // FIXME: should we be doing this here?
6178 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
6179 if (result.isInvalid()) {
6181 return;
6182 }
6183 Args[I] = result.get();
6184 }
6185
6186 // C++0x [dcl.init]p16:
6187 // The semantics of initializers are as follows. The destination type is
6188 // the type of the object or reference being initialized and the source
6189 // type is the type of the initializer expression. The source type is not
6190 // defined when the initializer is a braced-init-list or when it is a
6191 // parenthesized list of expressions.
6192 QualType DestType = Entity.getType();
6193
6194 if (DestType->isDependentType() ||
6197 return;
6198 }
6199
6200 // Almost everything is a normal sequence.
6202
6203 QualType SourceType;
6204 Expr *Initializer = nullptr;
6205 if (Args.size() == 1) {
6206 Initializer = Args[0];
6207 if (S.getLangOpts().ObjC) {
6209 DestType, Initializer->getType(),
6210 Initializer) ||
6212 Args[0] = Initializer;
6213 }
6214 if (!isa<InitListExpr>(Initializer))
6215 SourceType = Initializer->getType();
6216 }
6217
6218 // - If the initializer is a (non-parenthesized) braced-init-list, the
6219 // object is list-initialized (8.5.4).
6220 if (Kind.getKind() != InitializationKind::IK_Direct) {
6221 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
6222 TryListInitialization(S, Entity, Kind, InitList, *this,
6223 TreatUnavailableAsInvalid);
6224 return;
6225 }
6226 }
6227
6228 // - If the destination type is a reference type, see 8.5.3.
6229 if (DestType->isReferenceType()) {
6230 // C++0x [dcl.init.ref]p1:
6231 // A variable declared to be a T& or T&&, that is, "reference to type T"
6232 // (8.3.2), shall be initialized by an object, or function, of type T or
6233 // by an object that can be converted into a T.
6234 // (Therefore, multiple arguments are not permitted.)
6235 if (Args.size() != 1)
6237 // C++17 [dcl.init.ref]p5:
6238 // A reference [...] is initialized by an expression [...] as follows:
6239 // If the initializer is not an expression, presumably we should reject,
6240 // but the standard fails to actually say so.
6241 else if (isa<InitListExpr>(Args[0]))
6243 else
6244 TryReferenceInitialization(S, Entity, Kind, Args[0], *this,
6245 TopLevelOfInitList);
6246 return;
6247 }
6248
6249 // - If the initializer is (), the object is value-initialized.
6250 if (Kind.getKind() == InitializationKind::IK_Value ||
6251 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6252 TryValueInitialization(S, Entity, Kind, *this);
6253 return;
6254 }
6255
6256 // Handle default initialization.
6257 if (Kind.getKind() == InitializationKind::IK_Default) {
6258 TryDefaultInitialization(S, Entity, Kind, *this);
6259 return;
6260 }
6261
6262 // - If the destination type is an array of characters, an array of
6263 // char16_t, an array of char32_t, or an array of wchar_t, and the
6264 // initializer is a string literal, see 8.5.2.
6265 // - Otherwise, if the destination type is an array, the program is
6266 // ill-formed.
6267 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
6268 if (Initializer && isa<VariableArrayType>(DestAT)) {
6270 return;
6271 }
6272
6273 if (Initializer) {
6274 switch (IsStringInit(Initializer, DestAT, Context)) {
6275 case SIF_None:
6276 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
6277 return;
6280 return;
6283 return;
6286 return;
6289 return;
6292 return;
6293 case SIF_Other:
6294 break;
6295 }
6296 }
6297
6298 // Some kinds of initialization permit an array to be initialized from
6299 // another array of the same type, and perform elementwise initialization.
6300 if (Initializer && isa<ConstantArrayType>(DestAT) &&
6302 Entity.getType()) &&
6303 canPerformArrayCopy(Entity)) {
6304 // If source is a prvalue, use it directly.
6305 if (Initializer->isPRValue()) {
6306 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
6307 return;
6308 }
6309
6310 // Emit element-at-a-time copy loop.
6311 InitializedEntity Element =
6313 QualType InitEltT =
6314 Context.getAsArrayType(Initializer->getType())->getElementType();
6315 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
6316 Initializer->getValueKind(),
6317 Initializer->getObjectKind());
6318 Expr *OVEAsExpr = &OVE;
6319 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
6320 TreatUnavailableAsInvalid);
6321 if (!Failed())
6322 AddArrayInitLoopStep(Entity.getType(), InitEltT);
6323 return;
6324 }
6325
6326 // Note: as an GNU C extension, we allow initialization of an
6327 // array from a compound literal that creates an array of the same
6328 // type, so long as the initializer has no side effects.
6329 if (!S.getLangOpts().CPlusPlus && Initializer &&
6330 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6331 Initializer->getType()->isArrayType()) {
6332 const ArrayType *SourceAT
6333 = Context.getAsArrayType(Initializer->getType());
6334 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
6336 else if (Initializer->HasSideEffects(S.Context))
6338 else {
6339 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
6340 }
6341 }
6342 // Note: as a GNU C++ extension, we allow list-initialization of a
6343 // class member of array type from a parenthesized initializer list.
6344 else if (S.getLangOpts().CPlusPlus &&
6346 Initializer && isa<InitListExpr>(Initializer)) {
6347 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
6348 *this, TreatUnavailableAsInvalid);
6350 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6351 Kind.getKind() == InitializationKind::IK_Direct)
6352 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6353 /*VerifyOnly=*/true);
6354 else if (DestAT->getElementType()->isCharType())
6356 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6358 else
6360
6361 return;
6362 }
6363
6364 // Determine whether we should consider writeback conversions for
6365 // Objective-C ARC.
6366 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6367 Entity.isParameterKind();
6368
6369 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
6370 return;
6371
6372 // We're at the end of the line for C: it's either a write-back conversion
6373 // or it's a C assignment. There's no need to check anything else.
6374 if (!S.getLangOpts().CPlusPlus) {
6375 assert(Initializer && "Initializer must be non-null");
6376 // If allowed, check whether this is an Objective-C writeback conversion.
6377 if (allowObjCWritebackConversion &&
6378 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
6379 return;
6380 }
6381
6382 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
6383 return;
6384
6385 // Handle initialization in C
6386 AddCAssignmentStep(DestType);
6387 MaybeProduceObjCObject(S, *this, Entity);
6388 return;
6389 }
6390
6391 assert(S.getLangOpts().CPlusPlus);
6392
6393 // - If the destination type is a (possibly cv-qualified) class type:
6394 if (DestType->isRecordType()) {
6395 // - If the initialization is direct-initialization, or if it is
6396 // copy-initialization where the cv-unqualified version of the
6397 // source type is the same class as, or a derived class of, the
6398 // class of the destination, constructors are considered. [...]
6399 if (Kind.getKind() == InitializationKind::IK_Direct ||
6400 (Kind.getKind() == InitializationKind::IK_Copy &&
6401 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
6402 (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
6403 SourceType, DestType))))) {
6404 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
6405 *this);
6406
6407 // We fall back to the "no matching constructor" path if the
6408 // failed candidate set has functions other than the three default
6409 // constructors. For example, conversion function.
6410 if (const auto *RD =
6411 dyn_cast<CXXRecordDecl>(DestType->getAs<RecordType>()->getDecl());
6412 // In general, we should call isCompleteType for RD to check its
6413 // completeness, we don't call it here as it was already called in the
6414 // above TryConstructorInitialization.
6415 S.getLangOpts().CPlusPlus20 && RD && RD->hasDefinition() &&
6416 RD->isAggregate() && Failed() &&
6418 // Do not attempt paren list initialization if overload resolution
6419 // resolves to a deleted function .
6420 //
6421 // We may reach this condition if we have a union wrapping a class with
6422 // a non-trivial copy or move constructor and we call one of those two
6423 // constructors. The union is an aggregate, but the matched constructor
6424 // is implicitly deleted, so we need to prevent aggregate initialization
6425 // (otherwise, it'll attempt aggregate initialization by initializing
6426 // the first element with a reference to the union).
6429 S, Kind.getLocation(), Best);
6431 // C++20 [dcl.init] 17.6.2.2:
6432 // - Otherwise, if no constructor is viable, the destination type is
6433 // an
6434 // aggregate class, and the initializer is a parenthesized
6435 // expression-list.
6436 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6437 /*VerifyOnly=*/true);
6438 }
6439 }
6440 } else {
6441 // - Otherwise (i.e., for the remaining copy-initialization cases),
6442 // user-defined conversion sequences that can convert from the
6443 // source type to the destination type or (when a conversion
6444 // function is used) to a derived class thereof are enumerated as
6445 // described in 13.3.1.4, and the best one is chosen through
6446 // overload resolution (13.3).
6447 assert(Initializer && "Initializer must be non-null");
6448 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6449 TopLevelOfInitList);
6450 }
6451 return;
6452 }
6453
6454 assert(Args.size() >= 1 && "Zero-argument case handled above");
6455
6456 // For HLSL ext vector types we allow list initialization behavior for C++
6457 // constructor syntax. This is accomplished by converting initialization
6458 // arguments an InitListExpr late.
6459 if (S.getLangOpts().HLSL && Args.size() > 1 && DestType->isExtVectorType() &&
6460 (SourceType.isNull() ||
6461 !Context.hasSameUnqualifiedType(SourceType, DestType))) {
6462
6464 for (auto *Arg : Args) {
6465 if (Arg->getType()->isExtVectorType()) {
6466 const auto *VTy = Arg->getType()->castAs<ExtVectorType>();
6467 unsigned Elm = VTy->getNumElements();
6468 for (unsigned Idx = 0; Idx < Elm; ++Idx) {
6469 InitArgs.emplace_back(new (Context) ArraySubscriptExpr(
6470 Arg,
6472 Context, llvm::APInt(Context.getIntWidth(Context.IntTy), Idx),
6473 Context.IntTy, SourceLocation()),
6474 VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(),
6475 SourceLocation()));
6476 }
6477 } else
6478 InitArgs.emplace_back(Arg);
6479 }
6480 InitListExpr *ILE = new (Context) InitListExpr(
6481 S.getASTContext(), SourceLocation(), InitArgs, SourceLocation());
6482 Args[0] = ILE;
6483 AddListInitializationStep(DestType);
6484 return;
6485 }
6486
6487 // The remaining cases all need a source type.
6488 if (Args.size() > 1) {
6490 return;
6491 } else if (isa<InitListExpr>(Args[0])) {
6493 return;
6494 }
6495
6496 // - Otherwise, if the source type is a (possibly cv-qualified) class
6497 // type, conversion functions are considered.
6498 if (!SourceType.isNull() && SourceType->isRecordType()) {
6499 assert(Initializer && "Initializer must be non-null");
6500 // For a conversion to _Atomic(T) from either T or a class type derived
6501 // from T, initialize the T object then convert to _Atomic type.
6502 bool NeedAtomicConversion = false;
6503 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
6504 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
6505 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
6506 Atomic->getValueType())) {
6507 DestType = Atomic->getValueType();
6508 NeedAtomicConversion = true;
6509 }
6510 }
6511
6512 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6513 TopLevelOfInitList);
6514 MaybeProduceObjCObject(S, *this, Entity);
6515 if (!Failed() && NeedAtomicConversion)
6517 return;
6518 }
6519
6520 // - Otherwise, if the initialization is direct-initialization, the source
6521 // type is std::nullptr_t, and the destination type is bool, the initial
6522 // value of the object being initialized is false.
6523 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
6524 DestType->isBooleanType() &&
6525 Kind.getKind() == InitializationKind::IK_Direct) {
6528 Initializer->isGLValue()),
6529 DestType);
6530 return;
6531 }
6532
6533 // - Otherwise, the initial value of the object being initialized is the
6534 // (possibly converted) value of the initializer expression. Standard
6535 // conversions (Clause 4) will be used, if necessary, to convert the
6536 // initializer expression to the cv-unqualified version of the
6537 // destination type; no user-defined conversions are considered.
6538
6540 = S.TryImplicitConversion(Initializer, DestType,
6541 /*SuppressUserConversions*/true,
6542 Sema::AllowedExplicit::None,
6543 /*InOverloadResolution*/ false,
6544 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
6545 allowObjCWritebackConversion);
6546
6547 if (ICS.isStandard() &&
6549 // Objective-C ARC writeback conversion.
6550
6551 // We should copy unless we're passing to an argument explicitly
6552 // marked 'out'.
6553 bool ShouldCopy = true;
6554 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6555 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6556
6557 // If there was an lvalue adjustment, add it as a separate conversion.
6558 if (ICS.Standard.First == ICK_Array_To_Pointer ||
6561 LvalueICS.setStandard();
6563 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
6564 LvalueICS.Standard.First = ICS.Standard.First;
6565 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
6566 }
6567
6568 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
6569 } else if (ICS.isBad()) {
6570 DeclAccessPair dap;
6573 } else if (Initializer->getType() == Context.OverloadTy &&
6575 false, dap))
6577 else if (Initializer->getType()->isFunctionType() &&
6580 else
6582 } else {
6583 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6584
6585 MaybeProduceObjCObject(S, *this, Entity);
6586 }
6587}
6588
6590 for (auto &S : Steps)
6591 S.Destroy();
6592}
6593
6594//===----------------------------------------------------------------------===//
6595// Perform initialization
6596//===----------------------------------------------------------------------===//
6598getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
6599 switch(Entity.getKind()) {
6605 return Sema::AA_Initializing;
6606
6608 if (Entity.getDecl() &&
6609 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6610 return Sema::AA_Sending;
6611
6612 return Sema::AA_Passing;
6613
6615 if (Entity.getDecl() &&
6616 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6617 return Sema::AA_Sending;
6618
6619 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
6620
6622 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
6623 return Sema::AA_Returning;
6624
6627 // FIXME: Can we tell apart casting vs. converting?
6628 return Sema::AA_Casting;
6629
6631 // This is really initialization, but refer to it as conversion for
6632 // consistency with CheckConvertedConstantExpression.
6633 return Sema::AA_Converting;
6634
6645 return Sema::AA_Initializing;
6646 }
6647
6648 llvm_unreachable("Invalid EntityKind!");
6649}
6650
6651/// Whether we should bind a created object as a temporary when
6652/// initializing the given entity.
6653static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
6654 switch (Entity.getKind()) {
6672 return false;
6673
6679 return true;
6680 }
6681
6682 llvm_unreachable("missed an InitializedEntity kind?");
6683}
6684
6685/// Whether the given entity, when initialized with an object
6686/// created for that initialization, requires destruction.
6687static bool shouldDestroyEntity(const InitializedEntity &Entity) {
6688 switch (Entity.getKind()) {
6699 return false;
6700
6713 return true;
6714 }
6715
6716 llvm_unreachable("missed an InitializedEntity kind?");
6717}
6718
6719/// Get the location at which initialization diagnostics should appear.
6721 Expr *Initializer) {
6722 switch (Entity.getKind()) {
6725 return Entity.getReturnLoc();
6726
6728 return Entity.getThrowLoc();
6729
6732 return Entity.getDecl()->getLocation();
6733
6735 return Entity.getCaptureLoc();
6736
6753 return Initializer->getBeginLoc();
6754 }
6755 llvm_unreachable("missed an InitializedEntity kind?");
6756}
6757
6758/// Make a (potentially elidable) temporary copy of the object
6759/// provided by the given initializer by calling the appropriate copy
6760/// constructor.
6761///
6762/// \param S The Sema object used for type-checking.
6763///
6764/// \param T The type of the temporary object, which must either be
6765/// the type of the initializer expression or a superclass thereof.
6766///
6767/// \param Entity The entity being initialized.
6768///
6769/// \param CurInit The initializer expression.
6770///
6771/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
6772/// is permitted in C++03 (but not C++0x) when binding a reference to
6773/// an rvalue.
6774///
6775/// \returns An expression that copies the initializer expression into
6776/// a temporary object, or an error expression if a copy could not be
6777/// created.
6779 QualType T,
6780 const InitializedEntity &Entity,
6781 ExprResult CurInit,
6782 bool IsExtraneousCopy) {
6783 if (CurInit.isInvalid())
6784 return CurInit;
6785 // Determine which class type we're copying to.
6786 Expr *CurInitExpr = (Expr *)CurInit.get();
6787 CXXRecordDecl *Class = nullptr;
6788 if (const RecordType *Record = T->getAs<RecordType>())
6789 Class = cast<CXXRecordDecl>(Record->getDecl());
6790 if (!Class)
6791 return CurInit;
6792
6793 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
6794
6795 // Make sure that the type we are copying is complete.
6796 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
6797 return CurInit;
6798
6799 // Perform overload resolution using the class's constructors. Per
6800 // C++11 [dcl.init]p16, second bullet for class types, this initialization
6801 // is direct-initialization.
6804
6807 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
6808 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6809 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6810 /*RequireActualConstructor=*/false,
6811 /*SecondStepOfCopyInit=*/true)) {
6812 case OR_Success:
6813 break;
6814
6816 CandidateSet.NoteCandidates(
6818 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
6819 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
6820 : diag::err_temp_copy_no_viable)
6821 << (int)Entity.getKind() << CurInitExpr->getType()
6822 << CurInitExpr->getSourceRange()),
6823 S, OCD_AllCandidates, CurInitExpr);
6824 if (!IsExtraneousCopy || S.isSFINAEContext())
6825 return ExprError();
6826 return CurInit;
6827
6828 case OR_Ambiguous:
6829 CandidateSet.NoteCandidates(
6830 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
6831 << (int)Entity.getKind()
6832 << CurInitExpr->getType()
6833 << CurInitExpr->getSourceRange()),
6834 S, OCD_AmbiguousCandidates, CurInitExpr);
6835 return ExprError();
6836
6837 case OR_Deleted:
6838 S.Diag(Loc, diag::err_temp_copy_deleted)
6839 << (int)Entity.getKind() << CurInitExpr->getType()
6840 << CurInitExpr->getSourceRange();
6841 S.NoteDeletedFunction(Best->Function);
6842 return ExprError();
6843 }
6844
6845 bool HadMultipleCandidates = CandidateSet.size() > 1;
6846
6847 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
6848 SmallVector<Expr*, 8> ConstructorArgs;
6849 CurInit.get(); // Ownership transferred into MultiExprArg, below.
6850
6851 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
6852 IsExtraneousCopy);
6853
6854 if (IsExtraneousCopy) {
6855 // If this is a totally extraneous copy for C++03 reference
6856 // binding purposes, just return the original initialization
6857 // expression. We don't generate an (elided) copy operation here
6858 // because doing so would require us to pass down a flag to avoid
6859 // infinite recursion, where each step adds another extraneous,
6860 // elidable copy.
6861
6862 // Instantiate the default arguments of any extra parameters in
6863 // the selected copy constructor, as if we were going to create a
6864 // proper call to the copy constructor.
6865 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
6866 ParmVarDecl *Parm = Constructor->getParamDecl(I);
6867 if (S.RequireCompleteType(Loc, Parm->getType(),
6868 diag::err_call_incomplete_argument))
6869 break;
6870
6871 // Build the default argument expression; we don't actually care
6872 // if this succeeds or not, because this routine will complain
6873 // if there was a problem.
6874 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
6875 }
6876
6877 return CurInitExpr;
6878 }
6879
6880 // Determine the arguments required to actually perform the
6881 // constructor call (we might have derived-to-base conversions, or
6882 // the copy constructor may have default arguments).
6883 if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
6884 ConstructorArgs))
6885 return ExprError();
6886
6887 // C++0x [class.copy]p32:
6888 // When certain criteria are met, an implementation is allowed to
6889 // omit the copy/move construction of a class object, even if the
6890 // copy/move constructor and/or destructor for the object have
6891 // side effects. [...]
6892 // - when a temporary class object that has not been bound to a
6893 // reference (12.2) would be copied/moved to a class object
6894 // with the same cv-unqualified type, the copy/move operation
6895 // can be omitted by constructing the temporary object
6896 // directly into the target of the omitted copy/move
6897 //
6898 // Note that the other three bullets are handled elsewhere. Copy
6899 // elision for return statements and throw expressions are handled as part
6900 // of constructor initialization, while copy elision for exception handlers
6901 // is handled by the run-time.
6902 //
6903 // FIXME: If the function parameter is not the same type as the temporary, we
6904 // should still be able to elide the copy, but we don't have a way to
6905 // represent in the AST how much should be elided in this case.
6906 bool Elidable =
6907 CurInitExpr->isTemporaryObject(S.Context, Class) &&
6909 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
6910 CurInitExpr->getType());
6911
6912 // Actually perform the constructor call.
6913 CurInit = S.BuildCXXConstructExpr(
6914 Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,
6915 HadMultipleCandidates,
6916 /*ListInit*/ false,
6917 /*StdInitListInit*/ false,
6918 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
6919
6920 // If we're supposed to bind temporaries, do so.
6921 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
6922 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6923 return CurInit;
6924}
6925
6926/// Check whether elidable copy construction for binding a reference to
6927/// a temporary would have succeeded if we were building in C++98 mode, for
6928/// -Wc++98-compat.
6930 const InitializedEntity &Entity,
6931 Expr *CurInitExpr) {
6932 assert(S.getLangOpts().CPlusPlus11);
6933
6934 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
6935 if (!Record)
6936 return;
6937
6938 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
6939 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
6940 return;
6941
6942 // Find constructors which would have been considered.
6945 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
6946
6947 // Perform overload resolution.
6950 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
6951 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6952 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6953 /*RequireActualConstructor=*/false,
6954 /*SecondStepOfCopyInit=*/true);
6955
6956 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
6957 << OR << (int)Entity.getKind() << CurInitExpr->getType()
6958 << CurInitExpr->getSourceRange();
6959
6960 switch (OR) {
6961 case OR_Success:
6962 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
6963 Best->FoundDecl, Entity, Diag);
6964 // FIXME: Check default arguments as far as that's possible.
6965 break;
6966
6968 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6969 OCD_AllCandidates, CurInitExpr);
6970 break;
6971
6972 case OR_Ambiguous:
6973 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6974 OCD_AmbiguousCandidates, CurInitExpr);
6975 break;
6976
6977 case OR_Deleted:
6978 S.Diag(Loc, Diag);
6979 S.NoteDeletedFunction(Best->Function);
6980 break;
6981 }
6982}
6983
6984void InitializationSequence::PrintInitLocationNote(Sema &S,
6985 const InitializedEntity &Entity) {
6986 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
6987 if (Entity.getDecl()->getLocation().isInvalid())
6988 return;
6989
6990 if (Entity.getDecl()->getDeclName())
6991 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
6992 << Entity.getDecl()->getDeclName();
6993 else
6994 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
6995 }
6996 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
6997 Entity.getMethodDecl())
6998 S.Diag(Entity.getMethodDecl()->getLocation(),
6999 diag::note_method_return_type_change)
7000 << Entity.getMethodDecl()->getDeclName();
7001}
7002
7003/// Returns true if the parameters describe a constructor initialization of
7004/// an explicit temporary object, e.g. "Point(x, y)".
7005static bool isExplicitTemporary(const InitializedEntity &Entity,
7006 const InitializationKind &Kind,
7007 unsigned NumArgs) {
7008 switch (Entity.getKind()) {
7012 break;
7013 default:
7014 return false;
7015 }
7016
7017 switch (Kind.getKind()) {
7019 return true;
7020 // FIXME: Hack to work around cast weirdness.
7023 return NumArgs != 1;
7024 default:
7025 return false;
7026 }
7027}
7028
7029static ExprResult
7031 const InitializedEntity &Entity,
7032 const InitializationKind &Kind,
7033 MultiExprArg Args,
7034 const InitializationSequence::Step& Step,
7035 bool &ConstructorInitRequiresZeroInit,
7036 bool IsListInitialization,
7037 bool IsStdInitListInitialization,
7038 SourceLocation LBraceLoc,
7039 SourceLocation RBraceLoc) {
7040 unsigned NumArgs = Args.size();
7041 CXXConstructorDecl *Constructor
7042 = cast<CXXConstructorDecl>(Step.Function.Function);
7043 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7044
7045 // Build a call to the selected constructor.
7046 SmallVector<Expr*, 8> ConstructorArgs;
7047 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7048 ? Kind.getEqualLoc()
7049 : Kind.getLocation();
7050
7051 if (Kind.getKind() == InitializationKind::IK_Default) {
7052 // Force even a trivial, implicit default constructor to be
7053 // semantically checked. We do this explicitly because we don't build
7054 // the definition for completely trivial constructors.
7055 assert(Constructor->getParent() && "No parent class for constructor.");
7056 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7057 Constructor->isTrivial() && !Constructor->isUsed(false)) {
7058 S.runWithSufficientStackSpace(Loc, [&] {
7059 S.DefineImplicitDefaultConstructor(Loc, Constructor);
7060 });
7061 }
7062 }
7063
7064 ExprResult CurInit((Expr *)nullptr);
7065
7066 // C++ [over.match.copy]p1:
7067 // - When initializing a temporary to be bound to the first parameter
7068 // of a constructor that takes a reference to possibly cv-qualified
7069 // T as its first argument, called with a single argument in the
7070 // context of direct-initialization, explicit conversion functions
7071 // are also considered.
7072 bool AllowExplicitConv =
7073 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7076
7077 // Determine the arguments required to actually perform the constructor
7078 // call.
7079 if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
7080 ConstructorArgs, AllowExplicitConv,
7081 IsListInitialization))
7082 return ExprError();
7083
7084 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7085 // An explicitly-constructed temporary, e.g., X(1, 2).
7086 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7087 return ExprError();
7088
7089 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7090 if (!TSInfo)
7091 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
7092 SourceRange ParenOrBraceRange =
7093 (Kind.getKind() == InitializationKind::IK_DirectList)
7094 ? SourceRange(LBraceLoc, RBraceLoc)
7095 : Kind.getParenOrBraceRange();
7096
7097 CXXConstructorDecl *CalleeDecl = Constructor;
7098 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7099 Step.Function.FoundDecl.getDecl())) {
7100 CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
7101 }
7102 S.MarkFunctionReferenced(Loc, CalleeDecl);
7103
7104 CurInit = S.CheckForImmediateInvocation(
7106 S.Context, CalleeDecl,
7107 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7108 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7109 IsListInitialization, IsStdInitListInitialization,
7110 ConstructorInitRequiresZeroInit),
7111 CalleeDecl);
7112 } else {
7114
7115 if (Entity.getKind() == InitializedEntity::EK_Base) {
7116 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7119 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7120 ConstructKind = CXXConstructionKind::Delegating;
7121 }
7122
7123 // Only get the parenthesis or brace range if it is a list initialization or
7124 // direct construction.
7125 SourceRange ParenOrBraceRange;
7126 if (IsListInitialization)
7127 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7128 else if (Kind.getKind() == InitializationKind::IK_Direct)
7129 ParenOrBraceRange = Kind.getParenOrBraceRange();
7130
7131 // If the entity allows NRVO, mark the construction as elidable
7132 // unconditionally.
7133 if (Entity.allowsNRVO())
7134 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7135 Step.Function.FoundDecl,
7136 Constructor, /*Elidable=*/true,
7137 ConstructorArgs,
7138 HadMultipleCandidates,
7139 IsListInitialization,
7140 IsStdInitListInitialization,
7141 ConstructorInitRequiresZeroInit,
7142 ConstructKind,
7143 ParenOrBraceRange);
7144 else
7145 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7146 Step.Function.FoundDecl,
7147 Constructor,
7148 ConstructorArgs,
7149 HadMultipleCandidates,
7150 IsListInitialization,
7151 IsStdInitListInitialization,
7152 ConstructorInitRequiresZeroInit,
7153 ConstructKind,
7154 ParenOrBraceRange);
7155 }
7156 if (CurInit.isInvalid())
7157 return ExprError();
7158
7159 // Only check access if all of that succeeded.
7160 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
7161 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7162 return ExprError();
7163
7164 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
7166 return ExprError();
7167
7168 if (shouldBindAsTemporary(Entity))
7169 CurInit = S.MaybeBindToTemporary(CurInit.get());
7170
7171 return CurInit;
7172}
7173
7174namespace {
7175enum LifetimeKind {
7176 /// The lifetime of a temporary bound to this entity ends at the end of the
7177 /// full-expression, and that's (probably) fine.
7178 LK_FullExpression,
7179
7180 /// The lifetime of a temporary bound to this entity is extended to the
7181 /// lifeitme of the entity itself.
7182 LK_Extended,
7183
7184 /// The lifetime of a temporary bound to this entity probably ends too soon,
7185 /// because the entity is allocated in a new-expression.
7186 LK_New,
7187
7188 /// The lifetime of a temporary bound to this entity ends too soon, because
7189 /// the entity is a return object.
7190 LK_Return,
7191
7192 /// The lifetime of a temporary bound to this entity ends too soon, because
7193 /// the entity is the result of a statement expression.
7194 LK_StmtExprResult,
7195
7196 /// This is a mem-initializer: if it would extend a temporary (other than via
7197 /// a default member initializer), the program is ill-formed.
7198 LK_MemInitializer,
7199};
7200using LifetimeResult =
7201 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
7202}
7203
7204/// Determine the declaration which an initialized entity ultimately refers to,
7205/// for the purpose of lifetime-extending a temporary bound to a reference in
7206/// the initialization of \p Entity.
7207static LifetimeResult getEntityLifetime(
7208 const InitializedEntity *Entity,
7209 const InitializedEntity *InitField = nullptr) {
7210 // C++11 [class.temporary]p5:
7211 switch (Entity->getKind()) {
7213 // The temporary [...] persists for the lifetime of the reference
7214 return {Entity, LK_Extended};
7215
7217 // For subobjects, we look at the complete object.
7218 if (Entity->getParent())
7219 return getEntityLifetime(Entity->getParent(), Entity);
7220
7221 // except:
7222 // C++17 [class.base.init]p8:
7223 // A temporary expression bound to a reference member in a
7224 // mem-initializer is ill-formed.
7225 // C++17 [class.base.init]p11:
7226 // A temporary expression bound to a reference member from a
7227 // default member initializer is ill-formed.
7228 //
7229 // The context of p11 and its example suggest that it's only the use of a
7230 // default member initializer from a constructor that makes the program
7231 // ill-formed, not its mere existence, and that it can even be used by
7232 // aggregate initialization.
7233 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
7234 : LK_MemInitializer};
7235
7237 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
7238 // type.
7239 return {Entity, LK_Extended};
7240
7243 // -- A temporary bound to a reference parameter in a function call
7244 // persists until the completion of the full-expression containing
7245 // the call.
7246 return {nullptr, LK_FullExpression};
7247
7249 // FIXME: This will always be ill-formed; should we eagerly diagnose it here?
7250 return {nullptr, LK_FullExpression};
7251
7253 // -- The lifetime of a temporary bound to the returned value in a
7254 // function return statement is not extended; the temporary is
7255 // destroyed at the end of the full-expression in the return statement.
7256 return {nullptr, LK_Return};
7257
7259 // FIXME: Should we lifetime-extend through the result of a statement
7260 // expression?
7261 return {nullptr, LK_StmtExprResult};
7262
7264 // -- A temporary bound to a reference in a new-initializer persists
7265 // until the completion of the full-expression containing the
7266 // new-initializer.
7267 return {nullptr, LK_New};
7268
7272 // We don't yet know the storage duration of the surrounding temporary.
7273 // Assume it's got full-expression duration for now, it will patch up our
7274 // storage duration if that's not correct.
7275 return {nullptr, LK_FullExpression};
7276
7278 // For subobjects, we look at the complete object.
7279 return getEntityLifetime(Entity->getParent(), InitField);
7280
7282 // For subobjects, we look at the complete object.
7283 if (Entity->getParent())
7284 return getEntityLifetime(Entity->getParent(), InitField);
7285 return {InitField, LK_MemInitializer};
7286
7288 // We can reach this case for aggregate initialization in a constructor:
7289 // struct A { int &&r; };
7290 // struct B : A { B() : A{0} {} };
7291 // In this case, use the outermost field decl as the context.
7292 return {InitField, LK_MemInitializer};
7293
7299 return {nullptr, LK_FullExpression};
7300
7302 // FIXME: Can we diagnose lifetime problems with exceptions?
7303 return {nullptr, LK_FullExpression};
7304
7306 // -- A temporary object bound to a reference element of an aggregate of
7307 // class type initialized from a parenthesized expression-list
7308 // [dcl.init, 9.3] persists until the completion of the full-expression
7309 // containing the expression-list.
7310 return {nullptr, LK_FullExpression};
7311 }
7312
7313 llvm_unreachable("unknown entity kind");
7314}
7315
7316namespace {
7317enum ReferenceKind {
7318 /// Lifetime would be extended by a reference binding to a temporary.
7319 RK_ReferenceBinding,
7320 /// Lifetime would be extended by a std::initializer_list object binding to
7321 /// its backing array.
7322 RK_StdInitializerList,
7323};
7324
7325/// A temporary or local variable. This will be one of:
7326/// * A MaterializeTemporaryExpr.
7327/// * A DeclRefExpr whose declaration is a local.
7328/// * An AddrLabelExpr.
7329/// * A BlockExpr for a block with captures.
7330using Local = Expr*;
7331
7332/// Expressions we stepped over when looking for the local state. Any steps
7333/// that would inhibit lifetime extension or take us out of subexpressions of
7334/// the initializer are included.
7335struct IndirectLocalPathEntry {
7336 enum EntryKind {
7337 DefaultInit,
7338 AddressOf,
7339 VarInit,
7340 LValToRVal,
7341 LifetimeBoundCall,
7342 TemporaryCopy,
7343 LambdaCaptureInit,
7344 GslReferenceInit,
7345 GslPointerInit
7346 } Kind;
7347 Expr *E;
7348 union {
7349 const Decl *D = nullptr;
7350 const LambdaCapture *Capture;
7351 };
7352 IndirectLocalPathEntry() {}
7353 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
7354 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
7355 : Kind(K), E(E), D(D) {}
7356 IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture)
7357 : Kind(K), E(E), Capture(Capture) {}
7358};
7359
7360using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
7361
7362struct RevertToOldSizeRAII {
7363 IndirectLocalPath &Path;
7364 unsigned OldSize = Path.size();
7365 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
7366 ~RevertToOldSizeRAII() { Path.resize(OldSize); }
7367};
7368
7369using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
7370 ReferenceKind RK)>;
7371}
7372
7373static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
7374 for (auto E : Path)
7375 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
7376 return true;
7377 return false;
7378}
7379
7380static bool pathContainsInit(IndirectLocalPath &Path) {
7381 return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
7382 return E.Kind == IndirectLocalPathEntry::DefaultInit ||
7383 E.Kind == IndirectLocalPathEntry::VarInit;
7384 });
7385}
7386
7387static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7388 Expr *Init, LocalVisitor Visit,
7389 bool RevisitSubinits,
7390 bool EnableLifetimeWarnings);
7391
7392static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7393 Expr *Init, ReferenceKind RK,
7394 LocalVisitor Visit,
7395 bool EnableLifetimeWarnings);
7396
7397template <typename T> static bool isRecordWithAttr(QualType Type) {
7398 if (auto *RD = Type->getAsCXXRecordDecl())
7399 return RD->hasAttr<T>();
7400 return false;
7401}
7402
7403// Decl::isInStdNamespace will return false for iterators in some STL
7404// implementations due to them being defined in a namespace outside of the std
7405// namespace.
7406static bool isInStlNamespace(const Decl *D) {
7407 const DeclContext *DC = D->getDeclContext();
7408 if (!DC)
7409 return false;
7410 if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
7411 if (const IdentifierInfo *II = ND->getIdentifier()) {
7412 StringRef Name = II->getName();
7413 if (Name.size() >= 2 && Name.front() == '_' &&
7414 (Name[1] == '_' || isUppercase(Name[1])))
7415 return true;
7416 }
7417
7418 return DC->isStdNamespace();
7419}
7420
7422 if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee))
7423 if (isRecordWithAttr<PointerAttr>(Conv->getConversionType()))
7424 return true;
7425 if (!isInStlNamespace(Callee->getParent()))
7426 return false;
7427 if (!isRecordWithAttr<PointerAttr>(
7428 Callee->getFunctionObjectParameterType()) &&
7429 !isRecordWithAttr<OwnerAttr>(Callee->getFunctionObjectParameterType()))
7430 return false;
7431 if (Callee->getReturnType()->isPointerType() ||
7432 isRecordWithAttr<PointerAttr>(Callee->getReturnType())) {
7433 if (!Callee->getIdentifier())
7434 return false;
7435 return llvm::StringSwitch<bool>(Callee->getName())
7436 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
7437 .Cases("end", "rend", "cend", "crend", true)
7438 .Cases("c_str", "data", "get", true)
7439 // Map and set types.
7440 .Cases("find", "equal_range", "lower_bound", "upper_bound", true)
7441 .Default(false);
7442 } else if (Callee->getReturnType()->isReferenceType()) {
7443 if (!Callee->getIdentifier()) {
7444 auto OO = Callee->getOverloadedOperator();
7445 return OO == OverloadedOperatorKind::OO_Subscript ||
7446 OO == OverloadedOperatorKind::OO_Star;
7447 }
7448 return llvm::StringSwitch<bool>(Callee->getName())
7449 .Cases("front", "back", "at", "top", "value", true)
7450 .Default(false);
7451 }
7452 return false;
7453}
7454
7456 if (!FD->getIdentifier() || FD->getNumParams() != 1)
7457 return false;
7458 const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl();
7459 if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace())
7460 return false;
7461 if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) &&
7462 !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0)))
7463 return false;
7464 if (FD->getReturnType()->isPointerType() ||
7465 isRecordWithAttr<PointerAttr>(FD->getReturnType())) {
7466 return llvm::StringSwitch<bool>(FD->getName())
7467 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
7468 .Cases("end", "rend", "cend", "crend", true)
7469 .Case("data", true)
7470 .Default(false);
7471 } else if (FD->getReturnType()->isReferenceType()) {
7472 return llvm::StringSwitch<bool>(FD->getName())
7473 .Cases("get", "any_cast", true)
7474 .Default(false);
7475 }
7476 return false;
7477}
7478
7479static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
7480 LocalVisitor Visit) {
7481 auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) {
7482 // We are not interested in the temporary base objects of gsl Pointers:
7483 // Temp().ptr; // Here ptr might not dangle.
7484 if (isa<MemberExpr>(Arg->IgnoreImpCasts()))
7485 return;
7486 // Once we initialized a value with a reference, it can no longer dangle.
7487 if (!Value) {
7488 for (const IndirectLocalPathEntry &PE : llvm::reverse(Path)) {
7489 if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit)
7490 continue;
7491 if (PE.Kind == IndirectLocalPathEntry::GslPointerInit)
7492 return;
7493 break;
7494 }
7495 }
7496 Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit
7497 : IndirectLocalPathEntry::GslReferenceInit,
7498 Arg, D});
7499 if (Arg->isGLValue())
7500 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
7501 Visit,
7502 /*EnableLifetimeWarnings=*/true);
7503 else
7504 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7505 /*EnableLifetimeWarnings=*/true);
7506 Path.pop_back();
7507 };
7508
7509 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
7510 const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee());
7511 if (MD && shouldTrackImplicitObjectArg(MD))
7512 VisitPointerArg(MD, MCE->getImplicitObjectArgument(),
7513 !MD->getReturnType()->isReferenceType());
7514 return;
7515 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) {
7516 FunctionDecl *Callee = OCE->getDirectCallee();
7517 if (Callee && Callee->isCXXInstanceMember() &&
7518 shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee)))
7519 VisitPointerArg(Callee, OCE->getArg(0),
7520 !Callee->getReturnType()->isReferenceType());
7521 return;
7522 } else if (auto *CE = dyn_cast<CallExpr>(Call)) {
7523 FunctionDecl *Callee = CE->getDirectCallee();
7524 if (Callee && shouldTrackFirstArgument(Callee))
7525 VisitPointerArg(Callee, CE->getArg(0),
7526 !Callee->getReturnType()->isReferenceType());
7527 return;
7528 }
7529
7530 if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) {
7531 const auto *Ctor = CCE->getConstructor();
7532 const CXXRecordDecl *RD = Ctor->getParent();
7533 if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>())
7534 VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true);
7535 }
7536}
7537
7539 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7540 if (!TSI)
7541 return false;
7542 // Don't declare this variable in the second operand of the for-statement;
7543 // GCC miscompiles that by ending its lifetime before evaluating the
7544 // third operand. See gcc.gnu.org/PR86769.
7546 for (TypeLoc TL = TSI->getTypeLoc();
7547 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7548 TL = ATL.getModifiedLoc()) {
7549 if (ATL.getAttrAs<LifetimeBoundAttr>())
7550 return true;
7551 }
7552
7553 // Assume that all assignment operators with a "normal" return type return
7554 // *this, that is, an lvalue reference that is the same type as the implicit
7555 // object parameter (or the LHS for a non-member operator$=).
7557 if (OO == OO_Equal || isCompoundAssignmentOperator(OO)) {
7558 QualType RetT = FD->getReturnType();
7559 if (RetT->isLValueReferenceType()) {
7560 ASTContext &Ctx = FD->getASTContext();
7561 QualType LHST;
7562 auto *MD = dyn_cast<CXXMethodDecl>(FD);
7563 if (MD && MD->isCXXInstanceMember())
7564 LHST = Ctx.getLValueReferenceType(MD->getFunctionObjectParameterType());
7565 else
7566 LHST = MD->getParamDecl(0)->getType();
7567 if (Ctx.hasSameType(RetT, LHST))
7568 return true;
7569 }
7570 }
7571
7572 return false;
7573}
7574
7575static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
7576 LocalVisitor Visit) {
7577 const FunctionDecl *Callee;
7578 ArrayRef<Expr*> Args;
7579
7580 if (auto *CE = dyn_cast<CallExpr>(Call)) {
7581 Callee = CE->getDirectCallee();
7582 Args = llvm::ArrayRef(CE->getArgs(), CE->getNumArgs());
7583 } else {
7584 auto *CCE = cast<CXXConstructExpr>(Call);
7585 Callee = CCE->getConstructor();
7586 Args = llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs());
7587 }
7588 if (!Callee)
7589 return;
7590
7591 Expr *ObjectArg = nullptr;
7592 if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
7593 ObjectArg = Args[0];
7594 Args = Args.slice(1);
7595 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
7596 ObjectArg = MCE->getImplicitObjectArgument();
7597 }
7598
7599 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
7600 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
7601 if (Arg->isGLValue())
7602 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
7603 Visit,
7604 /*EnableLifetimeWarnings=*/false);
7605 else
7606 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7607 /*EnableLifetimeWarnings=*/false);
7608 Path.pop_back();
7609 };
7610
7611 bool CheckCoroCall = false;
7612 if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
7613 CheckCoroCall = RD->hasAttr<CoroLifetimeBoundAttr>() &&
7614 RD->hasAttr<CoroReturnTypeAttr>() &&
7615 !Callee->hasAttr<CoroDisableLifetimeBoundAttr>();
7616 }
7617
7618 if (ObjectArg) {
7619 bool CheckCoroObjArg = CheckCoroCall;
7620 // Coroutine lambda objects with empty capture list are not lifetimebound.
7621 if (auto *LE = dyn_cast<LambdaExpr>(ObjectArg->IgnoreImplicit());
7622 LE && LE->captures().empty())
7623 CheckCoroObjArg = false;
7624 // Allow `get_return_object()` as the object param (__promise) is not
7625 // lifetimebound.
7626 if (Sema::CanBeGetReturnObject(Callee))
7627 CheckCoroObjArg = false;
7628 if (implicitObjectParamIsLifetimeBound(Callee) || CheckCoroObjArg)
7629 VisitLifetimeBoundArg(Callee, ObjectArg);
7630 }
7631
7632 for (unsigned I = 0,
7633 N = std::min<unsigned>(Callee->getNumParams(), Args.size());
7634 I != N; ++I) {
7635 if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
7636 VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
7637 }
7638}
7639
7640/// Visit the locals that would be reachable through a reference bound to the
7641/// glvalue expression \c Init.
7642static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7643 Expr *Init, ReferenceKind RK,
7644 LocalVisitor Visit,
7645 bool EnableLifetimeWarnings) {
7646 RevertToOldSizeRAII RAII(Path);
7647
7648 // Walk past any constructs which we can lifetime-extend across.
7649 Expr *Old;
7650 do {
7651 Old = Init;
7652
7653 if (auto *FE = dyn_cast<FullExpr>(Init))
7654 Init = FE->getSubExpr();
7655
7656 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7657 // If this is just redundant braces around an initializer, step over it.
7658 if (ILE->isTransparent())
7659 Init = ILE->getInit(0);
7660 }
7661
7662 // Step over any subobject adjustments; we may have a materialized
7663 // temporary inside them.
7664 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7665
7666 // Per current approach for DR1376, look through casts to reference type
7667 // when performing lifetime extension.
7668 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
7669 if (CE->getSubExpr()->isGLValue())
7670 Init = CE->getSubExpr();
7671
7672 // Per the current approach for DR1299, look through array element access
7673 // on array glvalues when performing lifetime extension.
7674 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
7675 Init = ASE->getBase();
7676 auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
7677 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
7678 Init = ICE->getSubExpr();
7679 else
7680 // We can't lifetime extend through this but we might still find some
7681 // retained temporaries.
7682 return visitLocalsRetainedByInitializer(Path, Init, Visit, true,
7683 EnableLifetimeWarnings);
7684 }
7685
7686 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7687 // constructor inherits one as an implicit mem-initializer.
7688 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7689 Path.push_back(
7690 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7691 Init = DIE->getExpr();
7692 }
7693 } while (Init != Old);
7694
7695 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
7696 if (Visit(Path, Local(MTE), RK))
7697 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true,
7698 EnableLifetimeWarnings);
7699 }
7700
7701 if (isa<CallExpr>(Init)) {
7702 if (EnableLifetimeWarnings)
7703 handleGslAnnotatedTypes(Path, Init, Visit);
7704 return visitLifetimeBoundArguments(Path, Init, Visit);
7705 }
7706
7707 switch (Init->getStmtClass()) {
7708 case Stmt::DeclRefExprClass: {
7709 // If we find the name of a local non-reference parameter, we could have a
7710 // lifetime problem.
7711 auto *DRE = cast<DeclRefExpr>(Init);
7712 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7713 if (VD && VD->hasLocalStorage() &&
7714 !DRE->refersToEnclosingVariableOrCapture()) {
7715 if (!VD->getType()->isReferenceType()) {
7716 Visit(Path, Local(DRE), RK);
7717 } else if (isa<ParmVarDecl>(DRE->getDecl())) {
7718 // The lifetime of a reference parameter is unknown; assume it's OK
7719 // for now.
7720 break;
7721 } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
7722 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7723 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
7724 RK_ReferenceBinding, Visit,
7725 EnableLifetimeWarnings);
7726 }
7727 }
7728 break;
7729 }
7730
7731 case Stmt::UnaryOperatorClass: {
7732 // The only unary operator that make sense to handle here
7733 // is Deref. All others don't resolve to a "name." This includes
7734 // handling all sorts of rvalues passed to a unary operator.
7735 const UnaryOperator *U = cast<UnaryOperator>(Init);
7736 if (U->getOpcode() == UO_Deref)
7737 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true,
7738 EnableLifetimeWarnings);
7739 break;
7740 }
7741
7742 case Stmt::OMPArraySectionExprClass: {
7744 cast<OMPArraySectionExpr>(Init)->getBase(),
7745 Visit, true, EnableLifetimeWarnings);
7746 break;
7747 }
7748
7749 case Stmt::ConditionalOperatorClass:
7750 case Stmt::BinaryConditionalOperatorClass: {
7751 auto *C = cast<AbstractConditionalOperator>(Init);
7752 if (!C->getTrueExpr()->getType()->isVoidType())
7753 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit,
7754 EnableLifetimeWarnings);
7755 if (!C->getFalseExpr()->getType()->isVoidType())
7756 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit,
7757 EnableLifetimeWarnings);
7758 break;
7759 }
7760
7761 case Stmt::CompoundLiteralExprClass: {
7762 if (auto *CLE = dyn_cast<CompoundLiteralExpr>(Init)) {
7763 if (!CLE->isFileScope())
7764 Visit(Path, Local(CLE), RK);
7765 }
7766 break;
7767 }
7768
7769 // FIXME: Visit the left-hand side of an -> or ->*.
7770
7771 default:
7772 break;
7773 }
7774}
7775
7776/// Visit the locals that would be reachable through an object initialized by
7777/// the prvalue expression \c Init.
7778static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7779 Expr *Init, LocalVisitor Visit,
7780 bool RevisitSubinits,
7781 bool EnableLifetimeWarnings) {
7782 RevertToOldSizeRAII RAII(Path);
7783
7784 Expr *Old;
7785 do {
7786 Old = Init;
7787
7788 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7789 // constructor inherits one as an implicit mem-initializer.
7790 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7791 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7792 Init = DIE->getExpr();
7793 }
7794
7795 if (auto *FE = dyn_cast<FullExpr>(Init))
7796 Init = FE->getSubExpr();
7797
7798 // Dig out the expression which constructs the extended temporary.
7799 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7800
7801 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
7802 Init = BTE->getSubExpr();
7803
7804 Init = Init->IgnoreParens();
7805
7806 // Step over value-preserving rvalue casts.
7807 if (auto *CE = dyn_cast<CastExpr>(Init)) {
7808 switch (CE->getCastKind()) {
7809 case CK_LValueToRValue:
7810 // If we can match the lvalue to a const object, we can look at its
7811 // initializer.
7812 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
7814 Path, Init, RK_ReferenceBinding,
7815 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
7816 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
7817 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7818 if (VD && VD->getType().isConstQualified() && VD->getInit() &&
7819 !isVarOnPath(Path, VD)) {
7820 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7821 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true,
7822 EnableLifetimeWarnings);
7823 }
7824 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
7825 if (MTE->getType().isConstQualified())
7826 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit,
7827 true, EnableLifetimeWarnings);
7828 }
7829 return false;
7830 }, EnableLifetimeWarnings);
7831
7832 // We assume that objects can be retained by pointers cast to integers,
7833 // but not if the integer is cast to floating-point type or to _Complex.
7834 // We assume that casts to 'bool' do not preserve enough information to
7835 // retain a local object.
7836 case CK_NoOp:
7837 case CK_BitCast:
7838 case CK_BaseToDerived:
7839 case CK_DerivedToBase:
7840 case CK_UncheckedDerivedToBase:
7841 case CK_Dynamic:
7842 case CK_ToUnion:
7843 case CK_UserDefinedConversion:
7844 case CK_ConstructorConversion:
7845 case CK_IntegralToPointer:
7846 case CK_PointerToIntegral:
7847 case CK_VectorSplat:
7848 case CK_IntegralCast:
7849 case CK_CPointerToObjCPointerCast:
7850 case CK_BlockPointerToObjCPointerCast:
7851 case CK_AnyPointerToBlockPointerCast:
7852 case CK_AddressSpaceConversion:
7853 break;
7854
7855 case CK_ArrayToPointerDecay:
7856 // Model array-to-pointer decay as taking the address of the array
7857 // lvalue.
7858 Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
7859 return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
7860 RK_ReferenceBinding, Visit,
7861 EnableLifetimeWarnings);
7862
7863 default:
7864 return;
7865 }
7866
7867 Init = CE->getSubExpr();
7868 }
7869 } while (Old != Init);
7870
7871 // C++17 [dcl.init.list]p6:
7872 // initializing an initializer_list object from the array extends the
7873 // lifetime of the array exactly like binding a reference to a temporary.
7874 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
7875 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
7876 RK_StdInitializerList, Visit,
7877 EnableLifetimeWarnings);
7878
7879 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7880 // We already visited the elements of this initializer list while
7881 // performing the initialization. Don't visit them again unless we've
7882 // changed the lifetime of the initialized entity.
7883 if (!RevisitSubinits)
7884 return;
7885
7886 if (ILE->isTransparent())
7887 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
7888 RevisitSubinits,
7889 EnableLifetimeWarnings);
7890
7891 if (ILE->getType()->isArrayType()) {
7892 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
7893 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
7894 RevisitSubinits,
7895 EnableLifetimeWarnings);
7896 return;
7897 }
7898
7899 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
7900 assert(RD->isAggregate() && "aggregate init on non-aggregate");
7901
7902 // If we lifetime-extend a braced initializer which is initializing an
7903 // aggregate, and that aggregate contains reference members which are
7904 // bound to temporaries, those temporaries are also lifetime-extended.
7905 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
7908 RK_ReferenceBinding, Visit,
7909 EnableLifetimeWarnings);
7910 else {
7911 unsigned Index = 0;
7912 for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
7913 visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
7914 RevisitSubinits,
7915 EnableLifetimeWarnings);
7916 for (const auto *I : RD->fields()) {
7917 if (Index >= ILE->getNumInits())
7918 break;
7919 if (I->isUnnamedBitfield())
7920 continue;
7921 Expr *SubInit = ILE->getInit(Index);
7922 if (I->getType()->isReferenceType())
7924 RK_ReferenceBinding, Visit,
7925 EnableLifetimeWarnings);
7926 else
7927 // This might be either aggregate-initialization of a member or
7928 // initialization of a std::initializer_list object. Regardless,
7929 // we should recursively lifetime-extend that initializer.
7930 visitLocalsRetainedByInitializer(Path, SubInit, Visit,
7931 RevisitSubinits,
7932 EnableLifetimeWarnings);
7933 ++Index;
7934 }
7935 }
7936 }
7937 return;
7938 }
7939
7940 // The lifetime of an init-capture is that of the closure object constructed
7941 // by a lambda-expression.
7942 if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
7943 LambdaExpr::capture_iterator CapI = LE->capture_begin();
7944 for (Expr *E : LE->capture_inits()) {
7945 assert(CapI != LE->capture_end());
7946 const LambdaCapture &Cap = *CapI++;
7947 if (!E)
7948 continue;
7949 if (Cap.capturesVariable())
7950 Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap});
7951 if (E->isGLValue())
7952 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
7953 Visit, EnableLifetimeWarnings);
7954 else
7955 visitLocalsRetainedByInitializer(Path, E, Visit, true,
7956 EnableLifetimeWarnings);
7957 if (Cap.capturesVariable())
7958 Path.pop_back();
7959 }
7960 }
7961
7962 // Assume that a copy or move from a temporary references the same objects
7963 // that the temporary does.
7964 if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
7965 if (CCE->getConstructor()->isCopyOrMoveConstructor()) {
7966 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) {
7967 Expr *Arg = MTE->getSubExpr();
7968 Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg,
7969 CCE->getConstructor()});
7970 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7971 /*EnableLifetimeWarnings*/false);
7972 Path.pop_back();
7973 }
7974 }
7975 }
7976
7977 if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) {
7978 if (EnableLifetimeWarnings)
7979 handleGslAnnotatedTypes(Path, Init, Visit);
7980 return visitLifetimeBoundArguments(Path, Init, Visit);
7981 }
7982
7983 switch (Init->getStmtClass()) {
7984 case Stmt::UnaryOperatorClass: {
7985 auto *UO = cast<UnaryOperator>(Init);
7986 // If the initializer is the address of a local, we could have a lifetime
7987 // problem.
7988 if (UO->getOpcode() == UO_AddrOf) {
7989 // If this is &rvalue, then it's ill-formed and we have already diagnosed
7990 // it. Don't produce a redundant warning about the lifetime of the
7991 // temporary.
7992 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
7993 return;
7994
7995 Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
7996 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
7997 RK_ReferenceBinding, Visit,
7998 EnableLifetimeWarnings);
7999 }
8000 break;
8001 }
8002
8003 case Stmt::BinaryOperatorClass: {
8004 // Handle pointer arithmetic.
8005 auto *BO = cast<BinaryOperator>(Init);
8006 BinaryOperatorKind BOK = BO->getOpcode();
8007 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
8008 break;
8009
8010 if (BO->getLHS()->getType()->isPointerType())
8011 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true,
8012 EnableLifetimeWarnings);
8013 else if (BO->getRHS()->getType()->isPointerType())
8014 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true,
8015 EnableLifetimeWarnings);
8016 break;
8017 }
8018
8019 case Stmt::ConditionalOperatorClass:
8020 case Stmt::BinaryConditionalOperatorClass: {
8021 auto *C = cast<AbstractConditionalOperator>(Init);
8022 // In C++, we can have a throw-expression operand, which has 'void' type
8023 // and isn't interesting from a lifetime perspective.
8024 if (!C->getTrueExpr()->getType()->isVoidType())
8025 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true,
8026 EnableLifetimeWarnings);
8027 if (!C->getFalseExpr()->getType()->isVoidType())
8028 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true,
8029 EnableLifetimeWarnings);
8030 break;
8031 }
8032
8033 case Stmt::BlockExprClass:
8034 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
8035 // This is a local block, whose lifetime is that of the function.
8036 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
8037 }
8038 break;
8039
8040 case Stmt::AddrLabelExprClass:
8041 // We want to warn if the address of a label would escape the function.
8042 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
8043 break;
8044
8045 default:
8046 break;
8047 }
8048}
8049
8050/// Whether a path to an object supports lifetime extension.
8052 /// Lifetime-extend along this path.
8054 /// We should lifetime-extend, but we don't because (due to technical
8055 /// limitations) we can't. This happens for default member initializers,
8056 /// which we don't clone for every use, so we don't have a unique
8057 /// MaterializeTemporaryExpr to update.
8059 /// Do not lifetime extend along this path.
8060 NoExtend
8062
8063/// Determine whether this is an indirect path to a temporary that we are
8064/// supposed to lifetime-extend along.
8065static PathLifetimeKind
8066shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
8067 PathLifetimeKind Kind = PathLifetimeKind::Extend;
8068 for (auto Elem : Path) {
8069 if (Elem.Kind == IndirectLocalPathEntry::DefaultInit)
8070 Kind = PathLifetimeKind::ShouldExtend;
8071 else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit)
8072 return PathLifetimeKind::NoExtend;
8073 }
8074 return Kind;
8075}
8076
8077/// Find the range for the first interesting entry in the path at or after I.
8078static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
8079 Expr *E) {
8080 for (unsigned N = Path.size(); I != N; ++I) {
8081 switch (Path[I].Kind) {
8082 case IndirectLocalPathEntry::AddressOf:
8083 case IndirectLocalPathEntry::LValToRVal:
8084 case IndirectLocalPathEntry::LifetimeBoundCall:
8085 case IndirectLocalPathEntry::TemporaryCopy:
8086 case IndirectLocalPathEntry::GslReferenceInit:
8087 case IndirectLocalPathEntry::GslPointerInit:
8088 // These exist primarily to mark the path as not permitting or
8089 // supporting lifetime extension.
8090 break;
8091
8092 case IndirectLocalPathEntry::VarInit:
8093 if (cast<VarDecl>(Path[I].D)->isImplicit())
8094 return SourceRange();
8095 [[fallthrough]];
8096 case IndirectLocalPathEntry::DefaultInit:
8097 return Path[I].E->getSourceRange();
8098
8099 case IndirectLocalPathEntry::LambdaCaptureInit:
8100 if (!Path[I].Capture->capturesVariable())
8101 continue;
8102 return Path[I].E->getSourceRange();
8103 }
8104 }
8105 return E->getSourceRange();
8106}
8107
8108static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
8109 for (const auto &It : llvm::reverse(Path)) {
8110 if (It.Kind == IndirectLocalPathEntry::VarInit)
8111 continue;
8112 if (It.Kind == IndirectLocalPathEntry::AddressOf)
8113 continue;
8114 if (It.Kind == IndirectLocalPathEntry::LifetimeBoundCall)
8115 continue;
8116 return It.Kind == IndirectLocalPathEntry::GslPointerInit ||
8117 It.Kind == IndirectLocalPathEntry::GslReferenceInit;
8118 }
8119 return false;
8120}
8121
8123 Expr *Init) {
8124 LifetimeResult LR = getEntityLifetime(&Entity);
8125 LifetimeKind LK = LR.getInt();
8126 const InitializedEntity *ExtendingEntity = LR.getPointer();
8127
8128 // If this entity doesn't have an interesting lifetime, don't bother looking
8129 // for temporaries within its initializer.
8130 if (LK == LK_FullExpression)
8131 return;
8132
8133 auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
8134 ReferenceKind RK) -> bool {
8135 SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
8136 SourceLocation DiagLoc = DiagRange.getBegin();
8137
8138 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
8139
8140 bool IsGslPtrInitWithGslTempOwner = false;
8141 bool IsLocalGslOwner = false;
8143 if (isa<DeclRefExpr>(L)) {
8144 // We do not want to follow the references when returning a pointer originating
8145 // from a local owner to avoid the following false positive:
8146 // int &p = *localUniquePtr;
8147 // someContainer.add(std::move(localUniquePtr));
8148 // return p;
8149 IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType());
8150 if (pathContainsInit(Path) || !IsLocalGslOwner)
8151 return false;
8152 } else {
8153 IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
8154 isRecordWithAttr<OwnerAttr>(MTE->getType());
8155 // Skipping a chain of initializing gsl::Pointer annotated objects.
8156 // We are looking only for the final source to find out if it was
8157 // a local or temporary owner or the address of a local variable/param.
8158 if (!IsGslPtrInitWithGslTempOwner)
8159 return true;
8160 }
8161 }
8162
8163 switch (LK) {
8164 case LK_FullExpression:
8165 llvm_unreachable("already handled this");
8166
8167 case LK_Extended: {
8168 if (!MTE) {
8169 // The initialized entity has lifetime beyond the full-expression,
8170 // and the local entity does too, so don't warn.
8171 //
8172 // FIXME: We should consider warning if a static / thread storage
8173 // duration variable retains an automatic storage duration local.
8174 return false;
8175 }
8176
8177 if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
8178 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8179 return false;
8180 }
8181
8182 switch (shouldLifetimeExtendThroughPath(Path)) {
8183 case PathLifetimeKind::Extend:
8184 // Update the storage duration of the materialized temporary.
8185 // FIXME: Rebuild the expression instead of mutating it.
8186 MTE->setExtendingDecl(ExtendingEntity->getDecl(),
8187 ExtendingEntity->allocateManglingNumber());
8188 // Also visit the temporaries lifetime-extended by this initializer.
8189 return true;
8190
8191 case PathLifetimeKind::ShouldExtend:
8192 // We're supposed to lifetime-extend the temporary along this path (per
8193 // the resolution of DR1815), but we don't support that yet.
8194 //
8195 // FIXME: Properly handle this situation. Perhaps the easiest approach
8196 // would be to clone the initializer expression on each use that would
8197 // lifetime extend its temporaries.
8198 Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
8199 << RK << DiagRange;
8200 break;
8201
8202 case PathLifetimeKind::NoExtend:
8203 // If the path goes through the initialization of a variable or field,
8204 // it can't possibly reach a temporary created in this full-expression.
8205 // We will have already diagnosed any problems with the initializer.
8206 if (pathContainsInit(Path))
8207 return false;
8208
8209 Diag(DiagLoc, diag::warn_dangling_variable)
8210 << RK << !Entity.getParent()
8211 << ExtendingEntity->getDecl()->isImplicit()
8212 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
8213 break;
8214 }
8215 break;
8216 }
8217
8218 case LK_MemInitializer: {
8219 if (isa<MaterializeTemporaryExpr>(L)) {
8220 // Under C++ DR1696, if a mem-initializer (or a default member
8221 // initializer used by the absence of one) would lifetime-extend a
8222 // temporary, the program is ill-formed.
8223 if (auto *ExtendingDecl =
8224 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8225 if (IsGslPtrInitWithGslTempOwner) {
8226 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
8227 << ExtendingDecl << DiagRange;
8228 Diag(ExtendingDecl->getLocation(),
8229 diag::note_ref_or_ptr_member_declared_here)
8230 << true;
8231 return false;
8232 }
8233 bool IsSubobjectMember = ExtendingEntity != &Entity;
8234 Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) !=
8235 PathLifetimeKind::NoExtend
8236 ? diag::err_dangling_member
8237 : diag::warn_dangling_member)
8238 << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
8239 // Don't bother adding a note pointing to the field if we're inside
8240 // its default member initializer; our primary diagnostic points to
8241 // the same place in that case.
8242 if (Path.empty() ||
8243 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
8244 Diag(ExtendingDecl->getLocation(),
8245 diag::note_lifetime_extending_member_declared_here)
8246 << RK << IsSubobjectMember;
8247 }
8248 } else {
8249 // We have a mem-initializer but no particular field within it; this
8250 // is either a base class or a delegating initializer directly
8251 // initializing the base-class from something that doesn't live long
8252 // enough.
8253 //
8254 // FIXME: Warn on this.
8255 return false;
8256 }
8257 } else {
8258 // Paths via a default initializer can only occur during error recovery
8259 // (there's no other way that a default initializer can refer to a
8260 // local). Don't produce a bogus warning on those cases.
8261 if (pathContainsInit(Path))
8262 return false;
8263
8264 // Suppress false positives for code like the one below:
8265 // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {}
8266 if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
8267 return false;
8268
8269 auto *DRE = dyn_cast<DeclRefExpr>(L);
8270 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
8271 if (!VD) {
8272 // A member was initialized to a local block.
8273 // FIXME: Warn on this.
8274 return false;
8275 }
8276
8277 if (auto *Member =
8278 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8279 bool IsPointer = !Member->getType()->isReferenceType();
8280 Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
8281 : diag::warn_bind_ref_member_to_parameter)
8282 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
8283 Diag(Member->getLocation(),
8284 diag::note_ref_or_ptr_member_declared_here)
8285 << (unsigned)IsPointer;
8286 }
8287 }
8288 break;
8289 }
8290
8291 case LK_New:
8292 if (isa<MaterializeTemporaryExpr>(L)) {
8293 if (IsGslPtrInitWithGslTempOwner)
8294 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8295 else
8296 Diag(DiagLoc, RK == RK_ReferenceBinding
8297 ? diag::warn_new_dangling_reference
8298 : diag::warn_new_dangling_initializer_list)
8299 << !Entity.getParent() << DiagRange;
8300 } else {
8301 // We can't determine if the allocation outlives the local declaration.
8302 return false;
8303 }
8304 break;
8305
8306 case LK_Return:
8307 case LK_StmtExprResult:
8308 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
8309 // We can't determine if the local variable outlives the statement
8310 // expression.
8311 if (LK == LK_StmtExprResult)
8312 return false;
8313 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
8314 << Entity.getType()->isReferenceType() << DRE->getDecl()
8315 << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
8316 } else if (isa<BlockExpr>(L)) {
8317 Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
8318 } else if (isa<AddrLabelExpr>(L)) {
8319 // Don't warn when returning a label from a statement expression.
8320 // Leaving the scope doesn't end its lifetime.
8321 if (LK == LK_StmtExprResult)
8322 return false;
8323 Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
8324 } else if (auto *CLE = dyn_cast<CompoundLiteralExpr>(L)) {
8325 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
8326 << Entity.getType()->isReferenceType() << CLE->getInitializer() << 2
8327 << DiagRange;
8328 } else {
8329 Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
8330 << Entity.getType()->isReferenceType() << DiagRange;
8331 }
8332 break;
8333 }
8334
8335 for (unsigned I = 0; I != Path.size(); ++I) {
8336 auto Elem = Path[I];
8337
8338 switch (Elem.Kind) {
8339 case IndirectLocalPathEntry::AddressOf:
8340 case IndirectLocalPathEntry::LValToRVal:
8341 // These exist primarily to mark the path as not permitting or
8342 // supporting lifetime extension.
8343 break;
8344
8345 case IndirectLocalPathEntry::LifetimeBoundCall:
8346 case IndirectLocalPathEntry::TemporaryCopy:
8347 case IndirectLocalPathEntry::GslPointerInit:
8348 case IndirectLocalPathEntry::GslReferenceInit:
8349 // FIXME: Consider adding a note for these.
8350 break;
8351
8352 case IndirectLocalPathEntry::DefaultInit: {
8353 auto *FD = cast<FieldDecl>(Elem.D);
8354 Diag(FD->getLocation(), diag::note_init_with_default_member_initializer)
8355 << FD << nextPathEntryRange(Path, I + 1, L);
8356 break;
8357 }
8358
8359 case IndirectLocalPathEntry::VarInit: {
8360 const VarDecl *VD = cast<VarDecl>(Elem.D);
8361 Diag(VD->getLocation(), diag::note_local_var_initializer)
8362 << VD->getType()->isReferenceType()
8363 << VD->isImplicit() << VD->getDeclName()
8364 << nextPathEntryRange(Path, I + 1, L);
8365 break;
8366 }
8367
8368 case IndirectLocalPathEntry::LambdaCaptureInit:
8369 if (!Elem.Capture->capturesVariable())
8370 break;
8371 // FIXME: We can't easily tell apart an init-capture from a nested
8372 // capture of an init-capture.
8373 const ValueDecl *VD = Elem.Capture->getCapturedVar();
8374 Diag(Elem.Capture->getLocation(), diag::note_lambda_capture_initializer)
8375 << VD << VD->isInitCapture() << Elem.Capture->isExplicit()
8376 << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD
8377 << nextPathEntryRange(Path, I + 1, L);
8378 break;
8379 }
8380 }
8381
8382 // We didn't lifetime-extend, so don't go any further; we don't need more
8383 // warnings or errors on inner temporaries within this one's initializer.
8384 return false;
8385 };
8386
8387 bool EnableLifetimeWarnings = !getDiagnostics().isIgnored(
8388 diag::warn_dangling_lifetime_pointer, SourceLocation());
8390 if (Init->isGLValue())
8391 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
8392 TemporaryVisitor,
8393 EnableLifetimeWarnings);
8394 else
8395 visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false,
8396 EnableLifetimeWarnings);
8397}
8398
8399static void DiagnoseNarrowingInInitList(Sema &S,
8400 const ImplicitConversionSequence &ICS,
8401 QualType PreNarrowingType,
8402 QualType EntityType,
8403 const Expr *PostInit);
8404
8405static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
8406 QualType ToType, Expr *Init);
8407
8408/// Provide warnings when std::move is used on construction.
8409static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
8410 bool IsReturnStmt) {
8411 if (!InitExpr)
8412 return;
8413
8415 return;
8416
8417 QualType DestType = InitExpr->getType();
8418 if (!DestType->isRecordType())
8419 return;
8420
8421 unsigned DiagID = 0;
8422 if (IsReturnStmt) {
8423 const CXXConstructExpr *CCE =
8424 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
8425 if (!CCE || CCE->getNumArgs() != 1)
8426 return;
8427
8429 return;
8430
8431 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
8432 }
8433
8434 // Find the std::move call and get the argument.
8435 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
8436 if (!CE || !CE->isCallToStdMove())
8437 return;
8438
8439 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
8440
8441 if (IsReturnStmt) {
8442 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
8443 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
8444 return;
8445
8446 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
8447 if (!VD || !VD->hasLocalStorage())
8448 return;
8449
8450 // __block variables are not moved implicitly.
8451 if (VD->hasAttr<BlocksAttr>())
8452 return;
8453
8454 QualType SourceType = VD->getType();
8455 if (!SourceType->isRecordType())
8456 return;
8457
8458 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
8459 return;
8460 }
8461
8462 // If we're returning a function parameter, copy elision
8463 // is not possible.
8464 if (isa<ParmVarDecl>(VD))
8465 DiagID = diag::warn_redundant_move_on_return;
8466 else
8467 DiagID = diag::warn_pessimizing_move_on_return;
8468 } else {
8469 DiagID = diag::warn_pessimizing_move_on_initialization;
8470 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
8471 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
8472 return;
8473 }
8474
8475 S.Diag(CE->getBeginLoc(), DiagID);
8476
8477 // Get all the locations for a fix-it. Don't emit the fix-it if any location
8478 // is within a macro.
8479 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
8480 if (CallBegin.isMacroID())
8481 return;
8482 SourceLocation RParen = CE->getRParenLoc();
8483 if (RParen.isMacroID())
8484 return;
8485 SourceLocation LParen;
8486 SourceLocation ArgLoc = Arg->getBeginLoc();
8487
8488 // Special testing for the argument location. Since the fix-it needs the
8489 // location right before the argument, the argument location can be in a
8490 // macro only if it is at the beginning of the macro.
8491 while (ArgLoc.isMacroID() &&
8494 }
8495
8496 if (LParen.isMacroID())
8497 return;
8498
8499 LParen = ArgLoc.getLocWithOffset(-1);
8500
8501 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
8502 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
8503 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
8504}
8505
8506static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
8507 // Check to see if we are dereferencing a null pointer. If so, this is
8508 // undefined behavior, so warn about it. This only handles the pattern
8509 // "*null", which is a very syntactic check.
8510 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
8511 if (UO->getOpcode() == UO_Deref &&
8512 UO->getSubExpr()->IgnoreParenCasts()->
8513 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
8514 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
8515 S.PDiag(diag::warn_binding_null_to_reference)
8516 << UO->getSubExpr()->getSourceRange());
8517 }
8518}
8519
8522 bool BoundToLvalueReference) {
8523 auto MTE = new (Context)
8524 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
8525
8526 // Order an ExprWithCleanups for lifetime marks.
8527 //
8528 // TODO: It'll be good to have a single place to check the access of the
8529 // destructor and generate ExprWithCleanups for various uses. Currently these
8530 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
8531 // but there may be a chance to merge them.
8534 auto &Record = ExprEvalContexts.back();
8535 Record.ForRangeLifetimeExtendTemps.push_back(MTE);
8536 }
8537 return MTE;
8538}
8539
8541 // In C++98, we don't want to implicitly create an xvalue.
8542 // FIXME: This means that AST consumers need to deal with "prvalues" that
8543 // denote materialized temporaries. Maybe we should add another ValueKind
8544 // for "xvalue pretending to be a prvalue" for C++98 support.
8545 if (!E->isPRValue() || !getLangOpts().CPlusPlus11)
8546 return E;
8547
8548 // C++1z [conv.rval]/1: T shall be a complete type.
8549 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
8550 // If so, we should check for a non-abstract class type here too.
8551 QualType T = E->getType();
8552 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
8553 return ExprError();
8554
8555 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
8556}
8557
8559 ExprValueKind VK,
8561
8562 CastKind CK = CK_NoOp;
8563
8564 if (VK == VK_PRValue) {
8565 auto PointeeTy = Ty->getPointeeType();
8566 auto ExprPointeeTy = E->getType()->getPointeeType();
8567 if (!PointeeTy.isNull() &&
8568 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
8569 CK = CK_AddressSpaceConversion;
8570 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
8571 CK = CK_AddressSpaceConversion;
8572 }
8573
8574 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
8575}
8576
8578 const InitializedEntity &Entity,
8579 const InitializationKind &Kind,
8580 MultiExprArg Args,
8581 QualType *ResultType) {
8582 if (Failed()) {
8583 Diagnose(S, Entity, Kind, Args);
8584 return ExprError();
8585 }
8586 if (!ZeroInitializationFixit.empty()) {
8587 const Decl *D = Entity.getDecl();
8588 const auto *VD = dyn_cast_or_null<VarDecl>(D);
8589 QualType DestType = Entity.getType();
8590
8591 // The initialization would have succeeded with this fixit. Since the fixit
8592 // is on the error, we need to build a valid AST in this case, so this isn't
8593 // handled in the Failed() branch above.
8594 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
8595 // Use a more useful diagnostic for constexpr variables.
8596 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
8597 << VD
8598 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8599 ZeroInitializationFixit);
8600 } else {
8601 unsigned DiagID = diag::err_default_init_const;
8602 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
8603 DiagID = diag::ext_default_init_const;
8604
8605 S.Diag(Kind.getLocation(), DiagID)
8606 << DestType << (bool)DestType->getAs<RecordType>()
8607 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8608 ZeroInitializationFixit);
8609 }
8610 }
8611
8612 if (getKind() == DependentSequence) {
8613 // If the declaration is a non-dependent, incomplete array type
8614 // that has an initializer, then its type will be completed once
8615 // the initializer is instantiated.
8616 if (ResultType && !Entity.getType()->isDependentType() &&
8617 Args.size() == 1) {
8618 QualType DeclType = Entity.getType();
8619 if (const IncompleteArrayType *ArrayT
8620 = S.Context.getAsIncompleteArrayType(DeclType)) {
8621 // FIXME: We don't currently have the ability to accurately
8622 // compute the length of an initializer list without
8623 // performing full type-checking of the initializer list
8624 // (since we have to determine where braces are implicitly
8625 // introduced and such). So, we fall back to making the array
8626 // type a dependently-sized array type with no specified
8627 // bound.
8628 if (isa<InitListExpr>((Expr *)Args[0])) {
8629 SourceRange Brackets;
8630
8631 // Scavange the location of the brackets from the entity, if we can.
8632 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
8633 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
8634 TypeLoc TL = TInfo->getTypeLoc();
8635 if (IncompleteArrayTypeLoc ArrayLoc =
8637 Brackets = ArrayLoc.getBracketsRange();
8638 }
8639 }
8640
8641 *ResultType
8642 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
8643 /*NumElts=*/nullptr,
8644 ArrayT->getSizeModifier(),
8645 ArrayT->getIndexTypeCVRQualifiers(),
8646 Brackets);
8647 }
8648
8649 }
8650 }
8651 if (Kind.getKind() == InitializationKind::IK_Direct &&
8652 !Kind.isExplicitCast()) {
8653 // Rebuild the ParenListExpr.
8654 SourceRange ParenRange = Kind.getParenOrBraceRange();
8655 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
8656 Args);
8657 }
8658 assert(Kind.getKind() == InitializationKind::IK_Copy ||
8659 Kind.isExplicitCast() ||
8660 Kind.getKind() == InitializationKind::IK_DirectList);
8661 return ExprResult(Args[0]);
8662 }
8663
8664 // No steps means no initialization.
8665 if (Steps.empty())
8666 return ExprResult((Expr *)nullptr);
8667
8668 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
8669 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
8670 !Entity.isParamOrTemplateParamKind()) {
8671 // Produce a C++98 compatibility warning if we are initializing a reference
8672 // from an initializer list. For parameters, we produce a better warning
8673 // elsewhere.
8674 Expr *Init = Args[0];
8675 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
8676 << Init->getSourceRange();
8677 }
8678
8679 if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
8680 isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
8681 // Produce a Microsoft compatibility warning when initializing from a
8682 // predefined expression since MSVC treats predefined expressions as string
8683 // literals.
8684 Expr *Init = Args[0];
8685 S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
8686 }
8687
8688 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8689 QualType ETy = Entity.getType();
8690 bool HasGlobalAS = ETy.hasAddressSpace() &&
8692
8693 if (S.getLangOpts().OpenCLVersion >= 200 &&
8694 ETy->isAtomicType() && !HasGlobalAS &&
8695 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8696 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
8697 << 1
8698 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8699 return ExprError();
8700 }
8701
8702 QualType DestType = Entity.getType().getNonReferenceType();
8703 // FIXME: Ugly hack around the fact that Entity.getType() is not
8704 // the same as Entity.getDecl()->getType() in cases involving type merging,
8705 // and we want latter when it makes sense.
8706 if (ResultType)
8707 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8708 Entity.getType();
8709
8710 ExprResult CurInit((Expr *)nullptr);
8711 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8712
8713 // HLSL allows vector initialization to function like list initialization, but
8714 // use the syntax of a C++-like constructor.
8715 bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() &&
8716 isa<InitListExpr>(Args[0]);
8717 (void)IsHLSLVectorInit;
8718
8719 // For initialization steps that start with a single initializer,
8720 // grab the only argument out the Args and place it into the "current"
8721 // initializer.
8722 switch (Steps.front().Kind) {
8727 case SK_BindReference:
8729 case SK_FinalCopy:
8731 case SK_UserConversion:
8740 case SK_UnwrapInitList:
8741 case SK_RewrapInitList:
8742 case SK_CAssignment:
8743 case SK_StringInit:
8745 case SK_ArrayLoopIndex:
8746 case SK_ArrayLoopInit:
8747 case SK_ArrayInit:
8748 case SK_GNUArrayInit:
8754 case SK_OCLSamplerInit:
8755 case SK_OCLZeroOpaqueType: {
8756 assert(Args.size() == 1 || IsHLSLVectorInit);
8757 CurInit = Args[0];
8758 if (!CurInit.get()) return ExprError();
8759 break;
8760 }
8761
8767 break;
8768 }
8769
8770 // Promote from an unevaluated context to an unevaluated list context in
8771 // C++11 list-initialization; we need to instantiate entities usable in
8772 // constant expressions here in order to perform narrowing checks =(
8775 CurInit.get() && isa<InitListExpr>(CurInit.get()));
8776
8777 // C++ [class.abstract]p2:
8778 // no objects of an abstract class can be created except as subobjects
8779 // of a class derived from it
8780 auto checkAbstractType = [&](QualType T) -> bool {
8781 if (Entity.getKind() == InitializedEntity::EK_Base ||
8783 return false;
8784 return S.RequireNonAbstractType(Kind.getLocation(), T,
8785 diag::err_allocation_of_abstract_type);
8786 };
8787
8788 // Walk through the computed steps for the initialization sequence,
8789 // performing the specified conversions along the way.
8790 bool ConstructorInitRequiresZeroInit = false;
8791 for (step_iterator Step = step_begin(), StepEnd = step_end();
8792 Step != StepEnd; ++Step) {
8793 if (CurInit.isInvalid())
8794 return ExprError();
8795
8796 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8797
8798 switch (Step->Kind) {
8800 // Overload resolution determined which function invoke; update the
8801 // initializer to reflect that choice.
8803 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
8804 return ExprError();
8805 CurInit = S.FixOverloadedFunctionReference(CurInit,
8808 // We might get back another placeholder expression if we resolved to a
8809 // builtin.
8810 if (!CurInit.isInvalid())
8811 CurInit = S.CheckPlaceholderExpr(CurInit.get());
8812 break;
8813
8817 // We have a derived-to-base cast that produces either an rvalue or an
8818 // lvalue. Perform that cast.
8819
8820 CXXCastPath BasePath;
8821
8822 // Casts to inaccessible base classes are allowed with C-style casts.
8823 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8825 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8826 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8827 return ExprError();
8828
8829 ExprValueKind VK =
8831 ? VK_LValue
8833 : VK_PRValue);
8835 CK_DerivedToBase, CurInit.get(),
8836 &BasePath, VK, FPOptionsOverride());
8837 break;
8838 }
8839
8840 case SK_BindReference:
8841 // Reference binding does not have any corresponding ASTs.
8842
8843 // Check exception specifications
8844 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8845 return ExprError();
8846
8847 // We don't check for e.g. function pointers here, since address
8848 // availability checks should only occur when the function first decays
8849 // into a pointer or reference.
8850 if (CurInit.get()->getType()->isFunctionProtoType()) {
8851 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8852 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8853 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8854 DRE->getBeginLoc()))
8855 return ExprError();
8856 }
8857 }
8858 }
8859
8860 CheckForNullPointerDereference(S, CurInit.get());
8861 break;
8862
8864 // Make sure the "temporary" is actually an rvalue.
8865 assert(CurInit.get()->isPRValue() && "not a temporary");
8866
8867 // Check exception specifications
8868 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8869 return ExprError();
8870
8871 QualType MTETy = Step->Type;
8872
8873 // When this is an incomplete array type (such as when this is
8874 // initializing an array of unknown bounds from an init list), use THAT
8875 // type instead so that we propagate the array bounds.
8876 if (MTETy->isIncompleteArrayType() &&
8877 !CurInit.get()->getType()->isIncompleteArrayType() &&
8880 CurInit.get()->getType()->getPointeeOrArrayElementType()))
8881 MTETy = CurInit.get()->getType();
8882
8883 // Materialize the temporary into memory.
8885 MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8886 CurInit = MTE;
8887
8888 // If we're extending this temporary to automatic storage duration -- we
8889 // need to register its cleanup during the full-expression's cleanups.
8890 if (MTE->getStorageDuration() == SD_Automatic &&
8891 MTE->getType().isDestructedType())
8893 break;
8894 }
8895
8896 case SK_FinalCopy:
8897 if (checkAbstractType(Step->Type))
8898 return ExprError();
8899
8900 // If the overall initialization is initializing a temporary, we already
8901 // bound our argument if it was necessary to do so. If not (if we're
8902 // ultimately initializing a non-temporary), our argument needs to be
8903 // bound since it's initializing a function parameter.
8904 // FIXME: This is a mess. Rationalize temporary destruction.
8905 if (!shouldBindAsTemporary(Entity))
8906 CurInit = S.MaybeBindToTemporary(CurInit.get());
8907 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8908 /*IsExtraneousCopy=*/false);
8909 break;
8910
8912 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8913 /*IsExtraneousCopy=*/true);
8914 break;
8915
8916 case SK_UserConversion: {
8917 // We have a user-defined conversion that invokes either a constructor
8918 // or a conversion function.
8922 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8923 bool CreatedObject = false;
8924 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8925 // Build a call to the selected constructor.
8926 SmallVector<Expr*, 8> ConstructorArgs;
8927 SourceLocation Loc = CurInit.get()->getBeginLoc();
8928
8929 // Determine the arguments required to actually perform the constructor
8930 // call.
8931 Expr *Arg = CurInit.get();
8932 if (S.CompleteConstructorCall(Constructor, Step->Type,
8933 MultiExprArg(&Arg, 1), Loc,
8934 ConstructorArgs))
8935 return ExprError();
8936
8937 // Build an expression that constructs a temporary.
8938 CurInit = S.BuildCXXConstructExpr(
8939 Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
8940 HadMultipleCandidates,
8941 /*ListInit*/ false,
8942 /*StdInitListInit*/ false,
8943 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
8944 if (CurInit.isInvalid())
8945 return ExprError();
8946
8947 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8948 Entity);
8949 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8950 return ExprError();
8951
8952 CastKind = CK_ConstructorConversion;
8953 CreatedObject = true;
8954 } else {
8955 // Build a call to the conversion function.
8956 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
8957 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8958 FoundFn);
8959 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8960 return ExprError();
8961
8962 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8963 HadMultipleCandidates);
8964 if (CurInit.isInvalid())
8965 return ExprError();
8966
8967 CastKind = CK_UserDefinedConversion;
8968 CreatedObject = Conversion->getReturnType()->isRecordType();
8969 }
8970
8971 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8972 return ExprError();
8973
8974 CurInit = ImplicitCastExpr::Create(
8975 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8976 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
8977
8978 if (shouldBindAsTemporary(Entity))
8979 // The overall entity is temporary, so this expression should be
8980 // destroyed at the end of its full-expression.
8981 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
8982 else if (CreatedObject && shouldDestroyEntity(Entity)) {
8983 // The object outlasts the full-expression, but we need to prepare for
8984 // a destructor being run on it.
8985 // FIXME: It makes no sense to do this here. This should happen
8986 // regardless of how we initialized the entity.
8987 QualType T = CurInit.get()->getType();
8988 if (const RecordType *Record = T->getAs<RecordType>()) {
8989 CXXDestructorDecl *Destructor
8990 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
8991 S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
8992 S.PDiag(diag::err_access_dtor_temp) << T);
8993 S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
8994 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
8995 return ExprError();
8996 }
8997 }
8998 break;
8999 }
9000
9004 // Perform a qualification conversion; these can never go wrong.
9005 ExprValueKind VK =
9007 ? VK_LValue
9009 : VK_PRValue);
9010 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
9011 break;
9012 }
9013
9015 assert(CurInit.get()->isLValue() &&
9016 "function reference should be lvalue");
9017 CurInit =
9018 S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
9019 break;
9020
9021 case SK_AtomicConversion: {
9022 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
9023 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9024 CK_NonAtomicToAtomic, VK_PRValue);
9025 break;
9026 }
9027
9030 if (const auto *FromPtrType =
9031 CurInit.get()->getType()->getAs<PointerType>()) {
9032 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
9033 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9034 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9035 // Do not check static casts here because they are checked earlier
9036 // in Sema::ActOnCXXNamedCast()
9037 if (!Kind.isStaticCast()) {
9038 S.Diag(CurInit.get()->getExprLoc(),
9039 diag::warn_noderef_to_dereferenceable_pointer)
9040 << CurInit.get()->getSourceRange();
9041 }
9042 }
9043 }
9044 }
9045
9047 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
9048 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
9049 : Kind.isExplicitCast()? Sema::CCK_OtherCast
9051 ExprResult CurInitExprRes =
9052 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
9053 getAssignmentAction(Entity), CCK);
9054 if (CurInitExprRes.isInvalid())
9055 return ExprError();
9056
9058
9059 CurInit = CurInitExprRes;
9060
9062 S.getLangOpts().CPlusPlus)
9063 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
9064 CurInit.get());
9065
9066 break;
9067 }
9068
9069 case SK_ListInitialization: {
9070 if (checkAbstractType(Step->Type))
9071 return ExprError();
9072
9073 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
9074 // If we're not initializing the top-level entity, we need to create an
9075 // InitializeTemporary entity for our target type.
9076 QualType Ty = Step->Type;
9077 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
9079 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
9080 InitListChecker PerformInitList(S, InitEntity,
9081 InitList, Ty, /*VerifyOnly=*/false,
9082 /*TreatUnavailableAsInvalid=*/false);
9083 if (PerformInitList.HadError())
9084 return ExprError();
9085
9086 // Hack: We must update *ResultType if available in order to set the
9087 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
9088 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
9089 if (ResultType &&
9090 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
9091 if ((*ResultType)->isRValueReferenceType())
9093 else if ((*ResultType)->isLValueReferenceType())
9095 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
9096 *ResultType = Ty;
9097 }
9098
9099 InitListExpr *StructuredInitList =
9100 PerformInitList.getFullyStructuredList();
9101 CurInit.get();
9102 CurInit = shouldBindAsTemporary(InitEntity)
9103 ? S.MaybeBindToTemporary(StructuredInitList)
9104 : StructuredInitList;
9105 break;
9106 }
9107
9109 if (checkAbstractType(Step->Type))
9110 return ExprError();
9111
9112 // When an initializer list is passed for a parameter of type "reference
9113 // to object", we don't get an EK_Temporary entity, but instead an
9114 // EK_Parameter entity with reference type.
9115 // FIXME: This is a hack. What we really should do is create a user
9116 // conversion step for this case, but this makes it considerably more
9117 // complicated. For now, this will do.
9119 Entity.getType().getNonReferenceType());
9120 bool UseTemporary = Entity.getType()->isReferenceType();
9121 assert(Args.size() == 1 && "expected a single argument for list init");
9122 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9123 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
9124 << InitList->getSourceRange();
9125 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
9126 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
9127 Entity,
9128 Kind, Arg, *Step,
9129 ConstructorInitRequiresZeroInit,
9130 /*IsListInitialization*/true,
9131 /*IsStdInitListInit*/false,
9132 InitList->getLBraceLoc(),
9133 InitList->getRBraceLoc());
9134 break;
9135 }
9136
9137 case SK_UnwrapInitList:
9138 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
9139 break;
9140
9141 case SK_RewrapInitList: {
9142 Expr *E = CurInit.get();
9144 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
9145 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
9146 ILE->setSyntacticForm(Syntactic);
9147 ILE->setType(E->getType());
9148 ILE->setValueKind(E->getValueKind());
9149 CurInit = ILE;
9150 break;
9151 }
9152
9155 if (checkAbstractType(Step->Type))
9156 return ExprError();
9157
9158 // When an initializer list is passed for a parameter of type "reference
9159 // to object", we don't get an EK_Temporary entity, but instead an
9160 // EK_Parameter entity with reference type.
9161 // FIXME: This is a hack. What we really should do is create a user
9162 // conversion step for this case, but this makes it considerably more
9163 // complicated. For now, this will do.
9165 Entity.getType().getNonReferenceType());
9166 bool UseTemporary = Entity.getType()->isReferenceType();
9167 bool IsStdInitListInit =
9169 Expr *Source = CurInit.get();
9170 SourceRange Range = Kind.hasParenOrBraceRange()
9171 ? Kind.getParenOrBraceRange()
9172 : SourceRange();
9174 S, UseTemporary ? TempEntity : Entity, Kind,
9175 Source ? MultiExprArg(Source) : Args, *Step,
9176 ConstructorInitRequiresZeroInit,
9177 /*IsListInitialization*/ IsStdInitListInit,
9178 /*IsStdInitListInitialization*/ IsStdInitListInit,
9179 /*LBraceLoc*/ Range.getBegin(),
9180 /*RBraceLoc*/ Range.getEnd());
9181 break;
9182 }
9183
9184 case SK_ZeroInitialization: {
9185 step_iterator NextStep = Step;
9186 ++NextStep;
9187 if (NextStep != StepEnd &&
9188 (NextStep->Kind == SK_ConstructorInitialization ||
9189 NextStep->Kind == SK_ConstructorInitializationFromList)) {
9190 // The need for zero-initialization is recorded directly into
9191 // the call to the object's constructor within the next step.
9192 ConstructorInitRequiresZeroInit = true;
9193 } else if (Kind.getKind() == InitializationKind::IK_Value &&
9194 S.getLangOpts().CPlusPlus &&
9195 !Kind.isImplicitValueInit()) {
9196 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
9197 if (!TSInfo)
9199 Kind.getRange().getBegin());
9200
9201 CurInit = new (S.Context) CXXScalarValueInitExpr(
9202 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
9203 Kind.getRange().getEnd());
9204 } else {
9205 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
9206 }
9207 break;
9208 }
9209
9210 case SK_CAssignment: {
9211 QualType SourceType = CurInit.get()->getType();
9212
9213 // Save off the initial CurInit in case we need to emit a diagnostic
9214 ExprResult InitialCurInit = CurInit;
9215 ExprResult Result = CurInit;
9219 if (Result.isInvalid())
9220 return ExprError();
9221 CurInit = Result;
9222
9223 // If this is a call, allow conversion to a transparent union.
9224 ExprResult CurInitExprRes = CurInit;
9225 if (ConvTy != Sema::Compatible &&
9226 Entity.isParameterKind() &&
9229 ConvTy = Sema::Compatible;
9230 if (CurInitExprRes.isInvalid())
9231 return ExprError();
9232 CurInit = CurInitExprRes;
9233
9234 if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) {
9235 CheckC23ConstexprInitConversion(S, SourceType, Entity.getType(),
9236 CurInit.get());
9237
9238 // C23 6.7.1p6: If an object or subobject declared with storage-class
9239 // specifier constexpr has pointer, integer, or arithmetic type, any
9240 // explicit initializer value for it shall be null, an integer
9241 // constant expression, or an arithmetic constant expression,
9242 // respectively.
9244 if (Entity.getType()->getAs<PointerType>() &&
9245 CurInit.get()->EvaluateAsRValue(ER, S.Context) &&
9246 !ER.Val.isNullPointer()) {
9247 S.Diag(Kind.getLocation(), diag::err_c23_constexpr_pointer_not_null);
9248 }
9249 }
9250
9251 bool Complained;
9252 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
9253 Step->Type, SourceType,
9254 InitialCurInit.get(),
9255 getAssignmentAction(Entity, true),
9256 &Complained)) {
9257 PrintInitLocationNote(S, Entity);
9258 return ExprError();
9259 } else if (Complained)
9260 PrintInitLocationNote(S, Entity);
9261 break;
9262 }
9263
9264 case SK_StringInit: {
9265 QualType Ty = Step->Type;
9266 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
9267 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
9268 S.Context.getAsArrayType(Ty), S,
9269 S.getLangOpts().C23 &&
9271 break;
9272 }
9273
9275 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9276 CK_ObjCObjectLValueCast,
9277 CurInit.get()->getValueKind());
9278 break;
9279
9280 case SK_ArrayLoopIndex: {
9281 Expr *Cur = CurInit.get();
9282 Expr *BaseExpr = new (S.Context)
9283 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
9284 Cur->getValueKind(), Cur->getObjectKind(), Cur);
9285 Expr *IndexExpr =
9288 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
9289 ArrayLoopCommonExprs.push_back(BaseExpr);
9290 break;
9291 }
9292
9293 case SK_ArrayLoopInit: {
9294 assert(!ArrayLoopCommonExprs.empty() &&
9295 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
9296 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
9297 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
9298 CurInit.get());
9299 break;
9300 }
9301
9302 case SK_GNUArrayInit:
9303 // Okay: we checked everything before creating this step. Note that
9304 // this is a GNU extension.
9305 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
9306 << Step->Type << CurInit.get()->getType()
9307 << CurInit.get()->getSourceRange();
9309 [[fallthrough]];
9310 case SK_ArrayInit:
9311 // If the destination type is an incomplete array type, update the
9312 // type accordingly.
9313 if (ResultType) {
9314 if (const IncompleteArrayType *IncompleteDest
9316 if (const ConstantArrayType *ConstantSource
9317 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
9318 *ResultType = S.Context.getConstantArrayType(
9319 IncompleteDest->getElementType(), ConstantSource->getSize(),
9320 ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
9321 }
9322 }
9323 }
9324 break;
9325
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_parens)
9330 << CurInit.get()->getSourceRange();
9331 break;
9332
9335 checkIndirectCopyRestoreSource(S, CurInit.get());
9336 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
9337 CurInit.get(), Step->Type,
9339 break;
9340
9342 CurInit = ImplicitCastExpr::Create(
9343 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
9345 break;
9346
9347 case SK_StdInitializerList: {
9348 S.Diag(CurInit.get()->getExprLoc(),
9349 diag::warn_cxx98_compat_initializer_list_init)
9350 << CurInit.get()->getSourceRange();
9351
9352 // Materialize the temporary into memory.
9354 CurInit.get()->getType(), CurInit.get(),
9355 /*BoundToLvalueReference=*/false);
9356
9357 // Wrap it in a construction of a std::initializer_list<T>.
9358 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
9359
9360 // Bind the result, in case the library has given initializer_list a
9361 // non-trivial destructor.
9362 if (shouldBindAsTemporary(Entity))
9363 CurInit = S.MaybeBindToTemporary(CurInit.get());
9364 break;
9365 }
9366
9367 case SK_OCLSamplerInit: {
9368 // Sampler initialization have 5 cases:
9369 // 1. function argument passing
9370 // 1a. argument is a file-scope variable
9371 // 1b. argument is a function-scope variable
9372 // 1c. argument is one of caller function's parameters
9373 // 2. variable initialization
9374 // 2a. initializing a file-scope variable
9375 // 2b. initializing a function-scope variable
9376 //
9377 // For file-scope variables, since they cannot be initialized by function
9378 // call of __translate_sampler_initializer in LLVM IR, their references
9379 // need to be replaced by a cast from their literal initializers to
9380 // sampler type. Since sampler variables can only be used in function
9381 // calls as arguments, we only need to replace them when handling the
9382 // argument passing.
9383 assert(Step->Type->isSamplerT() &&
9384 "Sampler initialization on non-sampler type.");
9385 Expr *Init = CurInit.get()->IgnoreParens();
9386 QualType SourceType = Init->getType();
9387 // Case 1
9388 if (Entity.isParameterKind()) {
9389 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
9390 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
9391 << SourceType;
9392 break;
9393 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
9394 auto Var = cast<VarDecl>(DRE->getDecl());
9395 // Case 1b and 1c
9396 // No cast from integer to sampler is needed.
9397 if (!Var->hasGlobalStorage()) {
9398 CurInit = ImplicitCastExpr::Create(
9399 S.Context, Step->Type, CK_LValueToRValue, Init,
9400 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
9401 break;
9402 }
9403 // Case 1a
9404 // For function call with a file-scope sampler variable as argument,
9405 // get the integer literal.
9406 // Do not diagnose if the file-scope variable does not have initializer
9407 // since this has already been diagnosed when parsing the variable
9408 // declaration.
9409 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
9410 break;
9411 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
9412 Var->getInit()))->getSubExpr();
9413 SourceType = Init->getType();
9414 }
9415 } else {
9416 // Case 2
9417 // Check initializer is 32 bit integer constant.
9418 // If the initializer is taken from global variable, do not diagnose since
9419 // this has already been done when parsing the variable declaration.
9420 if (!Init->isConstantInitializer(S.Context, false))
9421 break;
9422
9423 if (!SourceType->isIntegerType() ||
9424 32 != S.Context.getIntWidth(SourceType)) {
9425 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
9426 << SourceType;
9427 break;
9428 }
9429
9430 Expr::EvalResult EVResult;
9431 Init->EvaluateAsInt(EVResult, S.Context);
9432 llvm::APSInt Result = EVResult.Val.getInt();
9433 const uint64_t SamplerValue = Result.getLimitedValue();
9434 // 32-bit value of sampler's initializer is interpreted as
9435 // bit-field with the following structure:
9436 // |unspecified|Filter|Addressing Mode| Normalized Coords|
9437 // |31 6|5 4|3 1| 0|
9438 // This structure corresponds to enum values of sampler properties
9439 // defined in SPIR spec v1.2 and also opencl-c.h
9440 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
9441 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
9442 if (FilterMode != 1 && FilterMode != 2 &&
9444 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
9445 S.Diag(Kind.getLocation(),
9446 diag::warn_sampler_initializer_invalid_bits)
9447 << "Filter Mode";
9448 if (AddressingMode > 4)
9449 S.Diag(Kind.getLocation(),
9450 diag::warn_sampler_initializer_invalid_bits)
9451 << "Addressing Mode";
9452 }
9453
9454 // Cases 1a, 2a and 2b
9455 // Insert cast from integer to sampler.
9457 CK_IntToOCLSampler);
9458 break;
9459 }
9460 case SK_OCLZeroOpaqueType: {
9461 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
9463 "Wrong type for initialization of OpenCL opaque type.");
9464
9465 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9466 CK_ZeroToOCLOpaqueType,
9467 CurInit.get()->getValueKind());
9468 break;
9469 }
9471 CurInit = nullptr;
9472 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9473 /*VerifyOnly=*/false, &CurInit);
9474 if (CurInit.get() && ResultType)
9475 *ResultType = CurInit.get()->getType();
9476 if (shouldBindAsTemporary(Entity))
9477 CurInit = S.MaybeBindToTemporary(CurInit.get());
9478 break;
9479 }
9480 }
9481 }
9482
9483 Expr *Init = CurInit.get();
9484 if (!Init)
9485 return ExprError();
9486
9487 // Check whether the initializer has a shorter lifetime than the initialized
9488 // entity, and if not, either lifetime-extend or warn as appropriate.
9489 S.checkInitializerLifetime(Entity, Init);
9490
9491 // Diagnose non-fatal problems with the completed initialization.
9492 if (InitializedEntity::EntityKind EK = Entity.getKind();
9495 cast<FieldDecl>(Entity.getDecl())->isBitField())
9496 S.CheckBitFieldInitialization(Kind.getLocation(),
9497 cast<FieldDecl>(Entity.getDecl()), Init);
9498
9499 // Check for std::move on construction.
9502
9503 return Init;
9504}
9505
9506/// Somewhere within T there is an uninitialized reference subobject.
9507/// Dig it out and diagnose it.
9509 QualType T) {
9510 if (T->isReferenceType()) {
9511 S.Diag(Loc, diag::err_reference_without_init)
9512 << T.getNonReferenceType();
9513 return true;
9514 }
9515
9517 if (!RD || !RD->hasUninitializedReferenceMember())
9518 return false;
9519
9520 for (const auto *FI : RD->fields()) {
9521 if (FI->isUnnamedBitfield())
9522 continue;
9523
9524 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
9525 S.Diag(Loc, diag::note_value_initialization_here) << RD;
9526 return true;
9527 }
9528 }
9529
9530 for (const auto &BI : RD->bases()) {
9531 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
9532 S.Diag(Loc, diag::note_value_initialization_here) << RD;
9533 return true;
9534 }
9535 }
9536
9537 return false;
9538}
9539
9540
9541//===----------------------------------------------------------------------===//
9542// Diagnose initialization failures
9543//===----------------------------------------------------------------------===//
9544
9545/// Emit notes associated with an initialization that failed due to a
9546/// "simple" conversion failure.
9547static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
9548 Expr *op) {
9549 QualType destType = entity.getType();
9550 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
9552
9553 // Emit a possible note about the conversion failing because the
9554 // operand is a message send with a related result type.
9556
9557 // Emit a possible note about a return failing because we're
9558 // expecting a related result type.
9559 if (entity.getKind() == InitializedEntity::EK_Result)
9561 }
9562 QualType fromType = op->getType();
9563 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
9564 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
9565 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
9566 auto *destDecl = destType->getPointeeCXXRecordDecl();
9567 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
9568 destDecl->getDeclKind() == Decl::CXXRecord &&
9569 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
9570 !fromDecl->hasDefinition() &&
9571 destPointeeType.getQualifiers().compatiblyIncludes(
9572 fromPointeeType.getQualifiers()))
9573 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
9574 << S.getASTContext().getTagDeclType(fromDecl)
9575 << S.getASTContext().getTagDeclType(destDecl);
9576}
9577
9578static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
9579 InitListExpr *InitList) {
9580 QualType DestType = Entity.getType();
9581
9582 QualType E;
9583 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
9585 E.withConst(),
9586 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
9587 InitList->getNumInits()),
9589 InitializedEntity HiddenArray =
9591 return diagnoseListInit(S, HiddenArray, InitList);
9592 }
9593
9594 if (DestType->isReferenceType()) {
9595 // A list-initialization failure for a reference means that we tried to
9596 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
9597 // inner initialization failed.
9598 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
9600 SourceLocation Loc = InitList->getBeginLoc();
9601 if (auto *D = Entity.getDecl())
9602 Loc = D->getLocation();
9603 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
9604 return;
9605 }
9606
9607 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
9608 /*VerifyOnly=*/false,
9609 /*TreatUnavailableAsInvalid=*/false);
9610 assert(DiagnoseInitList.HadError() &&
9611 "Inconsistent init list check result.");
9612}
9613
9615 const InitializedEntity &Entity,
9616 const InitializationKind &Kind,
9617 ArrayRef<Expr *> Args) {
9618 if (!Failed())
9619 return false;
9620
9621 // When we want to diagnose only one element of a braced-init-list,
9622 // we need to factor it out.
9623 Expr *OnlyArg;
9624 if (Args.size() == 1) {
9625 auto *List = dyn_cast<InitListExpr>(Args[0]);
9626 if (List && List->getNumInits() == 1)
9627 OnlyArg = List->getInit(0);
9628 else
9629 OnlyArg = Args[0];
9630 }
9631 else
9632 OnlyArg = nullptr;
9633
9634 QualType DestType = Entity.getType();
9635 switch (Failure) {
9637 // FIXME: Customize for the initialized entity?
9638 if (Args.empty()) {
9639 // Dig out the reference subobject which is uninitialized and diagnose it.
9640 // If this is value-initialization, this could be nested some way within
9641 // the target type.
9642 assert(Kind.getKind() == InitializationKind::IK_Value ||
9643 DestType->isReferenceType());
9644 bool Diagnosed =
9645 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
9646 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
9647 (void)Diagnosed;
9648 } else // FIXME: diagnostic below could be better!
9649 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
9650 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9651 break;
9653 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9654 << 1 << Entity.getType() << Args[0]->getSourceRange();
9655 break;
9656
9658 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
9659 break;
9661 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
9662 break;
9664 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
9665 break;
9667 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
9668 break;
9670 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
9671 break;
9673 S.Diag(Kind.getLocation(),
9674 diag::err_array_init_incompat_wide_string_into_wchar);
9675 break;
9677 S.Diag(Kind.getLocation(),
9678 diag::err_array_init_plain_string_into_char8_t);
9679 S.Diag(Args.front()->getBeginLoc(),
9680 diag::note_array_init_plain_string_into_char8_t)
9681 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
9682 break;
9684 S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
9685 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9686 break;
9689 S.Diag(Kind.getLocation(),
9690 (Failure == FK_ArrayTypeMismatch
9691 ? diag::err_array_init_different_type
9692 : diag::err_array_init_non_constant_array))
9693 << DestType.getNonReferenceType()
9694 << OnlyArg->getType()
9695 << Args[0]->getSourceRange();
9696 break;
9697
9699 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
9700 << Args[0]->getSourceRange();
9701 break;
9702
9704 DeclAccessPair Found;
9706 DestType.getNonReferenceType(),
9707 true,
9708 Found);
9709 break;
9710 }
9711
9713 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
9714 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9715 OnlyArg->getBeginLoc());
9716 break;
9717 }
9718
9721 switch (FailedOverloadResult) {
9722 case OR_Ambiguous:
9723
9724 FailedCandidateSet.NoteCandidates(
9726 Kind.getLocation(),
9728 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
9729 << OnlyArg->getType() << DestType
9730 << Args[0]->getSourceRange())
9731 : (S.PDiag(diag::err_ref_init_ambiguous)
9732 << DestType << OnlyArg->getType()
9733 << Args[0]->getSourceRange())),
9734 S, OCD_AmbiguousCandidates, Args);
9735 break;
9736
9737 case OR_No_Viable_Function: {
9738 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
9739 if (!S.RequireCompleteType(Kind.getLocation(),
9740 DestType.getNonReferenceType(),
9741 diag::err_typecheck_nonviable_condition_incomplete,
9742 OnlyArg->getType(), Args[0]->getSourceRange()))
9743 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9744 << (Entity.getKind() == InitializedEntity::EK_Result)
9745 << OnlyArg->getType() << Args[0]->getSourceRange()
9746 << DestType.getNonReferenceType();
9747
9748 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9749 break;
9750 }
9751 case OR_Deleted: {
9752 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9753 << OnlyArg->getType() << DestType.getNonReferenceType()
9754 << Args[0]->getSourceRange();
9757 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9758 if (Ovl == OR_Deleted) {
9759 S.NoteDeletedFunction(Best->Function);
9760 } else {
9761 llvm_unreachable("Inconsistent overload resolution?");
9762 }
9763 break;
9764 }
9765
9766 case OR_Success:
9767 llvm_unreachable("Conversion did not fail!");
9768 }
9769 break;
9770
9772 if (isa<InitListExpr>(Args[0])) {
9773 S.Diag(Kind.getLocation(),
9774 diag::err_lvalue_reference_bind_to_initlist)
9776 << DestType.getNonReferenceType()
9777 << Args[0]->getSourceRange();
9778 break;
9779 }
9780 [[fallthrough]];
9781
9783 S.Diag(Kind.getLocation(),
9785 ? diag::err_lvalue_reference_bind_to_temporary
9786 : diag::err_lvalue_reference_bind_to_unrelated)
9788 << DestType.getNonReferenceType()
9789 << OnlyArg->getType()
9790 << Args[0]->getSourceRange();
9791 break;
9792
9794 // We don't necessarily have an unambiguous source bit-field.
9795 FieldDecl *BitField = Args[0]->getSourceBitField();
9796 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9797 << DestType.isVolatileQualified()
9798 << (BitField ? BitField->getDeclName() : DeclarationName())
9799 << (BitField != nullptr)
9800 << Args[0]->getSourceRange();
9801 if (BitField)
9802 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9803 break;
9804 }
9805
9807 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9808 << DestType.isVolatileQualified()
9809 << Args[0]->getSourceRange();
9810 break;
9811
9813 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9814 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9815 break;
9816
9818 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9819 << DestType.getNonReferenceType() << OnlyArg->getType()
9820 << Args[0]->getSourceRange();
9821 break;
9822
9824 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9825 << DestType << Args[0]->getSourceRange();
9826 break;
9827
9829 QualType SourceType = OnlyArg->getType();
9830 QualType NonRefType = DestType.getNonReferenceType();
9831 Qualifiers DroppedQualifiers =
9832 SourceType.getQualifiers() - NonRefType.getQualifiers();
9833
9834 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9835 SourceType.getQualifiers()))
9836 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9837 << NonRefType << SourceType << 1 /*addr space*/
9838 << Args[0]->getSourceRange();
9839 else if (DroppedQualifiers.hasQualifiers())
9840 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9841 << NonRefType << SourceType << 0 /*cv quals*/
9842 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9843 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9844 else
9845 // FIXME: Consider decomposing the type and explaining which qualifiers
9846 // were dropped where, or on which level a 'const' is missing, etc.
9847 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9848 << NonRefType << SourceType << 2 /*incompatible quals*/
9849 << Args[0]->getSourceRange();
9850 break;
9851 }
9852
9854 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9855 << DestType.getNonReferenceType()
9856 << DestType.getNonReferenceType()->isIncompleteType()
9857 << OnlyArg->isLValue()
9858 << OnlyArg->getType()
9859 << Args[0]->getSourceRange();
9860 emitBadConversionNotes(S, Entity, Args[0]);
9861 break;
9862
9863 case FK_ConversionFailed: {
9864 QualType FromType = OnlyArg->getType();
9865 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9866 << (int)Entity.getKind()
9867 << DestType
9868 << OnlyArg->isLValue()
9869 << FromType
9870 << Args[0]->getSourceRange();
9871 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9872 S.Diag(Kind.getLocation(), PDiag);
9873 emitBadConversionNotes(S, Entity, Args[0]);
9874 break;
9875 }
9876
9878 // No-op. This error has already been reported.
9879 break;
9880
9882 SourceRange R;
9883
9884 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9885 if (InitList && InitList->getNumInits() >= 1) {
9886 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9887 } else {
9888 assert(Args.size() > 1 && "Expected multiple initializers!");
9889 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9890 }
9891
9893 if (Kind.isCStyleOrFunctionalCast())
9894 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9895 << R;
9896 else
9897 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9898 << /*scalar=*/2 << R;
9899 break;
9900 }
9901
9903 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9904 << 0 << Entity.getType() << Args[0]->getSourceRange();
9905 break;
9906
9908 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9909 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9910 break;
9911
9913 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9914 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9915 break;
9916
9919 SourceRange ArgsRange;
9920 if (Args.size())
9921 ArgsRange =
9922 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9923
9924 if (Failure == FK_ListConstructorOverloadFailed) {
9925 assert(Args.size() == 1 &&
9926 "List construction from other than 1 argument.");
9927 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9928 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9929 }
9930
9931 // FIXME: Using "DestType" for the entity we're printing is probably
9932 // bad.
9933 switch (FailedOverloadResult) {
9934 case OR_Ambiguous:
9935 FailedCandidateSet.NoteCandidates(
9936 PartialDiagnosticAt(Kind.getLocation(),
9937 S.PDiag(diag::err_ovl_ambiguous_init)
9938 << DestType << ArgsRange),
9939 S, OCD_AmbiguousCandidates, Args);
9940 break;
9941
9943 if (Kind.getKind() == InitializationKind::IK_Default &&
9944 (Entity.getKind() == InitializedEntity::EK_Base ||
9947 isa<CXXConstructorDecl>(S.CurContext)) {
9948 // This is implicit default initialization of a member or
9949 // base within a constructor. If no viable function was
9950 // found, notify the user that they need to explicitly
9951 // initialize this base/member.
9952 CXXConstructorDecl *Constructor
9953 = cast<CXXConstructorDecl>(S.CurContext);
9954 const CXXRecordDecl *InheritedFrom = nullptr;
9955 if (auto Inherited = Constructor->getInheritedConstructor())
9956 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9957 if (Entity.getKind() == InitializedEntity::EK_Base) {
9958 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9959 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9960 << S.Context.getTypeDeclType(Constructor->getParent())
9961 << /*base=*/0
9962 << Entity.getType()
9963 << InheritedFrom;
9964
9965 RecordDecl *BaseDecl
9966 = Entity.getBaseSpecifier()->getType()->castAs<RecordType>()
9967 ->getDecl();
9968 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9969 << S.Context.getTagDeclType(BaseDecl);
9970 } else {
9971 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9972 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9973 << S.Context.getTypeDeclType(Constructor->getParent())
9974 << /*member=*/1
9975 << Entity.getName()
9976 << InheritedFrom;
9977 S.Diag(Entity.getDecl()->getLocation(),
9978 diag::note_member_declared_at);
9979
9980 if (const RecordType *Record
9981 = Entity.getType()->getAs<RecordType>())
9982 S.Diag(Record->getDecl()->getLocation(),
9983 diag::note_previous_decl)
9984 << S.Context.getTagDeclType(Record->getDecl());
9985 }
9986 break;
9987 }
9988
9989 FailedCandidateSet.NoteCandidates(
9991 Kind.getLocation(),
9992 S.PDiag(diag::err_ovl_no_viable_function_in_init)
9993 << DestType << ArgsRange),
9994 S, OCD_AllCandidates, Args);
9995 break;
9996
9997 case OR_Deleted: {
10000 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
10001 if (Ovl != OR_Deleted) {
10002 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
10003 << DestType << ArgsRange;
10004 llvm_unreachable("Inconsistent overload resolution?");
10005 break;
10006 }
10007
10008 // If this is a defaulted or implicitly-declared function, then
10009 // it was implicitly deleted. Make it clear that the deletion was
10010 // implicit.
10011 if (S.isImplicitlyDeleted(Best->Function))
10012 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
10013 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
10014 << DestType << ArgsRange;
10015 else
10016 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
10017 << DestType << ArgsRange;
10018
10019 S.NoteDeletedFunction(Best->Function);
10020 break;
10021 }
10022
10023 case OR_Success:
10024 llvm_unreachable("Conversion did not fail!");
10025 }
10026 }
10027 break;
10028
10030 if (Entity.getKind() == InitializedEntity::EK_Member &&
10031 isa<CXXConstructorDecl>(S.CurContext)) {
10032 // This is implicit default-initialization of a const member in
10033 // a constructor. Complain that it needs to be explicitly
10034 // initialized.
10035 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
10036 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
10037 << (Constructor->getInheritedConstructor() ? 2 :
10038 Constructor->isImplicit() ? 1 : 0)
10039 << S.Context.getTypeDeclType(Constructor->getParent())
10040 << /*const=*/1
10041 << Entity.getName();
10042 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
10043 << Entity.getName();
10044 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
10045 VD && VD->isConstexpr()) {
10046 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
10047 << VD;
10048 } else {
10049 S.Diag(Kind.getLocation(), diag::err_default_init_const)
10050 << DestType << (bool)DestType->getAs<RecordType>();
10051 }
10052 break;
10053
10054 case FK_Incomplete:
10055 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
10056 diag::err_init_incomplete_type);
10057 break;
10058
10060 // Run the init list checker again to emit diagnostics.
10061 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
10062 diagnoseListInit(S, Entity, InitList);
10063 break;
10064 }
10065
10066 case FK_PlaceholderType: {
10067 // FIXME: Already diagnosed!
10068 break;
10069 }
10070
10072 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
10073 << Args[0]->getSourceRange();
10076 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
10077 (void)Ovl;
10078 assert(Ovl == OR_Success && "Inconsistent overload resolution");
10079 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
10080 S.Diag(CtorDecl->getLocation(),
10081 diag::note_explicit_ctor_deduction_guide_here) << false;
10082 break;
10083 }
10084
10086 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
10087 /*VerifyOnly=*/false);
10088 break;
10089
10091 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
10092 S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
10093 << Entity.getType() << InitList->getSourceRange();
10094 break;
10095 }
10096
10097 PrintInitLocationNote(S, Entity);
10098 return true;
10099}
10100
10101void InitializationSequence::dump(raw_ostream &OS) const {
10102 switch (SequenceKind) {
10103 case FailedSequence: {
10104 OS << "Failed sequence: ";
10105 switch (Failure) {
10107 OS << "too many initializers for reference";
10108 break;
10109
10111 OS << "parenthesized list init for reference";
10112 break;
10113
10115 OS << "array requires initializer list";
10116 break;
10117
10119 OS << "address of unaddressable function was taken";
10120 break;
10121
10123 OS << "array requires initializer list or string literal";
10124 break;
10125
10127 OS << "array requires initializer list or wide string literal";
10128 break;
10129
10131 OS << "narrow string into wide char array";
10132 break;
10133
10135 OS << "wide string into char array";
10136 break;
10137
10139 OS << "incompatible wide string into wide char array";
10140 break;
10141
10143 OS << "plain string literal into char8_t array";
10144 break;
10145
10147 OS << "u8 string literal into char array";
10148 break;
10149
10151 OS << "array type mismatch";
10152 break;
10153
10155 OS << "non-constant array initializer";
10156 break;
10157
10159 OS << "address of overloaded function failed";
10160 break;
10161
10163 OS << "overload resolution for reference initialization failed";
10164 break;
10165
10167 OS << "non-const lvalue reference bound to temporary";
10168 break;
10169
10171 OS << "non-const lvalue reference bound to bit-field";
10172 break;
10173
10175 OS << "non-const lvalue reference bound to vector element";
10176 break;
10177
10179 OS << "non-const lvalue reference bound to matrix element";
10180 break;
10181
10183 OS << "non-const lvalue reference bound to unrelated type";
10184 break;
10185
10187 OS << "rvalue reference bound to an lvalue";
10188 break;
10189
10191 OS << "reference initialization drops qualifiers";
10192 break;
10193
10195 OS << "reference with mismatching address space bound to temporary";
10196 break;
10197
10199 OS << "reference initialization failed";
10200 break;
10201
10203 OS << "conversion failed";
10204 break;
10205
10207 OS << "conversion from property failed";
10208 break;
10209
10211 OS << "too many initializers for scalar";
10212 break;
10213
10215 OS << "parenthesized list init for reference";
10216 break;
10217
10219 OS << "referencing binding to initializer list";
10220 break;
10221
10223 OS << "initializer list for non-aggregate, non-scalar type";
10224 break;
10225
10227 OS << "overloading failed for user-defined conversion";
10228 break;
10229
10231 OS << "constructor overloading failed";
10232 break;
10233
10235 OS << "default initialization of a const variable";
10236 break;
10237
10238 case FK_Incomplete:
10239 OS << "initialization of incomplete type";
10240 break;
10241
10243 OS << "list initialization checker failure";
10244 break;
10245
10247 OS << "variable length array has an initializer";
10248 break;
10249
10250 case FK_PlaceholderType:
10251 OS << "initializer expression isn't contextually valid";
10252 break;
10253
10255 OS << "list constructor overloading failed";
10256 break;
10257
10259 OS << "list copy initialization chose explicit constructor";
10260 break;
10261
10263 OS << "parenthesized list initialization failed";
10264 break;
10265
10267 OS << "designated initializer for non-aggregate type";
10268 break;
10269 }
10270 OS << '\n';
10271 return;
10272 }
10273
10274 case DependentSequence:
10275 OS << "Dependent sequence\n";
10276 return;
10277
10278 case NormalSequence:
10279 OS << "Normal sequence: ";
10280 break;
10281 }
10282
10283 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
10284 if (S != step_begin()) {
10285 OS << " -> ";
10286 }
10287
10288 switch (S->Kind) {
10290 OS << "resolve address of overloaded function";
10291 break;
10292
10294 OS << "derived-to-base (prvalue)";
10295 break;
10296
10298 OS << "derived-to-base (xvalue)";
10299 break;
10300
10302 OS << "derived-to-base (lvalue)";
10303 break;
10304
10305 case SK_BindReference:
10306 OS << "bind reference to lvalue";
10307 break;
10308
10310 OS << "bind reference to a temporary";
10311 break;
10312
10313 case SK_FinalCopy:
10314 OS << "final copy in class direct-initialization";
10315 break;
10316
10318 OS << "extraneous C++03 copy to temporary";
10319 break;
10320
10321 case SK_UserConversion:
10322 OS << "user-defined conversion via " << *S->Function.Function;
10323 break;
10324
10326 OS << "qualification conversion (prvalue)";
10327 break;
10328
10330 OS << "qualification conversion (xvalue)";
10331 break;
10332
10334 OS << "qualification conversion (lvalue)";
10335 break;
10336
10338 OS << "function reference conversion";
10339 break;
10340
10342 OS << "non-atomic-to-atomic conversion";
10343 break;
10344
10346 OS << "implicit conversion sequence (";
10347 S->ICS->dump(); // FIXME: use OS
10348 OS << ")";
10349 break;
10350
10352 OS << "implicit conversion sequence with narrowing prohibited (";
10353 S->ICS->dump(); // FIXME: use OS
10354 OS << ")";
10355 break;
10356
10358 OS << "list aggregate initialization";
10359 break;
10360
10361 case SK_UnwrapInitList:
10362 OS << "unwrap reference initializer list";
10363 break;
10364
10365 case SK_RewrapInitList:
10366 OS << "rewrap reference initializer list";
10367 break;
10368
10370 OS << "constructor initialization";
10371 break;
10372
10374 OS << "list initialization via constructor";
10375 break;
10376
10378 OS << "zero initialization";
10379 break;
10380
10381 case SK_CAssignment:
10382 OS << "C assignment";
10383 break;
10384
10385 case SK_StringInit:
10386 OS << "string initialization";
10387 break;
10388
10390 OS << "Objective-C object conversion";
10391 break;
10392
10393 case SK_ArrayLoopIndex:
10394 OS << "indexing for array initialization loop";
10395 break;
10396
10397 case SK_ArrayLoopInit:
10398 OS << "array initialization loop";
10399 break;
10400
10401 case SK_ArrayInit:
10402 OS << "array initialization";
10403 break;
10404
10405 case SK_GNUArrayInit:
10406 OS << "array initialization (GNU extension)";
10407 break;
10408
10410 OS << "parenthesized array initialization";
10411 break;
10412
10414 OS << "pass by indirect copy and restore";
10415 break;
10416
10418 OS << "pass by indirect restore";
10419 break;
10420
10422 OS << "Objective-C object retension";
10423 break;
10424
10426 OS << "std::initializer_list from initializer list";
10427 break;
10428
10430 OS << "list initialization from std::initializer_list";
10431 break;
10432
10433 case SK_OCLSamplerInit:
10434 OS << "OpenCL sampler_t from integer constant";
10435 break;
10436
10438 OS << "OpenCL opaque type from zero";
10439 break;
10441 OS << "initialization from a parenthesized list of values";
10442 break;
10443 }
10444
10445 OS << " [" << S->Type << ']';
10446 }
10447
10448 OS << '\n';
10449}
10450
10452 dump(llvm::errs());
10453}
10454
10456 const ImplicitConversionSequence &ICS,
10457 QualType PreNarrowingType,
10458 QualType EntityType,
10459 const Expr *PostInit) {
10460 const StandardConversionSequence *SCS = nullptr;
10461 switch (ICS.getKind()) {
10463 SCS = &ICS.Standard;
10464 break;
10466 SCS = &ICS.UserDefined.After;
10467 break;
10472 return;
10473 }
10474
10475 auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
10476 unsigned ConstRefDiagID, unsigned WarnDiagID) {
10477 unsigned DiagID;
10478 auto &L = S.getLangOpts();
10479 if (L.CPlusPlus11 &&
10480 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))
10481 DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
10482 else
10483 DiagID = WarnDiagID;
10484 return S.Diag(PostInit->getBeginLoc(), DiagID)
10485 << PostInit->getSourceRange();
10486 };
10487
10488 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
10489 APValue ConstantValue;
10490 QualType ConstantType;
10491 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
10492 ConstantType)) {
10493 case NK_Not_Narrowing:
10495 // No narrowing occurred.
10496 return;
10497
10498 case NK_Type_Narrowing: {
10499 // This was a floating-to-integer conversion, which is always considered a
10500 // narrowing conversion even if the value is a constant and can be
10501 // represented exactly as an integer.
10502 QualType T = EntityType.getNonReferenceType();
10503 MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
10504 diag::ext_init_list_type_narrowing_const_reference,
10505 diag::warn_init_list_type_narrowing)
10506 << PreNarrowingType.getLocalUnqualifiedType()
10508 break;
10509 }
10510
10511 case NK_Constant_Narrowing: {
10512 // A constant value was narrowed.
10513 MakeDiag(EntityType.getNonReferenceType() != EntityType,
10514 diag::ext_init_list_constant_narrowing,
10515 diag::ext_init_list_constant_narrowing_const_reference,
10516 diag::warn_init_list_constant_narrowing)
10517 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
10519 break;
10520 }
10521
10522 case NK_Variable_Narrowing: {
10523 // A variable's value may have been narrowed.
10524 MakeDiag(EntityType.getNonReferenceType() != EntityType,
10525 diag::ext_init_list_variable_narrowing,
10526 diag::ext_init_list_variable_narrowing_const_reference,
10527 diag::warn_init_list_variable_narrowing)
10528 << PreNarrowingType.getLocalUnqualifiedType()
10530 break;
10531 }
10532 }
10533
10534 SmallString<128> StaticCast;
10535 llvm::raw_svector_ostream OS(StaticCast);
10536 OS << "static_cast<";
10537 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
10538 // It's important to use the typedef's name if there is one so that the
10539 // fixit doesn't break code using types like int64_t.
10540 //
10541 // FIXME: This will break if the typedef requires qualification. But
10542 // getQualifiedNameAsString() includes non-machine-parsable components.
10543 OS << *TT->getDecl();
10544 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
10545 OS << BT->getName(S.getLangOpts());
10546 else {
10547 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
10548 // with a broken cast.
10549 return;
10550 }
10551 OS << ">(";
10552 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
10553 << PostInit->getSourceRange()
10554 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
10556 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
10557}
10558
10560 QualType ToType, Expr *Init) {
10561 assert(S.getLangOpts().C23);
10563 Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
10564 Sema::AllowedExplicit::None,
10565 /*InOverloadResolution*/ false,
10566 /*CStyle*/ false,
10567 /*AllowObjCWritebackConversion=*/false);
10568
10569 if (!ICS.isStandard())
10570 return;
10571
10572 APValue Value;
10573 QualType PreNarrowingType;
10574 // Reuse C++ narrowing check.
10575 switch (ICS.Standard.getNarrowingKind(
10576 S.Context, Init, Value, PreNarrowingType,
10577 /*IgnoreFloatToIntegralConversion*/ false)) {
10578 // The value doesn't fit.
10580 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
10581 << Value.getAsString(S.Context, PreNarrowingType) << ToType;
10582 return;
10583
10584 // Conversion to a narrower type.
10585 case NK_Type_Narrowing:
10586 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
10587 << ToType << FromType;
10588 return;
10589
10590 // Since we only reuse narrowing check for C23 constexpr variables here, we're
10591 // not really interested in these cases.
10594 case NK_Not_Narrowing:
10595 return;
10596 }
10597 llvm_unreachable("unhandled case in switch");
10598}
10599
10601 Sema &SemaRef, QualType &TT) {
10602 assert(SemaRef.getLangOpts().C23);
10603 // character that string literal contains fits into TT - target type.
10604 const ArrayType *AT = SemaRef.Context.getAsArrayType(TT);
10605 QualType CharType = AT->getElementType();
10606 uint32_t BitWidth = SemaRef.Context.getTypeSize(CharType);
10607 bool isUnsigned = CharType->isUnsignedIntegerType();
10608 llvm::APSInt Value(BitWidth, isUnsigned);
10609 for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
10610 int64_t C = SE->getCodeUnitS(I, SemaRef.Context.getCharWidth());
10611 Value = C;
10612 if (Value != C) {
10613 SemaRef.Diag(SemaRef.getLocationOfStringLiteralByte(SE, I),
10614 diag::err_c23_constexpr_init_not_representable)
10615 << C << CharType;
10616 return;
10617 }
10618 }
10619 return;
10620}
10621
10622//===----------------------------------------------------------------------===//
10623// Initialization helper functions
10624//===----------------------------------------------------------------------===//
10625bool
10627 ExprResult Init) {
10628 if (Init.isInvalid())
10629 return false;
10630
10631 Expr *InitE = Init.get();
10632 assert(InitE && "No initialization expression");
10633
10634 InitializationKind Kind =
10636 InitializationSequence Seq(*this, Entity, Kind, InitE);
10637 return !Seq.Failed();
10638}
10639
10642 SourceLocation EqualLoc,
10644 bool TopLevelOfInitList,
10645 bool AllowExplicit) {
10646 if (Init.isInvalid())
10647 return ExprError();
10648
10649 Expr *InitE = Init.get();
10650 assert(InitE && "No initialization expression?");
10651
10652 if (EqualLoc.isInvalid())
10653 EqualLoc = InitE->getBeginLoc();
10654
10656 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
10657 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10658
10659 // Prevent infinite recursion when performing parameter copy-initialization.
10660 const bool ShouldTrackCopy =
10661 Entity.isParameterKind() && Seq.isConstructorInitialization();
10662 if (ShouldTrackCopy) {
10663 if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
10664 Seq.SetOverloadFailure(
10667
10668 // Try to give a meaningful diagnostic note for the problematic
10669 // constructor.
10670 const auto LastStep = Seq.step_end() - 1;
10671 assert(LastStep->Kind ==
10673 const FunctionDecl *Function = LastStep->Function.Function;
10674 auto Candidate =
10675 llvm::find_if(Seq.getFailedCandidateSet(),
10676 [Function](const OverloadCandidate &Candidate) -> bool {
10677 return Candidate.Viable &&
10678 Candidate.Function == Function &&
10679 Candidate.Conversions.size() > 0;
10680 });
10681 if (Candidate != Seq.getFailedCandidateSet().end() &&
10682 Function->getNumParams() > 0) {
10683 Candidate->Viable = false;
10686 InitE,
10687 Function->getParamDecl(0)->getType());
10688 }
10689 }
10690 CurrentParameterCopyTypes.push_back(Entity.getType());
10691 }
10692
10693 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
10694
10695 if (ShouldTrackCopy)
10696 CurrentParameterCopyTypes.pop_back();
10697
10698 return Result;
10699}
10700
10701/// Determine whether RD is, or is derived from, a specialization of CTD.
10703 ClassTemplateDecl *CTD) {
10704 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10705 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
10706 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
10707 };
10708 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
10709}
10710
10712 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10713 const InitializationKind &Kind, MultiExprArg Inits) {
10714 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10715 TSInfo->getType()->getContainedDeducedType());
10716 assert(DeducedTST && "not a deduced template specialization type");
10717
10718 auto TemplateName = DeducedTST->getTemplateName();
10720 return SubstAutoTypeDependent(TSInfo->getType());
10721
10722 // We can only perform deduction for class templates or alias templates.
10723 auto *Template =
10724 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10725 TemplateDecl *LookupTemplateDecl = Template;
10726 if (!Template) {
10727 if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
10729 Diag(Kind.getLocation(),
10730 diag::warn_cxx17_compat_ctad_for_alias_templates);
10731 LookupTemplateDecl = AliasTemplate;
10732 auto UnderlyingType = AliasTemplate->getTemplatedDecl()
10733 ->getUnderlyingType()
10734 .getCanonicalType();
10735 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
10736 // of the form
10737 // [typename] [nested-name-specifier] [template] simple-template-id
10738 if (const auto *TST =
10739 UnderlyingType->getAs<TemplateSpecializationType>()) {
10740 Template = dyn_cast_or_null<ClassTemplateDecl>(
10741 TST->getTemplateName().getAsTemplateDecl());
10742 } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
10743 // Cases where template arguments in the RHS of the alias are not
10744 // dependent. e.g.
10745 // using AliasFoo = Foo<bool>;
10746 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(
10747 RT->getAsCXXRecordDecl()))
10748 Template = CTSD->getSpecializedTemplate();
10749 }
10750 }
10751 }
10752 if (!Template) {
10753 Diag(Kind.getLocation(),
10754 diag::err_deduced_non_class_or_alias_template_specialization_type)
10756 if (auto *TD = TemplateName.getAsTemplateDecl())
10758 return QualType();
10759 }
10760
10761 // Can't deduce from dependent arguments.
10763 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10764 diag::warn_cxx14_compat_class_template_argument_deduction)
10765 << TSInfo->getTypeLoc().getSourceRange() << 0;
10766 return SubstAutoTypeDependent(TSInfo->getType());
10767 }
10768
10769 // FIXME: Perform "exact type" matching first, per CWG discussion?
10770 // Or implement this via an implied 'T(T) -> T' deduction guide?
10771
10772 // FIXME: Do we need/want a std::initializer_list<T> special case?
10773
10774 // Look up deduction guides, including those synthesized from constructors.
10775 //
10776 // C++1z [over.match.class.deduct]p1:
10777 // A set of functions and function templates is formed comprising:
10778 // - For each constructor of the class template designated by the
10779 // template-name, a function template [...]
10780 // - For each deduction-guide, a function or function template [...]
10781 DeclarationNameInfo NameInfo(
10783 TSInfo->getTypeLoc().getEndLoc());
10784 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10785 LookupQualifiedName(Guides, LookupTemplateDecl->getDeclContext());
10786
10787 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10788 // clear on this, but they're not found by name so access does not apply.
10789 Guides.suppressDiagnostics();
10790
10791 // Figure out if this is list-initialization.
10793 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10794 ? dyn_cast<InitListExpr>(Inits[0])
10795 : nullptr;
10796
10797 // C++1z [over.match.class.deduct]p1:
10798 // Initialization and overload resolution are performed as described in
10799 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10800 // (as appropriate for the type of initialization performed) for an object
10801 // of a hypothetical class type, where the selected functions and function
10802 // templates are considered to be the constructors of that class type
10803 //
10804 // Since we know we're initializing a class type of a type unrelated to that
10805 // of the initializer, this reduces to something fairly reasonable.
10806 OverloadCandidateSet Candidates(Kind.getLocation(),
10809
10810 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10811
10812 // Return true if the candidate is added successfully, false otherwise.
10813 auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10815 DeclAccessPair FoundDecl,
10816 bool OnlyListConstructors,
10817 bool AllowAggregateDeductionCandidate) {
10818 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10819 // For copy-initialization, the candidate functions are all the
10820 // converting constructors (12.3.1) of that class.
10821 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10822 // The converting constructors of T are candidate functions.
10823 if (!AllowExplicit) {
10824 // Overload resolution checks whether the deduction guide is declared
10825 // explicit for us.
10826
10827 // When looking for a converting constructor, deduction guides that
10828 // could never be called with one argument are not interesting to
10829 // check or note.
10830 if (GD->getMinRequiredArguments() > 1 ||
10831 (GD->getNumParams() == 0 && !GD->isVariadic()))
10832 return;
10833 }
10834
10835 // C++ [over.match.list]p1.1: (first phase list initialization)
10836 // Initially, the candidate functions are the initializer-list
10837 // constructors of the class T
10838 if (OnlyListConstructors && !isInitListConstructor(GD))
10839 return;
10840
10841 if (!AllowAggregateDeductionCandidate &&
10842 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10843 return;
10844
10845 // C++ [over.match.list]p1.2: (second phase list initialization)
10846 // the candidate functions are all the constructors of the class T
10847 // C++ [over.match.ctor]p1: (all other cases)
10848 // the candidate functions are all the constructors of the class of
10849 // the object being initialized
10850
10851 // C++ [over.best.ics]p4:
10852 // When [...] the constructor [...] is a candidate by
10853 // - [over.match.copy] (in all cases)
10854 // FIXME: The "second phase of [over.match.list] case can also
10855 // theoretically happen here, but it's not clear whether we can
10856 // ever have a parameter of the right type.
10857 bool SuppressUserConversions = Kind.isCopyInit();
10858
10859 if (TD) {
10860 SmallVector<Expr *, 8> TmpInits;
10861 for (Expr *E : Inits)
10862 if (auto *DI = dyn_cast<DesignatedInitExpr>(E))
10863 TmpInits.push_back(DI->getInit());
10864 else
10865 TmpInits.push_back(E);
10867 TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
10868 SuppressUserConversions,
10869 /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
10870 /*PO=*/{}, AllowAggregateDeductionCandidate);
10871 } else {
10872 AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
10873 SuppressUserConversions,
10874 /*PartialOverloading=*/false, AllowExplicit);
10875 }
10876 };
10877
10878 bool FoundDeductionGuide = false;
10879
10880 auto TryToResolveOverload =
10881 [&](bool OnlyListConstructors) -> OverloadingResult {
10883 bool HasAnyDeductionGuide = false;
10884
10885 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10886 auto *Pattern = Template;
10887 while (Pattern->getInstantiatedFromMemberTemplate()) {
10888 if (Pattern->isMemberSpecialization())
10889 break;
10890 Pattern = Pattern->getInstantiatedFromMemberTemplate();
10891 }
10892
10893 auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());
10894 if (!(RD->getDefinition() && RD->isAggregate()))
10895 return;
10897 SmallVector<QualType, 8> ElementTypes;
10898
10899 InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10900 if (!CheckInitList.HadError()) {
10901 // C++ [over.match.class.deduct]p1.8:
10902 // if e_i is of array type and x_i is a braced-init-list, T_i is an
10903 // rvalue reference to the declared type of e_i and
10904 // C++ [over.match.class.deduct]p1.9:
10905 // if e_i is of array type and x_i is a bstring-literal, T_i is an
10906 // lvalue reference to the const-qualified declared type of e_i and
10907 // C++ [over.match.class.deduct]p1.10:
10908 // otherwise, T_i is the declared type of e_i
10909 for (int I = 0, E = ListInit->getNumInits();
10910 I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
10911 if (ElementTypes[I]->isArrayType()) {
10912 if (isa<InitListExpr>(ListInit->getInit(I)))
10913 ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);
10914 else if (isa<StringLiteral>(
10915 ListInit->getInit(I)->IgnoreParenImpCasts()))
10916 ElementTypes[I] =
10917 Context.getLValueReferenceType(ElementTypes[I].withConst());
10918 }
10919
10920 llvm::FoldingSetNodeID ID;
10921 ID.AddPointer(Template);
10922 for (auto &T : ElementTypes)
10923 T.getCanonicalType().Profile(ID);
10924 unsigned Hash = ID.ComputeHash();
10925 if (AggregateDeductionCandidates.count(Hash) == 0) {
10926 if (FunctionTemplateDecl *TD =
10928 Template, ElementTypes,
10929 TSInfo->getTypeLoc().getEndLoc())) {
10930 auto *GD = cast<CXXDeductionGuideDecl>(TD->getTemplatedDecl());
10931 GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
10933 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10934 OnlyListConstructors,
10935 /*AllowAggregateDeductionCandidate=*/true);
10936 }
10937 } else {
10940 assert(TD && "aggregate deduction candidate is function template");
10941 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10942 OnlyListConstructors,
10943 /*AllowAggregateDeductionCandidate=*/true);
10944 }
10945 HasAnyDeductionGuide = true;
10946 }
10947 };
10948
10949 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10950 NamedDecl *D = (*I)->getUnderlyingDecl();
10951 if (D->isInvalidDecl())
10952 continue;
10953
10954 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10955 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10956 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10957 if (!GD)
10958 continue;
10959
10960 if (!GD->isImplicit())
10961 HasAnyDeductionGuide = true;
10962
10963 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10964 /*AllowAggregateDeductionCandidate=*/false);
10965 }
10966
10967 // C++ [over.match.class.deduct]p1.4:
10968 // if C is defined and its definition satisfies the conditions for an
10969 // aggregate class ([dcl.init.aggr]) with the assumption that any
10970 // dependent base class has no virtual functions and no virtual base
10971 // classes, and the initializer is a non-empty braced-init-list or
10972 // parenthesized expression-list, and there are no deduction-guides for
10973 // C, the set contains an additional function template, called the
10974 // aggregate deduction candidate, defined as follows.
10975 if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10976 if (ListInit && ListInit->getNumInits()) {
10977 SynthesizeAggrGuide(ListInit);
10978 } else if (Inits.size()) { // parenthesized expression-list
10979 // Inits are expressions inside the parentheses. We don't have
10980 // the parentheses source locations, use the begin/end of Inits as the
10981 // best heuristic.
10982 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10983 Inits, Inits.back()->getEndLoc());
10984 SynthesizeAggrGuide(&TempListInit);
10985 }
10986 }
10987
10988 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10989
10990 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
10991 };
10992
10994
10995 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10996 // try initializer-list constructors.
10997 if (ListInit) {
10998 bool TryListConstructors = true;
10999
11000 // Try list constructors unless the list is empty and the class has one or
11001 // more default constructors, in which case those constructors win.
11002 if (!ListInit->getNumInits()) {
11003 for (NamedDecl *D : Guides) {
11004 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
11005 if (FD && FD->getMinRequiredArguments() == 0) {
11006 TryListConstructors = false;
11007 break;
11008 }
11009 }
11010 } else if (ListInit->getNumInits() == 1) {
11011 // C++ [over.match.class.deduct]:
11012 // As an exception, the first phase in [over.match.list] (considering
11013 // initializer-list constructors) is omitted if the initializer list
11014 // consists of a single expression of type cv U, where U is a
11015 // specialization of C or a class derived from a specialization of C.
11016 Expr *E = ListInit->getInit(0);
11017 auto *RD = E->getType()->getAsCXXRecordDecl();
11018 if (!isa<InitListExpr>(E) && RD &&
11019 isCompleteType(Kind.getLocation(), E->getType()) &&
11021 TryListConstructors = false;
11022 }
11023
11024 if (TryListConstructors)
11025 Result = TryToResolveOverload(/*OnlyListConstructor*/true);
11026 // Then unwrap the initializer list and try again considering all
11027 // constructors.
11028 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
11029 }
11030
11031 // If list-initialization fails, or if we're doing any other kind of
11032 // initialization, we (eventually) consider constructors.
11034 Result = TryToResolveOverload(/*OnlyListConstructor*/false);
11035
11036 switch (Result) {
11037 case OR_Ambiguous:
11038 // FIXME: For list-initialization candidates, it'd usually be better to
11039 // list why they were not viable when given the initializer list itself as
11040 // an argument.
11041 Candidates.NoteCandidates(
11043 Kind.getLocation(),
11044 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
11045 << TemplateName),
11046 *this, OCD_AmbiguousCandidates, Inits);
11047 return QualType();
11048
11049 case OR_No_Viable_Function: {
11050 CXXRecordDecl *Primary =
11051 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
11052 bool Complete =
11053 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
11054 Candidates.NoteCandidates(
11056 Kind.getLocation(),
11057 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
11058 : diag::err_deduced_class_template_incomplete)
11059 << TemplateName << !Guides.empty()),
11060 *this, OCD_AllCandidates, Inits);
11061 return QualType();
11062 }
11063
11064 case OR_Deleted: {
11065 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
11066 << TemplateName;
11067 NoteDeletedFunction(Best->Function);
11068 return QualType();
11069 }
11070
11071 case OR_Success:
11072 // C++ [over.match.list]p1:
11073 // In copy-list-initialization, if an explicit constructor is chosen, the
11074 // initialization is ill-formed.
11075 if (Kind.isCopyInit() && ListInit &&
11076 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
11077 bool IsDeductionGuide = !Best->Function->isImplicit();
11078 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
11079 << TemplateName << IsDeductionGuide;
11080 Diag(Best->Function->getLocation(),
11081 diag::note_explicit_ctor_deduction_guide_here)
11082 << IsDeductionGuide;
11083 return QualType();
11084 }
11085
11086 // Make sure we didn't select an unusable deduction guide, and mark it
11087 // as referenced.
11088 DiagnoseUseOfDecl(Best->FoundDecl, Kind.getLocation());
11089 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
11090 break;
11091 }
11092
11093 // C++ [dcl.type.class.deduct]p1:
11094 // The placeholder is replaced by the return type of the function selected
11095 // by overload resolution for class template deduction.
11097 SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
11098 Diag(TSInfo->getTypeLoc().getBeginLoc(),
11099 diag::warn_cxx14_compat_class_template_argument_deduction)
11100 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
11101
11102 // Warn if CTAD was used on a type that does not have any user-defined
11103 // deduction guides.
11104 if (!FoundDeductionGuide) {
11105 Diag(TSInfo->getTypeLoc().getBeginLoc(),
11106 diag::warn_ctad_maybe_unsupported)
11107 << TemplateName;
11108 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
11109 }
11110
11111 return DeducedType;
11112}
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:28
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:563
static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD)
Definition: SemaInit.cpp:7538
static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E)
Tries to get a FunctionDecl out of E.
Definition: SemaInit.cpp:6118
static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee)
Definition: SemaInit.cpp:7421
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:172
static void updateGNUCompoundLiteralRValue(Expr *E)
Fix a compound literal initializing an array so it's correctly marked as an rvalue.
Definition: SemaInit.cpp:184
static bool initializingConstexprVariable(const InitializedEntity &Entity)
Definition: SemaInit.cpp:193
static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call, LocalVisitor Visit)
Definition: SemaInit.cpp:7575
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:1170
static bool shouldDestroyEntity(const InitializedEntity &Entity)
Whether the given entity, when initialized with an object created for that initialization,...
Definition: SemaInit.cpp:6687
static SourceLocation getInitializationLoc(const InitializedEntity &Entity, Expr *Initializer)
Get the location at which initialization diagnostics should appear.
Definition: SemaInit.cpp:6720
static bool hasAnyDesignatedInits(const InitListExpr *IL)
Definition: SemaInit.cpp:973
static bool tryObjCWritebackConversion(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity, Expr *Initializer)
Definition: SemaInit.cpp:6000
static DesignatedInitExpr * CloneDesignatedInitExpr(Sema &SemaRef, DesignatedInitExpr *DIE)
Definition: SemaInit.cpp:2493
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:6778
static Sema::AssignmentAction getAssignmentAction(const InitializedEntity &Entity, bool Diagnose=false)
Definition: SemaInit.cpp:6598
static void TryOrBuildParenListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args, InitializationSequence &Sequence, bool VerifyOnly, ExprResult *Result=nullptr)
Definition: SemaInit.cpp:5445
static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, bool IsReturnStmt)
Provide warnings when std::move is used on construction.
Definition: SemaInit.cpp:8409
static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE, Sema &SemaRef, QualType &TT)
Definition: SemaInit.cpp:10600
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:6929
static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, ClassTemplateDecl *CTD)
Determine whether RD is, or is derived from, a specialization of CTD.
Definition: SemaInit.cpp:10702
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:4066
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:72
StringInitFailureKind
Definition: SemaInit.cpp:58
@ SIF_None
Definition: SemaInit.cpp:59
@ SIF_PlainStringIntoUTF8Char
Definition: SemaInit.cpp:64
@ SIF_IncompatWideStringIntoWideChar
Definition: SemaInit.cpp:62
@ SIF_UTF8StringIntoPlainChar
Definition: SemaInit.cpp:63
@ SIF_NarrowStringIntoWideChar
Definition: SemaInit.cpp:60
@ SIF_Other
Definition: SemaInit.cpp:65
@ SIF_WideStringIntoChar
Definition: SemaInit.cpp:61
static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call, LocalVisitor Visit)
Definition: SemaInit.cpp:7479
static void TryDefaultInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence)
Attempt default initialization (C++ [dcl.init]p6).
Definition: SemaInit.cpp:5407
static bool TryOCLSamplerInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
Definition: SemaInit.cpp:6047
static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path)
Definition: SemaInit.cpp:8108
static bool isInStlNamespace(const Decl *D)
Definition: SemaInit.cpp:7406
static bool maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
Tries to add a zero initializer. Returns true if that worked.
Definition: SemaInit.cpp:4006
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:3345
static bool canPerformArrayCopy(const InitializedEntity &Entity)
Determine whether we can perform an elementwise array copy for this kind of entity.
Definition: SemaInit.cpp:6129
static bool IsZeroInitializer(Expr *Initializer, Sema &S)
Definition: SemaInit.cpp:6060
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:4996
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:8066
static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType, QualType ToType, Expr *Init)
Definition: SemaInit.cpp:10559
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:2465
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:5329
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:5697
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:4114
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:7207
static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD)
Definition: SemaInit.cpp:7373
static bool shouldTrackFirstArgument(const FunctionDecl *FD)
Definition: SemaInit.cpp:7455
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:4556
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:5320
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:1925
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:4958
static void DiagnoseNarrowingInInitList(Sema &S, const ImplicitConversionSequence &ICS, QualType PreNarrowingType, QualType EntityType, const Expr *PostInit)
Definition: SemaInit.cpp:10455
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:5984
static bool pathContainsInit(IndirectLocalPath &Path)
Definition: SemaInit.cpp:7380
static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, Sema &S, bool CheckC23ConstexprInit=false)
Definition: SemaInit.cpp:211
static bool isRecordWithAttr(QualType Type)
Definition: SemaInit.cpp:7397
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:7005
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:4987
PathLifetimeKind
Whether a path to an object supports lifetime extension.
Definition: SemaInit.cpp:8051
@ ShouldExtend
We should lifetime-extend, but we don't because (due to technical limitations) we can't.
Definition: SemaInit.cpp:8058
@ NoExtend
Do not lifetime extend along this path.
Definition: SemaInit.cpp:8060
@ Extend
Lifetime-extend along this path.
Definition: SemaInit.cpp:8053
static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
Definition: SemaInit.cpp:6065
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:48
static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, InitListExpr *InitList)
Definition: SemaInit.cpp:9578
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:4773
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:4228
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:9547
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:1047
static void MaybeProduceObjCObject(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
Definition: SemaInit.cpp:4026
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:8078
static void checkIndirectCopyRestoreSource(Sema &S, Expr *src)
Check whether the given expression is a valid operand for an indirect copy/restore.
Definition: SemaInit.cpp:5966
static bool shouldBindAsTemporary(const InitializedEntity &Entity)
Whether we should bind a created object as a temporary when initializing the given entity.
Definition: SemaInit.cpp:6653
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:7642
static bool ResolveOverloadedFunctionForReferenceBinding(Sema &S, Expr *Initializer, QualType &SourceType, QualType &UnqualifiedSourceType, QualType UnqualifiedTargetType, InitializationSequence &Sequence)
Definition: SemaInit.cpp:4408
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:7778
InvalidICRKind
The non-zero enum values here are indexes into diagnostic alternatives.
Definition: SemaInit.cpp:5896
@ IIK_okay
Definition: SemaInit.cpp:5896
@ IIK_nonlocal
Definition: SemaInit.cpp:5896
@ IIK_nonscalar
Definition: SemaInit.cpp:5896
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:7030
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:4453
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:5884
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:4101
static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, QualType T)
Somewhere within T there is an uninitialized reference subobject.
Definition: SemaInit.cpp:9508
static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, bool isAddressOf, bool &isWeakAccess)
Determines whether this expression is an acceptable ICR source.
Definition: SemaInit.cpp:5899
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:945
bool isNullPointer() const
Definition: APValue.cpp:1009
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2749
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:645
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:2556
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2572
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:1095
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:2755
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:1582
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:772
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:1097
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2148
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:1116
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:2599
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:2322
CanQualType OCLSamplerTy
Definition: ASTContext.h:1124
CanQualType VoidTy
Definition: ASTContext.h:1088
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:2752
CanQualType Char32Ty
Definition: ASTContext.h:1096
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:754
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:1785
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:2326
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:5571
Represents a loop initializing the elements of an array.
Definition: Expr.h:5518
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:3307
QualType getElementType() const
Definition: Type.h:3319
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:2770
Kind getKind() const
Definition: Type.h:2812
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:1475
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1530
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1673
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1593
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1670
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2528
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2770
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2607
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition: DeclCXX.cpp:2771
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2855
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2895
Represents a C++ deduction guide declaration.
Definition: DeclCXX.h:1947
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2792
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2053
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2179
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:1161
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition: DeclCXX.h:1391
base_class_range bases()
Definition: DeclCXX.h:618
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition: DeclCXX.cpp:1832
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:612
llvm::iterator_range< base_class_iterator > base_class_range
Definition: DeclCXX.h:614
llvm::iterator_range< base_class_const_iterator > base_class_const_range
Definition: DeclCXX.h:616
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:2165
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:3516
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:3490
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:2875
QualType getElementType() const
Definition: Type.h:2885
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4186
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3344
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:3407
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:1379
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:2289
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2352
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1446
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2076
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2201
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:1958
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1785
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1921
bool isStdNamespace() const
Definition: DeclBase.cpp:1249
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2332
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:85
bool isInStdNamespace() const
Definition: DeclBase.cpp:403
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:440
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:598
bool isInvalidDecl() const
Definition: DeclBase.h:593
SourceLocation getLocation() const
Definition: DeclBase.h:444
DeclContext * getDeclContext()
Definition: DeclBase.h:453
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:436
bool hasAttr() const
Definition: DeclBase.h:582
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:5707
Represents a single C99 designator.
Definition: Expr.h:5142
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:5304
void setFieldDecl(FieldDecl *FD)
Definition: Expr.h:5240
FieldDecl * getFieldDecl() const
Definition: Expr.h:5233
SourceLocation getFieldLoc() const
Definition: Expr.h:5250
const IdentifierInfo * getFieldName() const
Definition: Expr.cpp:4546
SourceLocation getDotLoc() const
Definition: Expr.h:5245
SourceLocation getLBracketLoc() const
Definition: Expr.h:5286
Represents a C99 designated initializer expression.
Definition: Expr.h:5099
bool isDirectInit() const
Whether this designated initializer should result in direct-initialization of the designated subobjec...
Definition: Expr.h:5359
Expr * getArrayRangeEnd(const Designator &D) const
Definition: Expr.cpp:4655
void setInit(Expr *init)
Definition: Expr.h:5371
Expr * getSubExpr(unsigned Idx) const
Definition: Expr.h:5381
llvm::MutableArrayRef< Designator > designators()
Definition: Expr.h:5332
bool usesGNUSyntax() const
Determines whether this designated initializer used the deprecated GNU syntax for designated initiali...
Definition: Expr.h:5363
Expr * getArrayRangeStart(const Designator &D) const
Definition: Expr.cpp:4650
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:4662
static DesignatedInitExpr * Create(const ASTContext &C, llvm::ArrayRef< Designator > Designators, ArrayRef< Expr * > IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
Definition: Expr.cpp:4588
Expr * getArrayIndex(const Designator &D) const
Definition: Expr.cpp:4645
Designator * getDesignator(unsigned Idx)
Definition: Expr.h:5340
Expr * getInit() const
Retrieve the initializer value.
Definition: Expr.h:5367
unsigned size() const
Returns the number of designators in this initializer.
Definition: Expr.h:5329
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:4624
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:4641
SourceLocation getEqualOrColonLoc() const
Retrieve the location of the '=' that precedes the initializer value itself, if present.
Definition: Expr.h:5354
unsigned getNumSubExprs() const
Retrieve the total number of subexpressions in this designated initializer expression,...
Definition: Expr.h:5379
InitListExpr * getUpdater() const
Definition: Expr.h:5486
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:5335
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:3070
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:4139
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:3065
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3053
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3061
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:3285
@ 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:3562
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3045
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:3199
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:3924
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:3821
Represents difference between two FPOptions values.
Definition: LangOptions.h:901
Represents a member of a struct/union/class.
Definition: Decl.h:3025
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3186
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4611
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4633
bool isUnnamedBitfield() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:3119
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:1959
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2674
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3678
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4007
QualType getReturnType() const
Definition: Decl.h:2722
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2477
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2322
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3657
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
One of these records is kept for each identifier that is lexed.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2080
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:540
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition: Overload.h:591
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:595
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:739
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5607
Represents a C array with an unspecified size.
Definition: Type.h:3463
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3309
chain_iterator chain_end() const
Definition: Decl.h:3334
chain_iterator chain_begin() const
Definition: Decl.h:3333
ArrayRef< NamedDecl * >::const_iterator chain_iterator
Definition: Decl.h:3328
Describes an C or C++ initializer list.
Definition: Expr.h:4854
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition: Expr.h:4958
void setSyntacticForm(InitListExpr *Init)
Definition: Expr.h:5024
void markError()
Mark the semantic form of the InitListExpr as error when the semantic analysis fails.
Definition: Expr.h:4920
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition: Expr.h:4961
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition: Expr.cpp:2438
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition: Expr.cpp:2398
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition: Expr.h:4973
unsigned getNumInits() const
Definition: Expr.h:4884
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:2472
void setInit(unsigned Init, Expr *expr)
Definition: Expr.h:4910
SourceLocation getLBraceLoc() const
Definition: Expr.h:5008
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:2402
void setArrayFiller(Expr *filler)
Definition: Expr.cpp:2414
InitListExpr * getSyntacticForm() const
Definition: Expr.h:5020
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition: Expr.h:4948
SourceLocation getRBraceLoc() const
Definition: Expr.h:5010
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4900
bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const
Is this the zero initializer {0} in a language which considers it idiomatic?
Definition: Expr.cpp:2461
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:2490
void setInitializedFieldInUnion(FieldDecl *FD)
Definition: Expr.h:4979
bool isSyntacticForm() const
Definition: Expr.h:5017
void setRBraceLoc(SourceLocation Loc)
Definition: Expr.h:5011
void sawArrayRangeDesignator(bool ARD=true)
Definition: Expr.h:5034
Expr ** getInits()
Retrieve the set of initializers.
Definition: Expr.h:4887
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:3860
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:8577
void AddStringInitStep(QualType T)
Add a string init step.
Definition: SemaInit.cpp:3895
void AddStdInitializerListConstructionStep(QualType T)
Add a step to construct a std::initializer_list object from an initializer list.
Definition: SemaInit.cpp:3950
void AddConstructorInitializationStep(DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, bool HadMultipleCandidates, bool FromInitList, bool AsInitList)
Add a constructor-initialization step.
Definition: SemaInit.cpp:3867
@ 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:3803
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:6107
void AddQualificationConversionStep(QualType Ty, ExprValueKind Category)
Add a new step that performs a qualification conversion to the given type.
Definition: SemaInit.cpp:3816
void AddFunctionReferenceConversionStep(QualType Ty)
Add a new step that performs a function reference conversion to the given type.
Definition: SemaInit.cpp:3835
void AddDerivedToBaseCastStep(QualType BaseType, ExprValueKind Category)
Add a new step in the initialization that performs a derived-to- base cast.
Definition: SemaInit.cpp:3766
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:6163
void AddParenthesizedListInitStep(QualType T)
Definition: SemaInit.cpp:3971
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:3694
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:3964
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:3788
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:3902
void SetOverloadFailure(FailureKind Failure, OverloadingResult Result)
Note that this initialization sequence failed due to failed overload resolution.
Definition: SemaInit.cpp:3993
step_iterator step_end() const
void AddParenthesizedArrayInitStep(QualType T)
Add a parenthesized array initialization step.
Definition: SemaInit.cpp:3927
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:3795
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:3957
void AddCAssignmentStep(QualType T)
Add a C assignment step.
Definition: SemaInit.cpp:3888
void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy)
Add a step to pass an object by indirect copy-restore.
Definition: SemaInit.cpp:3934
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:3978
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
Definition: SemaInit.cpp:9614
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:3842
void dump() const
Dump a representation of this initialization sequence to standard error, for debugging purposes.
Definition: SemaInit.cpp:10451
void AddConversionSequenceStep(const ImplicitConversionSequence &ICS, QualType T, bool TopLevelOfInitList=false)
Add a new step that applies an implicit conversion sequence.
Definition: SemaInit.cpp:3849
void AddZeroInitializationStep(QualType T)
Add a zero-initialization step.
Definition: SemaInit.cpp:3881
void AddProduceObjCObjectStep(QualType T)
Add a step to "produce" an Objective-C object (by retaining it).
Definition: SemaInit.cpp:3943
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:3780
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:3683
void AddArrayInitLoopStep(QualType T, QualType EltTy)
Add an array initialization loop step.
Definition: SemaInit.cpp:3916
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:3754
void AddArrayInitStep(QualType T, bool IsGNUExtension)
Add an array initialization step.
Definition: SemaInit.cpp:3909
bool isConstructorInitialization() const
Determine whether this initialization is direct call to a constructor.
Definition: SemaInit.cpp:3748
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:3464
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:3476
unsigned allocateManglingNumber() const
QualType getType() const
Retrieve type being initialized.
ValueDecl * getDecl() const
Retrieve the variable, parameter, or field being initialized.
Definition: SemaInit.cpp:3514
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:3548
void dump() const
Dump a representation of the initialized entity to standard error, for debugging purposes.
Definition: SemaInit.cpp:3629
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:5981
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:3213
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:359
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:629
iterator end() const
Definition: Lookup.h:356
iterator begin() const
Definition: Lookup.h:355
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4679
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:4704
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:5427
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:977
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void setDestAS(LangAS AS)
Definition: Overload.h:1212
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition: Overload.h:998
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition: Overload.h:993
@ CSK_Normal
Normal lookup.
Definition: Overload.h:981
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1150
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:1749
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2928
A (possibly-)qualified type.
Definition: Type.h:738
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7202
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7207
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3446
QualType withConst() const
Definition: Type.h:952
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1018
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:805
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7119
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7244
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7159
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1230
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:7319
QualType getCanonicalType() const
Definition: Type.h:7171
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7212
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7191
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7239
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1324
The collection of all-type qualifiers we support.
Definition: Type.h:148
unsigned getCVRQualifiers() const
Definition: Type.h:296
void addAddressSpace(LangAS space)
Definition: Type.h:405
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:179
bool hasConst() const
Definition: Type.h:265
bool hasQualifiers() const
Return true if the set contains any qualifiers.
Definition: Type.h:440
bool hasAddressSpace() const
Definition: Type.h:378
Qualifiers withoutAddressSpace() const
Definition: Type.h:346
void removeAddressSpace()
Definition: Type.h:404
static Qualifiers fromCVRMask(unsigned CVR)
Definition: Type.h:241
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:496
bool hasVolatile() const
Definition: Type.h:275
bool hasObjCLifetime() const
Definition: Type.h:352
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:533
LangAS getAddressSpace() const
Definition: Type.h:379
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3231
Represents a struct/union/class.
Definition: Decl.h:4133
bool hasFlexibleArrayMember() const
Definition: Decl.h:4166
field_iterator field_end() const
Definition: Decl.h:4342
field_range fields() const
Definition: Decl.h:4339
bool isRandomized() const
Definition: Decl.h:4283
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4324
specific_decl_iterator< FieldDecl > field_iterator
Definition: Decl.h:4336
bool field_empty() const
Definition: Decl.h:4347
field_iterator field_begin() const
Definition: Decl.cpp:5035
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5309
RecordDecl * getDecl() const
Definition: Type.h:5319
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3169
bool isSpelledAsLValue() const
Definition: Type.h:3182
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:426
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:4808
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7612
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7620
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose=true)
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1912
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition: SemaInit.cpp:166
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:8393
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:8396
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:8402
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:8400
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...
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:18019
ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init)
Definition: SemaInit.cpp:3362
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1556
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CCK_ImplicitConversion)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
ASTContext & Context
Definition: Sema.h:1030
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:498
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())
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:6015
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:755
ASTContext & getASTContext() const
Definition: Sema.h:501
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:10533
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:8717
llvm::SmallVector< QualType, 4 > CurrentParameterCopyTypes
Stack of types that correspond to the parameter entities that are currently being copy-initialized.
Definition: Sema.h:7295
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
FunctionTemplateDecl * DeclareImplicitDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
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:58
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
const LangOptions & getLangOpts() const
Definition: Sema.h:494
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 ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:637
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
llvm::DenseMap< unsigned, CXXDeductionGuideDecl * > AggregateDeductionCandidates
Definition: Sema.h:7298
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:18350
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:8540
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:68
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:5376
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:10585
ExprResult PerformQualificationConversion(Expr *E, QualType Ty, ExprValueKind VK=VK_PRValue, CheckedConversionKind CCK=CCK_ImplicitConversion)
Definition: SemaInit.cpp:8558
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:10711
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:6518
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1163
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:8521
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:6314
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6316
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:6395
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1305
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21754
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...
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:890
@ CCK_OtherCast
A cast other than a C-style cast.
Definition: Sema.h:898
@ CCK_CStyleCast
A C-style cast.
Definition: Sema.h:894
@ CCK_ImplicitConversion
An implicit conversion.
Definition: Sema.h:892
@ CCK_FunctionalCast
A functional-style cast.
Definition: Sema.h:896
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10727
SourceManager & getSourceManager() const
Definition: Sema.h:499
AssignmentAction
Definition: Sema.h:5384
@ AA_Returning
Definition: Sema.h:5387
@ AA_Passing_CFAudited
Definition: Sema.h:5392
@ AA_Initializing
Definition: Sema.h:5389
@ AA_Converting
Definition: Sema.h:5388
@ AA_Passing
Definition: Sema.h:5386
@ AA_Casting
Definition: Sema.h:5391
@ AA_Sending
Definition: Sema.h:5390
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:21032
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:6280
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...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:224
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11950
@ CTK_ErrorRecovery
Definition: Sema.h:7864
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3328
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:117
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5922
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:9257
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:8122
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6674
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
Definition: SemaType.cpp:9198
SourceManager & SourceMgr
Definition: Sema.h:1033
DiagnosticsEngine & Diags
Definition: Sema.h:1032
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:495
static bool CanBeGetReturnObject(const FunctionDecl *FD)
Definition: SemaDecl.cpp:16108
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10641
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:6355
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:512
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:17686
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:18915
bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
Definition: SemaExpr.cpp:17612
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:10626
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:264
void setFromType(QualType T)
Definition: Overload.h:354
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:275
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:269
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:356
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:361
QualType getToType(unsigned Idx) const
Definition: Overload.h:371
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
bool isUnion() const
Definition: Decl.h:3755
bool isBigEndian() const
Definition: TargetInfo.h:1614
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:5849
const Type * getTypeForDecl() const
Definition: Decl.h:3381
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:2679
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7090
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:7101
The base class of the type hierarchy.
Definition: Type.h:1607
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1862
bool isVoidType() const
Definition: Type.h:7660
bool isBooleanType() const
Definition: Type.h:7788
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:7835
bool isIncompleteArrayType() const
Definition: Type.h:7445
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2126
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2051
bool isRValueReferenceType() const
Definition: Type.h:7391
bool isConstantArrayType() const
Definition: Type.h:7441
bool isArrayType() const
Definition: Type.h:7437
bool isCharType() const
Definition: Type.cpp:2069
bool isPointerType() const
Definition: Type.h:7371
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7700
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7945
bool isReferenceType() const
Definition: Type.h:7383
bool isScalarType() const
Definition: Type.h:7759
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:1847
bool isChar8Type() const
Definition: Type.cpp:2085
bool isSizelessBuiltinType() const
Definition: Type.cpp:2413
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isExtVectorType() const
Definition: Type.h:7477
bool isOCLIntelSubgroupAVCType() const
Definition: Type.h:7605
bool isLValueReferenceType() const
Definition: Type.h:7387
bool isOpenCLSpecificType() const
Definition: Type.h:7620
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2442
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2318
bool isAnyComplexType() const
Definition: Type.h:7469
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:1991
bool isQueueT() const
Definition: Type.h:7576
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:7828
bool isAtomicType() const
Definition: Type.h:7512
bool isFunctionProtoType() const
Definition: Type.h:2284
bool isObjCObjectType() const
Definition: Type.h:7503
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:7931
bool isEventT() const
Definition: Type.h:7568
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2342
bool isFunctionType() const
Definition: Type.h:7367
bool isObjCObjectPointerType() const
Definition: Type.h:7499
bool isVectorType() const
Definition: Type.h:7473
bool isFloatingType() const
Definition: Type.cpp:2229
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:2176
bool isSamplerT() const
Definition: Type.h:7564
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7878
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:604
bool isNullPtrType() const
Definition: Type.h:7693
bool isRecordType() const
Definition: Type.h:7461
bool isObjCRetainableType() const
Definition: Type.cpp:4838
bool isUnionType() const
Definition: Type.cpp:660
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:5330
Represents a variable declaration or definition.
Definition: Decl.h:918
const Expr * getInit() const
Definition: Decl.h:1352
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1168
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3507
Represents a GCC generic vector type.
Definition: Type.h:3729
unsigned getNumElements() const
Definition: Type.h:3744
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3753
VectorKind getVectorKind() const
Definition: Type.h:3749
QualType getElementType() const
Definition: Type.h:3743
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:1809
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
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:774
@ 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:1522
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:325
@ 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
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:242
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:248
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:256
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:245
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:252
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1285
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition: Overload.h:1238
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Braces
New-expression has a C++11 list-initializer.
@ AS_public
Definition: Specifiers.h:121
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
unsigned long uint64_t
#define true
Definition: stdbool.h:21
#define false
Definition: stdbool.h:22
#define bool
Definition: stdbool.h:20
CXXConstructorDecl * Constructor
Definition: Overload.h:1230
DeclAccessPair FoundDecl
Definition: Overload.h:1229
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:845
bool Viable
Viable - True to indicate that this overload candidate is viable.
Definition: Overload.h:874
unsigned char FailureKind
FailureKind - The reason why this candidate is not viable.
Definition: Overload.h:908
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition: Overload.h:868
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:8410
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:424