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.Context) && 4889 !Initializer->getType()->isSamplerT())) 4890 return false; 4891 4892 Sequence.AddOCLSamplerInitStep(DestType); 4893 return true; 4894 } 4895 4896 // 4897 // OpenCL 1.2 spec, s6.12.10 4898 // 4899 // The event argument can also be used to associate the 4900 // async_work_group_copy with a previous async copy allowing 4901 // an event to be shared by multiple async copies; otherwise 4902 // event should be zero. 4903 // 4904 static bool TryOCLZeroEventInitialization(Sema &S, 4905 InitializationSequence &Sequence, 4906 QualType DestType, 4907 Expr *Initializer) { 4908 if (!S.getLangOpts().OpenCL || !DestType->isEventT() || 4909 !Initializer->isIntegerConstantExpr(S.getASTContext()) || 4910 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0)) 4911 return false; 4912 4913 Sequence.AddOCLZeroEventStep(DestType); 4914 return true; 4915 } 4916 4917 InitializationSequence::InitializationSequence(Sema &S, 4918 const InitializedEntity &Entity, 4919 const InitializationKind &Kind, 4920 MultiExprArg Args, 4921 bool TopLevelOfInitList, 4922 bool TreatUnavailableAsInvalid) 4923 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) { 4924 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList, 4925 TreatUnavailableAsInvalid); 4926 } 4927 4928 /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the 4929 /// address of that function, this returns true. Otherwise, it returns false. 4930 static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) { 4931 auto *DRE = dyn_cast<DeclRefExpr>(E); 4932 if (!DRE || !isa<FunctionDecl>(DRE->getDecl())) 4933 return false; 4934 4935 return !S.checkAddressOfFunctionIsAvailable( 4936 cast<FunctionDecl>(DRE->getDecl())); 4937 } 4938 4939 void InitializationSequence::InitializeFrom(Sema &S, 4940 const InitializedEntity &Entity, 4941 const InitializationKind &Kind, 4942 MultiExprArg Args, 4943 bool TopLevelOfInitList, 4944 bool TreatUnavailableAsInvalid) { 4945 ASTContext &Context = S.Context; 4946 4947 // Eliminate non-overload placeholder types in the arguments. We 4948 // need to do this before checking whether types are dependent 4949 // because lowering a pseudo-object expression might well give us 4950 // something of dependent type. 4951 for (unsigned I = 0, E = Args.size(); I != E; ++I) 4952 if (Args[I]->getType()->isNonOverloadPlaceholderType()) { 4953 // FIXME: should we be doing this here? 4954 ExprResult result = S.CheckPlaceholderExpr(Args[I]); 4955 if (result.isInvalid()) { 4956 SetFailed(FK_PlaceholderType); 4957 return; 4958 } 4959 Args[I] = result.get(); 4960 } 4961 4962 // C++0x [dcl.init]p16: 4963 // The semantics of initializers are as follows. The destination type is 4964 // the type of the object or reference being initialized and the source 4965 // type is the type of the initializer expression. The source type is not 4966 // defined when the initializer is a braced-init-list or when it is a 4967 // parenthesized list of expressions. 4968 QualType DestType = Entity.getType(); 4969 4970 if (DestType->isDependentType() || 4971 Expr::hasAnyTypeDependentArguments(Args)) { 4972 SequenceKind = DependentSequence; 4973 return; 4974 } 4975 4976 // Almost everything is a normal sequence. 4977 setSequenceKind(NormalSequence); 4978 4979 QualType SourceType; 4980 Expr *Initializer = nullptr; 4981 if (Args.size() == 1) { 4982 Initializer = Args[0]; 4983 if (S.getLangOpts().ObjC1) { 4984 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(), 4985 DestType, Initializer->getType(), 4986 Initializer) || 4987 S.ConversionToObjCStringLiteralCheck(DestType, Initializer)) 4988 Args[0] = Initializer; 4989 } 4990 if (!isa<InitListExpr>(Initializer)) 4991 SourceType = Initializer->getType(); 4992 } 4993 4994 // - If the initializer is a (non-parenthesized) braced-init-list, the 4995 // object is list-initialized (8.5.4). 4996 if (Kind.getKind() != InitializationKind::IK_Direct) { 4997 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { 4998 TryListInitialization(S, Entity, Kind, InitList, *this, 4999 TreatUnavailableAsInvalid); 5000 return; 5001 } 5002 } 5003 5004 // - If the destination type is a reference type, see 8.5.3. 5005 if (DestType->isReferenceType()) { 5006 // C++0x [dcl.init.ref]p1: 5007 // A variable declared to be a T& or T&&, that is, "reference to type T" 5008 // (8.3.2), shall be initialized by an object, or function, of type T or 5009 // by an object that can be converted into a T. 5010 // (Therefore, multiple arguments are not permitted.) 5011 if (Args.size() != 1) 5012 SetFailed(FK_TooManyInitsForReference); 5013 else 5014 TryReferenceInitialization(S, Entity, Kind, Args[0], *this); 5015 return; 5016 } 5017 5018 // - If the initializer is (), the object is value-initialized. 5019 if (Kind.getKind() == InitializationKind::IK_Value || 5020 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) { 5021 TryValueInitialization(S, Entity, Kind, *this); 5022 return; 5023 } 5024 5025 // Handle default initialization. 5026 if (Kind.getKind() == InitializationKind::IK_Default) { 5027 TryDefaultInitialization(S, Entity, Kind, *this); 5028 return; 5029 } 5030 5031 // - If the destination type is an array of characters, an array of 5032 // char16_t, an array of char32_t, or an array of wchar_t, and the 5033 // initializer is a string literal, see 8.5.2. 5034 // - Otherwise, if the destination type is an array, the program is 5035 // ill-formed. 5036 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) { 5037 if (Initializer && isa<VariableArrayType>(DestAT)) { 5038 SetFailed(FK_VariableLengthArrayHasInitializer); 5039 return; 5040 } 5041 5042 if (Initializer) { 5043 switch (IsStringInit(Initializer, DestAT, Context)) { 5044 case SIF_None: 5045 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); 5046 return; 5047 case SIF_NarrowStringIntoWideChar: 5048 SetFailed(FK_NarrowStringIntoWideCharArray); 5049 return; 5050 case SIF_WideStringIntoChar: 5051 SetFailed(FK_WideStringIntoCharArray); 5052 return; 5053 case SIF_IncompatWideStringIntoWideChar: 5054 SetFailed(FK_IncompatWideStringIntoWideChar); 5055 return; 5056 case SIF_Other: 5057 break; 5058 } 5059 } 5060 5061 // Note: as an GNU C extension, we allow initialization of an 5062 // array from a compound literal that creates an array of the same 5063 // type, so long as the initializer has no side effects. 5064 if (!S.getLangOpts().CPlusPlus && Initializer && 5065 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) && 5066 Initializer->getType()->isArrayType()) { 5067 const ArrayType *SourceAT 5068 = Context.getAsArrayType(Initializer->getType()); 5069 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT)) 5070 SetFailed(FK_ArrayTypeMismatch); 5071 else if (Initializer->HasSideEffects(S.Context)) 5072 SetFailed(FK_NonConstantArrayInit); 5073 else { 5074 AddArrayInitStep(DestType); 5075 } 5076 } 5077 // Note: as a GNU C++ extension, we allow list-initialization of a 5078 // class member of array type from a parenthesized initializer list. 5079 else if (S.getLangOpts().CPlusPlus && 5080 Entity.getKind() == InitializedEntity::EK_Member && 5081 Initializer && isa<InitListExpr>(Initializer)) { 5082 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer), 5083 *this, TreatUnavailableAsInvalid); 5084 AddParenthesizedArrayInitStep(DestType); 5085 } else if (DestAT->getElementType()->isCharType()) 5086 SetFailed(FK_ArrayNeedsInitListOrStringLiteral); 5087 else if (IsWideCharCompatible(DestAT->getElementType(), Context)) 5088 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral); 5089 else 5090 SetFailed(FK_ArrayNeedsInitList); 5091 5092 return; 5093 } 5094 5095 // Determine whether we should consider writeback conversions for 5096 // Objective-C ARC. 5097 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount && 5098 Entity.isParameterKind(); 5099 5100 // We're at the end of the line for C: it's either a write-back conversion 5101 // or it's a C assignment. There's no need to check anything else. 5102 if (!S.getLangOpts().CPlusPlus) { 5103 // If allowed, check whether this is an Objective-C writeback conversion. 5104 if (allowObjCWritebackConversion && 5105 tryObjCWritebackConversion(S, *this, Entity, Initializer)) { 5106 return; 5107 } 5108 5109 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer)) 5110 return; 5111 5112 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer)) 5113 return; 5114 5115 // Handle initialization in C 5116 AddCAssignmentStep(DestType); 5117 MaybeProduceObjCObject(S, *this, Entity); 5118 return; 5119 } 5120 5121 assert(S.getLangOpts().CPlusPlus); 5122 5123 // - If the destination type is a (possibly cv-qualified) class type: 5124 if (DestType->isRecordType()) { 5125 // - If the initialization is direct-initialization, or if it is 5126 // copy-initialization where the cv-unqualified version of the 5127 // source type is the same class as, or a derived class of, the 5128 // class of the destination, constructors are considered. [...] 5129 if (Kind.getKind() == InitializationKind::IK_Direct || 5130 (Kind.getKind() == InitializationKind::IK_Copy && 5131 (Context.hasSameUnqualifiedType(SourceType, DestType) || 5132 S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType)))) 5133 TryConstructorInitialization(S, Entity, Kind, Args, 5134 DestType, *this); 5135 // - Otherwise (i.e., for the remaining copy-initialization cases), 5136 // user-defined conversion sequences that can convert from the source 5137 // type to the destination type or (when a conversion function is 5138 // used) to a derived class thereof are enumerated as described in 5139 // 13.3.1.4, and the best one is chosen through overload resolution 5140 // (13.3). 5141 else 5142 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, 5143 TopLevelOfInitList); 5144 return; 5145 } 5146 5147 if (Args.size() > 1) { 5148 SetFailed(FK_TooManyInitsForScalar); 5149 return; 5150 } 5151 assert(Args.size() == 1 && "Zero-argument case handled above"); 5152 5153 // - Otherwise, if the source type is a (possibly cv-qualified) class 5154 // type, conversion functions are considered. 5155 if (!SourceType.isNull() && SourceType->isRecordType()) { 5156 // For a conversion to _Atomic(T) from either T or a class type derived 5157 // from T, initialize the T object then convert to _Atomic type. 5158 bool NeedAtomicConversion = false; 5159 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) { 5160 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) || 5161 S.IsDerivedFrom(Initializer->getLocStart(), SourceType, 5162 Atomic->getValueType())) { 5163 DestType = Atomic->getValueType(); 5164 NeedAtomicConversion = true; 5165 } 5166 } 5167 5168 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, 5169 TopLevelOfInitList); 5170 MaybeProduceObjCObject(S, *this, Entity); 5171 if (!Failed() && NeedAtomicConversion) 5172 AddAtomicConversionStep(Entity.getType()); 5173 return; 5174 } 5175 5176 // - Otherwise, the initial value of the object being initialized is the 5177 // (possibly converted) value of the initializer expression. Standard 5178 // conversions (Clause 4) will be used, if necessary, to convert the 5179 // initializer expression to the cv-unqualified version of the 5180 // destination type; no user-defined conversions are considered. 5181 5182 ImplicitConversionSequence ICS 5183 = S.TryImplicitConversion(Initializer, DestType, 5184 /*SuppressUserConversions*/true, 5185 /*AllowExplicitConversions*/ false, 5186 /*InOverloadResolution*/ false, 5187 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 5188 allowObjCWritebackConversion); 5189 5190 if (ICS.isStandard() && 5191 ICS.Standard.Second == ICK_Writeback_Conversion) { 5192 // Objective-C ARC writeback conversion. 5193 5194 // We should copy unless we're passing to an argument explicitly 5195 // marked 'out'. 5196 bool ShouldCopy = true; 5197 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 5198 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 5199 5200 // If there was an lvalue adjustment, add it as a separate conversion. 5201 if (ICS.Standard.First == ICK_Array_To_Pointer || 5202 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5203 ImplicitConversionSequence LvalueICS; 5204 LvalueICS.setStandard(); 5205 LvalueICS.Standard.setAsIdentityConversion(); 5206 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0)); 5207 LvalueICS.Standard.First = ICS.Standard.First; 5208 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); 5209 } 5210 5211 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy); 5212 } else if (ICS.isBad()) { 5213 DeclAccessPair dap; 5214 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) { 5215 AddZeroInitializationStep(Entity.getType()); 5216 } else if (Initializer->getType() == Context.OverloadTy && 5217 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType, 5218 false, dap)) 5219 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 5220 else if (Initializer->getType()->isFunctionType() && 5221 isExprAnUnaddressableFunction(S, Initializer)) 5222 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction); 5223 else 5224 SetFailed(InitializationSequence::FK_ConversionFailed); 5225 } else { 5226 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); 5227 5228 MaybeProduceObjCObject(S, *this, Entity); 5229 } 5230 } 5231 5232 InitializationSequence::~InitializationSequence() { 5233 for (auto &S : Steps) 5234 S.Destroy(); 5235 } 5236 5237 //===----------------------------------------------------------------------===// 5238 // Perform initialization 5239 //===----------------------------------------------------------------------===// 5240 static Sema::AssignmentAction 5241 getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) { 5242 switch(Entity.getKind()) { 5243 case InitializedEntity::EK_Variable: 5244 case InitializedEntity::EK_New: 5245 case InitializedEntity::EK_Exception: 5246 case InitializedEntity::EK_Base: 5247 case InitializedEntity::EK_Delegating: 5248 return Sema::AA_Initializing; 5249 5250 case InitializedEntity::EK_Parameter: 5251 if (Entity.getDecl() && 5252 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 5253 return Sema::AA_Sending; 5254 5255 return Sema::AA_Passing; 5256 5257 case InitializedEntity::EK_Parameter_CF_Audited: 5258 if (Entity.getDecl() && 5259 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 5260 return Sema::AA_Sending; 5261 5262 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited; 5263 5264 case InitializedEntity::EK_Result: 5265 return Sema::AA_Returning; 5266 5267 case InitializedEntity::EK_Temporary: 5268 case InitializedEntity::EK_RelatedResult: 5269 // FIXME: Can we tell apart casting vs. converting? 5270 return Sema::AA_Casting; 5271 5272 case InitializedEntity::EK_Member: 5273 case InitializedEntity::EK_ArrayElement: 5274 case InitializedEntity::EK_VectorElement: 5275 case InitializedEntity::EK_ComplexElement: 5276 case InitializedEntity::EK_BlockElement: 5277 case InitializedEntity::EK_LambdaCapture: 5278 case InitializedEntity::EK_CompoundLiteralInit: 5279 return Sema::AA_Initializing; 5280 } 5281 5282 llvm_unreachable("Invalid EntityKind!"); 5283 } 5284 5285 /// \brief Whether we should bind a created object as a temporary when 5286 /// initializing the given entity. 5287 static bool shouldBindAsTemporary(const InitializedEntity &Entity) { 5288 switch (Entity.getKind()) { 5289 case InitializedEntity::EK_ArrayElement: 5290 case InitializedEntity::EK_Member: 5291 case InitializedEntity::EK_Result: 5292 case InitializedEntity::EK_New: 5293 case InitializedEntity::EK_Variable: 5294 case InitializedEntity::EK_Base: 5295 case InitializedEntity::EK_Delegating: 5296 case InitializedEntity::EK_VectorElement: 5297 case InitializedEntity::EK_ComplexElement: 5298 case InitializedEntity::EK_Exception: 5299 case InitializedEntity::EK_BlockElement: 5300 case InitializedEntity::EK_LambdaCapture: 5301 case InitializedEntity::EK_CompoundLiteralInit: 5302 return false; 5303 5304 case InitializedEntity::EK_Parameter: 5305 case InitializedEntity::EK_Parameter_CF_Audited: 5306 case InitializedEntity::EK_Temporary: 5307 case InitializedEntity::EK_RelatedResult: 5308 return true; 5309 } 5310 5311 llvm_unreachable("missed an InitializedEntity kind?"); 5312 } 5313 5314 /// \brief Whether the given entity, when initialized with an object 5315 /// created for that initialization, requires destruction. 5316 static bool shouldDestroyTemporary(const InitializedEntity &Entity) { 5317 switch (Entity.getKind()) { 5318 case InitializedEntity::EK_Result: 5319 case InitializedEntity::EK_New: 5320 case InitializedEntity::EK_Base: 5321 case InitializedEntity::EK_Delegating: 5322 case InitializedEntity::EK_VectorElement: 5323 case InitializedEntity::EK_ComplexElement: 5324 case InitializedEntity::EK_BlockElement: 5325 case InitializedEntity::EK_LambdaCapture: 5326 return false; 5327 5328 case InitializedEntity::EK_Member: 5329 case InitializedEntity::EK_Variable: 5330 case InitializedEntity::EK_Parameter: 5331 case InitializedEntity::EK_Parameter_CF_Audited: 5332 case InitializedEntity::EK_Temporary: 5333 case InitializedEntity::EK_ArrayElement: 5334 case InitializedEntity::EK_Exception: 5335 case InitializedEntity::EK_CompoundLiteralInit: 5336 case InitializedEntity::EK_RelatedResult: 5337 return true; 5338 } 5339 5340 llvm_unreachable("missed an InitializedEntity kind?"); 5341 } 5342 5343 /// \brief Look for copy and move constructors and constructor templates, for 5344 /// copying an object via direct-initialization (per C++11 [dcl.init]p16). 5345 static void LookupCopyAndMoveConstructors(Sema &S, 5346 OverloadCandidateSet &CandidateSet, 5347 CXXRecordDecl *Class, 5348 Expr *CurInitExpr) { 5349 DeclContext::lookup_result R = S.LookupConstructors(Class); 5350 // The container holding the constructors can under certain conditions 5351 // be changed while iterating (e.g. because of deserialization). 5352 // To be safe we copy the lookup results to a new container. 5353 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end()); 5354 for (SmallVectorImpl<NamedDecl *>::iterator 5355 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) { 5356 NamedDecl *D = *CI; 5357 auto Info = getConstructorInfo(D); 5358 if (!Info.Constructor) 5359 continue; 5360 5361 if (!Info.ConstructorTmpl) { 5362 // Handle copy/move constructors, only. 5363 if (Info.Constructor->isInvalidDecl() || 5364 !Info.Constructor->isCopyOrMoveConstructor() || 5365 !Info.Constructor->isConvertingConstructor(/*AllowExplicit=*/true)) 5366 continue; 5367 5368 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 5369 CurInitExpr, CandidateSet); 5370 continue; 5371 } 5372 5373 // Handle constructor templates. 5374 if (Info.ConstructorTmpl->isInvalidDecl()) 5375 continue; 5376 5377 if (!Info.Constructor->isConvertingConstructor(/*AllowExplicit=*/true)) 5378 continue; 5379 5380 // FIXME: Do we need to limit this to copy-constructor-like 5381 // candidates? 5382 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 5383 nullptr, CurInitExpr, CandidateSet, true); 5384 } 5385 } 5386 5387 /// \brief Get the location at which initialization diagnostics should appear. 5388 static SourceLocation getInitializationLoc(const InitializedEntity &Entity, 5389 Expr *Initializer) { 5390 switch (Entity.getKind()) { 5391 case InitializedEntity::EK_Result: 5392 return Entity.getReturnLoc(); 5393 5394 case InitializedEntity::EK_Exception: 5395 return Entity.getThrowLoc(); 5396 5397 case InitializedEntity::EK_Variable: 5398 return Entity.getDecl()->getLocation(); 5399 5400 case InitializedEntity::EK_LambdaCapture: 5401 return Entity.getCaptureLoc(); 5402 5403 case InitializedEntity::EK_ArrayElement: 5404 case InitializedEntity::EK_Member: 5405 case InitializedEntity::EK_Parameter: 5406 case InitializedEntity::EK_Parameter_CF_Audited: 5407 case InitializedEntity::EK_Temporary: 5408 case InitializedEntity::EK_New: 5409 case InitializedEntity::EK_Base: 5410 case InitializedEntity::EK_Delegating: 5411 case InitializedEntity::EK_VectorElement: 5412 case InitializedEntity::EK_ComplexElement: 5413 case InitializedEntity::EK_BlockElement: 5414 case InitializedEntity::EK_CompoundLiteralInit: 5415 case InitializedEntity::EK_RelatedResult: 5416 return Initializer->getLocStart(); 5417 } 5418 llvm_unreachable("missed an InitializedEntity kind?"); 5419 } 5420 5421 /// \brief Make a (potentially elidable) temporary copy of the object 5422 /// provided by the given initializer by calling the appropriate copy 5423 /// constructor. 5424 /// 5425 /// \param S The Sema object used for type-checking. 5426 /// 5427 /// \param T The type of the temporary object, which must either be 5428 /// the type of the initializer expression or a superclass thereof. 5429 /// 5430 /// \param Entity The entity being initialized. 5431 /// 5432 /// \param CurInit The initializer expression. 5433 /// 5434 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that 5435 /// is permitted in C++03 (but not C++0x) when binding a reference to 5436 /// an rvalue. 5437 /// 5438 /// \returns An expression that copies the initializer expression into 5439 /// a temporary object, or an error expression if a copy could not be 5440 /// created. 5441 static ExprResult CopyObject(Sema &S, 5442 QualType T, 5443 const InitializedEntity &Entity, 5444 ExprResult CurInit, 5445 bool IsExtraneousCopy) { 5446 if (CurInit.isInvalid()) 5447 return CurInit; 5448 // Determine which class type we're copying to. 5449 Expr *CurInitExpr = (Expr *)CurInit.get(); 5450 CXXRecordDecl *Class = nullptr; 5451 if (const RecordType *Record = T->getAs<RecordType>()) 5452 Class = cast<CXXRecordDecl>(Record->getDecl()); 5453 if (!Class) 5454 return CurInit; 5455 5456 // C++0x [class.copy]p32: 5457 // When certain criteria are met, an implementation is allowed to 5458 // omit the copy/move construction of a class object, even if the 5459 // copy/move constructor and/or destructor for the object have 5460 // side effects. [...] 5461 // - when a temporary class object that has not been bound to a 5462 // reference (12.2) would be copied/moved to a class object 5463 // with the same cv-unqualified type, the copy/move operation 5464 // can be omitted by constructing the temporary object 5465 // directly into the target of the omitted copy/move 5466 // 5467 // Note that the other three bullets are handled elsewhere. Copy 5468 // elision for return statements and throw expressions are handled as part 5469 // of constructor initialization, while copy elision for exception handlers 5470 // is handled by the run-time. 5471 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class); 5472 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get()); 5473 5474 // Make sure that the type we are copying is complete. 5475 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete)) 5476 return CurInit; 5477 5478 // Perform overload resolution using the class's copy/move constructors. 5479 // Only consider constructors and constructor templates. Per 5480 // C++0x [dcl.init]p16, second bullet to class types, this initialization 5481 // is direct-initialization. 5482 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5483 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr); 5484 5485 bool HadMultipleCandidates = (CandidateSet.size() > 1); 5486 5487 OverloadCandidateSet::iterator Best; 5488 switch (CandidateSet.BestViableFunction(S, Loc, Best)) { 5489 case OR_Success: 5490 break; 5491 5492 case OR_No_Viable_Function: 5493 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext() 5494 ? diag::ext_rvalue_to_reference_temp_copy_no_viable 5495 : diag::err_temp_copy_no_viable) 5496 << (int)Entity.getKind() << CurInitExpr->getType() 5497 << CurInitExpr->getSourceRange(); 5498 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr); 5499 if (!IsExtraneousCopy || S.isSFINAEContext()) 5500 return ExprError(); 5501 return CurInit; 5502 5503 case OR_Ambiguous: 5504 S.Diag(Loc, diag::err_temp_copy_ambiguous) 5505 << (int)Entity.getKind() << CurInitExpr->getType() 5506 << CurInitExpr->getSourceRange(); 5507 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr); 5508 return ExprError(); 5509 5510 case OR_Deleted: 5511 S.Diag(Loc, diag::err_temp_copy_deleted) 5512 << (int)Entity.getKind() << CurInitExpr->getType() 5513 << CurInitExpr->getSourceRange(); 5514 S.NoteDeletedFunction(Best->Function); 5515 return ExprError(); 5516 } 5517 5518 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 5519 SmallVector<Expr*, 8> ConstructorArgs; 5520 CurInit.get(); // Ownership transferred into MultiExprArg, below. 5521 5522 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity, 5523 IsExtraneousCopy); 5524 5525 if (IsExtraneousCopy) { 5526 // If this is a totally extraneous copy for C++03 reference 5527 // binding purposes, just return the original initialization 5528 // expression. We don't generate an (elided) copy operation here 5529 // because doing so would require us to pass down a flag to avoid 5530 // infinite recursion, where each step adds another extraneous, 5531 // elidable copy. 5532 5533 // Instantiate the default arguments of any extra parameters in 5534 // the selected copy constructor, as if we were going to create a 5535 // proper call to the copy constructor. 5536 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { 5537 ParmVarDecl *Parm = Constructor->getParamDecl(I); 5538 if (S.RequireCompleteType(Loc, Parm->getType(), 5539 diag::err_call_incomplete_argument)) 5540 break; 5541 5542 // Build the default argument expression; we don't actually care 5543 // if this succeeds or not, because this routine will complain 5544 // if there was a problem. 5545 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); 5546 } 5547 5548 return CurInitExpr; 5549 } 5550 5551 // Determine the arguments required to actually perform the 5552 // constructor call (we might have derived-to-base conversions, or 5553 // the copy constructor may have default arguments). 5554 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs)) 5555 return ExprError(); 5556 5557 // Actually perform the constructor call. 5558 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor, 5559 Elidable, 5560 ConstructorArgs, 5561 HadMultipleCandidates, 5562 /*ListInit*/ false, 5563 /*StdInitListInit*/ false, 5564 /*ZeroInit*/ false, 5565 CXXConstructExpr::CK_Complete, 5566 SourceRange()); 5567 5568 // If we're supposed to bind temporaries, do so. 5569 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) 5570 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); 5571 return CurInit; 5572 } 5573 5574 /// \brief Check whether elidable copy construction for binding a reference to 5575 /// a temporary would have succeeded if we were building in C++98 mode, for 5576 /// -Wc++98-compat. 5577 static void CheckCXX98CompatAccessibleCopy(Sema &S, 5578 const InitializedEntity &Entity, 5579 Expr *CurInitExpr) { 5580 assert(S.getLangOpts().CPlusPlus11); 5581 5582 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>(); 5583 if (!Record) 5584 return; 5585 5586 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr); 5587 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc)) 5588 return; 5589 5590 // Find constructors which would have been considered. 5591 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5592 LookupCopyAndMoveConstructors( 5593 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr); 5594 5595 // Perform overload resolution. 5596 OverloadCandidateSet::iterator Best; 5597 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best); 5598 5599 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy) 5600 << OR << (int)Entity.getKind() << CurInitExpr->getType() 5601 << CurInitExpr->getSourceRange(); 5602 5603 switch (OR) { 5604 case OR_Success: 5605 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function), 5606 Best->FoundDecl, Entity, Diag); 5607 // FIXME: Check default arguments as far as that's possible. 5608 break; 5609 5610 case OR_No_Viable_Function: 5611 S.Diag(Loc, Diag); 5612 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr); 5613 break; 5614 5615 case OR_Ambiguous: 5616 S.Diag(Loc, Diag); 5617 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr); 5618 break; 5619 5620 case OR_Deleted: 5621 S.Diag(Loc, Diag); 5622 S.NoteDeletedFunction(Best->Function); 5623 break; 5624 } 5625 } 5626 5627 void InitializationSequence::PrintInitLocationNote(Sema &S, 5628 const InitializedEntity &Entity) { 5629 if (Entity.isParameterKind() && Entity.getDecl()) { 5630 if (Entity.getDecl()->getLocation().isInvalid()) 5631 return; 5632 5633 if (Entity.getDecl()->getDeclName()) 5634 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) 5635 << Entity.getDecl()->getDeclName(); 5636 else 5637 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); 5638 } 5639 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult && 5640 Entity.getMethodDecl()) 5641 S.Diag(Entity.getMethodDecl()->getLocation(), 5642 diag::note_method_return_type_change) 5643 << Entity.getMethodDecl()->getDeclName(); 5644 } 5645 5646 static bool isReferenceBinding(const InitializationSequence::Step &s) { 5647 return s.Kind == InitializationSequence::SK_BindReference || 5648 s.Kind == InitializationSequence::SK_BindReferenceToTemporary; 5649 } 5650 5651 /// Returns true if the parameters describe a constructor initialization of 5652 /// an explicit temporary object, e.g. "Point(x, y)". 5653 static bool isExplicitTemporary(const InitializedEntity &Entity, 5654 const InitializationKind &Kind, 5655 unsigned NumArgs) { 5656 switch (Entity.getKind()) { 5657 case InitializedEntity::EK_Temporary: 5658 case InitializedEntity::EK_CompoundLiteralInit: 5659 case InitializedEntity::EK_RelatedResult: 5660 break; 5661 default: 5662 return false; 5663 } 5664 5665 switch (Kind.getKind()) { 5666 case InitializationKind::IK_DirectList: 5667 return true; 5668 // FIXME: Hack to work around cast weirdness. 5669 case InitializationKind::IK_Direct: 5670 case InitializationKind::IK_Value: 5671 return NumArgs != 1; 5672 default: 5673 return false; 5674 } 5675 } 5676 5677 static ExprResult 5678 PerformConstructorInitialization(Sema &S, 5679 const InitializedEntity &Entity, 5680 const InitializationKind &Kind, 5681 MultiExprArg Args, 5682 const InitializationSequence::Step& Step, 5683 bool &ConstructorInitRequiresZeroInit, 5684 bool IsListInitialization, 5685 bool IsStdInitListInitialization, 5686 SourceLocation LBraceLoc, 5687 SourceLocation RBraceLoc) { 5688 unsigned NumArgs = Args.size(); 5689 CXXConstructorDecl *Constructor 5690 = cast<CXXConstructorDecl>(Step.Function.Function); 5691 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates; 5692 5693 // Build a call to the selected constructor. 5694 SmallVector<Expr*, 8> ConstructorArgs; 5695 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) 5696 ? Kind.getEqualLoc() 5697 : Kind.getLocation(); 5698 5699 if (Kind.getKind() == InitializationKind::IK_Default) { 5700 // Force even a trivial, implicit default constructor to be 5701 // semantically checked. We do this explicitly because we don't build 5702 // the definition for completely trivial constructors. 5703 assert(Constructor->getParent() && "No parent class for constructor."); 5704 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 5705 Constructor->isTrivial() && !Constructor->isUsed(false)) 5706 S.DefineImplicitDefaultConstructor(Loc, Constructor); 5707 } 5708 5709 ExprResult CurInit((Expr *)nullptr); 5710 5711 // C++ [over.match.copy]p1: 5712 // - When initializing a temporary to be bound to the first parameter 5713 // of a constructor that takes a reference to possibly cv-qualified 5714 // T as its first argument, called with a single argument in the 5715 // context of direct-initialization, explicit conversion functions 5716 // are also considered. 5717 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() && 5718 Args.size() == 1 && 5719 Constructor->isCopyOrMoveConstructor(); 5720 5721 // Determine the arguments required to actually perform the constructor 5722 // call. 5723 if (S.CompleteConstructorCall(Constructor, Args, 5724 Loc, ConstructorArgs, 5725 AllowExplicitConv, 5726 IsListInitialization)) 5727 return ExprError(); 5728 5729 5730 if (isExplicitTemporary(Entity, Kind, NumArgs)) { 5731 // An explicitly-constructed temporary, e.g., X(1, 2). 5732 if (S.DiagnoseUseOfDecl(Constructor, Loc)) 5733 return ExprError(); 5734 5735 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 5736 if (!TSInfo) 5737 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc); 5738 SourceRange ParenOrBraceRange = 5739 (Kind.getKind() == InitializationKind::IK_DirectList) 5740 ? SourceRange(LBraceLoc, RBraceLoc) 5741 : Kind.getParenRange(); 5742 5743 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>( 5744 Step.Function.FoundDecl.getDecl())) { 5745 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow); 5746 if (S.DiagnoseUseOfDecl(Constructor, Loc)) 5747 return ExprError(); 5748 } 5749 S.MarkFunctionReferenced(Loc, Constructor); 5750 5751 CurInit = new (S.Context) CXXTemporaryObjectExpr( 5752 S.Context, Constructor, TSInfo, 5753 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates, 5754 IsListInitialization, IsStdInitListInitialization, 5755 ConstructorInitRequiresZeroInit); 5756 } else { 5757 CXXConstructExpr::ConstructionKind ConstructKind = 5758 CXXConstructExpr::CK_Complete; 5759 5760 if (Entity.getKind() == InitializedEntity::EK_Base) { 5761 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ? 5762 CXXConstructExpr::CK_VirtualBase : 5763 CXXConstructExpr::CK_NonVirtualBase; 5764 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { 5765 ConstructKind = CXXConstructExpr::CK_Delegating; 5766 } 5767 5768 // Only get the parenthesis or brace range if it is a list initialization or 5769 // direct construction. 5770 SourceRange ParenOrBraceRange; 5771 if (IsListInitialization) 5772 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc); 5773 else if (Kind.getKind() == InitializationKind::IK_Direct) 5774 ParenOrBraceRange = Kind.getParenRange(); 5775 5776 // If the entity allows NRVO, mark the construction as elidable 5777 // unconditionally. 5778 if (Entity.allowsNRVO()) 5779 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(), 5780 Step.Function.FoundDecl, 5781 Constructor, /*Elidable=*/true, 5782 ConstructorArgs, 5783 HadMultipleCandidates, 5784 IsListInitialization, 5785 IsStdInitListInitialization, 5786 ConstructorInitRequiresZeroInit, 5787 ConstructKind, 5788 ParenOrBraceRange); 5789 else 5790 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(), 5791 Step.Function.FoundDecl, 5792 Constructor, 5793 ConstructorArgs, 5794 HadMultipleCandidates, 5795 IsListInitialization, 5796 IsStdInitListInitialization, 5797 ConstructorInitRequiresZeroInit, 5798 ConstructKind, 5799 ParenOrBraceRange); 5800 } 5801 if (CurInit.isInvalid()) 5802 return ExprError(); 5803 5804 // Only check access if all of that succeeded. 5805 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity); 5806 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc)) 5807 return ExprError(); 5808 5809 if (shouldBindAsTemporary(Entity)) 5810 CurInit = S.MaybeBindToTemporary(CurInit.get()); 5811 5812 return CurInit; 5813 } 5814 5815 /// Determine whether the specified InitializedEntity definitely has a lifetime 5816 /// longer than the current full-expression. Conservatively returns false if 5817 /// it's unclear. 5818 static bool 5819 InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) { 5820 const InitializedEntity *Top = &Entity; 5821 while (Top->getParent()) 5822 Top = Top->getParent(); 5823 5824 switch (Top->getKind()) { 5825 case InitializedEntity::EK_Variable: 5826 case InitializedEntity::EK_Result: 5827 case InitializedEntity::EK_Exception: 5828 case InitializedEntity::EK_Member: 5829 case InitializedEntity::EK_New: 5830 case InitializedEntity::EK_Base: 5831 case InitializedEntity::EK_Delegating: 5832 return true; 5833 5834 case InitializedEntity::EK_ArrayElement: 5835 case InitializedEntity::EK_VectorElement: 5836 case InitializedEntity::EK_BlockElement: 5837 case InitializedEntity::EK_ComplexElement: 5838 // Could not determine what the full initialization is. Assume it might not 5839 // outlive the full-expression. 5840 return false; 5841 5842 case InitializedEntity::EK_Parameter: 5843 case InitializedEntity::EK_Parameter_CF_Audited: 5844 case InitializedEntity::EK_Temporary: 5845 case InitializedEntity::EK_LambdaCapture: 5846 case InitializedEntity::EK_CompoundLiteralInit: 5847 case InitializedEntity::EK_RelatedResult: 5848 // The entity being initialized might not outlive the full-expression. 5849 return false; 5850 } 5851 5852 llvm_unreachable("unknown entity kind"); 5853 } 5854 5855 /// Determine the declaration which an initialized entity ultimately refers to, 5856 /// for the purpose of lifetime-extending a temporary bound to a reference in 5857 /// the initialization of \p Entity. 5858 static const InitializedEntity *getEntityForTemporaryLifetimeExtension( 5859 const InitializedEntity *Entity, 5860 const InitializedEntity *FallbackDecl = nullptr) { 5861 // C++11 [class.temporary]p5: 5862 switch (Entity->getKind()) { 5863 case InitializedEntity::EK_Variable: 5864 // The temporary [...] persists for the lifetime of the reference 5865 return Entity; 5866 5867 case InitializedEntity::EK_Member: 5868 // For subobjects, we look at the complete object. 5869 if (Entity->getParent()) 5870 return getEntityForTemporaryLifetimeExtension(Entity->getParent(), 5871 Entity); 5872 5873 // except: 5874 // -- A temporary bound to a reference member in a constructor's 5875 // ctor-initializer persists until the constructor exits. 5876 return Entity; 5877 5878 case InitializedEntity::EK_Parameter: 5879 case InitializedEntity::EK_Parameter_CF_Audited: 5880 // -- A temporary bound to a reference parameter in a function call 5881 // persists until the completion of the full-expression containing 5882 // the call. 5883 case InitializedEntity::EK_Result: 5884 // -- The lifetime of a temporary bound to the returned value in a 5885 // function return statement is not extended; the temporary is 5886 // destroyed at the end of the full-expression in the return statement. 5887 case InitializedEntity::EK_New: 5888 // -- A temporary bound to a reference in a new-initializer persists 5889 // until the completion of the full-expression containing the 5890 // new-initializer. 5891 return nullptr; 5892 5893 case InitializedEntity::EK_Temporary: 5894 case InitializedEntity::EK_CompoundLiteralInit: 5895 case InitializedEntity::EK_RelatedResult: 5896 // We don't yet know the storage duration of the surrounding temporary. 5897 // Assume it's got full-expression duration for now, it will patch up our 5898 // storage duration if that's not correct. 5899 return nullptr; 5900 5901 case InitializedEntity::EK_ArrayElement: 5902 // For subobjects, we look at the complete object. 5903 return getEntityForTemporaryLifetimeExtension(Entity->getParent(), 5904 FallbackDecl); 5905 5906 case InitializedEntity::EK_Base: 5907 // For subobjects, we look at the complete object. 5908 if (Entity->getParent()) 5909 return getEntityForTemporaryLifetimeExtension(Entity->getParent(), 5910 Entity); 5911 // Fall through. 5912 case InitializedEntity::EK_Delegating: 5913 // We can reach this case for aggregate initialization in a constructor: 5914 // struct A { int &&r; }; 5915 // struct B : A { B() : A{0} {} }; 5916 // In this case, use the innermost field decl as the context. 5917 return FallbackDecl; 5918 5919 case InitializedEntity::EK_BlockElement: 5920 case InitializedEntity::EK_LambdaCapture: 5921 case InitializedEntity::EK_Exception: 5922 case InitializedEntity::EK_VectorElement: 5923 case InitializedEntity::EK_ComplexElement: 5924 return nullptr; 5925 } 5926 llvm_unreachable("unknown entity kind"); 5927 } 5928 5929 static void performLifetimeExtension(Expr *Init, 5930 const InitializedEntity *ExtendingEntity); 5931 5932 /// Update a glvalue expression that is used as the initializer of a reference 5933 /// to note that its lifetime is extended. 5934 /// \return \c true if any temporary had its lifetime extended. 5935 static bool 5936 performReferenceExtension(Expr *Init, 5937 const InitializedEntity *ExtendingEntity) { 5938 // Walk past any constructs which we can lifetime-extend across. 5939 Expr *Old; 5940 do { 5941 Old = Init; 5942 5943 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 5944 if (ILE->getNumInits() == 1 && ILE->isGLValue()) { 5945 // This is just redundant braces around an initializer. Step over it. 5946 Init = ILE->getInit(0); 5947 } 5948 } 5949 5950 // Step over any subobject adjustments; we may have a materialized 5951 // temporary inside them. 5952 SmallVector<const Expr *, 2> CommaLHSs; 5953 SmallVector<SubobjectAdjustment, 2> Adjustments; 5954 Init = const_cast<Expr *>( 5955 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments)); 5956 5957 // Per current approach for DR1376, look through casts to reference type 5958 // when performing lifetime extension. 5959 if (CastExpr *CE = dyn_cast<CastExpr>(Init)) 5960 if (CE->getSubExpr()->isGLValue()) 5961 Init = CE->getSubExpr(); 5962 5963 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue. 5964 // It's unclear if binding a reference to that xvalue extends the array 5965 // temporary. 5966 } while (Init != Old); 5967 5968 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) { 5969 // Update the storage duration of the materialized temporary. 5970 // FIXME: Rebuild the expression instead of mutating it. 5971 ME->setExtendingDecl(ExtendingEntity->getDecl(), 5972 ExtendingEntity->allocateManglingNumber()); 5973 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity); 5974 return true; 5975 } 5976 5977 return false; 5978 } 5979 5980 /// Update a prvalue expression that is going to be materialized as a 5981 /// lifetime-extended temporary. 5982 static void performLifetimeExtension(Expr *Init, 5983 const InitializedEntity *ExtendingEntity) { 5984 // Dig out the expression which constructs the extended temporary. 5985 SmallVector<const Expr *, 2> CommaLHSs; 5986 SmallVector<SubobjectAdjustment, 2> Adjustments; 5987 Init = const_cast<Expr *>( 5988 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments)); 5989 5990 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init)) 5991 Init = BTE->getSubExpr(); 5992 5993 if (CXXStdInitializerListExpr *ILE = 5994 dyn_cast<CXXStdInitializerListExpr>(Init)) { 5995 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity); 5996 return; 5997 } 5998 5999 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 6000 if (ILE->getType()->isArrayType()) { 6001 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I) 6002 performLifetimeExtension(ILE->getInit(I), ExtendingEntity); 6003 return; 6004 } 6005 6006 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) { 6007 assert(RD->isAggregate() && "aggregate init on non-aggregate"); 6008 6009 // If we lifetime-extend a braced initializer which is initializing an 6010 // aggregate, and that aggregate contains reference members which are 6011 // bound to temporaries, those temporaries are also lifetime-extended. 6012 if (RD->isUnion() && ILE->getInitializedFieldInUnion() && 6013 ILE->getInitializedFieldInUnion()->getType()->isReferenceType()) 6014 performReferenceExtension(ILE->getInit(0), ExtendingEntity); 6015 else { 6016 unsigned Index = 0; 6017 for (const auto *I : RD->fields()) { 6018 if (Index >= ILE->getNumInits()) 6019 break; 6020 if (I->isUnnamedBitfield()) 6021 continue; 6022 Expr *SubInit = ILE->getInit(Index); 6023 if (I->getType()->isReferenceType()) 6024 performReferenceExtension(SubInit, ExtendingEntity); 6025 else if (isa<InitListExpr>(SubInit) || 6026 isa<CXXStdInitializerListExpr>(SubInit)) 6027 // This may be either aggregate-initialization of a member or 6028 // initialization of a std::initializer_list object. Either way, 6029 // we should recursively lifetime-extend that initializer. 6030 performLifetimeExtension(SubInit, ExtendingEntity); 6031 ++Index; 6032 } 6033 } 6034 } 6035 } 6036 } 6037 6038 static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity, 6039 const Expr *Init, bool IsInitializerList, 6040 const ValueDecl *ExtendingDecl) { 6041 // Warn if a field lifetime-extends a temporary. 6042 if (isa<FieldDecl>(ExtendingDecl)) { 6043 if (IsInitializerList) { 6044 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list) 6045 << /*at end of constructor*/true; 6046 return; 6047 } 6048 6049 bool IsSubobjectMember = false; 6050 for (const InitializedEntity *Ent = Entity.getParent(); Ent; 6051 Ent = Ent->getParent()) { 6052 if (Ent->getKind() != InitializedEntity::EK_Base) { 6053 IsSubobjectMember = true; 6054 break; 6055 } 6056 } 6057 S.Diag(Init->getExprLoc(), 6058 diag::warn_bind_ref_member_to_temporary) 6059 << ExtendingDecl << Init->getSourceRange() 6060 << IsSubobjectMember << IsInitializerList; 6061 if (IsSubobjectMember) 6062 S.Diag(ExtendingDecl->getLocation(), 6063 diag::note_ref_subobject_of_member_declared_here); 6064 else 6065 S.Diag(ExtendingDecl->getLocation(), 6066 diag::note_ref_or_ptr_member_declared_here) 6067 << /*is pointer*/false; 6068 } 6069 } 6070 6071 static void DiagnoseNarrowingInInitList(Sema &S, 6072 const ImplicitConversionSequence &ICS, 6073 QualType PreNarrowingType, 6074 QualType EntityType, 6075 const Expr *PostInit); 6076 6077 /// Provide warnings when std::move is used on construction. 6078 static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, 6079 bool IsReturnStmt) { 6080 if (!InitExpr) 6081 return; 6082 6083 if (!S.ActiveTemplateInstantiations.empty()) 6084 return; 6085 6086 QualType DestType = InitExpr->getType(); 6087 if (!DestType->isRecordType()) 6088 return; 6089 6090 unsigned DiagID = 0; 6091 if (IsReturnStmt) { 6092 const CXXConstructExpr *CCE = 6093 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens()); 6094 if (!CCE || CCE->getNumArgs() != 1) 6095 return; 6096 6097 if (!CCE->getConstructor()->isCopyOrMoveConstructor()) 6098 return; 6099 6100 InitExpr = CCE->getArg(0)->IgnoreImpCasts(); 6101 } 6102 6103 // Find the std::move call and get the argument. 6104 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens()); 6105 if (!CE || CE->getNumArgs() != 1) 6106 return; 6107 6108 const FunctionDecl *MoveFunction = CE->getDirectCallee(); 6109 if (!MoveFunction || !MoveFunction->isInStdNamespace() || 6110 !MoveFunction->getIdentifier() || 6111 !MoveFunction->getIdentifier()->isStr("move")) 6112 return; 6113 6114 const Expr *Arg = CE->getArg(0)->IgnoreImplicit(); 6115 6116 if (IsReturnStmt) { 6117 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts()); 6118 if (!DRE || DRE->refersToEnclosingVariableOrCapture()) 6119 return; 6120 6121 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()); 6122 if (!VD || !VD->hasLocalStorage()) 6123 return; 6124 6125 QualType SourceType = VD->getType(); 6126 if (!SourceType->isRecordType()) 6127 return; 6128 6129 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) { 6130 return; 6131 } 6132 6133 // If we're returning a function parameter, copy elision 6134 // is not possible. 6135 if (isa<ParmVarDecl>(VD)) 6136 DiagID = diag::warn_redundant_move_on_return; 6137 else 6138 DiagID = diag::warn_pessimizing_move_on_return; 6139 } else { 6140 DiagID = diag::warn_pessimizing_move_on_initialization; 6141 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens(); 6142 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType()) 6143 return; 6144 } 6145 6146 S.Diag(CE->getLocStart(), DiagID); 6147 6148 // Get all the locations for a fix-it. Don't emit the fix-it if any location 6149 // is within a macro. 6150 SourceLocation CallBegin = CE->getCallee()->getLocStart(); 6151 if (CallBegin.isMacroID()) 6152 return; 6153 SourceLocation RParen = CE->getRParenLoc(); 6154 if (RParen.isMacroID()) 6155 return; 6156 SourceLocation LParen; 6157 SourceLocation ArgLoc = Arg->getLocStart(); 6158 6159 // Special testing for the argument location. Since the fix-it needs the 6160 // location right before the argument, the argument location can be in a 6161 // macro only if it is at the beginning of the macro. 6162 while (ArgLoc.isMacroID() && 6163 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) { 6164 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).first; 6165 } 6166 6167 if (LParen.isMacroID()) 6168 return; 6169 6170 LParen = ArgLoc.getLocWithOffset(-1); 6171 6172 S.Diag(CE->getLocStart(), diag::note_remove_move) 6173 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen)) 6174 << FixItHint::CreateRemoval(SourceRange(RParen, RParen)); 6175 } 6176 6177 static void CheckForNullPointerDereference(Sema &S, const Expr *E) { 6178 // Check to see if we are dereferencing a null pointer. If so, this is 6179 // undefined behavior, so warn about it. This only handles the pattern 6180 // "*null", which is a very syntactic check. 6181 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 6182 if (UO->getOpcode() == UO_Deref && 6183 UO->getSubExpr()->IgnoreParenCasts()-> 6184 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) { 6185 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 6186 S.PDiag(diag::warn_binding_null_to_reference) 6187 << UO->getSubExpr()->getSourceRange()); 6188 } 6189 } 6190 6191 MaterializeTemporaryExpr * 6192 Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, 6193 bool BoundToLvalueReference) { 6194 auto MTE = new (Context) 6195 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference); 6196 6197 // Order an ExprWithCleanups for lifetime marks. 6198 // 6199 // TODO: It'll be good to have a single place to check the access of the 6200 // destructor and generate ExprWithCleanups for various uses. Currently these 6201 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary, 6202 // but there may be a chance to merge them. 6203 Cleanup.setExprNeedsCleanups(false); 6204 return MTE; 6205 } 6206 6207 ExprResult 6208 InitializationSequence::Perform(Sema &S, 6209 const InitializedEntity &Entity, 6210 const InitializationKind &Kind, 6211 MultiExprArg Args, 6212 QualType *ResultType) { 6213 if (Failed()) { 6214 Diagnose(S, Entity, Kind, Args); 6215 return ExprError(); 6216 } 6217 if (!ZeroInitializationFixit.empty()) { 6218 unsigned DiagID = diag::err_default_init_const; 6219 if (Decl *D = Entity.getDecl()) 6220 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>()) 6221 DiagID = diag::ext_default_init_const; 6222 6223 // The initialization would have succeeded with this fixit. Since the fixit 6224 // is on the error, we need to build a valid AST in this case, so this isn't 6225 // handled in the Failed() branch above. 6226 QualType DestType = Entity.getType(); 6227 S.Diag(Kind.getLocation(), DiagID) 6228 << DestType << (bool)DestType->getAs<RecordType>() 6229 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc, 6230 ZeroInitializationFixit); 6231 } 6232 6233 if (getKind() == DependentSequence) { 6234 // If the declaration is a non-dependent, incomplete array type 6235 // that has an initializer, then its type will be completed once 6236 // the initializer is instantiated. 6237 if (ResultType && !Entity.getType()->isDependentType() && 6238 Args.size() == 1) { 6239 QualType DeclType = Entity.getType(); 6240 if (const IncompleteArrayType *ArrayT 6241 = S.Context.getAsIncompleteArrayType(DeclType)) { 6242 // FIXME: We don't currently have the ability to accurately 6243 // compute the length of an initializer list without 6244 // performing full type-checking of the initializer list 6245 // (since we have to determine where braces are implicitly 6246 // introduced and such). So, we fall back to making the array 6247 // type a dependently-sized array type with no specified 6248 // bound. 6249 if (isa<InitListExpr>((Expr *)Args[0])) { 6250 SourceRange Brackets; 6251 6252 // Scavange the location of the brackets from the entity, if we can. 6253 if (DeclaratorDecl *DD = Entity.getDecl()) { 6254 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { 6255 TypeLoc TL = TInfo->getTypeLoc(); 6256 if (IncompleteArrayTypeLoc ArrayLoc = 6257 TL.getAs<IncompleteArrayTypeLoc>()) 6258 Brackets = ArrayLoc.getBracketsRange(); 6259 } 6260 } 6261 6262 *ResultType 6263 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), 6264 /*NumElts=*/nullptr, 6265 ArrayT->getSizeModifier(), 6266 ArrayT->getIndexTypeCVRQualifiers(), 6267 Brackets); 6268 } 6269 6270 } 6271 } 6272 if (Kind.getKind() == InitializationKind::IK_Direct && 6273 !Kind.isExplicitCast()) { 6274 // Rebuild the ParenListExpr. 6275 SourceRange ParenRange = Kind.getParenRange(); 6276 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(), 6277 Args); 6278 } 6279 assert(Kind.getKind() == InitializationKind::IK_Copy || 6280 Kind.isExplicitCast() || 6281 Kind.getKind() == InitializationKind::IK_DirectList); 6282 return ExprResult(Args[0]); 6283 } 6284 6285 // No steps means no initialization. 6286 if (Steps.empty()) 6287 return ExprResult((Expr *)nullptr); 6288 6289 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() && 6290 Args.size() == 1 && isa<InitListExpr>(Args[0]) && 6291 !Entity.isParameterKind()) { 6292 // Produce a C++98 compatibility warning if we are initializing a reference 6293 // from an initializer list. For parameters, we produce a better warning 6294 // elsewhere. 6295 Expr *Init = Args[0]; 6296 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init) 6297 << Init->getSourceRange(); 6298 } 6299 6300 // Diagnose cases where we initialize a pointer to an array temporary, and the 6301 // pointer obviously outlives the temporary. 6302 if (Args.size() == 1 && Args[0]->getType()->isArrayType() && 6303 Entity.getType()->isPointerType() && 6304 InitializedEntityOutlivesFullExpression(Entity)) { 6305 Expr *Init = Args[0]; 6306 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context); 6307 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary) 6308 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay) 6309 << Init->getSourceRange(); 6310 } 6311 6312 QualType DestType = Entity.getType().getNonReferenceType(); 6313 // FIXME: Ugly hack around the fact that Entity.getType() is not 6314 // the same as Entity.getDecl()->getType() in cases involving type merging, 6315 // and we want latter when it makes sense. 6316 if (ResultType) 6317 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : 6318 Entity.getType(); 6319 6320 ExprResult CurInit((Expr *)nullptr); 6321 6322 // For initialization steps that start with a single initializer, 6323 // grab the only argument out the Args and place it into the "current" 6324 // initializer. 6325 switch (Steps.front().Kind) { 6326 case SK_ResolveAddressOfOverloadedFunction: 6327 case SK_CastDerivedToBaseRValue: 6328 case SK_CastDerivedToBaseXValue: 6329 case SK_CastDerivedToBaseLValue: 6330 case SK_BindReference: 6331 case SK_BindReferenceToTemporary: 6332 case SK_ExtraneousCopyToTemporary: 6333 case SK_UserConversion: 6334 case SK_QualificationConversionLValue: 6335 case SK_QualificationConversionXValue: 6336 case SK_QualificationConversionRValue: 6337 case SK_AtomicConversion: 6338 case SK_LValueToRValue: 6339 case SK_ConversionSequence: 6340 case SK_ConversionSequenceNoNarrowing: 6341 case SK_ListInitialization: 6342 case SK_UnwrapInitList: 6343 case SK_RewrapInitList: 6344 case SK_CAssignment: 6345 case SK_StringInit: 6346 case SK_ObjCObjectConversion: 6347 case SK_ArrayInit: 6348 case SK_ParenthesizedArrayInit: 6349 case SK_PassByIndirectCopyRestore: 6350 case SK_PassByIndirectRestore: 6351 case SK_ProduceObjCObject: 6352 case SK_StdInitializerList: 6353 case SK_OCLSamplerInit: 6354 case SK_OCLZeroEvent: { 6355 assert(Args.size() == 1); 6356 CurInit = Args[0]; 6357 if (!CurInit.get()) return ExprError(); 6358 break; 6359 } 6360 6361 case SK_ConstructorInitialization: 6362 case SK_ConstructorInitializationFromList: 6363 case SK_StdInitializerListConstructorCall: 6364 case SK_ZeroInitialization: 6365 break; 6366 } 6367 6368 // Walk through the computed steps for the initialization sequence, 6369 // performing the specified conversions along the way. 6370 bool ConstructorInitRequiresZeroInit = false; 6371 for (step_iterator Step = step_begin(), StepEnd = step_end(); 6372 Step != StepEnd; ++Step) { 6373 if (CurInit.isInvalid()) 6374 return ExprError(); 6375 6376 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); 6377 6378 switch (Step->Kind) { 6379 case SK_ResolveAddressOfOverloadedFunction: 6380 // Overload resolution determined which function invoke; update the 6381 // initializer to reflect that choice. 6382 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl); 6383 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation())) 6384 return ExprError(); 6385 CurInit = S.FixOverloadedFunctionReference(CurInit, 6386 Step->Function.FoundDecl, 6387 Step->Function.Function); 6388 break; 6389 6390 case SK_CastDerivedToBaseRValue: 6391 case SK_CastDerivedToBaseXValue: 6392 case SK_CastDerivedToBaseLValue: { 6393 // We have a derived-to-base cast that produces either an rvalue or an 6394 // lvalue. Perform that cast. 6395 6396 CXXCastPath BasePath; 6397 6398 // Casts to inaccessible base classes are allowed with C-style casts. 6399 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); 6400 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type, 6401 CurInit.get()->getLocStart(), 6402 CurInit.get()->getSourceRange(), 6403 &BasePath, IgnoreBaseAccess)) 6404 return ExprError(); 6405 6406 ExprValueKind VK = 6407 Step->Kind == SK_CastDerivedToBaseLValue ? 6408 VK_LValue : 6409 (Step->Kind == SK_CastDerivedToBaseXValue ? 6410 VK_XValue : 6411 VK_RValue); 6412 CurInit = 6413 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase, 6414 CurInit.get(), &BasePath, VK); 6415 break; 6416 } 6417 6418 case SK_BindReference: 6419 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5). 6420 if (CurInit.get()->refersToBitField()) { 6421 // We don't necessarily have an unambiguous source bit-field. 6422 FieldDecl *BitField = CurInit.get()->getSourceBitField(); 6423 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) 6424 << Entity.getType().isVolatileQualified() 6425 << (BitField ? BitField->getDeclName() : DeclarationName()) 6426 << (BitField != nullptr) 6427 << CurInit.get()->getSourceRange(); 6428 if (BitField) 6429 S.Diag(BitField->getLocation(), diag::note_bitfield_decl); 6430 6431 return ExprError(); 6432 } 6433 6434 if (CurInit.get()->refersToVectorElement()) { 6435 // References cannot bind to vector elements. 6436 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element) 6437 << Entity.getType().isVolatileQualified() 6438 << CurInit.get()->getSourceRange(); 6439 PrintInitLocationNote(S, Entity); 6440 return ExprError(); 6441 } 6442 6443 // Reference binding does not have any corresponding ASTs. 6444 6445 // Check exception specifications 6446 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 6447 return ExprError(); 6448 6449 // Even though we didn't materialize a temporary, the binding may still 6450 // extend the lifetime of a temporary. This happens if we bind a reference 6451 // to the result of a cast to reference type. 6452 if (const InitializedEntity *ExtendingEntity = 6453 getEntityForTemporaryLifetimeExtension(&Entity)) 6454 if (performReferenceExtension(CurInit.get(), ExtendingEntity)) 6455 warnOnLifetimeExtension(S, Entity, CurInit.get(), 6456 /*IsInitializerList=*/false, 6457 ExtendingEntity->getDecl()); 6458 6459 CheckForNullPointerDereference(S, CurInit.get()); 6460 break; 6461 6462 case SK_BindReferenceToTemporary: { 6463 // Make sure the "temporary" is actually an rvalue. 6464 assert(CurInit.get()->isRValue() && "not a temporary"); 6465 6466 // Check exception specifications 6467 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 6468 return ExprError(); 6469 6470 // Materialize the temporary into memory. 6471 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( 6472 Entity.getType().getNonReferenceType(), CurInit.get(), 6473 Entity.getType()->isLValueReferenceType()); 6474 6475 // Maybe lifetime-extend the temporary's subobjects to match the 6476 // entity's lifetime. 6477 if (const InitializedEntity *ExtendingEntity = 6478 getEntityForTemporaryLifetimeExtension(&Entity)) 6479 if (performReferenceExtension(MTE, ExtendingEntity)) 6480 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false, 6481 ExtendingEntity->getDecl()); 6482 6483 // If we're binding to an Objective-C object that has lifetime, we 6484 // need cleanups. Likewise if we're extending this temporary to automatic 6485 // storage duration -- we need to register its cleanup during the 6486 // full-expression's cleanups. 6487 if ((S.getLangOpts().ObjCAutoRefCount && 6488 MTE->getType()->isObjCLifetimeType()) || 6489 (MTE->getStorageDuration() == SD_Automatic && 6490 MTE->getType().isDestructedType())) 6491 S.Cleanup.setExprNeedsCleanups(true); 6492 6493 CurInit = MTE; 6494 break; 6495 } 6496 6497 case SK_ExtraneousCopyToTemporary: 6498 CurInit = CopyObject(S, Step->Type, Entity, CurInit, 6499 /*IsExtraneousCopy=*/true); 6500 break; 6501 6502 case SK_UserConversion: { 6503 // We have a user-defined conversion that invokes either a constructor 6504 // or a conversion function. 6505 CastKind CastKind; 6506 bool IsCopy = false; 6507 FunctionDecl *Fn = Step->Function.Function; 6508 DeclAccessPair FoundFn = Step->Function.FoundDecl; 6509 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates; 6510 bool CreatedObject = false; 6511 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) { 6512 // Build a call to the selected constructor. 6513 SmallVector<Expr*, 8> ConstructorArgs; 6514 SourceLocation Loc = CurInit.get()->getLocStart(); 6515 CurInit.get(); // Ownership transferred into MultiExprArg, below. 6516 6517 // Determine the arguments required to actually perform the constructor 6518 // call. 6519 Expr *Arg = CurInit.get(); 6520 if (S.CompleteConstructorCall(Constructor, 6521 MultiExprArg(&Arg, 1), 6522 Loc, ConstructorArgs)) 6523 return ExprError(); 6524 6525 // Build an expression that constructs a temporary. 6526 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, 6527 FoundFn, Constructor, 6528 ConstructorArgs, 6529 HadMultipleCandidates, 6530 /*ListInit*/ false, 6531 /*StdInitListInit*/ false, 6532 /*ZeroInit*/ false, 6533 CXXConstructExpr::CK_Complete, 6534 SourceRange()); 6535 if (CurInit.isInvalid()) 6536 return ExprError(); 6537 6538 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn, 6539 Entity); 6540 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) 6541 return ExprError(); 6542 6543 CastKind = CK_ConstructorConversion; 6544 QualType Class = S.Context.getTypeDeclType(Constructor->getParent()); 6545 if (S.Context.hasSameUnqualifiedType(SourceType, Class) || 6546 S.IsDerivedFrom(Loc, SourceType, Class)) 6547 IsCopy = true; 6548 6549 CreatedObject = true; 6550 } else { 6551 // Build a call to the conversion function. 6552 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn); 6553 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr, 6554 FoundFn); 6555 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) 6556 return ExprError(); 6557 6558 // FIXME: Should we move this initialization into a separate 6559 // derived-to-base conversion? I believe the answer is "no", because 6560 // we don't want to turn off access control here for c-style casts. 6561 ExprResult CurInitExprRes = 6562 S.PerformObjectArgumentInitialization(CurInit.get(), 6563 /*Qualifier=*/nullptr, 6564 FoundFn, Conversion); 6565 if(CurInitExprRes.isInvalid()) 6566 return ExprError(); 6567 CurInit = CurInitExprRes; 6568 6569 // Build the actual call to the conversion function. 6570 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion, 6571 HadMultipleCandidates); 6572 if (CurInit.isInvalid() || !CurInit.get()) 6573 return ExprError(); 6574 6575 CastKind = CK_UserDefinedConversion; 6576 6577 CreatedObject = Conversion->getReturnType()->isRecordType(); 6578 } 6579 6580 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back()); 6581 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity); 6582 6583 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) { 6584 QualType T = CurInit.get()->getType(); 6585 if (const RecordType *Record = T->getAs<RecordType>()) { 6586 CXXDestructorDecl *Destructor 6587 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl())); 6588 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor, 6589 S.PDiag(diag::err_access_dtor_temp) << T); 6590 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor); 6591 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart())) 6592 return ExprError(); 6593 } 6594 } 6595 6596 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(), 6597 CastKind, CurInit.get(), nullptr, 6598 CurInit.get()->getValueKind()); 6599 if (MaybeBindToTemp) 6600 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); 6601 if (RequiresCopy) 6602 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity, 6603 CurInit, /*IsExtraneousCopy=*/false); 6604 break; 6605 } 6606 6607 case SK_QualificationConversionLValue: 6608 case SK_QualificationConversionXValue: 6609 case SK_QualificationConversionRValue: { 6610 // Perform a qualification conversion; these can never go wrong. 6611 ExprValueKind VK = 6612 Step->Kind == SK_QualificationConversionLValue ? 6613 VK_LValue : 6614 (Step->Kind == SK_QualificationConversionXValue ? 6615 VK_XValue : 6616 VK_RValue); 6617 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK); 6618 break; 6619 } 6620 6621 case SK_AtomicConversion: { 6622 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic"); 6623 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, 6624 CK_NonAtomicToAtomic, VK_RValue); 6625 break; 6626 } 6627 6628 case SK_LValueToRValue: { 6629 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue"); 6630 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type, 6631 CK_LValueToRValue, CurInit.get(), 6632 /*BasePath=*/nullptr, VK_RValue); 6633 break; 6634 } 6635 6636 case SK_ConversionSequence: 6637 case SK_ConversionSequenceNoNarrowing: { 6638 Sema::CheckedConversionKind CCK 6639 = Kind.isCStyleCast()? Sema::CCK_CStyleCast 6640 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast 6641 : Kind.isExplicitCast()? Sema::CCK_OtherCast 6642 : Sema::CCK_ImplicitConversion; 6643 ExprResult CurInitExprRes = 6644 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS, 6645 getAssignmentAction(Entity), CCK); 6646 if (CurInitExprRes.isInvalid()) 6647 return ExprError(); 6648 CurInit = CurInitExprRes; 6649 6650 if (Step->Kind == SK_ConversionSequenceNoNarrowing && 6651 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent()) 6652 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(), 6653 CurInit.get()); 6654 break; 6655 } 6656 6657 case SK_ListInitialization: { 6658 InitListExpr *InitList = cast<InitListExpr>(CurInit.get()); 6659 // If we're not initializing the top-level entity, we need to create an 6660 // InitializeTemporary entity for our target type. 6661 QualType Ty = Step->Type; 6662 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty); 6663 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty); 6664 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity; 6665 InitListChecker PerformInitList(S, InitEntity, 6666 InitList, Ty, /*VerifyOnly=*/false, 6667 /*TreatUnavailableAsInvalid=*/false); 6668 if (PerformInitList.HadError()) 6669 return ExprError(); 6670 6671 // Hack: We must update *ResultType if available in order to set the 6672 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'. 6673 // Worst case: 'const int (&arref)[] = {1, 2, 3};'. 6674 if (ResultType && 6675 ResultType->getNonReferenceType()->isIncompleteArrayType()) { 6676 if ((*ResultType)->isRValueReferenceType()) 6677 Ty = S.Context.getRValueReferenceType(Ty); 6678 else if ((*ResultType)->isLValueReferenceType()) 6679 Ty = S.Context.getLValueReferenceType(Ty, 6680 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue()); 6681 *ResultType = Ty; 6682 } 6683 6684 InitListExpr *StructuredInitList = 6685 PerformInitList.getFullyStructuredList(); 6686 CurInit.get(); 6687 CurInit = shouldBindAsTemporary(InitEntity) 6688 ? S.MaybeBindToTemporary(StructuredInitList) 6689 : StructuredInitList; 6690 break; 6691 } 6692 6693 case SK_ConstructorInitializationFromList: { 6694 // When an initializer list is passed for a parameter of type "reference 6695 // to object", we don't get an EK_Temporary entity, but instead an 6696 // EK_Parameter entity with reference type. 6697 // FIXME: This is a hack. What we really should do is create a user 6698 // conversion step for this case, but this makes it considerably more 6699 // complicated. For now, this will do. 6700 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( 6701 Entity.getType().getNonReferenceType()); 6702 bool UseTemporary = Entity.getType()->isReferenceType(); 6703 assert(Args.size() == 1 && "expected a single argument for list init"); 6704 InitListExpr *InitList = cast<InitListExpr>(Args[0]); 6705 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init) 6706 << InitList->getSourceRange(); 6707 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits()); 6708 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity : 6709 Entity, 6710 Kind, Arg, *Step, 6711 ConstructorInitRequiresZeroInit, 6712 /*IsListInitialization*/true, 6713 /*IsStdInitListInit*/false, 6714 InitList->getLBraceLoc(), 6715 InitList->getRBraceLoc()); 6716 break; 6717 } 6718 6719 case SK_UnwrapInitList: 6720 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0); 6721 break; 6722 6723 case SK_RewrapInitList: { 6724 Expr *E = CurInit.get(); 6725 InitListExpr *Syntactic = Step->WrappingSyntacticList; 6726 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context, 6727 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc()); 6728 ILE->setSyntacticForm(Syntactic); 6729 ILE->setType(E->getType()); 6730 ILE->setValueKind(E->getValueKind()); 6731 CurInit = ILE; 6732 break; 6733 } 6734 6735 case SK_ConstructorInitialization: 6736 case SK_StdInitializerListConstructorCall: { 6737 // When an initializer list is passed for a parameter of type "reference 6738 // to object", we don't get an EK_Temporary entity, but instead an 6739 // EK_Parameter entity with reference type. 6740 // FIXME: This is a hack. What we really should do is create a user 6741 // conversion step for this case, but this makes it considerably more 6742 // complicated. For now, this will do. 6743 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( 6744 Entity.getType().getNonReferenceType()); 6745 bool UseTemporary = Entity.getType()->isReferenceType(); 6746 bool IsStdInitListInit = 6747 Step->Kind == SK_StdInitializerListConstructorCall; 6748 CurInit = PerformConstructorInitialization( 6749 S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step, 6750 ConstructorInitRequiresZeroInit, 6751 /*IsListInitialization*/IsStdInitListInit, 6752 /*IsStdInitListInitialization*/IsStdInitListInit, 6753 /*LBraceLoc*/SourceLocation(), 6754 /*RBraceLoc*/SourceLocation()); 6755 break; 6756 } 6757 6758 case SK_ZeroInitialization: { 6759 step_iterator NextStep = Step; 6760 ++NextStep; 6761 if (NextStep != StepEnd && 6762 (NextStep->Kind == SK_ConstructorInitialization || 6763 NextStep->Kind == SK_ConstructorInitializationFromList)) { 6764 // The need for zero-initialization is recorded directly into 6765 // the call to the object's constructor within the next step. 6766 ConstructorInitRequiresZeroInit = true; 6767 } else if (Kind.getKind() == InitializationKind::IK_Value && 6768 S.getLangOpts().CPlusPlus && 6769 !Kind.isImplicitValueInit()) { 6770 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 6771 if (!TSInfo) 6772 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type, 6773 Kind.getRange().getBegin()); 6774 6775 CurInit = new (S.Context) CXXScalarValueInitExpr( 6776 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo, 6777 Kind.getRange().getEnd()); 6778 } else { 6779 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type); 6780 } 6781 break; 6782 } 6783 6784 case SK_CAssignment: { 6785 QualType SourceType = CurInit.get()->getType(); 6786 // Save off the initial CurInit in case we need to emit a diagnostic 6787 ExprResult InitialCurInit = CurInit; 6788 ExprResult Result = CurInit; 6789 Sema::AssignConvertType ConvTy = 6790 S.CheckSingleAssignmentConstraints(Step->Type, Result, true, 6791 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited); 6792 if (Result.isInvalid()) 6793 return ExprError(); 6794 CurInit = Result; 6795 6796 // If this is a call, allow conversion to a transparent union. 6797 ExprResult CurInitExprRes = CurInit; 6798 if (ConvTy != Sema::Compatible && 6799 Entity.isParameterKind() && 6800 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes) 6801 == Sema::Compatible) 6802 ConvTy = Sema::Compatible; 6803 if (CurInitExprRes.isInvalid()) 6804 return ExprError(); 6805 CurInit = CurInitExprRes; 6806 6807 bool Complained; 6808 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), 6809 Step->Type, SourceType, 6810 InitialCurInit.get(), 6811 getAssignmentAction(Entity, true), 6812 &Complained)) { 6813 PrintInitLocationNote(S, Entity); 6814 return ExprError(); 6815 } else if (Complained) 6816 PrintInitLocationNote(S, Entity); 6817 break; 6818 } 6819 6820 case SK_StringInit: { 6821 QualType Ty = Step->Type; 6822 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty, 6823 S.Context.getAsArrayType(Ty), S); 6824 break; 6825 } 6826 6827 case SK_ObjCObjectConversion: 6828 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, 6829 CK_ObjCObjectLValueCast, 6830 CurInit.get()->getValueKind()); 6831 break; 6832 6833 case SK_ArrayInit: 6834 // Okay: we checked everything before creating this step. Note that 6835 // this is a GNU extension. 6836 S.Diag(Kind.getLocation(), diag::ext_array_init_copy) 6837 << Step->Type << CurInit.get()->getType() 6838 << CurInit.get()->getSourceRange(); 6839 6840 // If the destination type is an incomplete array type, update the 6841 // type accordingly. 6842 if (ResultType) { 6843 if (const IncompleteArrayType *IncompleteDest 6844 = S.Context.getAsIncompleteArrayType(Step->Type)) { 6845 if (const ConstantArrayType *ConstantSource 6846 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) { 6847 *ResultType = S.Context.getConstantArrayType( 6848 IncompleteDest->getElementType(), 6849 ConstantSource->getSize(), 6850 ArrayType::Normal, 0); 6851 } 6852 } 6853 } 6854 break; 6855 6856 case SK_ParenthesizedArrayInit: 6857 // Okay: we checked everything before creating this step. Note that 6858 // this is a GNU extension. 6859 S.Diag(Kind.getLocation(), diag::ext_array_init_parens) 6860 << CurInit.get()->getSourceRange(); 6861 break; 6862 6863 case SK_PassByIndirectCopyRestore: 6864 case SK_PassByIndirectRestore: 6865 checkIndirectCopyRestoreSource(S, CurInit.get()); 6866 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr( 6867 CurInit.get(), Step->Type, 6868 Step->Kind == SK_PassByIndirectCopyRestore); 6869 break; 6870 6871 case SK_ProduceObjCObject: 6872 CurInit = 6873 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject, 6874 CurInit.get(), nullptr, VK_RValue); 6875 break; 6876 6877 case SK_StdInitializerList: { 6878 S.Diag(CurInit.get()->getExprLoc(), 6879 diag::warn_cxx98_compat_initializer_list_init) 6880 << CurInit.get()->getSourceRange(); 6881 6882 // Materialize the temporary into memory. 6883 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( 6884 CurInit.get()->getType(), CurInit.get(), 6885 /*BoundToLvalueReference=*/false); 6886 6887 // Maybe lifetime-extend the array temporary's subobjects to match the 6888 // entity's lifetime. 6889 if (const InitializedEntity *ExtendingEntity = 6890 getEntityForTemporaryLifetimeExtension(&Entity)) 6891 if (performReferenceExtension(MTE, ExtendingEntity)) 6892 warnOnLifetimeExtension(S, Entity, CurInit.get(), 6893 /*IsInitializerList=*/true, 6894 ExtendingEntity->getDecl()); 6895 6896 // Wrap it in a construction of a std::initializer_list<T>. 6897 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE); 6898 6899 // Bind the result, in case the library has given initializer_list a 6900 // non-trivial destructor. 6901 if (shouldBindAsTemporary(Entity)) 6902 CurInit = S.MaybeBindToTemporary(CurInit.get()); 6903 break; 6904 } 6905 6906 case SK_OCLSamplerInit: { 6907 // Sampler initialzation have 5 cases: 6908 // 1. function argument passing 6909 // 1a. argument is a file-scope variable 6910 // 1b. argument is a function-scope variable 6911 // 1c. argument is one of caller function's parameters 6912 // 2. variable initialization 6913 // 2a. initializing a file-scope variable 6914 // 2b. initializing a function-scope variable 6915 // 6916 // For file-scope variables, since they cannot be initialized by function 6917 // call of __translate_sampler_initializer in LLVM IR, their references 6918 // need to be replaced by a cast from their literal initializers to 6919 // sampler type. Since sampler variables can only be used in function 6920 // calls as arguments, we only need to replace them when handling the 6921 // argument passing. 6922 assert(Step->Type->isSamplerT() && 6923 "Sampler initialization on non-sampler type."); 6924 Expr *Init = CurInit.get(); 6925 QualType SourceType = Init->getType(); 6926 // Case 1 6927 if (Entity.isParameterKind()) { 6928 if (!SourceType->isSamplerT()) { 6929 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required) 6930 << SourceType; 6931 break; 6932 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) { 6933 auto Var = cast<VarDecl>(DRE->getDecl()); 6934 // Case 1b and 1c 6935 // No cast from integer to sampler is needed. 6936 if (!Var->hasGlobalStorage()) { 6937 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type, 6938 CK_LValueToRValue, Init, 6939 /*BasePath=*/nullptr, VK_RValue); 6940 break; 6941 } 6942 // Case 1a 6943 // For function call with a file-scope sampler variable as argument, 6944 // get the integer literal. 6945 // Do not diagnose if the file-scope variable does not have initializer 6946 // since this has already been diagnosed when parsing the variable 6947 // declaration. 6948 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit())) 6949 break; 6950 Init = cast<ImplicitCastExpr>(const_cast<Expr*>( 6951 Var->getInit()))->getSubExpr(); 6952 SourceType = Init->getType(); 6953 } 6954 } else { 6955 // Case 2 6956 // Check initializer is 32 bit integer constant. 6957 // If the initializer is taken from global variable, do not diagnose since 6958 // this has already been done when parsing the variable declaration. 6959 if (!Init->isConstantInitializer(S.Context, false)) 6960 break; 6961 6962 if (!SourceType->isIntegerType() || 6963 32 != S.Context.getIntWidth(SourceType)) { 6964 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer) 6965 << SourceType; 6966 break; 6967 } 6968 6969 llvm::APSInt Result; 6970 Init->EvaluateAsInt(Result, S.Context); 6971 const uint64_t SamplerValue = Result.getLimitedValue(); 6972 // 32-bit value of sampler's initializer is interpreted as 6973 // bit-field with the following structure: 6974 // |unspecified|Filter|Addressing Mode| Normalized Coords| 6975 // |31 6|5 4|3 1| 0| 6976 // This structure corresponds to enum values of sampler properties 6977 // defined in SPIR spec v1.2 and also opencl-c.h 6978 unsigned AddressingMode = (0x0E & SamplerValue) >> 1; 6979 unsigned FilterMode = (0x30 & SamplerValue) >> 4; 6980 if (FilterMode != 1 && FilterMode != 2) 6981 S.Diag(Kind.getLocation(), 6982 diag::warn_sampler_initializer_invalid_bits) 6983 << "Filter Mode"; 6984 if (AddressingMode > 4) 6985 S.Diag(Kind.getLocation(), 6986 diag::warn_sampler_initializer_invalid_bits) 6987 << "Addressing Mode"; 6988 } 6989 6990 // Cases 1a, 2a and 2b 6991 // Insert cast from integer to sampler. 6992 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy, 6993 CK_IntToOCLSampler); 6994 break; 6995 } 6996 case SK_OCLZeroEvent: { 6997 assert(Step->Type->isEventT() && 6998 "Event initialization on non-event type."); 6999 7000 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, 7001 CK_ZeroToOCLEvent, 7002 CurInit.get()->getValueKind()); 7003 break; 7004 } 7005 } 7006 } 7007 7008 // Diagnose non-fatal problems with the completed initialization. 7009 if (Entity.getKind() == InitializedEntity::EK_Member && 7010 cast<FieldDecl>(Entity.getDecl())->isBitField()) 7011 S.CheckBitFieldInitialization(Kind.getLocation(), 7012 cast<FieldDecl>(Entity.getDecl()), 7013 CurInit.get()); 7014 7015 // Check for std::move on construction. 7016 if (const Expr *E = CurInit.get()) { 7017 CheckMoveOnConstruction(S, E, 7018 Entity.getKind() == InitializedEntity::EK_Result); 7019 } 7020 7021 return CurInit; 7022 } 7023 7024 /// Somewhere within T there is an uninitialized reference subobject. 7025 /// Dig it out and diagnose it. 7026 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, 7027 QualType T) { 7028 if (T->isReferenceType()) { 7029 S.Diag(Loc, diag::err_reference_without_init) 7030 << T.getNonReferenceType(); 7031 return true; 7032 } 7033 7034 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 7035 if (!RD || !RD->hasUninitializedReferenceMember()) 7036 return false; 7037 7038 for (const auto *FI : RD->fields()) { 7039 if (FI->isUnnamedBitfield()) 7040 continue; 7041 7042 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) { 7043 S.Diag(Loc, diag::note_value_initialization_here) << RD; 7044 return true; 7045 } 7046 } 7047 7048 for (const auto &BI : RD->bases()) { 7049 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) { 7050 S.Diag(Loc, diag::note_value_initialization_here) << RD; 7051 return true; 7052 } 7053 } 7054 7055 return false; 7056 } 7057 7058 7059 //===----------------------------------------------------------------------===// 7060 // Diagnose initialization failures 7061 //===----------------------------------------------------------------------===// 7062 7063 /// Emit notes associated with an initialization that failed due to a 7064 /// "simple" conversion failure. 7065 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, 7066 Expr *op) { 7067 QualType destType = entity.getType(); 7068 if (destType.getNonReferenceType()->isObjCObjectPointerType() && 7069 op->getType()->isObjCObjectPointerType()) { 7070 7071 // Emit a possible note about the conversion failing because the 7072 // operand is a message send with a related result type. 7073 S.EmitRelatedResultTypeNote(op); 7074 7075 // Emit a possible note about a return failing because we're 7076 // expecting a related result type. 7077 if (entity.getKind() == InitializedEntity::EK_Result) 7078 S.EmitRelatedResultTypeNoteForReturn(destType); 7079 } 7080 } 7081 7082 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, 7083 InitListExpr *InitList) { 7084 QualType DestType = Entity.getType(); 7085 7086 QualType E; 7087 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) { 7088 QualType ArrayType = S.Context.getConstantArrayType( 7089 E.withConst(), 7090 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), 7091 InitList->getNumInits()), 7092 clang::ArrayType::Normal, 0); 7093 InitializedEntity HiddenArray = 7094 InitializedEntity::InitializeTemporary(ArrayType); 7095 return diagnoseListInit(S, HiddenArray, InitList); 7096 } 7097 7098 if (DestType->isReferenceType()) { 7099 // A list-initialization failure for a reference means that we tried to 7100 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the 7101 // inner initialization failed. 7102 QualType T = DestType->getAs<ReferenceType>()->getPointeeType(); 7103 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList); 7104 SourceLocation Loc = InitList->getLocStart(); 7105 if (auto *D = Entity.getDecl()) 7106 Loc = D->getLocation(); 7107 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T; 7108 return; 7109 } 7110 7111 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType, 7112 /*VerifyOnly=*/false, 7113 /*TreatUnavailableAsInvalid=*/false); 7114 assert(DiagnoseInitList.HadError() && 7115 "Inconsistent init list check result."); 7116 } 7117 7118 bool InitializationSequence::Diagnose(Sema &S, 7119 const InitializedEntity &Entity, 7120 const InitializationKind &Kind, 7121 ArrayRef<Expr *> Args) { 7122 if (!Failed()) 7123 return false; 7124 7125 QualType DestType = Entity.getType(); 7126 switch (Failure) { 7127 case FK_TooManyInitsForReference: 7128 // FIXME: Customize for the initialized entity? 7129 if (Args.empty()) { 7130 // Dig out the reference subobject which is uninitialized and diagnose it. 7131 // If this is value-initialization, this could be nested some way within 7132 // the target type. 7133 assert(Kind.getKind() == InitializationKind::IK_Value || 7134 DestType->isReferenceType()); 7135 bool Diagnosed = 7136 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType); 7137 assert(Diagnosed && "couldn't find uninitialized reference to diagnose"); 7138 (void)Diagnosed; 7139 } else // FIXME: diagnostic below could be better! 7140 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) 7141 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd()); 7142 break; 7143 7144 case FK_ArrayNeedsInitList: 7145 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0; 7146 break; 7147 case FK_ArrayNeedsInitListOrStringLiteral: 7148 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1; 7149 break; 7150 case FK_ArrayNeedsInitListOrWideStringLiteral: 7151 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2; 7152 break; 7153 case FK_NarrowStringIntoWideCharArray: 7154 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar); 7155 break; 7156 case FK_WideStringIntoCharArray: 7157 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char); 7158 break; 7159 case FK_IncompatWideStringIntoWideChar: 7160 S.Diag(Kind.getLocation(), 7161 diag::err_array_init_incompat_wide_string_into_wchar); 7162 break; 7163 case FK_ArrayTypeMismatch: 7164 case FK_NonConstantArrayInit: 7165 S.Diag(Kind.getLocation(), 7166 (Failure == FK_ArrayTypeMismatch 7167 ? diag::err_array_init_different_type 7168 : diag::err_array_init_non_constant_array)) 7169 << DestType.getNonReferenceType() 7170 << Args[0]->getType() 7171 << Args[0]->getSourceRange(); 7172 break; 7173 7174 case FK_VariableLengthArrayHasInitializer: 7175 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init) 7176 << Args[0]->getSourceRange(); 7177 break; 7178 7179 case FK_AddressOfOverloadFailed: { 7180 DeclAccessPair Found; 7181 S.ResolveAddressOfOverloadedFunction(Args[0], 7182 DestType.getNonReferenceType(), 7183 true, 7184 Found); 7185 break; 7186 } 7187 7188 case FK_AddressOfUnaddressableFunction: { 7189 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(Args[0])->getDecl()); 7190 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 7191 Args[0]->getLocStart()); 7192 break; 7193 } 7194 7195 case FK_ReferenceInitOverloadFailed: 7196 case FK_UserConversionOverloadFailed: 7197 switch (FailedOverloadResult) { 7198 case OR_Ambiguous: 7199 if (Failure == FK_UserConversionOverloadFailed) 7200 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition) 7201 << Args[0]->getType() << DestType 7202 << Args[0]->getSourceRange(); 7203 else 7204 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous) 7205 << DestType << Args[0]->getType() 7206 << Args[0]->getSourceRange(); 7207 7208 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args); 7209 break; 7210 7211 case OR_No_Viable_Function: 7212 if (!S.RequireCompleteType(Kind.getLocation(), 7213 DestType.getNonReferenceType(), 7214 diag::err_typecheck_nonviable_condition_incomplete, 7215 Args[0]->getType(), Args[0]->getSourceRange())) 7216 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) 7217 << (Entity.getKind() == InitializedEntity::EK_Result) 7218 << Args[0]->getType() << Args[0]->getSourceRange() 7219 << DestType.getNonReferenceType(); 7220 7221 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args); 7222 break; 7223 7224 case OR_Deleted: { 7225 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) 7226 << Args[0]->getType() << DestType.getNonReferenceType() 7227 << Args[0]->getSourceRange(); 7228 OverloadCandidateSet::iterator Best; 7229 OverloadingResult Ovl 7230 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best, 7231 true); 7232 if (Ovl == OR_Deleted) { 7233 S.NoteDeletedFunction(Best->Function); 7234 } else { 7235 llvm_unreachable("Inconsistent overload resolution?"); 7236 } 7237 break; 7238 } 7239 7240 case OR_Success: 7241 llvm_unreachable("Conversion did not fail!"); 7242 } 7243 break; 7244 7245 case FK_NonConstLValueReferenceBindingToTemporary: 7246 if (isa<InitListExpr>(Args[0])) { 7247 S.Diag(Kind.getLocation(), 7248 diag::err_lvalue_reference_bind_to_initlist) 7249 << DestType.getNonReferenceType().isVolatileQualified() 7250 << DestType.getNonReferenceType() 7251 << Args[0]->getSourceRange(); 7252 break; 7253 } 7254 // Intentional fallthrough 7255 7256 case FK_NonConstLValueReferenceBindingToUnrelated: 7257 S.Diag(Kind.getLocation(), 7258 Failure == FK_NonConstLValueReferenceBindingToTemporary 7259 ? diag::err_lvalue_reference_bind_to_temporary 7260 : diag::err_lvalue_reference_bind_to_unrelated) 7261 << DestType.getNonReferenceType().isVolatileQualified() 7262 << DestType.getNonReferenceType() 7263 << Args[0]->getType() 7264 << Args[0]->getSourceRange(); 7265 break; 7266 7267 case FK_RValueReferenceBindingToLValue: 7268 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) 7269 << DestType.getNonReferenceType() << Args[0]->getType() 7270 << Args[0]->getSourceRange(); 7271 break; 7272 7273 case FK_ReferenceInitDropsQualifiers: { 7274 QualType SourceType = Args[0]->getType(); 7275 QualType NonRefType = DestType.getNonReferenceType(); 7276 Qualifiers DroppedQualifiers = 7277 SourceType.getQualifiers() - NonRefType.getQualifiers(); 7278 7279 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 7280 << SourceType 7281 << NonRefType 7282 << DroppedQualifiers.getCVRQualifiers() 7283 << Args[0]->getSourceRange(); 7284 break; 7285 } 7286 7287 case FK_ReferenceInitFailed: 7288 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) 7289 << DestType.getNonReferenceType() 7290 << Args[0]->isLValue() 7291 << Args[0]->getType() 7292 << Args[0]->getSourceRange(); 7293 emitBadConversionNotes(S, Entity, Args[0]); 7294 break; 7295 7296 case FK_ConversionFailed: { 7297 QualType FromType = Args[0]->getType(); 7298 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed) 7299 << (int)Entity.getKind() 7300 << DestType 7301 << Args[0]->isLValue() 7302 << FromType 7303 << Args[0]->getSourceRange(); 7304 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType); 7305 S.Diag(Kind.getLocation(), PDiag); 7306 emitBadConversionNotes(S, Entity, Args[0]); 7307 break; 7308 } 7309 7310 case FK_ConversionFromPropertyFailed: 7311 // No-op. This error has already been reported. 7312 break; 7313 7314 case FK_TooManyInitsForScalar: { 7315 SourceRange R; 7316 7317 auto *InitList = dyn_cast<InitListExpr>(Args[0]); 7318 if (InitList && InitList->getNumInits() >= 1) { 7319 R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd()); 7320 } else { 7321 assert(Args.size() > 1 && "Expected multiple initializers!"); 7322 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd()); 7323 } 7324 7325 R.setBegin(S.getLocForEndOfToken(R.getBegin())); 7326 if (Kind.isCStyleOrFunctionalCast()) 7327 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg) 7328 << R; 7329 else 7330 S.Diag(Kind.getLocation(), diag::err_excess_initializers) 7331 << /*scalar=*/2 << R; 7332 break; 7333 } 7334 7335 case FK_ReferenceBindingToInitList: 7336 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) 7337 << DestType.getNonReferenceType() << Args[0]->getSourceRange(); 7338 break; 7339 7340 case FK_InitListBadDestinationType: 7341 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) 7342 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); 7343 break; 7344 7345 case FK_ListConstructorOverloadFailed: 7346 case FK_ConstructorOverloadFailed: { 7347 SourceRange ArgsRange; 7348 if (Args.size()) 7349 ArgsRange = SourceRange(Args.front()->getLocStart(), 7350 Args.back()->getLocEnd()); 7351 7352 if (Failure == FK_ListConstructorOverloadFailed) { 7353 assert(Args.size() == 1 && 7354 "List construction from other than 1 argument."); 7355 InitListExpr *InitList = cast<InitListExpr>(Args[0]); 7356 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 7357 } 7358 7359 // FIXME: Using "DestType" for the entity we're printing is probably 7360 // bad. 7361 switch (FailedOverloadResult) { 7362 case OR_Ambiguous: 7363 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init) 7364 << DestType << ArgsRange; 7365 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args); 7366 break; 7367 7368 case OR_No_Viable_Function: 7369 if (Kind.getKind() == InitializationKind::IK_Default && 7370 (Entity.getKind() == InitializedEntity::EK_Base || 7371 Entity.getKind() == InitializedEntity::EK_Member) && 7372 isa<CXXConstructorDecl>(S.CurContext)) { 7373 // This is implicit default initialization of a member or 7374 // base within a constructor. If no viable function was 7375 // found, notify the user that they need to explicitly 7376 // initialize this base/member. 7377 CXXConstructorDecl *Constructor 7378 = cast<CXXConstructorDecl>(S.CurContext); 7379 const CXXRecordDecl *InheritedFrom = nullptr; 7380 if (auto Inherited = Constructor->getInheritedConstructor()) 7381 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass(); 7382 if (Entity.getKind() == InitializedEntity::EK_Base) { 7383 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 7384 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) 7385 << S.Context.getTypeDeclType(Constructor->getParent()) 7386 << /*base=*/0 7387 << Entity.getType() 7388 << InheritedFrom; 7389 7390 RecordDecl *BaseDecl 7391 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>() 7392 ->getDecl(); 7393 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl) 7394 << S.Context.getTagDeclType(BaseDecl); 7395 } else { 7396 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 7397 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) 7398 << S.Context.getTypeDeclType(Constructor->getParent()) 7399 << /*member=*/1 7400 << Entity.getName() 7401 << InheritedFrom; 7402 S.Diag(Entity.getDecl()->getLocation(), 7403 diag::note_member_declared_at); 7404 7405 if (const RecordType *Record 7406 = Entity.getType()->getAs<RecordType>()) 7407 S.Diag(Record->getDecl()->getLocation(), 7408 diag::note_previous_decl) 7409 << S.Context.getTagDeclType(Record->getDecl()); 7410 } 7411 break; 7412 } 7413 7414 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init) 7415 << DestType << ArgsRange; 7416 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args); 7417 break; 7418 7419 case OR_Deleted: { 7420 OverloadCandidateSet::iterator Best; 7421 OverloadingResult Ovl 7422 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 7423 if (Ovl != OR_Deleted) { 7424 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 7425 << true << DestType << ArgsRange; 7426 llvm_unreachable("Inconsistent overload resolution?"); 7427 break; 7428 } 7429 7430 // If this is a defaulted or implicitly-declared function, then 7431 // it was implicitly deleted. Make it clear that the deletion was 7432 // implicit. 7433 if (S.isImplicitlyDeleted(Best->Function)) 7434 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init) 7435 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)) 7436 << DestType << ArgsRange; 7437 else 7438 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 7439 << true << DestType << ArgsRange; 7440 7441 S.NoteDeletedFunction(Best->Function); 7442 break; 7443 } 7444 7445 case OR_Success: 7446 llvm_unreachable("Conversion did not fail!"); 7447 } 7448 } 7449 break; 7450 7451 case FK_DefaultInitOfConst: 7452 if (Entity.getKind() == InitializedEntity::EK_Member && 7453 isa<CXXConstructorDecl>(S.CurContext)) { 7454 // This is implicit default-initialization of a const member in 7455 // a constructor. Complain that it needs to be explicitly 7456 // initialized. 7457 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext); 7458 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor) 7459 << (Constructor->getInheritedConstructor() ? 2 : 7460 Constructor->isImplicit() ? 1 : 0) 7461 << S.Context.getTypeDeclType(Constructor->getParent()) 7462 << /*const=*/1 7463 << Entity.getName(); 7464 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl) 7465 << Entity.getName(); 7466 } else { 7467 S.Diag(Kind.getLocation(), diag::err_default_init_const) 7468 << DestType << (bool)DestType->getAs<RecordType>(); 7469 } 7470 break; 7471 7472 case FK_Incomplete: 7473 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType, 7474 diag::err_init_incomplete_type); 7475 break; 7476 7477 case FK_ListInitializationFailed: { 7478 // Run the init list checker again to emit diagnostics. 7479 InitListExpr *InitList = cast<InitListExpr>(Args[0]); 7480 diagnoseListInit(S, Entity, InitList); 7481 break; 7482 } 7483 7484 case FK_PlaceholderType: { 7485 // FIXME: Already diagnosed! 7486 break; 7487 } 7488 7489 case FK_ExplicitConstructor: { 7490 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor) 7491 << Args[0]->getSourceRange(); 7492 OverloadCandidateSet::iterator Best; 7493 OverloadingResult Ovl 7494 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 7495 (void)Ovl; 7496 assert(Ovl == OR_Success && "Inconsistent overload resolution"); 7497 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 7498 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here); 7499 break; 7500 } 7501 } 7502 7503 PrintInitLocationNote(S, Entity); 7504 return true; 7505 } 7506 7507 void InitializationSequence::dump(raw_ostream &OS) const { 7508 switch (SequenceKind) { 7509 case FailedSequence: { 7510 OS << "Failed sequence: "; 7511 switch (Failure) { 7512 case FK_TooManyInitsForReference: 7513 OS << "too many initializers for reference"; 7514 break; 7515 7516 case FK_ArrayNeedsInitList: 7517 OS << "array requires initializer list"; 7518 break; 7519 7520 case FK_AddressOfUnaddressableFunction: 7521 OS << "address of unaddressable function was taken"; 7522 break; 7523 7524 case FK_ArrayNeedsInitListOrStringLiteral: 7525 OS << "array requires initializer list or string literal"; 7526 break; 7527 7528 case FK_ArrayNeedsInitListOrWideStringLiteral: 7529 OS << "array requires initializer list or wide string literal"; 7530 break; 7531 7532 case FK_NarrowStringIntoWideCharArray: 7533 OS << "narrow string into wide char array"; 7534 break; 7535 7536 case FK_WideStringIntoCharArray: 7537 OS << "wide string into char array"; 7538 break; 7539 7540 case FK_IncompatWideStringIntoWideChar: 7541 OS << "incompatible wide string into wide char array"; 7542 break; 7543 7544 case FK_ArrayTypeMismatch: 7545 OS << "array type mismatch"; 7546 break; 7547 7548 case FK_NonConstantArrayInit: 7549 OS << "non-constant array initializer"; 7550 break; 7551 7552 case FK_AddressOfOverloadFailed: 7553 OS << "address of overloaded function failed"; 7554 break; 7555 7556 case FK_ReferenceInitOverloadFailed: 7557 OS << "overload resolution for reference initialization failed"; 7558 break; 7559 7560 case FK_NonConstLValueReferenceBindingToTemporary: 7561 OS << "non-const lvalue reference bound to temporary"; 7562 break; 7563 7564 case FK_NonConstLValueReferenceBindingToUnrelated: 7565 OS << "non-const lvalue reference bound to unrelated type"; 7566 break; 7567 7568 case FK_RValueReferenceBindingToLValue: 7569 OS << "rvalue reference bound to an lvalue"; 7570 break; 7571 7572 case FK_ReferenceInitDropsQualifiers: 7573 OS << "reference initialization drops qualifiers"; 7574 break; 7575 7576 case FK_ReferenceInitFailed: 7577 OS << "reference initialization failed"; 7578 break; 7579 7580 case FK_ConversionFailed: 7581 OS << "conversion failed"; 7582 break; 7583 7584 case FK_ConversionFromPropertyFailed: 7585 OS << "conversion from property failed"; 7586 break; 7587 7588 case FK_TooManyInitsForScalar: 7589 OS << "too many initializers for scalar"; 7590 break; 7591 7592 case FK_ReferenceBindingToInitList: 7593 OS << "referencing binding to initializer list"; 7594 break; 7595 7596 case FK_InitListBadDestinationType: 7597 OS << "initializer list for non-aggregate, non-scalar type"; 7598 break; 7599 7600 case FK_UserConversionOverloadFailed: 7601 OS << "overloading failed for user-defined conversion"; 7602 break; 7603 7604 case FK_ConstructorOverloadFailed: 7605 OS << "constructor overloading failed"; 7606 break; 7607 7608 case FK_DefaultInitOfConst: 7609 OS << "default initialization of a const variable"; 7610 break; 7611 7612 case FK_Incomplete: 7613 OS << "initialization of incomplete type"; 7614 break; 7615 7616 case FK_ListInitializationFailed: 7617 OS << "list initialization checker failure"; 7618 break; 7619 7620 case FK_VariableLengthArrayHasInitializer: 7621 OS << "variable length array has an initializer"; 7622 break; 7623 7624 case FK_PlaceholderType: 7625 OS << "initializer expression isn't contextually valid"; 7626 break; 7627 7628 case FK_ListConstructorOverloadFailed: 7629 OS << "list constructor overloading failed"; 7630 break; 7631 7632 case FK_ExplicitConstructor: 7633 OS << "list copy initialization chose explicit constructor"; 7634 break; 7635 } 7636 OS << '\n'; 7637 return; 7638 } 7639 7640 case DependentSequence: 7641 OS << "Dependent sequence\n"; 7642 return; 7643 7644 case NormalSequence: 7645 OS << "Normal sequence: "; 7646 break; 7647 } 7648 7649 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { 7650 if (S != step_begin()) { 7651 OS << " -> "; 7652 } 7653 7654 switch (S->Kind) { 7655 case SK_ResolveAddressOfOverloadedFunction: 7656 OS << "resolve address of overloaded function"; 7657 break; 7658 7659 case SK_CastDerivedToBaseRValue: 7660 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")"; 7661 break; 7662 7663 case SK_CastDerivedToBaseXValue: 7664 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")"; 7665 break; 7666 7667 case SK_CastDerivedToBaseLValue: 7668 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")"; 7669 break; 7670 7671 case SK_BindReference: 7672 OS << "bind reference to lvalue"; 7673 break; 7674 7675 case SK_BindReferenceToTemporary: 7676 OS << "bind reference to a temporary"; 7677 break; 7678 7679 case SK_ExtraneousCopyToTemporary: 7680 OS << "extraneous C++03 copy to temporary"; 7681 break; 7682 7683 case SK_UserConversion: 7684 OS << "user-defined conversion via " << *S->Function.Function; 7685 break; 7686 7687 case SK_QualificationConversionRValue: 7688 OS << "qualification conversion (rvalue)"; 7689 break; 7690 7691 case SK_QualificationConversionXValue: 7692 OS << "qualification conversion (xvalue)"; 7693 break; 7694 7695 case SK_QualificationConversionLValue: 7696 OS << "qualification conversion (lvalue)"; 7697 break; 7698 7699 case SK_AtomicConversion: 7700 OS << "non-atomic-to-atomic conversion"; 7701 break; 7702 7703 case SK_LValueToRValue: 7704 OS << "load (lvalue to rvalue)"; 7705 break; 7706 7707 case SK_ConversionSequence: 7708 OS << "implicit conversion sequence ("; 7709 S->ICS->dump(); // FIXME: use OS 7710 OS << ")"; 7711 break; 7712 7713 case SK_ConversionSequenceNoNarrowing: 7714 OS << "implicit conversion sequence with narrowing prohibited ("; 7715 S->ICS->dump(); // FIXME: use OS 7716 OS << ")"; 7717 break; 7718 7719 case SK_ListInitialization: 7720 OS << "list aggregate initialization"; 7721 break; 7722 7723 case SK_UnwrapInitList: 7724 OS << "unwrap reference initializer list"; 7725 break; 7726 7727 case SK_RewrapInitList: 7728 OS << "rewrap reference initializer list"; 7729 break; 7730 7731 case SK_ConstructorInitialization: 7732 OS << "constructor initialization"; 7733 break; 7734 7735 case SK_ConstructorInitializationFromList: 7736 OS << "list initialization via constructor"; 7737 break; 7738 7739 case SK_ZeroInitialization: 7740 OS << "zero initialization"; 7741 break; 7742 7743 case SK_CAssignment: 7744 OS << "C assignment"; 7745 break; 7746 7747 case SK_StringInit: 7748 OS << "string initialization"; 7749 break; 7750 7751 case SK_ObjCObjectConversion: 7752 OS << "Objective-C object conversion"; 7753 break; 7754 7755 case SK_ArrayInit: 7756 OS << "array initialization"; 7757 break; 7758 7759 case SK_ParenthesizedArrayInit: 7760 OS << "parenthesized array initialization"; 7761 break; 7762 7763 case SK_PassByIndirectCopyRestore: 7764 OS << "pass by indirect copy and restore"; 7765 break; 7766 7767 case SK_PassByIndirectRestore: 7768 OS << "pass by indirect restore"; 7769 break; 7770 7771 case SK_ProduceObjCObject: 7772 OS << "Objective-C object retension"; 7773 break; 7774 7775 case SK_StdInitializerList: 7776 OS << "std::initializer_list from initializer list"; 7777 break; 7778 7779 case SK_StdInitializerListConstructorCall: 7780 OS << "list initialization from std::initializer_list"; 7781 break; 7782 7783 case SK_OCLSamplerInit: 7784 OS << "OpenCL sampler_t from integer constant"; 7785 break; 7786 7787 case SK_OCLZeroEvent: 7788 OS << "OpenCL event_t from zero"; 7789 break; 7790 } 7791 7792 OS << " [" << S->Type.getAsString() << ']'; 7793 } 7794 7795 OS << '\n'; 7796 } 7797 7798 void InitializationSequence::dump() const { 7799 dump(llvm::errs()); 7800 } 7801 7802 static void DiagnoseNarrowingInInitList(Sema &S, 7803 const ImplicitConversionSequence &ICS, 7804 QualType PreNarrowingType, 7805 QualType EntityType, 7806 const Expr *PostInit) { 7807 const StandardConversionSequence *SCS = nullptr; 7808 switch (ICS.getKind()) { 7809 case ImplicitConversionSequence::StandardConversion: 7810 SCS = &ICS.Standard; 7811 break; 7812 case ImplicitConversionSequence::UserDefinedConversion: 7813 SCS = &ICS.UserDefined.After; 7814 break; 7815 case ImplicitConversionSequence::AmbiguousConversion: 7816 case ImplicitConversionSequence::EllipsisConversion: 7817 case ImplicitConversionSequence::BadConversion: 7818 return; 7819 } 7820 7821 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion. 7822 APValue ConstantValue; 7823 QualType ConstantType; 7824 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue, 7825 ConstantType)) { 7826 case NK_Not_Narrowing: 7827 // No narrowing occurred. 7828 return; 7829 7830 case NK_Type_Narrowing: 7831 // This was a floating-to-integer conversion, which is always considered a 7832 // narrowing conversion even if the value is a constant and can be 7833 // represented exactly as an integer. 7834 S.Diag(PostInit->getLocStart(), 7835 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11) 7836 ? diag::warn_init_list_type_narrowing 7837 : diag::ext_init_list_type_narrowing) 7838 << PostInit->getSourceRange() 7839 << PreNarrowingType.getLocalUnqualifiedType() 7840 << EntityType.getLocalUnqualifiedType(); 7841 break; 7842 7843 case NK_Constant_Narrowing: 7844 // A constant value was narrowed. 7845 S.Diag(PostInit->getLocStart(), 7846 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11) 7847 ? diag::warn_init_list_constant_narrowing 7848 : diag::ext_init_list_constant_narrowing) 7849 << PostInit->getSourceRange() 7850 << ConstantValue.getAsString(S.getASTContext(), ConstantType) 7851 << EntityType.getLocalUnqualifiedType(); 7852 break; 7853 7854 case NK_Variable_Narrowing: 7855 // A variable's value may have been narrowed. 7856 S.Diag(PostInit->getLocStart(), 7857 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11) 7858 ? diag::warn_init_list_variable_narrowing 7859 : diag::ext_init_list_variable_narrowing) 7860 << PostInit->getSourceRange() 7861 << PreNarrowingType.getLocalUnqualifiedType() 7862 << EntityType.getLocalUnqualifiedType(); 7863 break; 7864 } 7865 7866 SmallString<128> StaticCast; 7867 llvm::raw_svector_ostream OS(StaticCast); 7868 OS << "static_cast<"; 7869 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) { 7870 // It's important to use the typedef's name if there is one so that the 7871 // fixit doesn't break code using types like int64_t. 7872 // 7873 // FIXME: This will break if the typedef requires qualification. But 7874 // getQualifiedNameAsString() includes non-machine-parsable components. 7875 OS << *TT->getDecl(); 7876 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>()) 7877 OS << BT->getName(S.getLangOpts()); 7878 else { 7879 // Oops, we didn't find the actual type of the variable. Don't emit a fixit 7880 // with a broken cast. 7881 return; 7882 } 7883 OS << ">("; 7884 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence) 7885 << PostInit->getSourceRange() 7886 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str()) 7887 << FixItHint::CreateInsertion( 7888 S.getLocForEndOfToken(PostInit->getLocEnd()), ")"); 7889 } 7890 7891 //===----------------------------------------------------------------------===// 7892 // Initialization helper functions 7893 //===----------------------------------------------------------------------===// 7894 bool 7895 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, 7896 ExprResult Init) { 7897 if (Init.isInvalid()) 7898 return false; 7899 7900 Expr *InitE = Init.get(); 7901 assert(InitE && "No initialization expression"); 7902 7903 InitializationKind Kind 7904 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation()); 7905 InitializationSequence Seq(*this, Entity, Kind, InitE); 7906 return !Seq.Failed(); 7907 } 7908 7909 ExprResult 7910 Sema::PerformCopyInitialization(const InitializedEntity &Entity, 7911 SourceLocation EqualLoc, 7912 ExprResult Init, 7913 bool TopLevelOfInitList, 7914 bool AllowExplicit) { 7915 if (Init.isInvalid()) 7916 return ExprError(); 7917 7918 Expr *InitE = Init.get(); 7919 assert(InitE && "No initialization expression?"); 7920 7921 if (EqualLoc.isInvalid()) 7922 EqualLoc = InitE->getLocStart(); 7923 7924 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(), 7925 EqualLoc, 7926 AllowExplicit); 7927 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList); 7928 7929 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE); 7930 7931 return Result; 7932 } 7933