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