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