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