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