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