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