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