1 1.1 joerg //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===// 2 1.1 joerg // 3 1.1 joerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 1.1 joerg // See https://llvm.org/LICENSE.txt for license information. 5 1.1 joerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 1.1 joerg // 7 1.1 joerg //===----------------------------------------------------------------------===// 8 1.1 joerg // 9 1.1 joerg // This file implements semantic analysis for initializers. 10 1.1 joerg // 11 1.1 joerg //===----------------------------------------------------------------------===// 12 1.1 joerg 13 1.1 joerg #include "clang/AST/ASTContext.h" 14 1.1 joerg #include "clang/AST/DeclObjC.h" 15 1.1 joerg #include "clang/AST/ExprCXX.h" 16 1.1 joerg #include "clang/AST/ExprObjC.h" 17 1.1 joerg #include "clang/AST/ExprOpenMP.h" 18 1.1 joerg #include "clang/AST/TypeLoc.h" 19 1.1 joerg #include "clang/Basic/CharInfo.h" 20 1.1.1.2 joerg #include "clang/Basic/SourceManager.h" 21 1.1 joerg #include "clang/Basic/TargetInfo.h" 22 1.1 joerg #include "clang/Sema/Designator.h" 23 1.1 joerg #include "clang/Sema/Initialization.h" 24 1.1 joerg #include "clang/Sema/Lookup.h" 25 1.1 joerg #include "clang/Sema/SemaInternal.h" 26 1.1 joerg #include "llvm/ADT/APInt.h" 27 1.1.1.2 joerg #include "llvm/ADT/PointerIntPair.h" 28 1.1 joerg #include "llvm/ADT/SmallString.h" 29 1.1 joerg #include "llvm/Support/ErrorHandling.h" 30 1.1 joerg #include "llvm/Support/raw_ostream.h" 31 1.1 joerg 32 1.1 joerg using namespace clang; 33 1.1 joerg 34 1.1 joerg //===----------------------------------------------------------------------===// 35 1.1 joerg // Sema Initialization Checking 36 1.1 joerg //===----------------------------------------------------------------------===// 37 1.1 joerg 38 1.1 joerg /// Check whether T is compatible with a wide character type (wchar_t, 39 1.1 joerg /// char16_t or char32_t). 40 1.1 joerg static bool IsWideCharCompatible(QualType T, ASTContext &Context) { 41 1.1 joerg if (Context.typesAreCompatible(Context.getWideCharType(), T)) 42 1.1 joerg return true; 43 1.1 joerg if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) { 44 1.1 joerg return Context.typesAreCompatible(Context.Char16Ty, T) || 45 1.1 joerg Context.typesAreCompatible(Context.Char32Ty, T); 46 1.1 joerg } 47 1.1 joerg return false; 48 1.1 joerg } 49 1.1 joerg 50 1.1 joerg enum StringInitFailureKind { 51 1.1 joerg SIF_None, 52 1.1 joerg SIF_NarrowStringIntoWideChar, 53 1.1 joerg SIF_WideStringIntoChar, 54 1.1 joerg SIF_IncompatWideStringIntoWideChar, 55 1.1 joerg SIF_UTF8StringIntoPlainChar, 56 1.1 joerg SIF_PlainStringIntoUTF8Char, 57 1.1 joerg SIF_Other 58 1.1 joerg }; 59 1.1 joerg 60 1.1 joerg /// Check whether the array of type AT can be initialized by the Init 61 1.1 joerg /// expression by means of string initialization. Returns SIF_None if so, 62 1.1 joerg /// otherwise returns a StringInitFailureKind that describes why the 63 1.1 joerg /// initialization would not work. 64 1.1 joerg static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT, 65 1.1 joerg ASTContext &Context) { 66 1.1 joerg if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT)) 67 1.1 joerg return SIF_Other; 68 1.1 joerg 69 1.1 joerg // See if this is a string literal or @encode. 70 1.1 joerg Init = Init->IgnoreParens(); 71 1.1 joerg 72 1.1 joerg // Handle @encode, which is a narrow string. 73 1.1 joerg if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType()) 74 1.1 joerg return SIF_None; 75 1.1 joerg 76 1.1 joerg // Otherwise we can only handle string literals. 77 1.1 joerg StringLiteral *SL = dyn_cast<StringLiteral>(Init); 78 1.1 joerg if (!SL) 79 1.1 joerg return SIF_Other; 80 1.1 joerg 81 1.1 joerg const QualType ElemTy = 82 1.1 joerg Context.getCanonicalType(AT->getElementType()).getUnqualifiedType(); 83 1.1 joerg 84 1.1 joerg switch (SL->getKind()) { 85 1.1 joerg case StringLiteral::UTF8: 86 1.1 joerg // char8_t array can be initialized with a UTF-8 string. 87 1.1 joerg if (ElemTy->isChar8Type()) 88 1.1 joerg return SIF_None; 89 1.1 joerg LLVM_FALLTHROUGH; 90 1.1 joerg case StringLiteral::Ascii: 91 1.1 joerg // char array can be initialized with a narrow string. 92 1.1 joerg // Only allow char x[] = "foo"; not char x[] = L"foo"; 93 1.1 joerg if (ElemTy->isCharType()) 94 1.1 joerg return (SL->getKind() == StringLiteral::UTF8 && 95 1.1 joerg Context.getLangOpts().Char8) 96 1.1 joerg ? SIF_UTF8StringIntoPlainChar 97 1.1 joerg : SIF_None; 98 1.1 joerg if (ElemTy->isChar8Type()) 99 1.1 joerg return SIF_PlainStringIntoUTF8Char; 100 1.1 joerg if (IsWideCharCompatible(ElemTy, Context)) 101 1.1 joerg return SIF_NarrowStringIntoWideChar; 102 1.1 joerg return SIF_Other; 103 1.1 joerg // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15: 104 1.1 joerg // "An array with element type compatible with a qualified or unqualified 105 1.1 joerg // version of wchar_t, char16_t, or char32_t may be initialized by a wide 106 1.1 joerg // string literal with the corresponding encoding prefix (L, u, or U, 107 1.1 joerg // respectively), optionally enclosed in braces. 108 1.1 joerg case StringLiteral::UTF16: 109 1.1 joerg if (Context.typesAreCompatible(Context.Char16Ty, ElemTy)) 110 1.1 joerg return SIF_None; 111 1.1 joerg if (ElemTy->isCharType() || ElemTy->isChar8Type()) 112 1.1 joerg return SIF_WideStringIntoChar; 113 1.1 joerg if (IsWideCharCompatible(ElemTy, Context)) 114 1.1 joerg return SIF_IncompatWideStringIntoWideChar; 115 1.1 joerg return SIF_Other; 116 1.1 joerg case StringLiteral::UTF32: 117 1.1 joerg if (Context.typesAreCompatible(Context.Char32Ty, ElemTy)) 118 1.1 joerg return SIF_None; 119 1.1 joerg if (ElemTy->isCharType() || ElemTy->isChar8Type()) 120 1.1 joerg return SIF_WideStringIntoChar; 121 1.1 joerg if (IsWideCharCompatible(ElemTy, Context)) 122 1.1 joerg return SIF_IncompatWideStringIntoWideChar; 123 1.1 joerg return SIF_Other; 124 1.1 joerg case StringLiteral::Wide: 125 1.1 joerg if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy)) 126 1.1 joerg return SIF_None; 127 1.1 joerg if (ElemTy->isCharType() || ElemTy->isChar8Type()) 128 1.1 joerg return SIF_WideStringIntoChar; 129 1.1 joerg if (IsWideCharCompatible(ElemTy, Context)) 130 1.1 joerg return SIF_IncompatWideStringIntoWideChar; 131 1.1 joerg return SIF_Other; 132 1.1 joerg } 133 1.1 joerg 134 1.1 joerg llvm_unreachable("missed a StringLiteral kind?"); 135 1.1 joerg } 136 1.1 joerg 137 1.1 joerg static StringInitFailureKind IsStringInit(Expr *init, QualType declType, 138 1.1 joerg ASTContext &Context) { 139 1.1 joerg const ArrayType *arrayType = Context.getAsArrayType(declType); 140 1.1 joerg if (!arrayType) 141 1.1 joerg return SIF_Other; 142 1.1 joerg return IsStringInit(init, arrayType, Context); 143 1.1 joerg } 144 1.1 joerg 145 1.1.1.2 joerg bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) { 146 1.1.1.2 joerg return ::IsStringInit(Init, AT, Context) == SIF_None; 147 1.1.1.2 joerg } 148 1.1.1.2 joerg 149 1.1 joerg /// Update the type of a string literal, including any surrounding parentheses, 150 1.1 joerg /// to match the type of the object which it is initializing. 151 1.1 joerg static void updateStringLiteralType(Expr *E, QualType Ty) { 152 1.1 joerg while (true) { 153 1.1 joerg E->setType(Ty); 154 1.1 joerg E->setValueKind(VK_RValue); 155 1.1 joerg if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) { 156 1.1 joerg break; 157 1.1 joerg } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 158 1.1 joerg E = PE->getSubExpr(); 159 1.1 joerg } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 160 1.1 joerg assert(UO->getOpcode() == UO_Extension); 161 1.1 joerg E = UO->getSubExpr(); 162 1.1 joerg } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) { 163 1.1 joerg E = GSE->getResultExpr(); 164 1.1 joerg } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) { 165 1.1 joerg E = CE->getChosenSubExpr(); 166 1.1 joerg } else { 167 1.1 joerg llvm_unreachable("unexpected expr in string literal init"); 168 1.1 joerg } 169 1.1 joerg } 170 1.1 joerg } 171 1.1 joerg 172 1.1 joerg /// Fix a compound literal initializing an array so it's correctly marked 173 1.1 joerg /// as an rvalue. 174 1.1 joerg static void updateGNUCompoundLiteralRValue(Expr *E) { 175 1.1 joerg while (true) { 176 1.1 joerg E->setValueKind(VK_RValue); 177 1.1 joerg if (isa<CompoundLiteralExpr>(E)) { 178 1.1 joerg break; 179 1.1 joerg } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 180 1.1 joerg E = PE->getSubExpr(); 181 1.1 joerg } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 182 1.1 joerg assert(UO->getOpcode() == UO_Extension); 183 1.1 joerg E = UO->getSubExpr(); 184 1.1 joerg } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) { 185 1.1 joerg E = GSE->getResultExpr(); 186 1.1 joerg } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) { 187 1.1 joerg E = CE->getChosenSubExpr(); 188 1.1 joerg } else { 189 1.1 joerg llvm_unreachable("unexpected expr in array compound literal init"); 190 1.1 joerg } 191 1.1 joerg } 192 1.1 joerg } 193 1.1 joerg 194 1.1 joerg static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, 195 1.1 joerg Sema &S) { 196 1.1 joerg // Get the length of the string as parsed. 197 1.1 joerg auto *ConstantArrayTy = 198 1.1 joerg cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe()); 199 1.1 joerg uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue(); 200 1.1 joerg 201 1.1 joerg if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 202 1.1 joerg // C99 6.7.8p14. We have an array of character type with unknown size 203 1.1 joerg // being initialized to a string literal. 204 1.1 joerg llvm::APInt ConstVal(32, StrLength); 205 1.1 joerg // Return a new array type (C99 6.7.8p22). 206 1.1 joerg DeclT = S.Context.getConstantArrayType(IAT->getElementType(), 207 1.1 joerg ConstVal, nullptr, 208 1.1 joerg ArrayType::Normal, 0); 209 1.1 joerg updateStringLiteralType(Str, DeclT); 210 1.1 joerg return; 211 1.1 joerg } 212 1.1 joerg 213 1.1 joerg const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); 214 1.1 joerg 215 1.1 joerg // We have an array of character type with known size. However, 216 1.1 joerg // the size may be smaller or larger than the string we are initializing. 217 1.1 joerg // FIXME: Avoid truncation for 64-bit length strings. 218 1.1 joerg if (S.getLangOpts().CPlusPlus) { 219 1.1 joerg if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) { 220 1.1 joerg // For Pascal strings it's OK to strip off the terminating null character, 221 1.1 joerg // so the example below is valid: 222 1.1 joerg // 223 1.1 joerg // unsigned char a[2] = "\pa"; 224 1.1 joerg if (SL->isPascal()) 225 1.1 joerg StrLength--; 226 1.1 joerg } 227 1.1 joerg 228 1.1 joerg // [dcl.init.string]p2 229 1.1 joerg if (StrLength > CAT->getSize().getZExtValue()) 230 1.1 joerg S.Diag(Str->getBeginLoc(), 231 1.1 joerg diag::err_initializer_string_for_char_array_too_long) 232 1.1 joerg << Str->getSourceRange(); 233 1.1 joerg } else { 234 1.1 joerg // C99 6.7.8p14. 235 1.1 joerg if (StrLength-1 > CAT->getSize().getZExtValue()) 236 1.1 joerg S.Diag(Str->getBeginLoc(), 237 1.1 joerg diag::ext_initializer_string_for_char_array_too_long) 238 1.1 joerg << Str->getSourceRange(); 239 1.1 joerg } 240 1.1 joerg 241 1.1 joerg // Set the type to the actual size that we are initializing. If we have 242 1.1 joerg // something like: 243 1.1 joerg // char x[1] = "foo"; 244 1.1 joerg // then this will set the string literal's type to char[1]. 245 1.1 joerg updateStringLiteralType(Str, DeclT); 246 1.1 joerg } 247 1.1 joerg 248 1.1 joerg //===----------------------------------------------------------------------===// 249 1.1 joerg // Semantic checking for initializer lists. 250 1.1 joerg //===----------------------------------------------------------------------===// 251 1.1 joerg 252 1.1 joerg namespace { 253 1.1 joerg 254 1.1 joerg /// Semantic checking for initializer lists. 255 1.1 joerg /// 256 1.1 joerg /// The InitListChecker class contains a set of routines that each 257 1.1 joerg /// handle the initialization of a certain kind of entity, e.g., 258 1.1 joerg /// arrays, vectors, struct/union types, scalars, etc. The 259 1.1 joerg /// InitListChecker itself performs a recursive walk of the subobject 260 1.1 joerg /// structure of the type to be initialized, while stepping through 261 1.1 joerg /// the initializer list one element at a time. The IList and Index 262 1.1 joerg /// parameters to each of the Check* routines contain the active 263 1.1 joerg /// (syntactic) initializer list and the index into that initializer 264 1.1 joerg /// list that represents the current initializer. Each routine is 265 1.1 joerg /// responsible for moving that Index forward as it consumes elements. 266 1.1 joerg /// 267 1.1 joerg /// Each Check* routine also has a StructuredList/StructuredIndex 268 1.1 joerg /// arguments, which contains the current "structured" (semantic) 269 1.1 joerg /// initializer list and the index into that initializer list where we 270 1.1 joerg /// are copying initializers as we map them over to the semantic 271 1.1 joerg /// list. Once we have completed our recursive walk of the subobject 272 1.1 joerg /// structure, we will have constructed a full semantic initializer 273 1.1 joerg /// list. 274 1.1 joerg /// 275 1.1 joerg /// C99 designators cause changes in the initializer list traversal, 276 1.1 joerg /// because they make the initialization "jump" into a specific 277 1.1 joerg /// subobject and then continue the initialization from that 278 1.1 joerg /// point. CheckDesignatedInitializer() recursively steps into the 279 1.1 joerg /// designated subobject and manages backing out the recursion to 280 1.1 joerg /// initialize the subobjects after the one designated. 281 1.1 joerg /// 282 1.1 joerg /// If an initializer list contains any designators, we build a placeholder 283 1.1 joerg /// structured list even in 'verify only' mode, so that we can track which 284 1.1 joerg /// elements need 'empty' initializtion. 285 1.1 joerg class InitListChecker { 286 1.1 joerg Sema &SemaRef; 287 1.1 joerg bool hadError = false; 288 1.1 joerg bool VerifyOnly; // No diagnostics. 289 1.1 joerg bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode. 290 1.1 joerg bool InOverloadResolution; 291 1.1 joerg InitListExpr *FullyStructuredList = nullptr; 292 1.1 joerg NoInitExpr *DummyExpr = nullptr; 293 1.1 joerg 294 1.1 joerg NoInitExpr *getDummyInit() { 295 1.1 joerg if (!DummyExpr) 296 1.1 joerg DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy); 297 1.1 joerg return DummyExpr; 298 1.1 joerg } 299 1.1 joerg 300 1.1 joerg void CheckImplicitInitList(const InitializedEntity &Entity, 301 1.1 joerg InitListExpr *ParentIList, QualType T, 302 1.1 joerg unsigned &Index, InitListExpr *StructuredList, 303 1.1 joerg unsigned &StructuredIndex); 304 1.1 joerg void CheckExplicitInitList(const InitializedEntity &Entity, 305 1.1 joerg InitListExpr *IList, QualType &T, 306 1.1 joerg InitListExpr *StructuredList, 307 1.1 joerg bool TopLevelObject = false); 308 1.1 joerg void CheckListElementTypes(const InitializedEntity &Entity, 309 1.1 joerg InitListExpr *IList, QualType &DeclType, 310 1.1 joerg bool SubobjectIsDesignatorContext, 311 1.1 joerg unsigned &Index, 312 1.1 joerg InitListExpr *StructuredList, 313 1.1 joerg unsigned &StructuredIndex, 314 1.1 joerg bool TopLevelObject = false); 315 1.1 joerg void CheckSubElementType(const InitializedEntity &Entity, 316 1.1 joerg InitListExpr *IList, QualType ElemType, 317 1.1 joerg unsigned &Index, 318 1.1 joerg InitListExpr *StructuredList, 319 1.1.1.2 joerg unsigned &StructuredIndex, 320 1.1.1.2 joerg bool DirectlyDesignated = false); 321 1.1 joerg void CheckComplexType(const InitializedEntity &Entity, 322 1.1 joerg InitListExpr *IList, QualType DeclType, 323 1.1 joerg unsigned &Index, 324 1.1 joerg InitListExpr *StructuredList, 325 1.1 joerg unsigned &StructuredIndex); 326 1.1 joerg void CheckScalarType(const InitializedEntity &Entity, 327 1.1 joerg InitListExpr *IList, QualType DeclType, 328 1.1 joerg unsigned &Index, 329 1.1 joerg InitListExpr *StructuredList, 330 1.1 joerg unsigned &StructuredIndex); 331 1.1 joerg void CheckReferenceType(const InitializedEntity &Entity, 332 1.1 joerg InitListExpr *IList, QualType DeclType, 333 1.1 joerg unsigned &Index, 334 1.1 joerg InitListExpr *StructuredList, 335 1.1 joerg unsigned &StructuredIndex); 336 1.1 joerg void CheckVectorType(const InitializedEntity &Entity, 337 1.1 joerg InitListExpr *IList, QualType DeclType, unsigned &Index, 338 1.1 joerg InitListExpr *StructuredList, 339 1.1 joerg unsigned &StructuredIndex); 340 1.1 joerg void CheckStructUnionTypes(const InitializedEntity &Entity, 341 1.1 joerg InitListExpr *IList, QualType DeclType, 342 1.1 joerg CXXRecordDecl::base_class_range Bases, 343 1.1 joerg RecordDecl::field_iterator Field, 344 1.1 joerg bool SubobjectIsDesignatorContext, unsigned &Index, 345 1.1 joerg InitListExpr *StructuredList, 346 1.1 joerg unsigned &StructuredIndex, 347 1.1 joerg bool TopLevelObject = false); 348 1.1 joerg void CheckArrayType(const InitializedEntity &Entity, 349 1.1 joerg InitListExpr *IList, QualType &DeclType, 350 1.1 joerg llvm::APSInt elementIndex, 351 1.1 joerg bool SubobjectIsDesignatorContext, unsigned &Index, 352 1.1 joerg InitListExpr *StructuredList, 353 1.1 joerg unsigned &StructuredIndex); 354 1.1 joerg bool CheckDesignatedInitializer(const InitializedEntity &Entity, 355 1.1 joerg InitListExpr *IList, DesignatedInitExpr *DIE, 356 1.1 joerg unsigned DesigIdx, 357 1.1 joerg QualType &CurrentObjectType, 358 1.1 joerg RecordDecl::field_iterator *NextField, 359 1.1 joerg llvm::APSInt *NextElementIndex, 360 1.1 joerg unsigned &Index, 361 1.1 joerg InitListExpr *StructuredList, 362 1.1 joerg unsigned &StructuredIndex, 363 1.1 joerg bool FinishSubobjectInit, 364 1.1 joerg bool TopLevelObject); 365 1.1 joerg InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 366 1.1 joerg QualType CurrentObjectType, 367 1.1 joerg InitListExpr *StructuredList, 368 1.1 joerg unsigned StructuredIndex, 369 1.1 joerg SourceRange InitRange, 370 1.1 joerg bool IsFullyOverwritten = false); 371 1.1 joerg void UpdateStructuredListElement(InitListExpr *StructuredList, 372 1.1 joerg unsigned &StructuredIndex, 373 1.1 joerg Expr *expr); 374 1.1 joerg InitListExpr *createInitListExpr(QualType CurrentObjectType, 375 1.1 joerg SourceRange InitRange, 376 1.1 joerg unsigned ExpectedNumInits); 377 1.1 joerg int numArrayElements(QualType DeclType); 378 1.1 joerg int numStructUnionElements(QualType DeclType); 379 1.1 joerg 380 1.1 joerg ExprResult PerformEmptyInit(SourceLocation Loc, 381 1.1 joerg const InitializedEntity &Entity); 382 1.1 joerg 383 1.1 joerg /// Diagnose that OldInit (or part thereof) has been overridden by NewInit. 384 1.1 joerg void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange, 385 1.1 joerg bool FullyOverwritten = true) { 386 1.1 joerg // Overriding an initializer via a designator is valid with C99 designated 387 1.1 joerg // initializers, but ill-formed with C++20 designated initializers. 388 1.1 joerg unsigned DiagID = SemaRef.getLangOpts().CPlusPlus 389 1.1 joerg ? diag::ext_initializer_overrides 390 1.1 joerg : diag::warn_initializer_overrides; 391 1.1 joerg 392 1.1 joerg if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) { 393 1.1 joerg // In overload resolution, we have to strictly enforce the rules, and so 394 1.1 joerg // don't allow any overriding of prior initializers. This matters for a 395 1.1 joerg // case such as: 396 1.1 joerg // 397 1.1 joerg // union U { int a, b; }; 398 1.1 joerg // struct S { int a, b; }; 399 1.1 joerg // void f(U), f(S); 400 1.1 joerg // 401 1.1 joerg // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For 402 1.1 joerg // consistency, we disallow all overriding of prior initializers in 403 1.1 joerg // overload resolution, not only overriding of union members. 404 1.1 joerg hadError = true; 405 1.1 joerg } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) { 406 1.1 joerg // If we'll be keeping around the old initializer but overwriting part of 407 1.1 joerg // the object it initialized, and that object is not trivially 408 1.1 joerg // destructible, this can leak. Don't allow that, not even as an 409 1.1 joerg // extension. 410 1.1 joerg // 411 1.1 joerg // FIXME: It might be reasonable to allow this in cases where the part of 412 1.1 joerg // the initializer that we're overriding has trivial destruction. 413 1.1 joerg DiagID = diag::err_initializer_overrides_destructed; 414 1.1 joerg } else if (!OldInit->getSourceRange().isValid()) { 415 1.1 joerg // We need to check on source range validity because the previous 416 1.1 joerg // initializer does not have to be an explicit initializer. e.g., 417 1.1 joerg // 418 1.1 joerg // struct P { int a, b; }; 419 1.1 joerg // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 }; 420 1.1 joerg // 421 1.1 joerg // There is an overwrite taking place because the first braced initializer 422 1.1 joerg // list "{ .a = 2 }" already provides value for .p.b (which is zero). 423 1.1 joerg // 424 1.1 joerg // Such overwrites are harmless, so we don't diagnose them. (Note that in 425 1.1 joerg // C++, this cannot be reached unless we've already seen and diagnosed a 426 1.1 joerg // different conformance issue, such as a mixture of designated and 427 1.1 joerg // non-designated initializers or a multi-level designator.) 428 1.1 joerg return; 429 1.1 joerg } 430 1.1 joerg 431 1.1 joerg if (!VerifyOnly) { 432 1.1 joerg SemaRef.Diag(NewInitRange.getBegin(), DiagID) 433 1.1 joerg << NewInitRange << FullyOverwritten << OldInit->getType(); 434 1.1 joerg SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer) 435 1.1 joerg << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten) 436 1.1 joerg << OldInit->getSourceRange(); 437 1.1 joerg } 438 1.1 joerg } 439 1.1 joerg 440 1.1 joerg // Explanation on the "FillWithNoInit" mode: 441 1.1 joerg // 442 1.1 joerg // Assume we have the following definitions (Case#1): 443 1.1 joerg // struct P { char x[6][6]; } xp = { .x[1] = "bar" }; 444 1.1 joerg // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' }; 445 1.1 joerg // 446 1.1 joerg // l.lp.x[1][0..1] should not be filled with implicit initializers because the 447 1.1 joerg // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf". 448 1.1 joerg // 449 1.1 joerg // But if we have (Case#2): 450 1.1 joerg // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } }; 451 1.1 joerg // 452 1.1 joerg // l.lp.x[1][0..1] are implicitly initialized and do not use values from the 453 1.1 joerg // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0". 454 1.1 joerg // 455 1.1 joerg // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes" 456 1.1 joerg // in the InitListExpr, the "holes" in Case#1 are filled not with empty 457 1.1 joerg // initializers but with special "NoInitExpr" place holders, which tells the 458 1.1 joerg // CodeGen not to generate any initializers for these parts. 459 1.1 joerg void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base, 460 1.1 joerg const InitializedEntity &ParentEntity, 461 1.1 joerg InitListExpr *ILE, bool &RequiresSecondPass, 462 1.1 joerg bool FillWithNoInit); 463 1.1 joerg void FillInEmptyInitForField(unsigned Init, FieldDecl *Field, 464 1.1 joerg const InitializedEntity &ParentEntity, 465 1.1 joerg InitListExpr *ILE, bool &RequiresSecondPass, 466 1.1 joerg bool FillWithNoInit = false); 467 1.1 joerg void FillInEmptyInitializations(const InitializedEntity &Entity, 468 1.1 joerg InitListExpr *ILE, bool &RequiresSecondPass, 469 1.1 joerg InitListExpr *OuterILE, unsigned OuterIndex, 470 1.1 joerg bool FillWithNoInit = false); 471 1.1 joerg bool CheckFlexibleArrayInit(const InitializedEntity &Entity, 472 1.1 joerg Expr *InitExpr, FieldDecl *Field, 473 1.1 joerg bool TopLevelObject); 474 1.1 joerg void CheckEmptyInitializable(const InitializedEntity &Entity, 475 1.1 joerg SourceLocation Loc); 476 1.1 joerg 477 1.1 joerg public: 478 1.1 joerg InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL, 479 1.1 joerg QualType &T, bool VerifyOnly, bool TreatUnavailableAsInvalid, 480 1.1 joerg bool InOverloadResolution = false); 481 1.1 joerg bool HadError() { return hadError; } 482 1.1 joerg 483 1.1 joerg // Retrieves the fully-structured initializer list used for 484 1.1 joerg // semantic analysis and code generation. 485 1.1 joerg InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } 486 1.1 joerg }; 487 1.1 joerg 488 1.1 joerg } // end anonymous namespace 489 1.1 joerg 490 1.1 joerg ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc, 491 1.1 joerg const InitializedEntity &Entity) { 492 1.1 joerg InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 493 1.1 joerg true); 494 1.1 joerg MultiExprArg SubInit; 495 1.1 joerg Expr *InitExpr; 496 1.1 joerg InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc); 497 1.1 joerg 498 1.1 joerg // C++ [dcl.init.aggr]p7: 499 1.1 joerg // If there are fewer initializer-clauses in the list than there are 500 1.1 joerg // members in the aggregate, then each member not explicitly initialized 501 1.1 joerg // ... 502 1.1 joerg bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 && 503 1.1 joerg Entity.getType()->getBaseElementTypeUnsafe()->isRecordType(); 504 1.1 joerg if (EmptyInitList) { 505 1.1 joerg // C++1y / DR1070: 506 1.1 joerg // shall be initialized [...] from an empty initializer list. 507 1.1 joerg // 508 1.1 joerg // We apply the resolution of this DR to C++11 but not C++98, since C++98 509 1.1 joerg // does not have useful semantics for initialization from an init list. 510 1.1 joerg // We treat this as copy-initialization, because aggregate initialization 511 1.1 joerg // always performs copy-initialization on its elements. 512 1.1 joerg // 513 1.1 joerg // Only do this if we're initializing a class type, to avoid filling in 514 1.1 joerg // the initializer list where possible. 515 1.1 joerg InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context) 516 1.1 joerg InitListExpr(SemaRef.Context, Loc, None, Loc); 517 1.1 joerg InitExpr->setType(SemaRef.Context.VoidTy); 518 1.1 joerg SubInit = InitExpr; 519 1.1 joerg Kind = InitializationKind::CreateCopy(Loc, Loc); 520 1.1 joerg } else { 521 1.1 joerg // C++03: 522 1.1 joerg // shall be value-initialized. 523 1.1 joerg } 524 1.1 joerg 525 1.1 joerg InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit); 526 1.1 joerg // libstdc++4.6 marks the vector default constructor as explicit in 527 1.1 joerg // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case. 528 1.1 joerg // stlport does so too. Look for std::__debug for libstdc++, and for 529 1.1 joerg // std:: for stlport. This is effectively a compiler-side implementation of 530 1.1 joerg // LWG2193. 531 1.1 joerg if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() == 532 1.1 joerg InitializationSequence::FK_ExplicitConstructor) { 533 1.1 joerg OverloadCandidateSet::iterator Best; 534 1.1 joerg OverloadingResult O = 535 1.1 joerg InitSeq.getFailedCandidateSet() 536 1.1 joerg .BestViableFunction(SemaRef, Kind.getLocation(), Best); 537 1.1 joerg (void)O; 538 1.1 joerg assert(O == OR_Success && "Inconsistent overload resolution"); 539 1.1 joerg CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 540 1.1 joerg CXXRecordDecl *R = CtorDecl->getParent(); 541 1.1 joerg 542 1.1 joerg if (CtorDecl->getMinRequiredArguments() == 0 && 543 1.1 joerg CtorDecl->isExplicit() && R->getDeclName() && 544 1.1 joerg SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) { 545 1.1 joerg bool IsInStd = false; 546 1.1 joerg for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext()); 547 1.1 joerg ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) { 548 1.1 joerg if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND)) 549 1.1 joerg IsInStd = true; 550 1.1 joerg } 551 1.1 joerg 552 1.1 joerg if (IsInStd && llvm::StringSwitch<bool>(R->getName()) 553 1.1 joerg .Cases("basic_string", "deque", "forward_list", true) 554 1.1 joerg .Cases("list", "map", "multimap", "multiset", true) 555 1.1 joerg .Cases("priority_queue", "queue", "set", "stack", true) 556 1.1 joerg .Cases("unordered_map", "unordered_set", "vector", true) 557 1.1 joerg .Default(false)) { 558 1.1 joerg InitSeq.InitializeFrom( 559 1.1 joerg SemaRef, Entity, 560 1.1 joerg InitializationKind::CreateValue(Loc, Loc, Loc, true), 561 1.1 joerg MultiExprArg(), /*TopLevelOfInitList=*/false, 562 1.1 joerg TreatUnavailableAsInvalid); 563 1.1 joerg // Emit a warning for this. System header warnings aren't shown 564 1.1 joerg // by default, but people working on system headers should see it. 565 1.1 joerg if (!VerifyOnly) { 566 1.1 joerg SemaRef.Diag(CtorDecl->getLocation(), 567 1.1 joerg diag::warn_invalid_initializer_from_system_header); 568 1.1 joerg if (Entity.getKind() == InitializedEntity::EK_Member) 569 1.1 joerg SemaRef.Diag(Entity.getDecl()->getLocation(), 570 1.1 joerg diag::note_used_in_initialization_here); 571 1.1 joerg else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) 572 1.1 joerg SemaRef.Diag(Loc, diag::note_used_in_initialization_here); 573 1.1 joerg } 574 1.1 joerg } 575 1.1 joerg } 576 1.1 joerg } 577 1.1 joerg if (!InitSeq) { 578 1.1 joerg if (!VerifyOnly) { 579 1.1 joerg InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit); 580 1.1 joerg if (Entity.getKind() == InitializedEntity::EK_Member) 581 1.1 joerg SemaRef.Diag(Entity.getDecl()->getLocation(), 582 1.1 joerg diag::note_in_omitted_aggregate_initializer) 583 1.1 joerg << /*field*/1 << Entity.getDecl(); 584 1.1 joerg else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) { 585 1.1 joerg bool IsTrailingArrayNewMember = 586 1.1 joerg Entity.getParent() && 587 1.1 joerg Entity.getParent()->isVariableLengthArrayNew(); 588 1.1 joerg SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer) 589 1.1 joerg << (IsTrailingArrayNewMember ? 2 : /*array element*/0) 590 1.1 joerg << Entity.getElementIndex(); 591 1.1 joerg } 592 1.1 joerg } 593 1.1 joerg hadError = true; 594 1.1 joerg return ExprError(); 595 1.1 joerg } 596 1.1 joerg 597 1.1 joerg return VerifyOnly ? ExprResult() 598 1.1 joerg : InitSeq.Perform(SemaRef, Entity, Kind, SubInit); 599 1.1 joerg } 600 1.1 joerg 601 1.1 joerg void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity, 602 1.1 joerg SourceLocation Loc) { 603 1.1 joerg // If we're building a fully-structured list, we'll check this at the end 604 1.1 joerg // once we know which elements are actually initialized. Otherwise, we know 605 1.1 joerg // that there are no designators so we can just check now. 606 1.1 joerg if (FullyStructuredList) 607 1.1 joerg return; 608 1.1 joerg PerformEmptyInit(Loc, Entity); 609 1.1 joerg } 610 1.1 joerg 611 1.1 joerg void InitListChecker::FillInEmptyInitForBase( 612 1.1 joerg unsigned Init, const CXXBaseSpecifier &Base, 613 1.1 joerg const InitializedEntity &ParentEntity, InitListExpr *ILE, 614 1.1 joerg bool &RequiresSecondPass, bool FillWithNoInit) { 615 1.1 joerg InitializedEntity BaseEntity = InitializedEntity::InitializeBase( 616 1.1 joerg SemaRef.Context, &Base, false, &ParentEntity); 617 1.1 joerg 618 1.1 joerg if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) { 619 1.1 joerg ExprResult BaseInit = FillWithNoInit 620 1.1 joerg ? new (SemaRef.Context) NoInitExpr(Base.getType()) 621 1.1 joerg : PerformEmptyInit(ILE->getEndLoc(), BaseEntity); 622 1.1 joerg if (BaseInit.isInvalid()) { 623 1.1 joerg hadError = true; 624 1.1 joerg return; 625 1.1 joerg } 626 1.1 joerg 627 1.1 joerg if (!VerifyOnly) { 628 1.1 joerg assert(Init < ILE->getNumInits() && "should have been expanded"); 629 1.1 joerg ILE->setInit(Init, BaseInit.getAs<Expr>()); 630 1.1 joerg } 631 1.1 joerg } else if (InitListExpr *InnerILE = 632 1.1 joerg dyn_cast<InitListExpr>(ILE->getInit(Init))) { 633 1.1 joerg FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass, 634 1.1 joerg ILE, Init, FillWithNoInit); 635 1.1 joerg } else if (DesignatedInitUpdateExpr *InnerDIUE = 636 1.1 joerg dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) { 637 1.1 joerg FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(), 638 1.1 joerg RequiresSecondPass, ILE, Init, 639 1.1 joerg /*FillWithNoInit =*/true); 640 1.1 joerg } 641 1.1 joerg } 642 1.1 joerg 643 1.1 joerg void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field, 644 1.1 joerg const InitializedEntity &ParentEntity, 645 1.1 joerg InitListExpr *ILE, 646 1.1 joerg bool &RequiresSecondPass, 647 1.1 joerg bool FillWithNoInit) { 648 1.1 joerg SourceLocation Loc = ILE->getEndLoc(); 649 1.1 joerg unsigned NumInits = ILE->getNumInits(); 650 1.1 joerg InitializedEntity MemberEntity 651 1.1 joerg = InitializedEntity::InitializeMember(Field, &ParentEntity); 652 1.1 joerg 653 1.1 joerg if (Init >= NumInits || !ILE->getInit(Init)) { 654 1.1 joerg if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) 655 1.1 joerg if (!RType->getDecl()->isUnion()) 656 1.1 joerg assert((Init < NumInits || VerifyOnly) && 657 1.1 joerg "This ILE should have been expanded"); 658 1.1 joerg 659 1.1 joerg if (FillWithNoInit) { 660 1.1 joerg assert(!VerifyOnly && "should not fill with no-init in verify-only mode"); 661 1.1 joerg Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType()); 662 1.1 joerg if (Init < NumInits) 663 1.1 joerg ILE->setInit(Init, Filler); 664 1.1 joerg else 665 1.1 joerg ILE->updateInit(SemaRef.Context, Init, Filler); 666 1.1 joerg return; 667 1.1 joerg } 668 1.1 joerg // C++1y [dcl.init.aggr]p7: 669 1.1 joerg // If there are fewer initializer-clauses in the list than there are 670 1.1 joerg // members in the aggregate, then each member not explicitly initialized 671 1.1 joerg // shall be initialized from its brace-or-equal-initializer [...] 672 1.1 joerg if (Field->hasInClassInitializer()) { 673 1.1 joerg if (VerifyOnly) 674 1.1 joerg return; 675 1.1 joerg 676 1.1 joerg ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field); 677 1.1 joerg if (DIE.isInvalid()) { 678 1.1 joerg hadError = true; 679 1.1 joerg return; 680 1.1 joerg } 681 1.1 joerg SemaRef.checkInitializerLifetime(MemberEntity, DIE.get()); 682 1.1 joerg if (Init < NumInits) 683 1.1 joerg ILE->setInit(Init, DIE.get()); 684 1.1 joerg else { 685 1.1 joerg ILE->updateInit(SemaRef.Context, Init, DIE.get()); 686 1.1 joerg RequiresSecondPass = true; 687 1.1 joerg } 688 1.1 joerg return; 689 1.1 joerg } 690 1.1 joerg 691 1.1 joerg if (Field->getType()->isReferenceType()) { 692 1.1 joerg if (!VerifyOnly) { 693 1.1 joerg // C++ [dcl.init.aggr]p9: 694 1.1 joerg // If an incomplete or empty initializer-list leaves a 695 1.1 joerg // member of reference type uninitialized, the program is 696 1.1 joerg // ill-formed. 697 1.1 joerg SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) 698 1.1 joerg << Field->getType() 699 1.1 joerg << ILE->getSyntacticForm()->getSourceRange(); 700 1.1 joerg SemaRef.Diag(Field->getLocation(), 701 1.1 joerg diag::note_uninit_reference_member); 702 1.1 joerg } 703 1.1 joerg hadError = true; 704 1.1 joerg return; 705 1.1 joerg } 706 1.1 joerg 707 1.1 joerg ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity); 708 1.1 joerg if (MemberInit.isInvalid()) { 709 1.1 joerg hadError = true; 710 1.1 joerg return; 711 1.1 joerg } 712 1.1 joerg 713 1.1 joerg if (hadError || VerifyOnly) { 714 1.1 joerg // Do nothing 715 1.1 joerg } else if (Init < NumInits) { 716 1.1 joerg ILE->setInit(Init, MemberInit.getAs<Expr>()); 717 1.1 joerg } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) { 718 1.1 joerg // Empty initialization requires a constructor call, so 719 1.1 joerg // extend the initializer list to include the constructor 720 1.1 joerg // call and make a note that we'll need to take another pass 721 1.1 joerg // through the initializer list. 722 1.1 joerg ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>()); 723 1.1 joerg RequiresSecondPass = true; 724 1.1 joerg } 725 1.1 joerg } else if (InitListExpr *InnerILE 726 1.1 joerg = dyn_cast<InitListExpr>(ILE->getInit(Init))) { 727 1.1 joerg FillInEmptyInitializations(MemberEntity, InnerILE, 728 1.1 joerg RequiresSecondPass, ILE, Init, FillWithNoInit); 729 1.1 joerg } else if (DesignatedInitUpdateExpr *InnerDIUE = 730 1.1 joerg dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) { 731 1.1 joerg FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(), 732 1.1 joerg RequiresSecondPass, ILE, Init, 733 1.1 joerg /*FillWithNoInit =*/true); 734 1.1 joerg } 735 1.1 joerg } 736 1.1 joerg 737 1.1 joerg /// Recursively replaces NULL values within the given initializer list 738 1.1 joerg /// with expressions that perform value-initialization of the 739 1.1 joerg /// appropriate type, and finish off the InitListExpr formation. 740 1.1 joerg void 741 1.1 joerg InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity, 742 1.1 joerg InitListExpr *ILE, 743 1.1 joerg bool &RequiresSecondPass, 744 1.1 joerg InitListExpr *OuterILE, 745 1.1 joerg unsigned OuterIndex, 746 1.1 joerg bool FillWithNoInit) { 747 1.1 joerg assert((ILE->getType() != SemaRef.Context.VoidTy) && 748 1.1 joerg "Should not have void type"); 749 1.1 joerg 750 1.1 joerg // We don't need to do any checks when just filling NoInitExprs; that can't 751 1.1 joerg // fail. 752 1.1 joerg if (FillWithNoInit && VerifyOnly) 753 1.1 joerg return; 754 1.1 joerg 755 1.1 joerg // If this is a nested initializer list, we might have changed its contents 756 1.1 joerg // (and therefore some of its properties, such as instantiation-dependence) 757 1.1 joerg // while filling it in. Inform the outer initializer list so that its state 758 1.1 joerg // can be updated to match. 759 1.1 joerg // FIXME: We should fully build the inner initializers before constructing 760 1.1 joerg // the outer InitListExpr instead of mutating AST nodes after they have 761 1.1 joerg // been used as subexpressions of other nodes. 762 1.1 joerg struct UpdateOuterILEWithUpdatedInit { 763 1.1 joerg InitListExpr *Outer; 764 1.1 joerg unsigned OuterIndex; 765 1.1 joerg ~UpdateOuterILEWithUpdatedInit() { 766 1.1 joerg if (Outer) 767 1.1 joerg Outer->setInit(OuterIndex, Outer->getInit(OuterIndex)); 768 1.1 joerg } 769 1.1 joerg } UpdateOuterRAII = {OuterILE, OuterIndex}; 770 1.1 joerg 771 1.1 joerg // A transparent ILE is not performing aggregate initialization and should 772 1.1 joerg // not be filled in. 773 1.1 joerg if (ILE->isTransparent()) 774 1.1 joerg return; 775 1.1 joerg 776 1.1 joerg if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 777 1.1 joerg const RecordDecl *RDecl = RType->getDecl(); 778 1.1 joerg if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) 779 1.1 joerg FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), 780 1.1 joerg Entity, ILE, RequiresSecondPass, FillWithNoInit); 781 1.1 joerg else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) && 782 1.1 joerg cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) { 783 1.1 joerg for (auto *Field : RDecl->fields()) { 784 1.1 joerg if (Field->hasInClassInitializer()) { 785 1.1 joerg FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass, 786 1.1 joerg FillWithNoInit); 787 1.1 joerg break; 788 1.1 joerg } 789 1.1 joerg } 790 1.1 joerg } else { 791 1.1 joerg // The fields beyond ILE->getNumInits() are default initialized, so in 792 1.1 joerg // order to leave them uninitialized, the ILE is expanded and the extra 793 1.1 joerg // fields are then filled with NoInitExpr. 794 1.1 joerg unsigned NumElems = numStructUnionElements(ILE->getType()); 795 1.1 joerg if (RDecl->hasFlexibleArrayMember()) 796 1.1 joerg ++NumElems; 797 1.1 joerg if (!VerifyOnly && ILE->getNumInits() < NumElems) 798 1.1 joerg ILE->resizeInits(SemaRef.Context, NumElems); 799 1.1 joerg 800 1.1 joerg unsigned Init = 0; 801 1.1 joerg 802 1.1 joerg if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) { 803 1.1 joerg for (auto &Base : CXXRD->bases()) { 804 1.1 joerg if (hadError) 805 1.1 joerg return; 806 1.1 joerg 807 1.1 joerg FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass, 808 1.1 joerg FillWithNoInit); 809 1.1 joerg ++Init; 810 1.1 joerg } 811 1.1 joerg } 812 1.1 joerg 813 1.1 joerg for (auto *Field : RDecl->fields()) { 814 1.1 joerg if (Field->isUnnamedBitfield()) 815 1.1 joerg continue; 816 1.1 joerg 817 1.1 joerg if (hadError) 818 1.1 joerg return; 819 1.1 joerg 820 1.1 joerg FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass, 821 1.1 joerg FillWithNoInit); 822 1.1 joerg if (hadError) 823 1.1 joerg return; 824 1.1 joerg 825 1.1 joerg ++Init; 826 1.1 joerg 827 1.1 joerg // Only look at the first initialization of a union. 828 1.1 joerg if (RDecl->isUnion()) 829 1.1 joerg break; 830 1.1 joerg } 831 1.1 joerg } 832 1.1 joerg 833 1.1 joerg return; 834 1.1 joerg } 835 1.1 joerg 836 1.1 joerg QualType ElementType; 837 1.1 joerg 838 1.1 joerg InitializedEntity ElementEntity = Entity; 839 1.1 joerg unsigned NumInits = ILE->getNumInits(); 840 1.1 joerg unsigned NumElements = NumInits; 841 1.1 joerg if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { 842 1.1 joerg ElementType = AType->getElementType(); 843 1.1 joerg if (const auto *CAType = dyn_cast<ConstantArrayType>(AType)) 844 1.1 joerg NumElements = CAType->getSize().getZExtValue(); 845 1.1 joerg // For an array new with an unknown bound, ask for one additional element 846 1.1 joerg // in order to populate the array filler. 847 1.1 joerg if (Entity.isVariableLengthArrayNew()) 848 1.1 joerg ++NumElements; 849 1.1 joerg ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 850 1.1 joerg 0, Entity); 851 1.1 joerg } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { 852 1.1 joerg ElementType = VType->getElementType(); 853 1.1 joerg NumElements = VType->getNumElements(); 854 1.1 joerg ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 855 1.1 joerg 0, Entity); 856 1.1 joerg } else 857 1.1 joerg ElementType = ILE->getType(); 858 1.1 joerg 859 1.1 joerg bool SkipEmptyInitChecks = false; 860 1.1 joerg for (unsigned Init = 0; Init != NumElements; ++Init) { 861 1.1 joerg if (hadError) 862 1.1 joerg return; 863 1.1 joerg 864 1.1 joerg if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement || 865 1.1 joerg ElementEntity.getKind() == InitializedEntity::EK_VectorElement) 866 1.1 joerg ElementEntity.setElementIndex(Init); 867 1.1 joerg 868 1.1 joerg if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks)) 869 1.1 joerg return; 870 1.1 joerg 871 1.1 joerg Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr); 872 1.1 joerg if (!InitExpr && Init < NumInits && ILE->hasArrayFiller()) 873 1.1 joerg ILE->setInit(Init, ILE->getArrayFiller()); 874 1.1 joerg else if (!InitExpr && !ILE->hasArrayFiller()) { 875 1.1 joerg // In VerifyOnly mode, there's no point performing empty initialization 876 1.1 joerg // more than once. 877 1.1 joerg if (SkipEmptyInitChecks) 878 1.1 joerg continue; 879 1.1 joerg 880 1.1 joerg Expr *Filler = nullptr; 881 1.1 joerg 882 1.1 joerg if (FillWithNoInit) 883 1.1 joerg Filler = new (SemaRef.Context) NoInitExpr(ElementType); 884 1.1 joerg else { 885 1.1 joerg ExprResult ElementInit = 886 1.1 joerg PerformEmptyInit(ILE->getEndLoc(), ElementEntity); 887 1.1 joerg if (ElementInit.isInvalid()) { 888 1.1 joerg hadError = true; 889 1.1 joerg return; 890 1.1 joerg } 891 1.1 joerg 892 1.1 joerg Filler = ElementInit.getAs<Expr>(); 893 1.1 joerg } 894 1.1 joerg 895 1.1 joerg if (hadError) { 896 1.1 joerg // Do nothing 897 1.1 joerg } else if (VerifyOnly) { 898 1.1 joerg SkipEmptyInitChecks = true; 899 1.1 joerg } else if (Init < NumInits) { 900 1.1 joerg // For arrays, just set the expression used for value-initialization 901 1.1 joerg // of the "holes" in the array. 902 1.1 joerg if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) 903 1.1 joerg ILE->setArrayFiller(Filler); 904 1.1 joerg else 905 1.1 joerg ILE->setInit(Init, Filler); 906 1.1 joerg } else { 907 1.1 joerg // For arrays, just set the expression used for value-initialization 908 1.1 joerg // of the rest of elements and exit. 909 1.1 joerg if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) { 910 1.1 joerg ILE->setArrayFiller(Filler); 911 1.1 joerg return; 912 1.1 joerg } 913 1.1 joerg 914 1.1 joerg if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) { 915 1.1 joerg // Empty initialization requires a constructor call, so 916 1.1 joerg // extend the initializer list to include the constructor 917 1.1 joerg // call and make a note that we'll need to take another pass 918 1.1 joerg // through the initializer list. 919 1.1 joerg ILE->updateInit(SemaRef.Context, Init, Filler); 920 1.1 joerg RequiresSecondPass = true; 921 1.1 joerg } 922 1.1 joerg } 923 1.1 joerg } else if (InitListExpr *InnerILE 924 1.1 joerg = dyn_cast_or_null<InitListExpr>(InitExpr)) { 925 1.1 joerg FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass, 926 1.1 joerg ILE, Init, FillWithNoInit); 927 1.1 joerg } else if (DesignatedInitUpdateExpr *InnerDIUE = 928 1.1 joerg dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) { 929 1.1 joerg FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(), 930 1.1 joerg RequiresSecondPass, ILE, Init, 931 1.1 joerg /*FillWithNoInit =*/true); 932 1.1 joerg } 933 1.1 joerg } 934 1.1 joerg } 935 1.1 joerg 936 1.1 joerg static bool hasAnyDesignatedInits(const InitListExpr *IL) { 937 1.1 joerg for (const Stmt *Init : *IL) 938 1.1 joerg if (Init && isa<DesignatedInitExpr>(Init)) 939 1.1 joerg return true; 940 1.1 joerg return false; 941 1.1 joerg } 942 1.1 joerg 943 1.1 joerg InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity, 944 1.1 joerg InitListExpr *IL, QualType &T, bool VerifyOnly, 945 1.1 joerg bool TreatUnavailableAsInvalid, 946 1.1 joerg bool InOverloadResolution) 947 1.1 joerg : SemaRef(S), VerifyOnly(VerifyOnly), 948 1.1 joerg TreatUnavailableAsInvalid(TreatUnavailableAsInvalid), 949 1.1 joerg InOverloadResolution(InOverloadResolution) { 950 1.1 joerg if (!VerifyOnly || hasAnyDesignatedInits(IL)) { 951 1.1 joerg FullyStructuredList = 952 1.1 joerg createInitListExpr(T, IL->getSourceRange(), IL->getNumInits()); 953 1.1 joerg 954 1.1 joerg // FIXME: Check that IL isn't already the semantic form of some other 955 1.1 joerg // InitListExpr. If it is, we'd create a broken AST. 956 1.1 joerg if (!VerifyOnly) 957 1.1 joerg FullyStructuredList->setSyntacticForm(IL); 958 1.1 joerg } 959 1.1 joerg 960 1.1 joerg CheckExplicitInitList(Entity, IL, T, FullyStructuredList, 961 1.1 joerg /*TopLevelObject=*/true); 962 1.1 joerg 963 1.1 joerg if (!hadError && FullyStructuredList) { 964 1.1 joerg bool RequiresSecondPass = false; 965 1.1 joerg FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass, 966 1.1 joerg /*OuterILE=*/nullptr, /*OuterIndex=*/0); 967 1.1 joerg if (RequiresSecondPass && !hadError) 968 1.1 joerg FillInEmptyInitializations(Entity, FullyStructuredList, 969 1.1 joerg RequiresSecondPass, nullptr, 0); 970 1.1 joerg } 971 1.1.1.2 joerg if (hadError && FullyStructuredList) 972 1.1.1.2 joerg FullyStructuredList->markError(); 973 1.1 joerg } 974 1.1 joerg 975 1.1 joerg int InitListChecker::numArrayElements(QualType DeclType) { 976 1.1 joerg // FIXME: use a proper constant 977 1.1 joerg int maxElements = 0x7FFFFFFF; 978 1.1 joerg if (const ConstantArrayType *CAT = 979 1.1 joerg SemaRef.Context.getAsConstantArrayType(DeclType)) { 980 1.1 joerg maxElements = static_cast<int>(CAT->getSize().getZExtValue()); 981 1.1 joerg } 982 1.1 joerg return maxElements; 983 1.1 joerg } 984 1.1 joerg 985 1.1 joerg int InitListChecker::numStructUnionElements(QualType DeclType) { 986 1.1 joerg RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl(); 987 1.1 joerg int InitializableMembers = 0; 988 1.1 joerg if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl)) 989 1.1 joerg InitializableMembers += CXXRD->getNumBases(); 990 1.1 joerg for (const auto *Field : structDecl->fields()) 991 1.1 joerg if (!Field->isUnnamedBitfield()) 992 1.1 joerg ++InitializableMembers; 993 1.1 joerg 994 1.1 joerg if (structDecl->isUnion()) 995 1.1 joerg return std::min(InitializableMembers, 1); 996 1.1 joerg return InitializableMembers - structDecl->hasFlexibleArrayMember(); 997 1.1 joerg } 998 1.1 joerg 999 1.1 joerg /// Determine whether Entity is an entity for which it is idiomatic to elide 1000 1.1 joerg /// the braces in aggregate initialization. 1001 1.1 joerg static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) { 1002 1.1 joerg // Recursive initialization of the one and only field within an aggregate 1003 1.1 joerg // class is considered idiomatic. This case arises in particular for 1004 1.1 joerg // initialization of std::array, where the C++ standard suggests the idiom of 1005 1.1 joerg // 1006 1.1 joerg // std::array<T, N> arr = {1, 2, 3}; 1007 1.1 joerg // 1008 1.1 joerg // (where std::array is an aggregate struct containing a single array field. 1009 1.1 joerg 1010 1.1.1.2 joerg if (!Entity.getParent()) 1011 1.1 joerg return false; 1012 1.1 joerg 1013 1.1.1.2 joerg // Allows elide brace initialization for aggregates with empty base. 1014 1.1.1.2 joerg if (Entity.getKind() == InitializedEntity::EK_Base) { 1015 1.1.1.2 joerg auto *ParentRD = 1016 1.1.1.2 joerg Entity.getParent()->getType()->castAs<RecordType>()->getDecl(); 1017 1.1.1.2 joerg CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD); 1018 1.1.1.2 joerg return CXXRD->getNumBases() == 1 && CXXRD->field_empty(); 1019 1.1.1.2 joerg } 1020 1.1 joerg 1021 1.1.1.2 joerg // Allow brace elision if the only subobject is a field. 1022 1.1.1.2 joerg if (Entity.getKind() == InitializedEntity::EK_Member) { 1023 1.1.1.2 joerg auto *ParentRD = 1024 1.1.1.2 joerg Entity.getParent()->getType()->castAs<RecordType>()->getDecl(); 1025 1.1.1.2 joerg if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) { 1026 1.1.1.2 joerg if (CXXRD->getNumBases()) { 1027 1.1.1.2 joerg return false; 1028 1.1.1.2 joerg } 1029 1.1.1.2 joerg } 1030 1.1.1.2 joerg auto FieldIt = ParentRD->field_begin(); 1031 1.1.1.2 joerg assert(FieldIt != ParentRD->field_end() && 1032 1.1.1.2 joerg "no fields but have initializer for member?"); 1033 1.1.1.2 joerg return ++FieldIt == ParentRD->field_end(); 1034 1.1.1.2 joerg } 1035 1.1.1.2 joerg 1036 1.1.1.2 joerg return false; 1037 1.1 joerg } 1038 1.1 joerg 1039 1.1 joerg /// Check whether the range of the initializer \p ParentIList from element 1040 1.1 joerg /// \p Index onwards can be used to initialize an object of type \p T. Update 1041 1.1 joerg /// \p Index to indicate how many elements of the list were consumed. 1042 1.1 joerg /// 1043 1.1 joerg /// This also fills in \p StructuredList, from element \p StructuredIndex 1044 1.1 joerg /// onwards, with the fully-braced, desugared form of the initialization. 1045 1.1 joerg void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity, 1046 1.1 joerg InitListExpr *ParentIList, 1047 1.1 joerg QualType T, unsigned &Index, 1048 1.1 joerg InitListExpr *StructuredList, 1049 1.1 joerg unsigned &StructuredIndex) { 1050 1.1 joerg int maxElements = 0; 1051 1.1 joerg 1052 1.1 joerg if (T->isArrayType()) 1053 1.1 joerg maxElements = numArrayElements(T); 1054 1.1 joerg else if (T->isRecordType()) 1055 1.1 joerg maxElements = numStructUnionElements(T); 1056 1.1 joerg else if (T->isVectorType()) 1057 1.1 joerg maxElements = T->castAs<VectorType>()->getNumElements(); 1058 1.1 joerg else 1059 1.1 joerg llvm_unreachable("CheckImplicitInitList(): Illegal type"); 1060 1.1 joerg 1061 1.1 joerg if (maxElements == 0) { 1062 1.1 joerg if (!VerifyOnly) 1063 1.1 joerg SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(), 1064 1.1 joerg diag::err_implicit_empty_initializer); 1065 1.1 joerg ++Index; 1066 1.1 joerg hadError = true; 1067 1.1 joerg return; 1068 1.1 joerg } 1069 1.1 joerg 1070 1.1 joerg // Build a structured initializer list corresponding to this subobject. 1071 1.1 joerg InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit( 1072 1.1 joerg ParentIList, Index, T, StructuredList, StructuredIndex, 1073 1.1 joerg SourceRange(ParentIList->getInit(Index)->getBeginLoc(), 1074 1.1 joerg ParentIList->getSourceRange().getEnd())); 1075 1.1 joerg unsigned StructuredSubobjectInitIndex = 0; 1076 1.1 joerg 1077 1.1 joerg // Check the element types and build the structural subobject. 1078 1.1 joerg unsigned StartIndex = Index; 1079 1.1 joerg CheckListElementTypes(Entity, ParentIList, T, 1080 1.1 joerg /*SubobjectIsDesignatorContext=*/false, Index, 1081 1.1 joerg StructuredSubobjectInitList, 1082 1.1 joerg StructuredSubobjectInitIndex); 1083 1.1 joerg 1084 1.1 joerg if (StructuredSubobjectInitList) { 1085 1.1 joerg StructuredSubobjectInitList->setType(T); 1086 1.1 joerg 1087 1.1 joerg unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); 1088 1.1 joerg // Update the structured sub-object initializer so that it's ending 1089 1.1 joerg // range corresponds with the end of the last initializer it used. 1090 1.1 joerg if (EndIndex < ParentIList->getNumInits() && 1091 1.1 joerg ParentIList->getInit(EndIndex)) { 1092 1.1 joerg SourceLocation EndLoc 1093 1.1 joerg = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); 1094 1.1 joerg StructuredSubobjectInitList->setRBraceLoc(EndLoc); 1095 1.1 joerg } 1096 1.1 joerg 1097 1.1 joerg // Complain about missing braces. 1098 1.1 joerg if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) && 1099 1.1 joerg !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) && 1100 1.1 joerg !isIdiomaticBraceElisionEntity(Entity)) { 1101 1.1 joerg SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(), 1102 1.1 joerg diag::warn_missing_braces) 1103 1.1 joerg << StructuredSubobjectInitList->getSourceRange() 1104 1.1 joerg << FixItHint::CreateInsertion( 1105 1.1 joerg StructuredSubobjectInitList->getBeginLoc(), "{") 1106 1.1 joerg << FixItHint::CreateInsertion( 1107 1.1 joerg SemaRef.getLocForEndOfToken( 1108 1.1 joerg StructuredSubobjectInitList->getEndLoc()), 1109 1.1 joerg "}"); 1110 1.1 joerg } 1111 1.1 joerg 1112 1.1 joerg // Warn if this type won't be an aggregate in future versions of C++. 1113 1.1 joerg auto *CXXRD = T->getAsCXXRecordDecl(); 1114 1.1 joerg if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) { 1115 1.1 joerg SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(), 1116 1.1.1.2 joerg diag::warn_cxx20_compat_aggregate_init_with_ctors) 1117 1.1 joerg << StructuredSubobjectInitList->getSourceRange() << T; 1118 1.1 joerg } 1119 1.1 joerg } 1120 1.1 joerg } 1121 1.1 joerg 1122 1.1 joerg /// Warn that \p Entity was of scalar type and was initialized by a 1123 1.1 joerg /// single-element braced initializer list. 1124 1.1 joerg static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity, 1125 1.1 joerg SourceRange Braces) { 1126 1.1 joerg // Don't warn during template instantiation. If the initialization was 1127 1.1 joerg // non-dependent, we warned during the initial parse; otherwise, the 1128 1.1 joerg // type might not be scalar in some uses of the template. 1129 1.1 joerg if (S.inTemplateInstantiation()) 1130 1.1 joerg return; 1131 1.1 joerg 1132 1.1 joerg unsigned DiagID = 0; 1133 1.1 joerg 1134 1.1 joerg switch (Entity.getKind()) { 1135 1.1 joerg case InitializedEntity::EK_VectorElement: 1136 1.1 joerg case InitializedEntity::EK_ComplexElement: 1137 1.1 joerg case InitializedEntity::EK_ArrayElement: 1138 1.1 joerg case InitializedEntity::EK_Parameter: 1139 1.1 joerg case InitializedEntity::EK_Parameter_CF_Audited: 1140 1.1.1.2 joerg case InitializedEntity::EK_TemplateParameter: 1141 1.1 joerg case InitializedEntity::EK_Result: 1142 1.1 joerg // Extra braces here are suspicious. 1143 1.1.1.2 joerg DiagID = diag::warn_braces_around_init; 1144 1.1 joerg break; 1145 1.1 joerg 1146 1.1 joerg case InitializedEntity::EK_Member: 1147 1.1 joerg // Warn on aggregate initialization but not on ctor init list or 1148 1.1 joerg // default member initializer. 1149 1.1 joerg if (Entity.getParent()) 1150 1.1.1.2 joerg DiagID = diag::warn_braces_around_init; 1151 1.1 joerg break; 1152 1.1 joerg 1153 1.1 joerg case InitializedEntity::EK_Variable: 1154 1.1 joerg case InitializedEntity::EK_LambdaCapture: 1155 1.1 joerg // No warning, might be direct-list-initialization. 1156 1.1 joerg // FIXME: Should we warn for copy-list-initialization in these cases? 1157 1.1 joerg break; 1158 1.1 joerg 1159 1.1 joerg case InitializedEntity::EK_New: 1160 1.1 joerg case InitializedEntity::EK_Temporary: 1161 1.1 joerg case InitializedEntity::EK_CompoundLiteralInit: 1162 1.1 joerg // No warning, braces are part of the syntax of the underlying construct. 1163 1.1 joerg break; 1164 1.1 joerg 1165 1.1 joerg case InitializedEntity::EK_RelatedResult: 1166 1.1 joerg // No warning, we already warned when initializing the result. 1167 1.1 joerg break; 1168 1.1 joerg 1169 1.1 joerg case InitializedEntity::EK_Exception: 1170 1.1 joerg case InitializedEntity::EK_Base: 1171 1.1 joerg case InitializedEntity::EK_Delegating: 1172 1.1 joerg case InitializedEntity::EK_BlockElement: 1173 1.1 joerg case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 1174 1.1 joerg case InitializedEntity::EK_Binding: 1175 1.1 joerg case InitializedEntity::EK_StmtExprResult: 1176 1.1 joerg llvm_unreachable("unexpected braced scalar init"); 1177 1.1 joerg } 1178 1.1 joerg 1179 1.1 joerg if (DiagID) { 1180 1.1 joerg S.Diag(Braces.getBegin(), DiagID) 1181 1.1.1.2 joerg << Entity.getType()->isSizelessBuiltinType() << Braces 1182 1.1.1.2 joerg << FixItHint::CreateRemoval(Braces.getBegin()) 1183 1.1.1.2 joerg << FixItHint::CreateRemoval(Braces.getEnd()); 1184 1.1 joerg } 1185 1.1 joerg } 1186 1.1 joerg 1187 1.1 joerg /// Check whether the initializer \p IList (that was written with explicit 1188 1.1 joerg /// braces) can be used to initialize an object of type \p T. 1189 1.1 joerg /// 1190 1.1 joerg /// This also fills in \p StructuredList with the fully-braced, desugared 1191 1.1 joerg /// form of the initialization. 1192 1.1 joerg void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity, 1193 1.1 joerg InitListExpr *IList, QualType &T, 1194 1.1 joerg InitListExpr *StructuredList, 1195 1.1 joerg bool TopLevelObject) { 1196 1.1 joerg unsigned Index = 0, StructuredIndex = 0; 1197 1.1 joerg CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true, 1198 1.1 joerg Index, StructuredList, StructuredIndex, TopLevelObject); 1199 1.1 joerg if (StructuredList) { 1200 1.1 joerg QualType ExprTy = T; 1201 1.1 joerg if (!ExprTy->isArrayType()) 1202 1.1 joerg ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context); 1203 1.1 joerg if (!VerifyOnly) 1204 1.1 joerg IList->setType(ExprTy); 1205 1.1 joerg StructuredList->setType(ExprTy); 1206 1.1 joerg } 1207 1.1 joerg if (hadError) 1208 1.1 joerg return; 1209 1.1 joerg 1210 1.1 joerg // Don't complain for incomplete types, since we'll get an error elsewhere. 1211 1.1 joerg if (Index < IList->getNumInits() && !T->isIncompleteType()) { 1212 1.1 joerg // We have leftover initializers 1213 1.1 joerg bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus || 1214 1.1 joerg (SemaRef.getLangOpts().OpenCL && T->isVectorType()); 1215 1.1 joerg hadError = ExtraInitsIsError; 1216 1.1 joerg if (VerifyOnly) { 1217 1.1 joerg return; 1218 1.1 joerg } else if (StructuredIndex == 1 && 1219 1.1 joerg IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) == 1220 1.1 joerg SIF_None) { 1221 1.1 joerg unsigned DK = 1222 1.1 joerg ExtraInitsIsError 1223 1.1 joerg ? diag::err_excess_initializers_in_char_array_initializer 1224 1.1 joerg : diag::ext_excess_initializers_in_char_array_initializer; 1225 1.1 joerg SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) 1226 1.1 joerg << IList->getInit(Index)->getSourceRange(); 1227 1.1.1.2 joerg } else if (T->isSizelessBuiltinType()) { 1228 1.1.1.2 joerg unsigned DK = ExtraInitsIsError 1229 1.1.1.2 joerg ? diag::err_excess_initializers_for_sizeless_type 1230 1.1.1.2 joerg : diag::ext_excess_initializers_for_sizeless_type; 1231 1.1.1.2 joerg SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) 1232 1.1.1.2 joerg << T << IList->getInit(Index)->getSourceRange(); 1233 1.1 joerg } else { 1234 1.1 joerg int initKind = T->isArrayType() ? 0 : 1235 1.1 joerg T->isVectorType() ? 1 : 1236 1.1 joerg T->isScalarType() ? 2 : 1237 1.1 joerg T->isUnionType() ? 3 : 1238 1.1 joerg 4; 1239 1.1 joerg 1240 1.1 joerg unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers 1241 1.1 joerg : diag::ext_excess_initializers; 1242 1.1 joerg SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) 1243 1.1 joerg << initKind << IList->getInit(Index)->getSourceRange(); 1244 1.1 joerg } 1245 1.1 joerg } 1246 1.1 joerg 1247 1.1 joerg if (!VerifyOnly) { 1248 1.1 joerg if (T->isScalarType() && IList->getNumInits() == 1 && 1249 1.1 joerg !isa<InitListExpr>(IList->getInit(0))) 1250 1.1 joerg warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange()); 1251 1.1 joerg 1252 1.1 joerg // Warn if this is a class type that won't be an aggregate in future 1253 1.1 joerg // versions of C++. 1254 1.1 joerg auto *CXXRD = T->getAsCXXRecordDecl(); 1255 1.1 joerg if (CXXRD && CXXRD->hasUserDeclaredConstructor()) { 1256 1.1 joerg // Don't warn if there's an equivalent default constructor that would be 1257 1.1 joerg // used instead. 1258 1.1 joerg bool HasEquivCtor = false; 1259 1.1 joerg if (IList->getNumInits() == 0) { 1260 1.1 joerg auto *CD = SemaRef.LookupDefaultConstructor(CXXRD); 1261 1.1 joerg HasEquivCtor = CD && !CD->isDeleted(); 1262 1.1 joerg } 1263 1.1 joerg 1264 1.1 joerg if (!HasEquivCtor) { 1265 1.1 joerg SemaRef.Diag(IList->getBeginLoc(), 1266 1.1.1.2 joerg diag::warn_cxx20_compat_aggregate_init_with_ctors) 1267 1.1 joerg << IList->getSourceRange() << T; 1268 1.1 joerg } 1269 1.1 joerg } 1270 1.1 joerg } 1271 1.1 joerg } 1272 1.1 joerg 1273 1.1 joerg void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity, 1274 1.1 joerg InitListExpr *IList, 1275 1.1 joerg QualType &DeclType, 1276 1.1 joerg bool SubobjectIsDesignatorContext, 1277 1.1 joerg unsigned &Index, 1278 1.1 joerg InitListExpr *StructuredList, 1279 1.1 joerg unsigned &StructuredIndex, 1280 1.1 joerg bool TopLevelObject) { 1281 1.1 joerg if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) { 1282 1.1 joerg // Explicitly braced initializer for complex type can be real+imaginary 1283 1.1 joerg // parts. 1284 1.1 joerg CheckComplexType(Entity, IList, DeclType, Index, 1285 1.1 joerg StructuredList, StructuredIndex); 1286 1.1 joerg } else if (DeclType->isScalarType()) { 1287 1.1 joerg CheckScalarType(Entity, IList, DeclType, Index, 1288 1.1 joerg StructuredList, StructuredIndex); 1289 1.1 joerg } else if (DeclType->isVectorType()) { 1290 1.1 joerg CheckVectorType(Entity, IList, DeclType, Index, 1291 1.1 joerg StructuredList, StructuredIndex); 1292 1.1 joerg } else if (DeclType->isRecordType()) { 1293 1.1 joerg assert(DeclType->isAggregateType() && 1294 1.1 joerg "non-aggregate records should be handed in CheckSubElementType"); 1295 1.1 joerg RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); 1296 1.1 joerg auto Bases = 1297 1.1 joerg CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), 1298 1.1 joerg CXXRecordDecl::base_class_iterator()); 1299 1.1 joerg if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1300 1.1 joerg Bases = CXXRD->bases(); 1301 1.1 joerg CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(), 1302 1.1 joerg SubobjectIsDesignatorContext, Index, StructuredList, 1303 1.1 joerg StructuredIndex, TopLevelObject); 1304 1.1 joerg } else if (DeclType->isArrayType()) { 1305 1.1 joerg llvm::APSInt Zero( 1306 1.1 joerg SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), 1307 1.1 joerg false); 1308 1.1 joerg CheckArrayType(Entity, IList, DeclType, Zero, 1309 1.1 joerg SubobjectIsDesignatorContext, Index, 1310 1.1 joerg StructuredList, StructuredIndex); 1311 1.1 joerg } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { 1312 1.1 joerg // This type is invalid, issue a diagnostic. 1313 1.1 joerg ++Index; 1314 1.1 joerg if (!VerifyOnly) 1315 1.1 joerg SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type) 1316 1.1 joerg << DeclType; 1317 1.1 joerg hadError = true; 1318 1.1 joerg } else if (DeclType->isReferenceType()) { 1319 1.1 joerg CheckReferenceType(Entity, IList, DeclType, Index, 1320 1.1 joerg StructuredList, StructuredIndex); 1321 1.1 joerg } else if (DeclType->isObjCObjectType()) { 1322 1.1 joerg if (!VerifyOnly) 1323 1.1 joerg SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType; 1324 1.1 joerg hadError = true; 1325 1.1.1.2 joerg } else if (DeclType->isOCLIntelSubgroupAVCType() || 1326 1.1.1.2 joerg DeclType->isSizelessBuiltinType()) { 1327 1.1 joerg // Checks for scalar type are sufficient for these types too. 1328 1.1 joerg CheckScalarType(Entity, IList, DeclType, Index, StructuredList, 1329 1.1 joerg StructuredIndex); 1330 1.1 joerg } else { 1331 1.1 joerg if (!VerifyOnly) 1332 1.1 joerg SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type) 1333 1.1 joerg << DeclType; 1334 1.1 joerg hadError = true; 1335 1.1 joerg } 1336 1.1 joerg } 1337 1.1 joerg 1338 1.1 joerg void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, 1339 1.1 joerg InitListExpr *IList, 1340 1.1 joerg QualType ElemType, 1341 1.1 joerg unsigned &Index, 1342 1.1 joerg InitListExpr *StructuredList, 1343 1.1.1.2 joerg unsigned &StructuredIndex, 1344 1.1.1.2 joerg bool DirectlyDesignated) { 1345 1.1 joerg Expr *expr = IList->getInit(Index); 1346 1.1 joerg 1347 1.1 joerg if (ElemType->isReferenceType()) 1348 1.1 joerg return CheckReferenceType(Entity, IList, ElemType, Index, 1349 1.1 joerg StructuredList, StructuredIndex); 1350 1.1 joerg 1351 1.1 joerg if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { 1352 1.1 joerg if (SubInitList->getNumInits() == 1 && 1353 1.1 joerg IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) == 1354 1.1 joerg SIF_None) { 1355 1.1 joerg // FIXME: It would be more faithful and no less correct to include an 1356 1.1 joerg // InitListExpr in the semantic form of the initializer list in this case. 1357 1.1 joerg expr = SubInitList->getInit(0); 1358 1.1 joerg } 1359 1.1 joerg // Nested aggregate initialization and C++ initialization are handled later. 1360 1.1 joerg } else if (isa<ImplicitValueInitExpr>(expr)) { 1361 1.1 joerg // This happens during template instantiation when we see an InitListExpr 1362 1.1 joerg // that we've already checked once. 1363 1.1 joerg assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) && 1364 1.1 joerg "found implicit initialization for the wrong type"); 1365 1.1 joerg UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 1366 1.1 joerg ++Index; 1367 1.1 joerg return; 1368 1.1 joerg } 1369 1.1 joerg 1370 1.1 joerg if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) { 1371 1.1 joerg // C++ [dcl.init.aggr]p2: 1372 1.1 joerg // Each member is copy-initialized from the corresponding 1373 1.1 joerg // initializer-clause. 1374 1.1 joerg 1375 1.1 joerg // FIXME: Better EqualLoc? 1376 1.1 joerg InitializationKind Kind = 1377 1.1 joerg InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation()); 1378 1.1 joerg 1379 1.1 joerg // Vector elements can be initialized from other vectors in which case 1380 1.1 joerg // we need initialization entity with a type of a vector (and not a vector 1381 1.1 joerg // element!) initializing multiple vector elements. 1382 1.1 joerg auto TmpEntity = 1383 1.1 joerg (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType()) 1384 1.1 joerg ? InitializedEntity::InitializeTemporary(ElemType) 1385 1.1 joerg : Entity; 1386 1.1 joerg 1387 1.1 joerg InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr, 1388 1.1 joerg /*TopLevelOfInitList*/ true); 1389 1.1 joerg 1390 1.1 joerg // C++14 [dcl.init.aggr]p13: 1391 1.1 joerg // If the assignment-expression can initialize a member, the member is 1392 1.1 joerg // initialized. Otherwise [...] brace elision is assumed 1393 1.1 joerg // 1394 1.1 joerg // Brace elision is never performed if the element is not an 1395 1.1 joerg // assignment-expression. 1396 1.1 joerg if (Seq || isa<InitListExpr>(expr)) { 1397 1.1 joerg if (!VerifyOnly) { 1398 1.1 joerg ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr); 1399 1.1 joerg if (Result.isInvalid()) 1400 1.1 joerg hadError = true; 1401 1.1 joerg 1402 1.1 joerg UpdateStructuredListElement(StructuredList, StructuredIndex, 1403 1.1 joerg Result.getAs<Expr>()); 1404 1.1 joerg } else if (!Seq) { 1405 1.1 joerg hadError = true; 1406 1.1 joerg } else if (StructuredList) { 1407 1.1 joerg UpdateStructuredListElement(StructuredList, StructuredIndex, 1408 1.1 joerg getDummyInit()); 1409 1.1 joerg } 1410 1.1 joerg ++Index; 1411 1.1 joerg return; 1412 1.1 joerg } 1413 1.1 joerg 1414 1.1 joerg // Fall through for subaggregate initialization 1415 1.1 joerg } else if (ElemType->isScalarType() || ElemType->isAtomicType()) { 1416 1.1 joerg // FIXME: Need to handle atomic aggregate types with implicit init lists. 1417 1.1 joerg return CheckScalarType(Entity, IList, ElemType, Index, 1418 1.1 joerg StructuredList, StructuredIndex); 1419 1.1 joerg } else if (const ArrayType *arrayType = 1420 1.1 joerg SemaRef.Context.getAsArrayType(ElemType)) { 1421 1.1 joerg // arrayType can be incomplete if we're initializing a flexible 1422 1.1 joerg // array member. There's nothing we can do with the completed 1423 1.1 joerg // type here, though. 1424 1.1 joerg 1425 1.1 joerg if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) { 1426 1.1 joerg // FIXME: Should we do this checking in verify-only mode? 1427 1.1 joerg if (!VerifyOnly) 1428 1.1 joerg CheckStringInit(expr, ElemType, arrayType, SemaRef); 1429 1.1 joerg if (StructuredList) 1430 1.1 joerg UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 1431 1.1 joerg ++Index; 1432 1.1 joerg return; 1433 1.1 joerg } 1434 1.1 joerg 1435 1.1 joerg // Fall through for subaggregate initialization. 1436 1.1 joerg 1437 1.1 joerg } else { 1438 1.1 joerg assert((ElemType->isRecordType() || ElemType->isVectorType() || 1439 1.1 joerg ElemType->isOpenCLSpecificType()) && "Unexpected type"); 1440 1.1 joerg 1441 1.1 joerg // C99 6.7.8p13: 1442 1.1 joerg // 1443 1.1 joerg // The initializer for a structure or union object that has 1444 1.1 joerg // automatic storage duration shall be either an initializer 1445 1.1 joerg // list as described below, or a single expression that has 1446 1.1 joerg // compatible structure or union type. In the latter case, the 1447 1.1 joerg // initial value of the object, including unnamed members, is 1448 1.1 joerg // that of the expression. 1449 1.1 joerg ExprResult ExprRes = expr; 1450 1.1 joerg if (SemaRef.CheckSingleAssignmentConstraints( 1451 1.1 joerg ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) { 1452 1.1 joerg if (ExprRes.isInvalid()) 1453 1.1 joerg hadError = true; 1454 1.1 joerg else { 1455 1.1 joerg ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get()); 1456 1.1 joerg if (ExprRes.isInvalid()) 1457 1.1 joerg hadError = true; 1458 1.1 joerg } 1459 1.1 joerg UpdateStructuredListElement(StructuredList, StructuredIndex, 1460 1.1 joerg ExprRes.getAs<Expr>()); 1461 1.1 joerg ++Index; 1462 1.1 joerg return; 1463 1.1 joerg } 1464 1.1 joerg ExprRes.get(); 1465 1.1 joerg // Fall through for subaggregate initialization 1466 1.1 joerg } 1467 1.1 joerg 1468 1.1 joerg // C++ [dcl.init.aggr]p12: 1469 1.1 joerg // 1470 1.1 joerg // [...] Otherwise, if the member is itself a non-empty 1471 1.1 joerg // subaggregate, brace elision is assumed and the initializer is 1472 1.1 joerg // considered for the initialization of the first member of 1473 1.1 joerg // the subaggregate. 1474 1.1 joerg // OpenCL vector initializer is handled elsewhere. 1475 1.1 joerg if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) || 1476 1.1 joerg ElemType->isAggregateType()) { 1477 1.1 joerg CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList, 1478 1.1 joerg StructuredIndex); 1479 1.1 joerg ++StructuredIndex; 1480 1.1.1.2 joerg 1481 1.1.1.2 joerg // In C++20, brace elision is not permitted for a designated initializer. 1482 1.1.1.2 joerg if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) { 1483 1.1.1.2 joerg if (InOverloadResolution) 1484 1.1.1.2 joerg hadError = true; 1485 1.1.1.2 joerg if (!VerifyOnly) { 1486 1.1.1.2 joerg SemaRef.Diag(expr->getBeginLoc(), 1487 1.1.1.2 joerg diag::ext_designated_init_brace_elision) 1488 1.1.1.2 joerg << expr->getSourceRange() 1489 1.1.1.2 joerg << FixItHint::CreateInsertion(expr->getBeginLoc(), "{") 1490 1.1.1.2 joerg << FixItHint::CreateInsertion( 1491 1.1.1.2 joerg SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}"); 1492 1.1.1.2 joerg } 1493 1.1.1.2 joerg } 1494 1.1 joerg } else { 1495 1.1 joerg if (!VerifyOnly) { 1496 1.1 joerg // We cannot initialize this element, so let PerformCopyInitialization 1497 1.1 joerg // produce the appropriate diagnostic. We already checked that this 1498 1.1 joerg // initialization will fail. 1499 1.1 joerg ExprResult Copy = 1500 1.1 joerg SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr, 1501 1.1 joerg /*TopLevelOfInitList=*/true); 1502 1.1 joerg (void)Copy; 1503 1.1 joerg assert(Copy.isInvalid() && 1504 1.1 joerg "expected non-aggregate initialization to fail"); 1505 1.1 joerg } 1506 1.1 joerg hadError = true; 1507 1.1 joerg ++Index; 1508 1.1 joerg ++StructuredIndex; 1509 1.1 joerg } 1510 1.1 joerg } 1511 1.1 joerg 1512 1.1 joerg void InitListChecker::CheckComplexType(const InitializedEntity &Entity, 1513 1.1 joerg InitListExpr *IList, QualType DeclType, 1514 1.1 joerg unsigned &Index, 1515 1.1 joerg InitListExpr *StructuredList, 1516 1.1 joerg unsigned &StructuredIndex) { 1517 1.1 joerg assert(Index == 0 && "Index in explicit init list must be zero"); 1518 1.1 joerg 1519 1.1 joerg // As an extension, clang supports complex initializers, which initialize 1520 1.1 joerg // a complex number component-wise. When an explicit initializer list for 1521 1.1 joerg // a complex number contains two two initializers, this extension kicks in: 1522 1.1 joerg // it exepcts the initializer list to contain two elements convertible to 1523 1.1 joerg // the element type of the complex type. The first element initializes 1524 1.1 joerg // the real part, and the second element intitializes the imaginary part. 1525 1.1 joerg 1526 1.1 joerg if (IList->getNumInits() != 2) 1527 1.1 joerg return CheckScalarType(Entity, IList, DeclType, Index, StructuredList, 1528 1.1 joerg StructuredIndex); 1529 1.1 joerg 1530 1.1 joerg // This is an extension in C. (The builtin _Complex type does not exist 1531 1.1 joerg // in the C++ standard.) 1532 1.1 joerg if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly) 1533 1.1 joerg SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init) 1534 1.1 joerg << IList->getSourceRange(); 1535 1.1 joerg 1536 1.1 joerg // Initialize the complex number. 1537 1.1 joerg QualType elementType = DeclType->castAs<ComplexType>()->getElementType(); 1538 1.1 joerg InitializedEntity ElementEntity = 1539 1.1 joerg InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1540 1.1 joerg 1541 1.1 joerg for (unsigned i = 0; i < 2; ++i) { 1542 1.1 joerg ElementEntity.setElementIndex(Index); 1543 1.1 joerg CheckSubElementType(ElementEntity, IList, elementType, Index, 1544 1.1 joerg StructuredList, StructuredIndex); 1545 1.1 joerg } 1546 1.1 joerg } 1547 1.1 joerg 1548 1.1 joerg void InitListChecker::CheckScalarType(const InitializedEntity &Entity, 1549 1.1 joerg InitListExpr *IList, QualType DeclType, 1550 1.1 joerg unsigned &Index, 1551 1.1 joerg InitListExpr *StructuredList, 1552 1.1 joerg unsigned &StructuredIndex) { 1553 1.1 joerg if (Index >= IList->getNumInits()) { 1554 1.1.1.2 joerg if (!VerifyOnly) { 1555 1.1.1.2 joerg if (DeclType->isSizelessBuiltinType()) 1556 1.1.1.2 joerg SemaRef.Diag(IList->getBeginLoc(), 1557 1.1.1.2 joerg SemaRef.getLangOpts().CPlusPlus11 1558 1.1.1.2 joerg ? diag::warn_cxx98_compat_empty_sizeless_initializer 1559 1.1.1.2 joerg : diag::err_empty_sizeless_initializer) 1560 1.1.1.2 joerg << DeclType << IList->getSourceRange(); 1561 1.1.1.2 joerg else 1562 1.1.1.2 joerg SemaRef.Diag(IList->getBeginLoc(), 1563 1.1.1.2 joerg SemaRef.getLangOpts().CPlusPlus11 1564 1.1.1.2 joerg ? diag::warn_cxx98_compat_empty_scalar_initializer 1565 1.1.1.2 joerg : diag::err_empty_scalar_initializer) 1566 1.1.1.2 joerg << IList->getSourceRange(); 1567 1.1.1.2 joerg } 1568 1.1 joerg hadError = !SemaRef.getLangOpts().CPlusPlus11; 1569 1.1 joerg ++Index; 1570 1.1 joerg ++StructuredIndex; 1571 1.1 joerg return; 1572 1.1 joerg } 1573 1.1 joerg 1574 1.1 joerg Expr *expr = IList->getInit(Index); 1575 1.1 joerg if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) { 1576 1.1 joerg // FIXME: This is invalid, and accepting it causes overload resolution 1577 1.1 joerg // to pick the wrong overload in some corner cases. 1578 1.1 joerg if (!VerifyOnly) 1579 1.1.1.2 joerg SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init) 1580 1.1.1.2 joerg << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange(); 1581 1.1 joerg 1582 1.1 joerg CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList, 1583 1.1 joerg StructuredIndex); 1584 1.1 joerg return; 1585 1.1 joerg } else if (isa<DesignatedInitExpr>(expr)) { 1586 1.1 joerg if (!VerifyOnly) 1587 1.1.1.2 joerg SemaRef.Diag(expr->getBeginLoc(), 1588 1.1.1.2 joerg diag::err_designator_for_scalar_or_sizeless_init) 1589 1.1.1.2 joerg << DeclType->isSizelessBuiltinType() << DeclType 1590 1.1.1.2 joerg << expr->getSourceRange(); 1591 1.1 joerg hadError = true; 1592 1.1 joerg ++Index; 1593 1.1 joerg ++StructuredIndex; 1594 1.1 joerg return; 1595 1.1 joerg } 1596 1.1 joerg 1597 1.1 joerg ExprResult Result; 1598 1.1 joerg if (VerifyOnly) { 1599 1.1 joerg if (SemaRef.CanPerformCopyInitialization(Entity, expr)) 1600 1.1 joerg Result = getDummyInit(); 1601 1.1 joerg else 1602 1.1 joerg Result = ExprError(); 1603 1.1 joerg } else { 1604 1.1 joerg Result = 1605 1.1 joerg SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr, 1606 1.1 joerg /*TopLevelOfInitList=*/true); 1607 1.1 joerg } 1608 1.1 joerg 1609 1.1 joerg Expr *ResultExpr = nullptr; 1610 1.1 joerg 1611 1.1 joerg if (Result.isInvalid()) 1612 1.1 joerg hadError = true; // types weren't compatible. 1613 1.1 joerg else { 1614 1.1 joerg ResultExpr = Result.getAs<Expr>(); 1615 1.1 joerg 1616 1.1 joerg if (ResultExpr != expr && !VerifyOnly) { 1617 1.1 joerg // The type was promoted, update initializer list. 1618 1.1 joerg // FIXME: Why are we updating the syntactic init list? 1619 1.1 joerg IList->setInit(Index, ResultExpr); 1620 1.1 joerg } 1621 1.1 joerg } 1622 1.1.1.2 joerg UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); 1623 1.1 joerg ++Index; 1624 1.1 joerg } 1625 1.1 joerg 1626 1.1 joerg void InitListChecker::CheckReferenceType(const InitializedEntity &Entity, 1627 1.1 joerg InitListExpr *IList, QualType DeclType, 1628 1.1 joerg unsigned &Index, 1629 1.1 joerg InitListExpr *StructuredList, 1630 1.1 joerg unsigned &StructuredIndex) { 1631 1.1 joerg if (Index >= IList->getNumInits()) { 1632 1.1 joerg // FIXME: It would be wonderful if we could point at the actual member. In 1633 1.1 joerg // general, it would be useful to pass location information down the stack, 1634 1.1 joerg // so that we know the location (or decl) of the "current object" being 1635 1.1 joerg // initialized. 1636 1.1 joerg if (!VerifyOnly) 1637 1.1 joerg SemaRef.Diag(IList->getBeginLoc(), 1638 1.1 joerg diag::err_init_reference_member_uninitialized) 1639 1.1 joerg << DeclType << IList->getSourceRange(); 1640 1.1 joerg hadError = true; 1641 1.1 joerg ++Index; 1642 1.1 joerg ++StructuredIndex; 1643 1.1 joerg return; 1644 1.1 joerg } 1645 1.1 joerg 1646 1.1 joerg Expr *expr = IList->getInit(Index); 1647 1.1 joerg if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) { 1648 1.1 joerg if (!VerifyOnly) 1649 1.1 joerg SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list) 1650 1.1 joerg << DeclType << IList->getSourceRange(); 1651 1.1 joerg hadError = true; 1652 1.1 joerg ++Index; 1653 1.1 joerg ++StructuredIndex; 1654 1.1 joerg return; 1655 1.1 joerg } 1656 1.1 joerg 1657 1.1 joerg ExprResult Result; 1658 1.1 joerg if (VerifyOnly) { 1659 1.1 joerg if (SemaRef.CanPerformCopyInitialization(Entity,expr)) 1660 1.1 joerg Result = getDummyInit(); 1661 1.1 joerg else 1662 1.1 joerg Result = ExprError(); 1663 1.1 joerg } else { 1664 1.1 joerg Result = 1665 1.1 joerg SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr, 1666 1.1 joerg /*TopLevelOfInitList=*/true); 1667 1.1 joerg } 1668 1.1 joerg 1669 1.1 joerg if (Result.isInvalid()) 1670 1.1 joerg hadError = true; 1671 1.1 joerg 1672 1.1 joerg expr = Result.getAs<Expr>(); 1673 1.1 joerg // FIXME: Why are we updating the syntactic init list? 1674 1.1.1.2 joerg if (!VerifyOnly && expr) 1675 1.1 joerg IList->setInit(Index, expr); 1676 1.1 joerg 1677 1.1.1.2 joerg UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 1678 1.1 joerg ++Index; 1679 1.1 joerg } 1680 1.1 joerg 1681 1.1 joerg void InitListChecker::CheckVectorType(const InitializedEntity &Entity, 1682 1.1 joerg InitListExpr *IList, QualType DeclType, 1683 1.1 joerg unsigned &Index, 1684 1.1 joerg InitListExpr *StructuredList, 1685 1.1 joerg unsigned &StructuredIndex) { 1686 1.1 joerg const VectorType *VT = DeclType->castAs<VectorType>(); 1687 1.1 joerg unsigned maxElements = VT->getNumElements(); 1688 1.1 joerg unsigned numEltsInit = 0; 1689 1.1 joerg QualType elementType = VT->getElementType(); 1690 1.1 joerg 1691 1.1 joerg if (Index >= IList->getNumInits()) { 1692 1.1 joerg // Make sure the element type can be value-initialized. 1693 1.1 joerg CheckEmptyInitializable( 1694 1.1 joerg InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity), 1695 1.1 joerg IList->getEndLoc()); 1696 1.1 joerg return; 1697 1.1 joerg } 1698 1.1 joerg 1699 1.1 joerg if (!SemaRef.getLangOpts().OpenCL) { 1700 1.1 joerg // If the initializing element is a vector, try to copy-initialize 1701 1.1 joerg // instead of breaking it apart (which is doomed to failure anyway). 1702 1.1 joerg Expr *Init = IList->getInit(Index); 1703 1.1 joerg if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) { 1704 1.1 joerg ExprResult Result; 1705 1.1 joerg if (VerifyOnly) { 1706 1.1 joerg if (SemaRef.CanPerformCopyInitialization(Entity, Init)) 1707 1.1 joerg Result = getDummyInit(); 1708 1.1 joerg else 1709 1.1 joerg Result = ExprError(); 1710 1.1 joerg } else { 1711 1.1 joerg Result = 1712 1.1 joerg SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init, 1713 1.1 joerg /*TopLevelOfInitList=*/true); 1714 1.1 joerg } 1715 1.1 joerg 1716 1.1 joerg Expr *ResultExpr = nullptr; 1717 1.1 joerg if (Result.isInvalid()) 1718 1.1 joerg hadError = true; // types weren't compatible. 1719 1.1 joerg else { 1720 1.1 joerg ResultExpr = Result.getAs<Expr>(); 1721 1.1 joerg 1722 1.1 joerg if (ResultExpr != Init && !VerifyOnly) { 1723 1.1 joerg // The type was promoted, update initializer list. 1724 1.1 joerg // FIXME: Why are we updating the syntactic init list? 1725 1.1 joerg IList->setInit(Index, ResultExpr); 1726 1.1 joerg } 1727 1.1 joerg } 1728 1.1.1.2 joerg UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); 1729 1.1 joerg ++Index; 1730 1.1 joerg return; 1731 1.1 joerg } 1732 1.1 joerg 1733 1.1 joerg InitializedEntity ElementEntity = 1734 1.1 joerg InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1735 1.1 joerg 1736 1.1 joerg for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { 1737 1.1 joerg // Don't attempt to go past the end of the init list 1738 1.1 joerg if (Index >= IList->getNumInits()) { 1739 1.1 joerg CheckEmptyInitializable(ElementEntity, IList->getEndLoc()); 1740 1.1 joerg break; 1741 1.1 joerg } 1742 1.1 joerg 1743 1.1 joerg ElementEntity.setElementIndex(Index); 1744 1.1 joerg CheckSubElementType(ElementEntity, IList, elementType, Index, 1745 1.1 joerg StructuredList, StructuredIndex); 1746 1.1 joerg } 1747 1.1 joerg 1748 1.1 joerg if (VerifyOnly) 1749 1.1 joerg return; 1750 1.1 joerg 1751 1.1 joerg bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian(); 1752 1.1 joerg const VectorType *T = Entity.getType()->castAs<VectorType>(); 1753 1.1 joerg if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector || 1754 1.1 joerg T->getVectorKind() == VectorType::NeonPolyVector)) { 1755 1.1 joerg // The ability to use vector initializer lists is a GNU vector extension 1756 1.1 joerg // and is unrelated to the NEON intrinsics in arm_neon.h. On little 1757 1.1 joerg // endian machines it works fine, however on big endian machines it 1758 1.1 joerg // exhibits surprising behaviour: 1759 1.1 joerg // 1760 1.1 joerg // uint32x2_t x = {42, 64}; 1761 1.1 joerg // return vget_lane_u32(x, 0); // Will return 64. 1762 1.1 joerg // 1763 1.1 joerg // Because of this, explicitly call out that it is non-portable. 1764 1.1 joerg // 1765 1.1 joerg SemaRef.Diag(IList->getBeginLoc(), 1766 1.1 joerg diag::warn_neon_vector_initializer_non_portable); 1767 1.1 joerg 1768 1.1 joerg const char *typeCode; 1769 1.1 joerg unsigned typeSize = SemaRef.Context.getTypeSize(elementType); 1770 1.1 joerg 1771 1.1 joerg if (elementType->isFloatingType()) 1772 1.1 joerg typeCode = "f"; 1773 1.1 joerg else if (elementType->isSignedIntegerType()) 1774 1.1 joerg typeCode = "s"; 1775 1.1 joerg else if (elementType->isUnsignedIntegerType()) 1776 1.1 joerg typeCode = "u"; 1777 1.1 joerg else 1778 1.1 joerg llvm_unreachable("Invalid element type!"); 1779 1.1 joerg 1780 1.1 joerg SemaRef.Diag(IList->getBeginLoc(), 1781 1.1 joerg SemaRef.Context.getTypeSize(VT) > 64 1782 1.1 joerg ? diag::note_neon_vector_initializer_non_portable_q 1783 1.1 joerg : diag::note_neon_vector_initializer_non_portable) 1784 1.1 joerg << typeCode << typeSize; 1785 1.1 joerg } 1786 1.1 joerg 1787 1.1 joerg return; 1788 1.1 joerg } 1789 1.1 joerg 1790 1.1 joerg InitializedEntity ElementEntity = 1791 1.1 joerg InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1792 1.1 joerg 1793 1.1 joerg // OpenCL initializers allows vectors to be constructed from vectors. 1794 1.1 joerg for (unsigned i = 0; i < maxElements; ++i) { 1795 1.1 joerg // Don't attempt to go past the end of the init list 1796 1.1 joerg if (Index >= IList->getNumInits()) 1797 1.1 joerg break; 1798 1.1 joerg 1799 1.1 joerg ElementEntity.setElementIndex(Index); 1800 1.1 joerg 1801 1.1 joerg QualType IType = IList->getInit(Index)->getType(); 1802 1.1 joerg if (!IType->isVectorType()) { 1803 1.1 joerg CheckSubElementType(ElementEntity, IList, elementType, Index, 1804 1.1 joerg StructuredList, StructuredIndex); 1805 1.1 joerg ++numEltsInit; 1806 1.1 joerg } else { 1807 1.1 joerg QualType VecType; 1808 1.1 joerg const VectorType *IVT = IType->castAs<VectorType>(); 1809 1.1 joerg unsigned numIElts = IVT->getNumElements(); 1810 1.1 joerg 1811 1.1 joerg if (IType->isExtVectorType()) 1812 1.1 joerg VecType = SemaRef.Context.getExtVectorType(elementType, numIElts); 1813 1.1 joerg else 1814 1.1 joerg VecType = SemaRef.Context.getVectorType(elementType, numIElts, 1815 1.1 joerg IVT->getVectorKind()); 1816 1.1 joerg CheckSubElementType(ElementEntity, IList, VecType, Index, 1817 1.1 joerg StructuredList, StructuredIndex); 1818 1.1 joerg numEltsInit += numIElts; 1819 1.1 joerg } 1820 1.1 joerg } 1821 1.1 joerg 1822 1.1 joerg // OpenCL requires all elements to be initialized. 1823 1.1 joerg if (numEltsInit != maxElements) { 1824 1.1 joerg if (!VerifyOnly) 1825 1.1 joerg SemaRef.Diag(IList->getBeginLoc(), 1826 1.1 joerg diag::err_vector_incorrect_num_initializers) 1827 1.1 joerg << (numEltsInit < maxElements) << maxElements << numEltsInit; 1828 1.1 joerg hadError = true; 1829 1.1 joerg } 1830 1.1 joerg } 1831 1.1 joerg 1832 1.1 joerg /// Check if the type of a class element has an accessible destructor, and marks 1833 1.1 joerg /// it referenced. Returns true if we shouldn't form a reference to the 1834 1.1 joerg /// destructor. 1835 1.1 joerg /// 1836 1.1 joerg /// Aggregate initialization requires a class element's destructor be 1837 1.1 joerg /// accessible per 11.6.1 [dcl.init.aggr]: 1838 1.1 joerg /// 1839 1.1 joerg /// The destructor for each element of class type is potentially invoked 1840 1.1 joerg /// (15.4 [class.dtor]) from the context where the aggregate initialization 1841 1.1 joerg /// occurs. 1842 1.1 joerg static bool checkDestructorReference(QualType ElementType, SourceLocation Loc, 1843 1.1 joerg Sema &SemaRef) { 1844 1.1 joerg auto *CXXRD = ElementType->getAsCXXRecordDecl(); 1845 1.1 joerg if (!CXXRD) 1846 1.1 joerg return false; 1847 1.1 joerg 1848 1.1 joerg CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD); 1849 1.1 joerg SemaRef.CheckDestructorAccess(Loc, Destructor, 1850 1.1 joerg SemaRef.PDiag(diag::err_access_dtor_temp) 1851 1.1 joerg << ElementType); 1852 1.1 joerg SemaRef.MarkFunctionReferenced(Loc, Destructor); 1853 1.1 joerg return SemaRef.DiagnoseUseOfDecl(Destructor, Loc); 1854 1.1 joerg } 1855 1.1 joerg 1856 1.1 joerg void InitListChecker::CheckArrayType(const InitializedEntity &Entity, 1857 1.1 joerg InitListExpr *IList, QualType &DeclType, 1858 1.1 joerg llvm::APSInt elementIndex, 1859 1.1 joerg bool SubobjectIsDesignatorContext, 1860 1.1 joerg unsigned &Index, 1861 1.1 joerg InitListExpr *StructuredList, 1862 1.1 joerg unsigned &StructuredIndex) { 1863 1.1 joerg const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType); 1864 1.1 joerg 1865 1.1 joerg if (!VerifyOnly) { 1866 1.1 joerg if (checkDestructorReference(arrayType->getElementType(), 1867 1.1 joerg IList->getEndLoc(), SemaRef)) { 1868 1.1 joerg hadError = true; 1869 1.1 joerg return; 1870 1.1 joerg } 1871 1.1 joerg } 1872 1.1 joerg 1873 1.1 joerg // Check for the special-case of initializing an array with a string. 1874 1.1 joerg if (Index < IList->getNumInits()) { 1875 1.1 joerg if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) == 1876 1.1 joerg SIF_None) { 1877 1.1 joerg // We place the string literal directly into the resulting 1878 1.1 joerg // initializer list. This is the only place where the structure 1879 1.1 joerg // of the structured initializer list doesn't match exactly, 1880 1.1 joerg // because doing so would involve allocating one character 1881 1.1 joerg // constant for each string. 1882 1.1 joerg // FIXME: Should we do these checks in verify-only mode too? 1883 1.1 joerg if (!VerifyOnly) 1884 1.1 joerg CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef); 1885 1.1 joerg if (StructuredList) { 1886 1.1 joerg UpdateStructuredListElement(StructuredList, StructuredIndex, 1887 1.1 joerg IList->getInit(Index)); 1888 1.1 joerg StructuredList->resizeInits(SemaRef.Context, StructuredIndex); 1889 1.1 joerg } 1890 1.1 joerg ++Index; 1891 1.1 joerg return; 1892 1.1 joerg } 1893 1.1 joerg } 1894 1.1 joerg if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) { 1895 1.1 joerg // Check for VLAs; in standard C it would be possible to check this 1896 1.1 joerg // earlier, but I don't know where clang accepts VLAs (gcc accepts 1897 1.1 joerg // them in all sorts of strange places). 1898 1.1 joerg if (!VerifyOnly) 1899 1.1 joerg SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(), 1900 1.1 joerg diag::err_variable_object_no_init) 1901 1.1 joerg << VAT->getSizeExpr()->getSourceRange(); 1902 1.1 joerg hadError = true; 1903 1.1 joerg ++Index; 1904 1.1 joerg ++StructuredIndex; 1905 1.1 joerg return; 1906 1.1 joerg } 1907 1.1 joerg 1908 1.1 joerg // We might know the maximum number of elements in advance. 1909 1.1 joerg llvm::APSInt maxElements(elementIndex.getBitWidth(), 1910 1.1 joerg elementIndex.isUnsigned()); 1911 1.1 joerg bool maxElementsKnown = false; 1912 1.1 joerg if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) { 1913 1.1 joerg maxElements = CAT->getSize(); 1914 1.1 joerg elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth()); 1915 1.1 joerg elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1916 1.1 joerg maxElementsKnown = true; 1917 1.1 joerg } 1918 1.1 joerg 1919 1.1 joerg QualType elementType = arrayType->getElementType(); 1920 1.1 joerg while (Index < IList->getNumInits()) { 1921 1.1 joerg Expr *Init = IList->getInit(Index); 1922 1.1 joerg if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1923 1.1 joerg // If we're not the subobject that matches up with the '{' for 1924 1.1 joerg // the designator, we shouldn't be handling the 1925 1.1 joerg // designator. Return immediately. 1926 1.1 joerg if (!SubobjectIsDesignatorContext) 1927 1.1 joerg return; 1928 1.1 joerg 1929 1.1 joerg // Handle this designated initializer. elementIndex will be 1930 1.1 joerg // updated to be the next array element we'll initialize. 1931 1.1 joerg if (CheckDesignatedInitializer(Entity, IList, DIE, 0, 1932 1.1 joerg DeclType, nullptr, &elementIndex, Index, 1933 1.1 joerg StructuredList, StructuredIndex, true, 1934 1.1 joerg false)) { 1935 1.1 joerg hadError = true; 1936 1.1 joerg continue; 1937 1.1 joerg } 1938 1.1 joerg 1939 1.1 joerg if (elementIndex.getBitWidth() > maxElements.getBitWidth()) 1940 1.1 joerg maxElements = maxElements.extend(elementIndex.getBitWidth()); 1941 1.1 joerg else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) 1942 1.1 joerg elementIndex = elementIndex.extend(maxElements.getBitWidth()); 1943 1.1 joerg elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1944 1.1 joerg 1945 1.1 joerg // If the array is of incomplete type, keep track of the number of 1946 1.1 joerg // elements in the initializer. 1947 1.1 joerg if (!maxElementsKnown && elementIndex > maxElements) 1948 1.1 joerg maxElements = elementIndex; 1949 1.1 joerg 1950 1.1 joerg continue; 1951 1.1 joerg } 1952 1.1 joerg 1953 1.1 joerg // If we know the maximum number of elements, and we've already 1954 1.1 joerg // hit it, stop consuming elements in the initializer list. 1955 1.1 joerg if (maxElementsKnown && elementIndex == maxElements) 1956 1.1 joerg break; 1957 1.1 joerg 1958 1.1 joerg InitializedEntity ElementEntity = 1959 1.1 joerg InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex, 1960 1.1 joerg Entity); 1961 1.1 joerg // Check this element. 1962 1.1 joerg CheckSubElementType(ElementEntity, IList, elementType, Index, 1963 1.1 joerg StructuredList, StructuredIndex); 1964 1.1 joerg ++elementIndex; 1965 1.1 joerg 1966 1.1 joerg // If the array is of incomplete type, keep track of the number of 1967 1.1 joerg // elements in the initializer. 1968 1.1 joerg if (!maxElementsKnown && elementIndex > maxElements) 1969 1.1 joerg maxElements = elementIndex; 1970 1.1 joerg } 1971 1.1 joerg if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) { 1972 1.1 joerg // If this is an incomplete array type, the actual type needs to 1973 1.1 joerg // be calculated here. 1974 1.1 joerg llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); 1975 1.1 joerg if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) { 1976 1.1 joerg // Sizing an array implicitly to zero is not allowed by ISO C, 1977 1.1 joerg // but is supported by GNU. 1978 1.1 joerg SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size); 1979 1.1 joerg } 1980 1.1 joerg 1981 1.1 joerg DeclType = SemaRef.Context.getConstantArrayType( 1982 1.1 joerg elementType, maxElements, nullptr, ArrayType::Normal, 0); 1983 1.1 joerg } 1984 1.1 joerg if (!hadError) { 1985 1.1 joerg // If there are any members of the array that get value-initialized, check 1986 1.1 joerg // that is possible. That happens if we know the bound and don't have 1987 1.1 joerg // enough elements, or if we're performing an array new with an unknown 1988 1.1 joerg // bound. 1989 1.1 joerg if ((maxElementsKnown && elementIndex < maxElements) || 1990 1.1 joerg Entity.isVariableLengthArrayNew()) 1991 1.1 joerg CheckEmptyInitializable( 1992 1.1 joerg InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity), 1993 1.1 joerg IList->getEndLoc()); 1994 1.1 joerg } 1995 1.1 joerg } 1996 1.1 joerg 1997 1.1 joerg bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity, 1998 1.1 joerg Expr *InitExpr, 1999 1.1 joerg FieldDecl *Field, 2000 1.1 joerg bool TopLevelObject) { 2001 1.1 joerg // Handle GNU flexible array initializers. 2002 1.1 joerg unsigned FlexArrayDiag; 2003 1.1 joerg if (isa<InitListExpr>(InitExpr) && 2004 1.1 joerg cast<InitListExpr>(InitExpr)->getNumInits() == 0) { 2005 1.1 joerg // Empty flexible array init always allowed as an extension 2006 1.1 joerg FlexArrayDiag = diag::ext_flexible_array_init; 2007 1.1 joerg } else if (SemaRef.getLangOpts().CPlusPlus) { 2008 1.1 joerg // Disallow flexible array init in C++; it is not required for gcc 2009 1.1 joerg // compatibility, and it needs work to IRGen correctly in general. 2010 1.1 joerg FlexArrayDiag = diag::err_flexible_array_init; 2011 1.1 joerg } else if (!TopLevelObject) { 2012 1.1 joerg // Disallow flexible array init on non-top-level object 2013 1.1 joerg FlexArrayDiag = diag::err_flexible_array_init; 2014 1.1 joerg } else if (Entity.getKind() != InitializedEntity::EK_Variable) { 2015 1.1 joerg // Disallow flexible array init on anything which is not a variable. 2016 1.1 joerg FlexArrayDiag = diag::err_flexible_array_init; 2017 1.1 joerg } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) { 2018 1.1 joerg // Disallow flexible array init on local variables. 2019 1.1 joerg FlexArrayDiag = diag::err_flexible_array_init; 2020 1.1 joerg } else { 2021 1.1 joerg // Allow other cases. 2022 1.1 joerg FlexArrayDiag = diag::ext_flexible_array_init; 2023 1.1 joerg } 2024 1.1 joerg 2025 1.1 joerg if (!VerifyOnly) { 2026 1.1 joerg SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag) 2027 1.1 joerg << InitExpr->getBeginLoc(); 2028 1.1 joerg SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 2029 1.1 joerg << Field; 2030 1.1 joerg } 2031 1.1 joerg 2032 1.1 joerg return FlexArrayDiag != diag::ext_flexible_array_init; 2033 1.1 joerg } 2034 1.1 joerg 2035 1.1 joerg void InitListChecker::CheckStructUnionTypes( 2036 1.1 joerg const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, 2037 1.1 joerg CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field, 2038 1.1 joerg bool SubobjectIsDesignatorContext, unsigned &Index, 2039 1.1 joerg InitListExpr *StructuredList, unsigned &StructuredIndex, 2040 1.1 joerg bool TopLevelObject) { 2041 1.1 joerg RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl(); 2042 1.1 joerg 2043 1.1 joerg // If the record is invalid, some of it's members are invalid. To avoid 2044 1.1 joerg // confusion, we forgo checking the intializer for the entire record. 2045 1.1 joerg if (structDecl->isInvalidDecl()) { 2046 1.1 joerg // Assume it was supposed to consume a single initializer. 2047 1.1 joerg ++Index; 2048 1.1 joerg hadError = true; 2049 1.1 joerg return; 2050 1.1 joerg } 2051 1.1 joerg 2052 1.1 joerg if (DeclType->isUnionType() && IList->getNumInits() == 0) { 2053 1.1 joerg RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); 2054 1.1 joerg 2055 1.1 joerg if (!VerifyOnly) 2056 1.1 joerg for (FieldDecl *FD : RD->fields()) { 2057 1.1 joerg QualType ET = SemaRef.Context.getBaseElementType(FD->getType()); 2058 1.1 joerg if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) { 2059 1.1 joerg hadError = true; 2060 1.1 joerg return; 2061 1.1 joerg } 2062 1.1 joerg } 2063 1.1 joerg 2064 1.1 joerg // If there's a default initializer, use it. 2065 1.1 joerg if (isa<CXXRecordDecl>(RD) && 2066 1.1 joerg cast<CXXRecordDecl>(RD)->hasInClassInitializer()) { 2067 1.1 joerg if (!StructuredList) 2068 1.1 joerg return; 2069 1.1 joerg for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 2070 1.1 joerg Field != FieldEnd; ++Field) { 2071 1.1 joerg if (Field->hasInClassInitializer()) { 2072 1.1 joerg StructuredList->setInitializedFieldInUnion(*Field); 2073 1.1 joerg // FIXME: Actually build a CXXDefaultInitExpr? 2074 1.1 joerg return; 2075 1.1 joerg } 2076 1.1 joerg } 2077 1.1 joerg } 2078 1.1 joerg 2079 1.1 joerg // Value-initialize the first member of the union that isn't an unnamed 2080 1.1 joerg // bitfield. 2081 1.1 joerg for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 2082 1.1 joerg Field != FieldEnd; ++Field) { 2083 1.1 joerg if (!Field->isUnnamedBitfield()) { 2084 1.1 joerg CheckEmptyInitializable( 2085 1.1 joerg InitializedEntity::InitializeMember(*Field, &Entity), 2086 1.1 joerg IList->getEndLoc()); 2087 1.1 joerg if (StructuredList) 2088 1.1 joerg StructuredList->setInitializedFieldInUnion(*Field); 2089 1.1 joerg break; 2090 1.1 joerg } 2091 1.1 joerg } 2092 1.1 joerg return; 2093 1.1 joerg } 2094 1.1 joerg 2095 1.1 joerg bool InitializedSomething = false; 2096 1.1 joerg 2097 1.1 joerg // If we have any base classes, they are initialized prior to the fields. 2098 1.1 joerg for (auto &Base : Bases) { 2099 1.1 joerg Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr; 2100 1.1 joerg 2101 1.1 joerg // Designated inits always initialize fields, so if we see one, all 2102 1.1 joerg // remaining base classes have no explicit initializer. 2103 1.1 joerg if (Init && isa<DesignatedInitExpr>(Init)) 2104 1.1 joerg Init = nullptr; 2105 1.1 joerg 2106 1.1 joerg SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc(); 2107 1.1 joerg InitializedEntity BaseEntity = InitializedEntity::InitializeBase( 2108 1.1 joerg SemaRef.Context, &Base, false, &Entity); 2109 1.1 joerg if (Init) { 2110 1.1 joerg CheckSubElementType(BaseEntity, IList, Base.getType(), Index, 2111 1.1 joerg StructuredList, StructuredIndex); 2112 1.1 joerg InitializedSomething = true; 2113 1.1 joerg } else { 2114 1.1 joerg CheckEmptyInitializable(BaseEntity, InitLoc); 2115 1.1 joerg } 2116 1.1 joerg 2117 1.1 joerg if (!VerifyOnly) 2118 1.1 joerg if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) { 2119 1.1 joerg hadError = true; 2120 1.1 joerg return; 2121 1.1 joerg } 2122 1.1 joerg } 2123 1.1 joerg 2124 1.1 joerg // If structDecl is a forward declaration, this loop won't do 2125 1.1 joerg // anything except look at designated initializers; That's okay, 2126 1.1 joerg // because an error should get printed out elsewhere. It might be 2127 1.1 joerg // worthwhile to skip over the rest of the initializer, though. 2128 1.1 joerg RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); 2129 1.1 joerg RecordDecl::field_iterator FieldEnd = RD->field_end(); 2130 1.1 joerg bool CheckForMissingFields = 2131 1.1 joerg !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()); 2132 1.1 joerg bool HasDesignatedInit = false; 2133 1.1 joerg 2134 1.1 joerg while (Index < IList->getNumInits()) { 2135 1.1 joerg Expr *Init = IList->getInit(Index); 2136 1.1 joerg SourceLocation InitLoc = Init->getBeginLoc(); 2137 1.1 joerg 2138 1.1 joerg if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 2139 1.1 joerg // If we're not the subobject that matches up with the '{' for 2140 1.1 joerg // the designator, we shouldn't be handling the 2141 1.1 joerg // designator. Return immediately. 2142 1.1 joerg if (!SubobjectIsDesignatorContext) 2143 1.1 joerg return; 2144 1.1 joerg 2145 1.1 joerg HasDesignatedInit = true; 2146 1.1 joerg 2147 1.1 joerg // Handle this designated initializer. Field will be updated to 2148 1.1 joerg // the next field that we'll be initializing. 2149 1.1 joerg if (CheckDesignatedInitializer(Entity, IList, DIE, 0, 2150 1.1 joerg DeclType, &Field, nullptr, Index, 2151 1.1 joerg StructuredList, StructuredIndex, 2152 1.1 joerg true, TopLevelObject)) 2153 1.1 joerg hadError = true; 2154 1.1 joerg else if (!VerifyOnly) { 2155 1.1 joerg // Find the field named by the designated initializer. 2156 1.1 joerg RecordDecl::field_iterator F = RD->field_begin(); 2157 1.1 joerg while (std::next(F) != Field) 2158 1.1 joerg ++F; 2159 1.1 joerg QualType ET = SemaRef.Context.getBaseElementType(F->getType()); 2160 1.1 joerg if (checkDestructorReference(ET, InitLoc, SemaRef)) { 2161 1.1 joerg hadError = true; 2162 1.1 joerg return; 2163 1.1 joerg } 2164 1.1 joerg } 2165 1.1 joerg 2166 1.1 joerg InitializedSomething = true; 2167 1.1 joerg 2168 1.1 joerg // Disable check for missing fields when designators are used. 2169 1.1 joerg // This matches gcc behaviour. 2170 1.1 joerg CheckForMissingFields = false; 2171 1.1 joerg continue; 2172 1.1 joerg } 2173 1.1 joerg 2174 1.1 joerg if (Field == FieldEnd) { 2175 1.1 joerg // We've run out of fields. We're done. 2176 1.1 joerg break; 2177 1.1 joerg } 2178 1.1 joerg 2179 1.1 joerg // We've already initialized a member of a union. We're done. 2180 1.1 joerg if (InitializedSomething && DeclType->isUnionType()) 2181 1.1 joerg break; 2182 1.1 joerg 2183 1.1 joerg // If we've hit the flexible array member at the end, we're done. 2184 1.1 joerg if (Field->getType()->isIncompleteArrayType()) 2185 1.1 joerg break; 2186 1.1 joerg 2187 1.1 joerg if (Field->isUnnamedBitfield()) { 2188 1.1 joerg // Don't initialize unnamed bitfields, e.g. "int : 20;" 2189 1.1 joerg ++Field; 2190 1.1 joerg continue; 2191 1.1 joerg } 2192 1.1 joerg 2193 1.1 joerg // Make sure we can use this declaration. 2194 1.1 joerg bool InvalidUse; 2195 1.1 joerg if (VerifyOnly) 2196 1.1 joerg InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); 2197 1.1 joerg else 2198 1.1 joerg InvalidUse = SemaRef.DiagnoseUseOfDecl( 2199 1.1 joerg *Field, IList->getInit(Index)->getBeginLoc()); 2200 1.1 joerg if (InvalidUse) { 2201 1.1 joerg ++Index; 2202 1.1 joerg ++Field; 2203 1.1 joerg hadError = true; 2204 1.1 joerg continue; 2205 1.1 joerg } 2206 1.1 joerg 2207 1.1 joerg if (!VerifyOnly) { 2208 1.1 joerg QualType ET = SemaRef.Context.getBaseElementType(Field->getType()); 2209 1.1 joerg if (checkDestructorReference(ET, InitLoc, SemaRef)) { 2210 1.1 joerg hadError = true; 2211 1.1 joerg return; 2212 1.1 joerg } 2213 1.1 joerg } 2214 1.1 joerg 2215 1.1 joerg InitializedEntity MemberEntity = 2216 1.1 joerg InitializedEntity::InitializeMember(*Field, &Entity); 2217 1.1 joerg CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 2218 1.1 joerg StructuredList, StructuredIndex); 2219 1.1 joerg InitializedSomething = true; 2220 1.1 joerg 2221 1.1 joerg if (DeclType->isUnionType() && StructuredList) { 2222 1.1 joerg // Initialize the first field within the union. 2223 1.1 joerg StructuredList->setInitializedFieldInUnion(*Field); 2224 1.1 joerg } 2225 1.1 joerg 2226 1.1 joerg ++Field; 2227 1.1 joerg } 2228 1.1 joerg 2229 1.1 joerg // Emit warnings for missing struct field initializers. 2230 1.1 joerg if (!VerifyOnly && InitializedSomething && CheckForMissingFields && 2231 1.1 joerg Field != FieldEnd && !Field->getType()->isIncompleteArrayType() && 2232 1.1 joerg !DeclType->isUnionType()) { 2233 1.1 joerg // It is possible we have one or more unnamed bitfields remaining. 2234 1.1 joerg // Find first (if any) named field and emit warning. 2235 1.1 joerg for (RecordDecl::field_iterator it = Field, end = RD->field_end(); 2236 1.1 joerg it != end; ++it) { 2237 1.1 joerg if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) { 2238 1.1 joerg SemaRef.Diag(IList->getSourceRange().getEnd(), 2239 1.1 joerg diag::warn_missing_field_initializers) << *it; 2240 1.1 joerg break; 2241 1.1 joerg } 2242 1.1 joerg } 2243 1.1 joerg } 2244 1.1 joerg 2245 1.1 joerg // Check that any remaining fields can be value-initialized if we're not 2246 1.1 joerg // building a structured list. (If we are, we'll check this later.) 2247 1.1 joerg if (!StructuredList && Field != FieldEnd && !DeclType->isUnionType() && 2248 1.1 joerg !Field->getType()->isIncompleteArrayType()) { 2249 1.1 joerg for (; Field != FieldEnd && !hadError; ++Field) { 2250 1.1 joerg if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer()) 2251 1.1 joerg CheckEmptyInitializable( 2252 1.1 joerg InitializedEntity::InitializeMember(*Field, &Entity), 2253 1.1 joerg IList->getEndLoc()); 2254 1.1 joerg } 2255 1.1 joerg } 2256 1.1 joerg 2257 1.1 joerg // Check that the types of the remaining fields have accessible destructors. 2258 1.1 joerg if (!VerifyOnly) { 2259 1.1 joerg // If the initializer expression has a designated initializer, check the 2260 1.1 joerg // elements for which a designated initializer is not provided too. 2261 1.1 joerg RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin() 2262 1.1 joerg : Field; 2263 1.1 joerg for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) { 2264 1.1 joerg QualType ET = SemaRef.Context.getBaseElementType(I->getType()); 2265 1.1 joerg if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) { 2266 1.1 joerg hadError = true; 2267 1.1 joerg return; 2268 1.1 joerg } 2269 1.1 joerg } 2270 1.1 joerg } 2271 1.1 joerg 2272 1.1 joerg if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || 2273 1.1 joerg Index >= IList->getNumInits()) 2274 1.1 joerg return; 2275 1.1 joerg 2276 1.1 joerg if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field, 2277 1.1 joerg TopLevelObject)) { 2278 1.1 joerg hadError = true; 2279 1.1 joerg ++Index; 2280 1.1 joerg return; 2281 1.1 joerg } 2282 1.1 joerg 2283 1.1 joerg InitializedEntity MemberEntity = 2284 1.1 joerg InitializedEntity::InitializeMember(*Field, &Entity); 2285 1.1 joerg 2286 1.1 joerg if (isa<InitListExpr>(IList->getInit(Index))) 2287 1.1 joerg CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 2288 1.1 joerg StructuredList, StructuredIndex); 2289 1.1 joerg else 2290 1.1 joerg CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index, 2291 1.1 joerg StructuredList, StructuredIndex); 2292 1.1 joerg } 2293 1.1 joerg 2294 1.1 joerg /// Expand a field designator that refers to a member of an 2295 1.1 joerg /// anonymous struct or union into a series of field designators that 2296 1.1 joerg /// refers to the field within the appropriate subobject. 2297 1.1 joerg /// 2298 1.1 joerg static void ExpandAnonymousFieldDesignator(Sema &SemaRef, 2299 1.1 joerg DesignatedInitExpr *DIE, 2300 1.1 joerg unsigned DesigIdx, 2301 1.1 joerg IndirectFieldDecl *IndirectField) { 2302 1.1 joerg typedef DesignatedInitExpr::Designator Designator; 2303 1.1 joerg 2304 1.1 joerg // Build the replacement designators. 2305 1.1 joerg SmallVector<Designator, 4> Replacements; 2306 1.1 joerg for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(), 2307 1.1 joerg PE = IndirectField->chain_end(); PI != PE; ++PI) { 2308 1.1 joerg if (PI + 1 == PE) 2309 1.1 joerg Replacements.push_back(Designator((IdentifierInfo *)nullptr, 2310 1.1 joerg DIE->getDesignator(DesigIdx)->getDotLoc(), 2311 1.1 joerg DIE->getDesignator(DesigIdx)->getFieldLoc())); 2312 1.1 joerg else 2313 1.1 joerg Replacements.push_back(Designator((IdentifierInfo *)nullptr, 2314 1.1 joerg SourceLocation(), SourceLocation())); 2315 1.1 joerg assert(isa<FieldDecl>(*PI)); 2316 1.1 joerg Replacements.back().setField(cast<FieldDecl>(*PI)); 2317 1.1 joerg } 2318 1.1 joerg 2319 1.1 joerg // Expand the current designator into the set of replacement 2320 1.1 joerg // designators, so we have a full subobject path down to where the 2321 1.1 joerg // member of the anonymous struct/union is actually stored. 2322 1.1 joerg DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0], 2323 1.1 joerg &Replacements[0] + Replacements.size()); 2324 1.1 joerg } 2325 1.1 joerg 2326 1.1 joerg static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef, 2327 1.1 joerg DesignatedInitExpr *DIE) { 2328 1.1 joerg unsigned NumIndexExprs = DIE->getNumSubExprs() - 1; 2329 1.1 joerg SmallVector<Expr*, 4> IndexExprs(NumIndexExprs); 2330 1.1 joerg for (unsigned I = 0; I < NumIndexExprs; ++I) 2331 1.1 joerg IndexExprs[I] = DIE->getSubExpr(I + 1); 2332 1.1 joerg return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(), 2333 1.1 joerg IndexExprs, 2334 1.1 joerg DIE->getEqualOrColonLoc(), 2335 1.1 joerg DIE->usesGNUSyntax(), DIE->getInit()); 2336 1.1 joerg } 2337 1.1 joerg 2338 1.1 joerg namespace { 2339 1.1 joerg 2340 1.1 joerg // Callback to only accept typo corrections that are for field members of 2341 1.1 joerg // the given struct or union. 2342 1.1 joerg class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback { 2343 1.1 joerg public: 2344 1.1 joerg explicit FieldInitializerValidatorCCC(RecordDecl *RD) 2345 1.1 joerg : Record(RD) {} 2346 1.1 joerg 2347 1.1 joerg bool ValidateCandidate(const TypoCorrection &candidate) override { 2348 1.1 joerg FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>(); 2349 1.1 joerg return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record); 2350 1.1 joerg } 2351 1.1 joerg 2352 1.1 joerg std::unique_ptr<CorrectionCandidateCallback> clone() override { 2353 1.1 joerg return std::make_unique<FieldInitializerValidatorCCC>(*this); 2354 1.1 joerg } 2355 1.1 joerg 2356 1.1 joerg private: 2357 1.1 joerg RecordDecl *Record; 2358 1.1 joerg }; 2359 1.1 joerg 2360 1.1 joerg } // end anonymous namespace 2361 1.1 joerg 2362 1.1 joerg /// Check the well-formedness of a C99 designated initializer. 2363 1.1 joerg /// 2364 1.1 joerg /// Determines whether the designated initializer @p DIE, which 2365 1.1 joerg /// resides at the given @p Index within the initializer list @p 2366 1.1 joerg /// IList, is well-formed for a current object of type @p DeclType 2367 1.1 joerg /// (C99 6.7.8). The actual subobject that this designator refers to 2368 1.1 joerg /// within the current subobject is returned in either 2369 1.1 joerg /// @p NextField or @p NextElementIndex (whichever is appropriate). 2370 1.1 joerg /// 2371 1.1 joerg /// @param IList The initializer list in which this designated 2372 1.1 joerg /// initializer occurs. 2373 1.1 joerg /// 2374 1.1 joerg /// @param DIE The designated initializer expression. 2375 1.1 joerg /// 2376 1.1 joerg /// @param DesigIdx The index of the current designator. 2377 1.1 joerg /// 2378 1.1 joerg /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17), 2379 1.1 joerg /// into which the designation in @p DIE should refer. 2380 1.1 joerg /// 2381 1.1 joerg /// @param NextField If non-NULL and the first designator in @p DIE is 2382 1.1 joerg /// a field, this will be set to the field declaration corresponding 2383 1.1 joerg /// to the field named by the designator. On input, this is expected to be 2384 1.1 joerg /// the next field that would be initialized in the absence of designation, 2385 1.1 joerg /// if the complete object being initialized is a struct. 2386 1.1 joerg /// 2387 1.1 joerg /// @param NextElementIndex If non-NULL and the first designator in @p 2388 1.1 joerg /// DIE is an array designator or GNU array-range designator, this 2389 1.1 joerg /// will be set to the last index initialized by this designator. 2390 1.1 joerg /// 2391 1.1 joerg /// @param Index Index into @p IList where the designated initializer 2392 1.1 joerg /// @p DIE occurs. 2393 1.1 joerg /// 2394 1.1 joerg /// @param StructuredList The initializer list expression that 2395 1.1 joerg /// describes all of the subobject initializers in the order they'll 2396 1.1 joerg /// actually be initialized. 2397 1.1 joerg /// 2398 1.1 joerg /// @returns true if there was an error, false otherwise. 2399 1.1 joerg bool 2400 1.1 joerg InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, 2401 1.1 joerg InitListExpr *IList, 2402 1.1 joerg DesignatedInitExpr *DIE, 2403 1.1 joerg unsigned DesigIdx, 2404 1.1 joerg QualType &CurrentObjectType, 2405 1.1 joerg RecordDecl::field_iterator *NextField, 2406 1.1 joerg llvm::APSInt *NextElementIndex, 2407 1.1 joerg unsigned &Index, 2408 1.1 joerg InitListExpr *StructuredList, 2409 1.1 joerg unsigned &StructuredIndex, 2410 1.1 joerg bool FinishSubobjectInit, 2411 1.1 joerg bool TopLevelObject) { 2412 1.1 joerg if (DesigIdx == DIE->size()) { 2413 1.1 joerg // C++20 designated initialization can result in direct-list-initialization 2414 1.1 joerg // of the designated subobject. This is the only way that we can end up 2415 1.1 joerg // performing direct initialization as part of aggregate initialization, so 2416 1.1 joerg // it needs special handling. 2417 1.1 joerg if (DIE->isDirectInit()) { 2418 1.1 joerg Expr *Init = DIE->getInit(); 2419 1.1 joerg assert(isa<InitListExpr>(Init) && 2420 1.1 joerg "designator result in direct non-list initialization?"); 2421 1.1 joerg InitializationKind Kind = InitializationKind::CreateDirectList( 2422 1.1 joerg DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc()); 2423 1.1 joerg InitializationSequence Seq(SemaRef, Entity, Kind, Init, 2424 1.1 joerg /*TopLevelOfInitList*/ true); 2425 1.1 joerg if (StructuredList) { 2426 1.1 joerg ExprResult Result = VerifyOnly 2427 1.1 joerg ? getDummyInit() 2428 1.1 joerg : Seq.Perform(SemaRef, Entity, Kind, Init); 2429 1.1 joerg UpdateStructuredListElement(StructuredList, StructuredIndex, 2430 1.1 joerg Result.get()); 2431 1.1 joerg } 2432 1.1 joerg ++Index; 2433 1.1 joerg return !Seq; 2434 1.1 joerg } 2435 1.1 joerg 2436 1.1 joerg // Check the actual initialization for the designated object type. 2437 1.1 joerg bool prevHadError = hadError; 2438 1.1 joerg 2439 1.1 joerg // Temporarily remove the designator expression from the 2440 1.1 joerg // initializer list that the child calls see, so that we don't try 2441 1.1 joerg // to re-process the designator. 2442 1.1 joerg unsigned OldIndex = Index; 2443 1.1 joerg IList->setInit(OldIndex, DIE->getInit()); 2444 1.1 joerg 2445 1.1.1.2 joerg CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList, 2446 1.1.1.2 joerg StructuredIndex, /*DirectlyDesignated=*/true); 2447 1.1 joerg 2448 1.1 joerg // Restore the designated initializer expression in the syntactic 2449 1.1 joerg // form of the initializer list. 2450 1.1 joerg if (IList->getInit(OldIndex) != DIE->getInit()) 2451 1.1 joerg DIE->setInit(IList->getInit(OldIndex)); 2452 1.1 joerg IList->setInit(OldIndex, DIE); 2453 1.1 joerg 2454 1.1 joerg return hadError && !prevHadError; 2455 1.1 joerg } 2456 1.1 joerg 2457 1.1 joerg DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); 2458 1.1 joerg bool IsFirstDesignator = (DesigIdx == 0); 2459 1.1 joerg if (IsFirstDesignator ? FullyStructuredList : StructuredList) { 2460 1.1 joerg // Determine the structural initializer list that corresponds to the 2461 1.1 joerg // current subobject. 2462 1.1 joerg if (IsFirstDesignator) 2463 1.1 joerg StructuredList = FullyStructuredList; 2464 1.1 joerg else { 2465 1.1 joerg Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ? 2466 1.1 joerg StructuredList->getInit(StructuredIndex) : nullptr; 2467 1.1 joerg if (!ExistingInit && StructuredList->hasArrayFiller()) 2468 1.1 joerg ExistingInit = StructuredList->getArrayFiller(); 2469 1.1 joerg 2470 1.1 joerg if (!ExistingInit) 2471 1.1 joerg StructuredList = getStructuredSubobjectInit( 2472 1.1 joerg IList, Index, CurrentObjectType, StructuredList, StructuredIndex, 2473 1.1 joerg SourceRange(D->getBeginLoc(), DIE->getEndLoc())); 2474 1.1 joerg else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit)) 2475 1.1 joerg StructuredList = Result; 2476 1.1 joerg else { 2477 1.1 joerg // We are creating an initializer list that initializes the 2478 1.1 joerg // subobjects of the current object, but there was already an 2479 1.1 joerg // initialization that completely initialized the current 2480 1.1 joerg // subobject, e.g., by a compound literal: 2481 1.1 joerg // 2482 1.1 joerg // struct X { int a, b; }; 2483 1.1 joerg // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 2484 1.1 joerg // 2485 1.1 joerg // Here, xs[0].a == 1 and xs[0].b == 3, since the second, 2486 1.1 joerg // designated initializer re-initializes only its current object 2487 1.1 joerg // subobject [0].b. 2488 1.1 joerg diagnoseInitOverride(ExistingInit, 2489 1.1 joerg SourceRange(D->getBeginLoc(), DIE->getEndLoc()), 2490 1.1 joerg /*FullyOverwritten=*/false); 2491 1.1 joerg 2492 1.1 joerg if (!VerifyOnly) { 2493 1.1 joerg if (DesignatedInitUpdateExpr *E = 2494 1.1 joerg dyn_cast<DesignatedInitUpdateExpr>(ExistingInit)) 2495 1.1 joerg StructuredList = E->getUpdater(); 2496 1.1 joerg else { 2497 1.1 joerg DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context) 2498 1.1 joerg DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(), 2499 1.1 joerg ExistingInit, DIE->getEndLoc()); 2500 1.1 joerg StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE); 2501 1.1 joerg StructuredList = DIUE->getUpdater(); 2502 1.1 joerg } 2503 1.1 joerg } else { 2504 1.1 joerg // We don't need to track the structured representation of a 2505 1.1 joerg // designated init update of an already-fully-initialized object in 2506 1.1 joerg // verify-only mode. The only reason we would need the structure is 2507 1.1 joerg // to determine where the uninitialized "holes" are, and in this 2508 1.1 joerg // case, we know there aren't any and we can't introduce any. 2509 1.1 joerg StructuredList = nullptr; 2510 1.1 joerg } 2511 1.1 joerg } 2512 1.1 joerg } 2513 1.1 joerg } 2514 1.1 joerg 2515 1.1 joerg if (D->isFieldDesignator()) { 2516 1.1 joerg // C99 6.7.8p7: 2517 1.1 joerg // 2518 1.1 joerg // If a designator has the form 2519 1.1 joerg // 2520 1.1 joerg // . identifier 2521 1.1 joerg // 2522 1.1 joerg // then the current object (defined below) shall have 2523 1.1 joerg // structure or union type and the identifier shall be the 2524 1.1 joerg // name of a member of that type. 2525 1.1 joerg const RecordType *RT = CurrentObjectType->getAs<RecordType>(); 2526 1.1 joerg if (!RT) { 2527 1.1 joerg SourceLocation Loc = D->getDotLoc(); 2528 1.1 joerg if (Loc.isInvalid()) 2529 1.1 joerg Loc = D->getFieldLoc(); 2530 1.1 joerg if (!VerifyOnly) 2531 1.1 joerg SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) 2532 1.1 joerg << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType; 2533 1.1 joerg ++Index; 2534 1.1 joerg return true; 2535 1.1 joerg } 2536 1.1 joerg 2537 1.1 joerg FieldDecl *KnownField = D->getField(); 2538 1.1 joerg if (!KnownField) { 2539 1.1 joerg IdentifierInfo *FieldName = D->getFieldName(); 2540 1.1 joerg DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); 2541 1.1 joerg for (NamedDecl *ND : Lookup) { 2542 1.1 joerg if (auto *FD = dyn_cast<FieldDecl>(ND)) { 2543 1.1 joerg KnownField = FD; 2544 1.1 joerg break; 2545 1.1 joerg } 2546 1.1 joerg if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) { 2547 1.1 joerg // In verify mode, don't modify the original. 2548 1.1 joerg if (VerifyOnly) 2549 1.1 joerg DIE = CloneDesignatedInitExpr(SemaRef, DIE); 2550 1.1 joerg ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD); 2551 1.1 joerg D = DIE->getDesignator(DesigIdx); 2552 1.1 joerg KnownField = cast<FieldDecl>(*IFD->chain_begin()); 2553 1.1 joerg break; 2554 1.1 joerg } 2555 1.1 joerg } 2556 1.1 joerg if (!KnownField) { 2557 1.1 joerg if (VerifyOnly) { 2558 1.1 joerg ++Index; 2559 1.1 joerg return true; // No typo correction when just trying this out. 2560 1.1 joerg } 2561 1.1 joerg 2562 1.1 joerg // Name lookup found something, but it wasn't a field. 2563 1.1 joerg if (!Lookup.empty()) { 2564 1.1 joerg SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) 2565 1.1 joerg << FieldName; 2566 1.1 joerg SemaRef.Diag(Lookup.front()->getLocation(), 2567 1.1 joerg diag::note_field_designator_found); 2568 1.1 joerg ++Index; 2569 1.1 joerg return true; 2570 1.1 joerg } 2571 1.1 joerg 2572 1.1 joerg // Name lookup didn't find anything. 2573 1.1 joerg // Determine whether this was a typo for another field name. 2574 1.1 joerg FieldInitializerValidatorCCC CCC(RT->getDecl()); 2575 1.1 joerg if (TypoCorrection Corrected = SemaRef.CorrectTypo( 2576 1.1 joerg DeclarationNameInfo(FieldName, D->getFieldLoc()), 2577 1.1 joerg Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC, 2578 1.1 joerg Sema::CTK_ErrorRecovery, RT->getDecl())) { 2579 1.1 joerg SemaRef.diagnoseTypo( 2580 1.1 joerg Corrected, 2581 1.1 joerg SemaRef.PDiag(diag::err_field_designator_unknown_suggest) 2582 1.1 joerg << FieldName << CurrentObjectType); 2583 1.1 joerg KnownField = Corrected.getCorrectionDeclAs<FieldDecl>(); 2584 1.1 joerg hadError = true; 2585 1.1 joerg } else { 2586 1.1 joerg // Typo correction didn't find anything. 2587 1.1 joerg SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) 2588 1.1 joerg << FieldName << CurrentObjectType; 2589 1.1 joerg ++Index; 2590 1.1 joerg return true; 2591 1.1 joerg } 2592 1.1 joerg } 2593 1.1 joerg } 2594 1.1 joerg 2595 1.1 joerg unsigned NumBases = 0; 2596 1.1 joerg if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2597 1.1 joerg NumBases = CXXRD->getNumBases(); 2598 1.1 joerg 2599 1.1 joerg unsigned FieldIndex = NumBases; 2600 1.1 joerg 2601 1.1 joerg for (auto *FI : RT->getDecl()->fields()) { 2602 1.1 joerg if (FI->isUnnamedBitfield()) 2603 1.1 joerg continue; 2604 1.1 joerg if (declaresSameEntity(KnownField, FI)) { 2605 1.1 joerg KnownField = FI; 2606 1.1 joerg break; 2607 1.1 joerg } 2608 1.1 joerg ++FieldIndex; 2609 1.1 joerg } 2610 1.1 joerg 2611 1.1 joerg RecordDecl::field_iterator Field = 2612 1.1 joerg RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField)); 2613 1.1 joerg 2614 1.1 joerg // All of the fields of a union are located at the same place in 2615 1.1 joerg // the initializer list. 2616 1.1 joerg if (RT->getDecl()->isUnion()) { 2617 1.1 joerg FieldIndex = 0; 2618 1.1 joerg if (StructuredList) { 2619 1.1 joerg FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion(); 2620 1.1 joerg if (CurrentField && !declaresSameEntity(CurrentField, *Field)) { 2621 1.1 joerg assert(StructuredList->getNumInits() == 1 2622 1.1 joerg && "A union should never have more than one initializer!"); 2623 1.1 joerg 2624 1.1 joerg Expr *ExistingInit = StructuredList->getInit(0); 2625 1.1 joerg if (ExistingInit) { 2626 1.1 joerg // We're about to throw away an initializer, emit warning. 2627 1.1 joerg diagnoseInitOverride( 2628 1.1 joerg ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc())); 2629 1.1 joerg } 2630 1.1 joerg 2631 1.1 joerg // remove existing initializer 2632 1.1 joerg StructuredList->resizeInits(SemaRef.Context, 0); 2633 1.1 joerg StructuredList->setInitializedFieldInUnion(nullptr); 2634 1.1 joerg } 2635 1.1 joerg 2636 1.1 joerg StructuredList->setInitializedFieldInUnion(*Field); 2637 1.1 joerg } 2638 1.1 joerg } 2639 1.1 joerg 2640 1.1 joerg // Make sure we can use this declaration. 2641 1.1 joerg bool InvalidUse; 2642 1.1 joerg if (VerifyOnly) 2643 1.1 joerg InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); 2644 1.1 joerg else 2645 1.1 joerg InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc()); 2646 1.1 joerg if (InvalidUse) { 2647 1.1 joerg ++Index; 2648 1.1 joerg return true; 2649 1.1 joerg } 2650 1.1 joerg 2651 1.1 joerg // C++20 [dcl.init.list]p3: 2652 1.1 joerg // The ordered identifiers in the designators of the designated- 2653 1.1 joerg // initializer-list shall form a subsequence of the ordered identifiers 2654 1.1 joerg // in the direct non-static data members of T. 2655 1.1 joerg // 2656 1.1 joerg // Note that this is not a condition on forming the aggregate 2657 1.1 joerg // initialization, only on actually performing initialization, 2658 1.1 joerg // so it is not checked in VerifyOnly mode. 2659 1.1 joerg // 2660 1.1 joerg // FIXME: This is the only reordering diagnostic we produce, and it only 2661 1.1 joerg // catches cases where we have a top-level field designator that jumps 2662 1.1 joerg // backwards. This is the only such case that is reachable in an 2663 1.1 joerg // otherwise-valid C++20 program, so is the only case that's required for 2664 1.1 joerg // conformance, but for consistency, we should diagnose all the other 2665 1.1 joerg // cases where a designator takes us backwards too. 2666 1.1 joerg if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus && 2667 1.1 joerg NextField && 2668 1.1 joerg (*NextField == RT->getDecl()->field_end() || 2669 1.1 joerg (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) { 2670 1.1 joerg // Find the field that we just initialized. 2671 1.1 joerg FieldDecl *PrevField = nullptr; 2672 1.1 joerg for (auto FI = RT->getDecl()->field_begin(); 2673 1.1 joerg FI != RT->getDecl()->field_end(); ++FI) { 2674 1.1 joerg if (FI->isUnnamedBitfield()) 2675 1.1 joerg continue; 2676 1.1 joerg if (*NextField != RT->getDecl()->field_end() && 2677 1.1 joerg declaresSameEntity(*FI, **NextField)) 2678 1.1 joerg break; 2679 1.1 joerg PrevField = *FI; 2680 1.1 joerg } 2681 1.1 joerg 2682 1.1 joerg if (PrevField && 2683 1.1 joerg PrevField->getFieldIndex() > KnownField->getFieldIndex()) { 2684 1.1 joerg SemaRef.Diag(DIE->getBeginLoc(), diag::ext_designated_init_reordered) 2685 1.1 joerg << KnownField << PrevField << DIE->getSourceRange(); 2686 1.1 joerg 2687 1.1 joerg unsigned OldIndex = NumBases + PrevField->getFieldIndex(); 2688 1.1 joerg if (StructuredList && OldIndex <= StructuredList->getNumInits()) { 2689 1.1 joerg if (Expr *PrevInit = StructuredList->getInit(OldIndex)) { 2690 1.1 joerg SemaRef.Diag(PrevInit->getBeginLoc(), 2691 1.1 joerg diag::note_previous_field_init) 2692 1.1 joerg << PrevField << PrevInit->getSourceRange(); 2693 1.1 joerg } 2694 1.1 joerg } 2695 1.1 joerg } 2696 1.1 joerg } 2697 1.1 joerg 2698 1.1 joerg 2699 1.1 joerg // Update the designator with the field declaration. 2700 1.1 joerg if (!VerifyOnly) 2701 1.1 joerg D->setField(*Field); 2702 1.1 joerg 2703 1.1 joerg // Make sure that our non-designated initializer list has space 2704 1.1 joerg // for a subobject corresponding to this field. 2705 1.1 joerg if (StructuredList && FieldIndex >= StructuredList->getNumInits()) 2706 1.1 joerg StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); 2707 1.1 joerg 2708 1.1 joerg // This designator names a flexible array member. 2709 1.1 joerg if (Field->getType()->isIncompleteArrayType()) { 2710 1.1 joerg bool Invalid = false; 2711 1.1 joerg if ((DesigIdx + 1) != DIE->size()) { 2712 1.1 joerg // We can't designate an object within the flexible array 2713 1.1 joerg // member (because GCC doesn't allow it). 2714 1.1 joerg if (!VerifyOnly) { 2715 1.1 joerg DesignatedInitExpr::Designator *NextD 2716 1.1 joerg = DIE->getDesignator(DesigIdx + 1); 2717 1.1 joerg SemaRef.Diag(NextD->getBeginLoc(), 2718 1.1 joerg diag::err_designator_into_flexible_array_member) 2719 1.1 joerg << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc()); 2720 1.1 joerg SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 2721 1.1 joerg << *Field; 2722 1.1 joerg } 2723 1.1 joerg Invalid = true; 2724 1.1 joerg } 2725 1.1 joerg 2726 1.1 joerg if (!hadError && !isa<InitListExpr>(DIE->getInit()) && 2727 1.1 joerg !isa<StringLiteral>(DIE->getInit())) { 2728 1.1 joerg // The initializer is not an initializer list. 2729 1.1 joerg if (!VerifyOnly) { 2730 1.1 joerg SemaRef.Diag(DIE->getInit()->getBeginLoc(), 2731 1.1 joerg diag::err_flexible_array_init_needs_braces) 2732 1.1 joerg << DIE->getInit()->getSourceRange(); 2733 1.1 joerg SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 2734 1.1 joerg << *Field; 2735 1.1 joerg } 2736 1.1 joerg Invalid = true; 2737 1.1 joerg } 2738 1.1 joerg 2739 1.1 joerg // Check GNU flexible array initializer. 2740 1.1 joerg if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field, 2741 1.1 joerg TopLevelObject)) 2742 1.1 joerg Invalid = true; 2743 1.1 joerg 2744 1.1 joerg if (Invalid) { 2745 1.1 joerg ++Index; 2746 1.1 joerg return true; 2747 1.1 joerg } 2748 1.1 joerg 2749 1.1 joerg // Initialize the array. 2750 1.1 joerg bool prevHadError = hadError; 2751 1.1 joerg unsigned newStructuredIndex = FieldIndex; 2752 1.1 joerg unsigned OldIndex = Index; 2753 1.1 joerg IList->setInit(Index, DIE->getInit()); 2754 1.1 joerg 2755 1.1 joerg InitializedEntity MemberEntity = 2756 1.1 joerg InitializedEntity::InitializeMember(*Field, &Entity); 2757 1.1 joerg CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 2758 1.1 joerg StructuredList, newStructuredIndex); 2759 1.1 joerg 2760 1.1 joerg IList->setInit(OldIndex, DIE); 2761 1.1 joerg if (hadError && !prevHadError) { 2762 1.1 joerg ++Field; 2763 1.1 joerg ++FieldIndex; 2764 1.1 joerg if (NextField) 2765 1.1 joerg *NextField = Field; 2766 1.1 joerg StructuredIndex = FieldIndex; 2767 1.1 joerg return true; 2768 1.1 joerg } 2769 1.1 joerg } else { 2770 1.1 joerg // Recurse to check later designated subobjects. 2771 1.1 joerg QualType FieldType = Field->getType(); 2772 1.1 joerg unsigned newStructuredIndex = FieldIndex; 2773 1.1 joerg 2774 1.1 joerg InitializedEntity MemberEntity = 2775 1.1 joerg InitializedEntity::InitializeMember(*Field, &Entity); 2776 1.1 joerg if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1, 2777 1.1 joerg FieldType, nullptr, nullptr, Index, 2778 1.1 joerg StructuredList, newStructuredIndex, 2779 1.1 joerg FinishSubobjectInit, false)) 2780 1.1 joerg return true; 2781 1.1 joerg } 2782 1.1 joerg 2783 1.1 joerg // Find the position of the next field to be initialized in this 2784 1.1 joerg // subobject. 2785 1.1 joerg ++Field; 2786 1.1 joerg ++FieldIndex; 2787 1.1 joerg 2788 1.1 joerg // If this the first designator, our caller will continue checking 2789 1.1 joerg // the rest of this struct/class/union subobject. 2790 1.1 joerg if (IsFirstDesignator) { 2791 1.1 joerg if (NextField) 2792 1.1 joerg *NextField = Field; 2793 1.1 joerg StructuredIndex = FieldIndex; 2794 1.1 joerg return false; 2795 1.1 joerg } 2796 1.1 joerg 2797 1.1 joerg if (!FinishSubobjectInit) 2798 1.1 joerg return false; 2799 1.1 joerg 2800 1.1 joerg // We've already initialized something in the union; we're done. 2801 1.1 joerg if (RT->getDecl()->isUnion()) 2802 1.1 joerg return hadError; 2803 1.1 joerg 2804 1.1 joerg // Check the remaining fields within this class/struct/union subobject. 2805 1.1 joerg bool prevHadError = hadError; 2806 1.1 joerg 2807 1.1 joerg auto NoBases = 2808 1.1 joerg CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), 2809 1.1 joerg CXXRecordDecl::base_class_iterator()); 2810 1.1 joerg CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field, 2811 1.1 joerg false, Index, StructuredList, FieldIndex); 2812 1.1 joerg return hadError && !prevHadError; 2813 1.1 joerg } 2814 1.1 joerg 2815 1.1 joerg // C99 6.7.8p6: 2816 1.1 joerg // 2817 1.1 joerg // If a designator has the form 2818 1.1 joerg // 2819 1.1 joerg // [ constant-expression ] 2820 1.1 joerg // 2821 1.1 joerg // then the current object (defined below) shall have array 2822 1.1 joerg // type and the expression shall be an integer constant 2823 1.1 joerg // expression. If the array is of unknown size, any 2824 1.1 joerg // nonnegative value is valid. 2825 1.1 joerg // 2826 1.1 joerg // Additionally, cope with the GNU extension that permits 2827 1.1 joerg // designators of the form 2828 1.1 joerg // 2829 1.1 joerg // [ constant-expression ... constant-expression ] 2830 1.1 joerg const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); 2831 1.1 joerg if (!AT) { 2832 1.1 joerg if (!VerifyOnly) 2833 1.1 joerg SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) 2834 1.1 joerg << CurrentObjectType; 2835 1.1 joerg ++Index; 2836 1.1 joerg return true; 2837 1.1 joerg } 2838 1.1 joerg 2839 1.1 joerg Expr *IndexExpr = nullptr; 2840 1.1 joerg llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; 2841 1.1 joerg if (D->isArrayDesignator()) { 2842 1.1 joerg IndexExpr = DIE->getArrayIndex(*D); 2843 1.1 joerg DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context); 2844 1.1 joerg DesignatedEndIndex = DesignatedStartIndex; 2845 1.1 joerg } else { 2846 1.1 joerg assert(D->isArrayRangeDesignator() && "Need array-range designator"); 2847 1.1 joerg 2848 1.1 joerg DesignatedStartIndex = 2849 1.1 joerg DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context); 2850 1.1 joerg DesignatedEndIndex = 2851 1.1 joerg DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context); 2852 1.1 joerg IndexExpr = DIE->getArrayRangeEnd(*D); 2853 1.1 joerg 2854 1.1 joerg // Codegen can't handle evaluating array range designators that have side 2855 1.1 joerg // effects, because we replicate the AST value for each initialized element. 2856 1.1 joerg // As such, set the sawArrayRangeDesignator() bit if we initialize multiple 2857 1.1 joerg // elements with something that has a side effect, so codegen can emit an 2858 1.1 joerg // "error unsupported" error instead of miscompiling the app. 2859 1.1 joerg if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&& 2860 1.1 joerg DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly) 2861 1.1 joerg FullyStructuredList->sawArrayRangeDesignator(); 2862 1.1 joerg } 2863 1.1 joerg 2864 1.1 joerg if (isa<ConstantArrayType>(AT)) { 2865 1.1 joerg llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); 2866 1.1 joerg DesignatedStartIndex 2867 1.1 joerg = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); 2868 1.1 joerg DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); 2869 1.1 joerg DesignatedEndIndex 2870 1.1 joerg = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); 2871 1.1 joerg DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); 2872 1.1 joerg if (DesignatedEndIndex >= MaxElements) { 2873 1.1 joerg if (!VerifyOnly) 2874 1.1 joerg SemaRef.Diag(IndexExpr->getBeginLoc(), 2875 1.1 joerg diag::err_array_designator_too_large) 2876 1.1 joerg << DesignatedEndIndex.toString(10) << MaxElements.toString(10) 2877 1.1 joerg << IndexExpr->getSourceRange(); 2878 1.1 joerg ++Index; 2879 1.1 joerg return true; 2880 1.1 joerg } 2881 1.1 joerg } else { 2882 1.1 joerg unsigned DesignatedIndexBitWidth = 2883 1.1 joerg ConstantArrayType::getMaxSizeBits(SemaRef.Context); 2884 1.1 joerg DesignatedStartIndex = 2885 1.1 joerg DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth); 2886 1.1 joerg DesignatedEndIndex = 2887 1.1 joerg DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth); 2888 1.1 joerg DesignatedStartIndex.setIsUnsigned(true); 2889 1.1 joerg DesignatedEndIndex.setIsUnsigned(true); 2890 1.1 joerg } 2891 1.1 joerg 2892 1.1 joerg bool IsStringLiteralInitUpdate = 2893 1.1 joerg StructuredList && StructuredList->isStringLiteralInit(); 2894 1.1 joerg if (IsStringLiteralInitUpdate && VerifyOnly) { 2895 1.1 joerg // We're just verifying an update to a string literal init. We don't need 2896 1.1 joerg // to split the string up into individual characters to do that. 2897 1.1 joerg StructuredList = nullptr; 2898 1.1 joerg } else if (IsStringLiteralInitUpdate) { 2899 1.1 joerg // We're modifying a string literal init; we have to decompose the string 2900 1.1 joerg // so we can modify the individual characters. 2901 1.1 joerg ASTContext &Context = SemaRef.Context; 2902 1.1 joerg Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens(); 2903 1.1 joerg 2904 1.1 joerg // Compute the character type 2905 1.1 joerg QualType CharTy = AT->getElementType(); 2906 1.1 joerg 2907 1.1 joerg // Compute the type of the integer literals. 2908 1.1 joerg QualType PromotedCharTy = CharTy; 2909 1.1 joerg if (CharTy->isPromotableIntegerType()) 2910 1.1 joerg PromotedCharTy = Context.getPromotedIntegerType(CharTy); 2911 1.1 joerg unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy); 2912 1.1 joerg 2913 1.1 joerg if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) { 2914 1.1 joerg // Get the length of the string. 2915 1.1 joerg uint64_t StrLen = SL->getLength(); 2916 1.1 joerg if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) 2917 1.1 joerg StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); 2918 1.1 joerg StructuredList->resizeInits(Context, StrLen); 2919 1.1 joerg 2920 1.1 joerg // Build a literal for each character in the string, and put them into 2921 1.1 joerg // the init list. 2922 1.1 joerg for (unsigned i = 0, e = StrLen; i != e; ++i) { 2923 1.1 joerg llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i)); 2924 1.1 joerg Expr *Init = new (Context) IntegerLiteral( 2925 1.1 joerg Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); 2926 1.1 joerg if (CharTy != PromotedCharTy) 2927 1.1.1.2 joerg Init = 2928 1.1.1.2 joerg ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, Init, 2929 1.1.1.2 joerg nullptr, VK_RValue, FPOptionsOverride()); 2930 1.1 joerg StructuredList->updateInit(Context, i, Init); 2931 1.1 joerg } 2932 1.1 joerg } else { 2933 1.1 joerg ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr); 2934 1.1 joerg std::string Str; 2935 1.1 joerg Context.getObjCEncodingForType(E->getEncodedType(), Str); 2936 1.1 joerg 2937 1.1 joerg // Get the length of the string. 2938 1.1 joerg uint64_t StrLen = Str.size(); 2939 1.1 joerg if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) 2940 1.1 joerg StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); 2941 1.1 joerg StructuredList->resizeInits(Context, StrLen); 2942 1.1 joerg 2943 1.1 joerg // Build a literal for each character in the string, and put them into 2944 1.1 joerg // the init list. 2945 1.1 joerg for (unsigned i = 0, e = StrLen; i != e; ++i) { 2946 1.1 joerg llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]); 2947 1.1 joerg Expr *Init = new (Context) IntegerLiteral( 2948 1.1 joerg Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); 2949 1.1 joerg if (CharTy != PromotedCharTy) 2950 1.1.1.2 joerg Init = 2951 1.1.1.2 joerg ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, Init, 2952 1.1.1.2 joerg nullptr, VK_RValue, FPOptionsOverride()); 2953 1.1 joerg StructuredList->updateInit(Context, i, Init); 2954 1.1 joerg } 2955 1.1 joerg } 2956 1.1 joerg } 2957 1.1 joerg 2958 1.1 joerg // Make sure that our non-designated initializer list has space 2959 1.1 joerg // for a subobject corresponding to this array element. 2960 1.1 joerg if (StructuredList && 2961 1.1 joerg DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) 2962 1.1 joerg StructuredList->resizeInits(SemaRef.Context, 2963 1.1 joerg DesignatedEndIndex.getZExtValue() + 1); 2964 1.1 joerg 2965 1.1 joerg // Repeatedly perform subobject initializations in the range 2966 1.1 joerg // [DesignatedStartIndex, DesignatedEndIndex]. 2967 1.1 joerg 2968 1.1 joerg // Move to the next designator 2969 1.1 joerg unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); 2970 1.1 joerg unsigned OldIndex = Index; 2971 1.1 joerg 2972 1.1 joerg InitializedEntity ElementEntity = 2973 1.1 joerg InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 2974 1.1 joerg 2975 1.1 joerg while (DesignatedStartIndex <= DesignatedEndIndex) { 2976 1.1 joerg // Recurse to check later designated subobjects. 2977 1.1 joerg QualType ElementType = AT->getElementType(); 2978 1.1 joerg Index = OldIndex; 2979 1.1 joerg 2980 1.1 joerg ElementEntity.setElementIndex(ElementIndex); 2981 1.1 joerg if (CheckDesignatedInitializer( 2982 1.1 joerg ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr, 2983 1.1 joerg nullptr, Index, StructuredList, ElementIndex, 2984 1.1 joerg FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex), 2985 1.1 joerg false)) 2986 1.1 joerg return true; 2987 1.1 joerg 2988 1.1 joerg // Move to the next index in the array that we'll be initializing. 2989 1.1 joerg ++DesignatedStartIndex; 2990 1.1 joerg ElementIndex = DesignatedStartIndex.getZExtValue(); 2991 1.1 joerg } 2992 1.1 joerg 2993 1.1 joerg // If this the first designator, our caller will continue checking 2994 1.1 joerg // the rest of this array subobject. 2995 1.1 joerg if (IsFirstDesignator) { 2996 1.1 joerg if (NextElementIndex) 2997 1.1 joerg *NextElementIndex = DesignatedStartIndex; 2998 1.1 joerg StructuredIndex = ElementIndex; 2999 1.1 joerg return false; 3000 1.1 joerg } 3001 1.1 joerg 3002 1.1 joerg if (!FinishSubobjectInit) 3003 1.1 joerg return false; 3004 1.1 joerg 3005 1.1 joerg // Check the remaining elements within this array subobject. 3006 1.1 joerg bool prevHadError = hadError; 3007 1.1 joerg CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex, 3008 1.1 joerg /*SubobjectIsDesignatorContext=*/false, Index, 3009 1.1 joerg StructuredList, ElementIndex); 3010 1.1 joerg return hadError && !prevHadError; 3011 1.1 joerg } 3012 1.1 joerg 3013 1.1 joerg // Get the structured initializer list for a subobject of type 3014 1.1 joerg // @p CurrentObjectType. 3015 1.1 joerg InitListExpr * 3016 1.1 joerg InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 3017 1.1 joerg QualType CurrentObjectType, 3018 1.1 joerg InitListExpr *StructuredList, 3019 1.1 joerg unsigned StructuredIndex, 3020 1.1 joerg SourceRange InitRange, 3021 1.1 joerg bool IsFullyOverwritten) { 3022 1.1 joerg if (!StructuredList) 3023 1.1 joerg return nullptr; 3024 1.1 joerg 3025 1.1 joerg Expr *ExistingInit = nullptr; 3026 1.1 joerg if (StructuredIndex < StructuredList->getNumInits()) 3027 1.1 joerg ExistingInit = StructuredList->getInit(StructuredIndex); 3028 1.1 joerg 3029 1.1 joerg if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) 3030 1.1 joerg // There might have already been initializers for subobjects of the current 3031 1.1 joerg // object, but a subsequent initializer list will overwrite the entirety 3032 1.1 joerg // of the current object. (See DR 253 and C99 6.7.8p21). e.g., 3033 1.1 joerg // 3034 1.1 joerg // struct P { char x[6]; }; 3035 1.1 joerg // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } }; 3036 1.1 joerg // 3037 1.1 joerg // The first designated initializer is ignored, and l.x is just "f". 3038 1.1 joerg if (!IsFullyOverwritten) 3039 1.1 joerg return Result; 3040 1.1 joerg 3041 1.1 joerg if (ExistingInit) { 3042 1.1 joerg // We are creating an initializer list that initializes the 3043 1.1 joerg // subobjects of the current object, but there was already an 3044 1.1 joerg // initialization that completely initialized the current 3045 1.1 joerg // subobject: 3046 1.1 joerg // 3047 1.1 joerg // struct X { int a, b; }; 3048 1.1 joerg // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 }; 3049 1.1 joerg // 3050 1.1 joerg // Here, xs[0].a == 1 and xs[0].b == 3, since the second, 3051 1.1 joerg // designated initializer overwrites the [0].b initializer 3052 1.1 joerg // from the prior initialization. 3053 1.1 joerg // 3054 1.1 joerg // When the existing initializer is an expression rather than an 3055 1.1 joerg // initializer list, we cannot decompose and update it in this way. 3056 1.1 joerg // For example: 3057 1.1 joerg // 3058 1.1 joerg // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 3059 1.1 joerg // 3060 1.1 joerg // This case is handled by CheckDesignatedInitializer. 3061 1.1 joerg diagnoseInitOverride(ExistingInit, InitRange); 3062 1.1 joerg } 3063 1.1 joerg 3064 1.1 joerg unsigned ExpectedNumInits = 0; 3065 1.1 joerg if (Index < IList->getNumInits()) { 3066 1.1 joerg if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index))) 3067 1.1 joerg ExpectedNumInits = Init->getNumInits(); 3068 1.1 joerg else 3069 1.1 joerg ExpectedNumInits = IList->getNumInits() - Index; 3070 1.1 joerg } 3071 1.1 joerg 3072 1.1 joerg InitListExpr *Result = 3073 1.1 joerg createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits); 3074 1.1 joerg 3075 1.1 joerg // Link this new initializer list into the structured initializer 3076 1.1 joerg // lists. 3077 1.1 joerg StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result); 3078 1.1 joerg return Result; 3079 1.1 joerg } 3080 1.1 joerg 3081 1.1 joerg InitListExpr * 3082 1.1 joerg InitListChecker::createInitListExpr(QualType CurrentObjectType, 3083 1.1 joerg SourceRange InitRange, 3084 1.1 joerg unsigned ExpectedNumInits) { 3085 1.1 joerg InitListExpr *Result 3086 1.1 joerg = new (SemaRef.Context) InitListExpr(SemaRef.Context, 3087 1.1 joerg InitRange.getBegin(), None, 3088 1.1 joerg InitRange.getEnd()); 3089 1.1 joerg 3090 1.1 joerg QualType ResultType = CurrentObjectType; 3091 1.1 joerg if (!ResultType->isArrayType()) 3092 1.1 joerg ResultType = ResultType.getNonLValueExprType(SemaRef.Context); 3093 1.1 joerg Result->setType(ResultType); 3094 1.1 joerg 3095 1.1 joerg // Pre-allocate storage for the structured initializer list. 3096 1.1 joerg unsigned NumElements = 0; 3097 1.1 joerg 3098 1.1 joerg if (const ArrayType *AType 3099 1.1 joerg = SemaRef.Context.getAsArrayType(CurrentObjectType)) { 3100 1.1 joerg if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { 3101 1.1 joerg NumElements = CAType->getSize().getZExtValue(); 3102 1.1 joerg // Simple heuristic so that we don't allocate a very large 3103 1.1 joerg // initializer with many empty entries at the end. 3104 1.1 joerg if (NumElements > ExpectedNumInits) 3105 1.1 joerg NumElements = 0; 3106 1.1 joerg } 3107 1.1 joerg } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) { 3108 1.1 joerg NumElements = VType->getNumElements(); 3109 1.1 joerg } else if (CurrentObjectType->isRecordType()) { 3110 1.1 joerg NumElements = numStructUnionElements(CurrentObjectType); 3111 1.1 joerg } 3112 1.1 joerg 3113 1.1 joerg Result->reserveInits(SemaRef.Context, NumElements); 3114 1.1 joerg 3115 1.1 joerg return Result; 3116 1.1 joerg } 3117 1.1 joerg 3118 1.1 joerg /// Update the initializer at index @p StructuredIndex within the 3119 1.1 joerg /// structured initializer list to the value @p expr. 3120 1.1 joerg void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, 3121 1.1 joerg unsigned &StructuredIndex, 3122 1.1 joerg Expr *expr) { 3123 1.1 joerg // No structured initializer list to update 3124 1.1 joerg if (!StructuredList) 3125 1.1 joerg return; 3126 1.1 joerg 3127 1.1 joerg if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context, 3128 1.1 joerg StructuredIndex, expr)) { 3129 1.1.1.2 joerg // This initializer overwrites a previous initializer. 3130 1.1.1.2 joerg // No need to diagnose when `expr` is nullptr because a more relevant 3131 1.1.1.2 joerg // diagnostic has already been issued and this diagnostic is potentially 3132 1.1.1.2 joerg // noise. 3133 1.1.1.2 joerg if (expr) 3134 1.1.1.2 joerg diagnoseInitOverride(PrevInit, expr->getSourceRange()); 3135 1.1 joerg } 3136 1.1 joerg 3137 1.1 joerg ++StructuredIndex; 3138 1.1 joerg } 3139 1.1 joerg 3140 1.1 joerg /// Determine whether we can perform aggregate initialization for the purposes 3141 1.1 joerg /// of overload resolution. 3142 1.1 joerg bool Sema::CanPerformAggregateInitializationForOverloadResolution( 3143 1.1 joerg const InitializedEntity &Entity, InitListExpr *From) { 3144 1.1 joerg QualType Type = Entity.getType(); 3145 1.1 joerg InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true, 3146 1.1 joerg /*TreatUnavailableAsInvalid=*/false, 3147 1.1 joerg /*InOverloadResolution=*/true); 3148 1.1 joerg return !Check.HadError(); 3149 1.1 joerg } 3150 1.1 joerg 3151 1.1 joerg /// Check that the given Index expression is a valid array designator 3152 1.1 joerg /// value. This is essentially just a wrapper around 3153 1.1 joerg /// VerifyIntegerConstantExpression that also checks for negative values 3154 1.1 joerg /// and produces a reasonable diagnostic if there is a 3155 1.1 joerg /// failure. Returns the index expression, possibly with an implicit cast 3156 1.1 joerg /// added, on success. If everything went okay, Value will receive the 3157 1.1 joerg /// value of the constant expression. 3158 1.1 joerg static ExprResult 3159 1.1 joerg CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { 3160 1.1 joerg SourceLocation Loc = Index->getBeginLoc(); 3161 1.1 joerg 3162 1.1 joerg // Make sure this is an integer constant expression. 3163 1.1.1.2 joerg ExprResult Result = 3164 1.1.1.2 joerg S.VerifyIntegerConstantExpression(Index, &Value, Sema::AllowFold); 3165 1.1 joerg if (Result.isInvalid()) 3166 1.1 joerg return Result; 3167 1.1 joerg 3168 1.1 joerg if (Value.isSigned() && Value.isNegative()) 3169 1.1 joerg return S.Diag(Loc, diag::err_array_designator_negative) 3170 1.1 joerg << Value.toString(10) << Index->getSourceRange(); 3171 1.1 joerg 3172 1.1 joerg Value.setIsUnsigned(true); 3173 1.1 joerg return Result; 3174 1.1 joerg } 3175 1.1 joerg 3176 1.1 joerg ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, 3177 1.1 joerg SourceLocation EqualOrColonLoc, 3178 1.1 joerg bool GNUSyntax, 3179 1.1 joerg ExprResult Init) { 3180 1.1 joerg typedef DesignatedInitExpr::Designator ASTDesignator; 3181 1.1 joerg 3182 1.1 joerg bool Invalid = false; 3183 1.1 joerg SmallVector<ASTDesignator, 32> Designators; 3184 1.1 joerg SmallVector<Expr *, 32> InitExpressions; 3185 1.1 joerg 3186 1.1 joerg // Build designators and check array designator expressions. 3187 1.1 joerg for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { 3188 1.1 joerg const Designator &D = Desig.getDesignator(Idx); 3189 1.1 joerg switch (D.getKind()) { 3190 1.1 joerg case Designator::FieldDesignator: 3191 1.1 joerg Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), 3192 1.1 joerg D.getFieldLoc())); 3193 1.1 joerg break; 3194 1.1 joerg 3195 1.1 joerg case Designator::ArrayDesignator: { 3196 1.1 joerg Expr *Index = static_cast<Expr *>(D.getArrayIndex()); 3197 1.1 joerg llvm::APSInt IndexValue; 3198 1.1 joerg if (!Index->isTypeDependent() && !Index->isValueDependent()) 3199 1.1 joerg Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get(); 3200 1.1 joerg if (!Index) 3201 1.1 joerg Invalid = true; 3202 1.1 joerg else { 3203 1.1 joerg Designators.push_back(ASTDesignator(InitExpressions.size(), 3204 1.1 joerg D.getLBracketLoc(), 3205 1.1 joerg D.getRBracketLoc())); 3206 1.1 joerg InitExpressions.push_back(Index); 3207 1.1 joerg } 3208 1.1 joerg break; 3209 1.1 joerg } 3210 1.1 joerg 3211 1.1 joerg case Designator::ArrayRangeDesignator: { 3212 1.1 joerg Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); 3213 1.1 joerg Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); 3214 1.1 joerg llvm::APSInt StartValue; 3215 1.1 joerg llvm::APSInt EndValue; 3216 1.1 joerg bool StartDependent = StartIndex->isTypeDependent() || 3217 1.1 joerg StartIndex->isValueDependent(); 3218 1.1 joerg bool EndDependent = EndIndex->isTypeDependent() || 3219 1.1 joerg EndIndex->isValueDependent(); 3220 1.1 joerg if (!StartDependent) 3221 1.1 joerg StartIndex = 3222 1.1 joerg CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get(); 3223 1.1 joerg if (!EndDependent) 3224 1.1 joerg EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get(); 3225 1.1 joerg 3226 1.1 joerg if (!StartIndex || !EndIndex) 3227 1.1 joerg Invalid = true; 3228 1.1 joerg else { 3229 1.1 joerg // Make sure we're comparing values with the same bit width. 3230 1.1 joerg if (StartDependent || EndDependent) { 3231 1.1 joerg // Nothing to compute. 3232 1.1 joerg } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) 3233 1.1 joerg EndValue = EndValue.extend(StartValue.getBitWidth()); 3234 1.1 joerg else if (StartValue.getBitWidth() < EndValue.getBitWidth()) 3235 1.1 joerg StartValue = StartValue.extend(EndValue.getBitWidth()); 3236 1.1 joerg 3237 1.1 joerg if (!StartDependent && !EndDependent && EndValue < StartValue) { 3238 1.1 joerg Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) 3239 1.1 joerg << StartValue.toString(10) << EndValue.toString(10) 3240 1.1 joerg << StartIndex->getSourceRange() << EndIndex->getSourceRange(); 3241 1.1 joerg Invalid = true; 3242 1.1 joerg } else { 3243 1.1 joerg Designators.push_back(ASTDesignator(InitExpressions.size(), 3244 1.1 joerg D.getLBracketLoc(), 3245 1.1 joerg D.getEllipsisLoc(), 3246 1.1 joerg D.getRBracketLoc())); 3247 1.1 joerg InitExpressions.push_back(StartIndex); 3248 1.1 joerg InitExpressions.push_back(EndIndex); 3249 1.1 joerg } 3250 1.1 joerg } 3251 1.1 joerg break; 3252 1.1 joerg } 3253 1.1 joerg } 3254 1.1 joerg } 3255 1.1 joerg 3256 1.1 joerg if (Invalid || Init.isInvalid()) 3257 1.1 joerg return ExprError(); 3258 1.1 joerg 3259 1.1 joerg // Clear out the expressions within the designation. 3260 1.1 joerg Desig.ClearExprs(*this); 3261 1.1 joerg 3262 1.1 joerg return DesignatedInitExpr::Create(Context, Designators, InitExpressions, 3263 1.1 joerg EqualOrColonLoc, GNUSyntax, 3264 1.1 joerg Init.getAs<Expr>()); 3265 1.1 joerg } 3266 1.1 joerg 3267 1.1 joerg //===----------------------------------------------------------------------===// 3268 1.1 joerg // Initialization entity 3269 1.1 joerg //===----------------------------------------------------------------------===// 3270 1.1 joerg 3271 1.1 joerg InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, 3272 1.1 joerg const InitializedEntity &Parent) 3273 1.1 joerg : Parent(&Parent), Index(Index) 3274 1.1 joerg { 3275 1.1 joerg if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) { 3276 1.1 joerg Kind = EK_ArrayElement; 3277 1.1 joerg Type = AT->getElementType(); 3278 1.1 joerg } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) { 3279 1.1 joerg Kind = EK_VectorElement; 3280 1.1 joerg Type = VT->getElementType(); 3281 1.1 joerg } else { 3282 1.1 joerg const ComplexType *CT = Parent.getType()->getAs<ComplexType>(); 3283 1.1 joerg assert(CT && "Unexpected type"); 3284 1.1 joerg Kind = EK_ComplexElement; 3285 1.1 joerg Type = CT->getElementType(); 3286 1.1 joerg } 3287 1.1 joerg } 3288 1.1 joerg 3289 1.1 joerg InitializedEntity 3290 1.1 joerg InitializedEntity::InitializeBase(ASTContext &Context, 3291 1.1 joerg const CXXBaseSpecifier *Base, 3292 1.1 joerg bool IsInheritedVirtualBase, 3293 1.1 joerg const InitializedEntity *Parent) { 3294 1.1 joerg InitializedEntity Result; 3295 1.1 joerg Result.Kind = EK_Base; 3296 1.1 joerg Result.Parent = Parent; 3297 1.1.1.2 joerg Result.Base = {Base, IsInheritedVirtualBase}; 3298 1.1 joerg Result.Type = Base->getType(); 3299 1.1 joerg return Result; 3300 1.1 joerg } 3301 1.1 joerg 3302 1.1 joerg DeclarationName InitializedEntity::getName() const { 3303 1.1 joerg switch (getKind()) { 3304 1.1 joerg case EK_Parameter: 3305 1.1 joerg case EK_Parameter_CF_Audited: { 3306 1.1.1.2 joerg ParmVarDecl *D = Parameter.getPointer(); 3307 1.1 joerg return (D ? D->getDeclName() : DeclarationName()); 3308 1.1 joerg } 3309 1.1 joerg 3310 1.1 joerg case EK_Variable: 3311 1.1 joerg case EK_Member: 3312 1.1 joerg case EK_Binding: 3313 1.1.1.2 joerg case EK_TemplateParameter: 3314 1.1 joerg return Variable.VariableOrMember->getDeclName(); 3315 1.1 joerg 3316 1.1 joerg case EK_LambdaCapture: 3317 1.1 joerg return DeclarationName(Capture.VarID); 3318 1.1 joerg 3319 1.1 joerg case EK_Result: 3320 1.1 joerg case EK_StmtExprResult: 3321 1.1 joerg case EK_Exception: 3322 1.1 joerg case EK_New: 3323 1.1 joerg case EK_Temporary: 3324 1.1 joerg case EK_Base: 3325 1.1 joerg case EK_Delegating: 3326 1.1 joerg case EK_ArrayElement: 3327 1.1 joerg case EK_VectorElement: 3328 1.1 joerg case EK_ComplexElement: 3329 1.1 joerg case EK_BlockElement: 3330 1.1 joerg case EK_LambdaToBlockConversionBlockElement: 3331 1.1 joerg case EK_CompoundLiteralInit: 3332 1.1 joerg case EK_RelatedResult: 3333 1.1 joerg return DeclarationName(); 3334 1.1 joerg } 3335 1.1 joerg 3336 1.1 joerg llvm_unreachable("Invalid EntityKind!"); 3337 1.1 joerg } 3338 1.1 joerg 3339 1.1 joerg ValueDecl *InitializedEntity::getDecl() const { 3340 1.1 joerg switch (getKind()) { 3341 1.1 joerg case EK_Variable: 3342 1.1 joerg case EK_Member: 3343 1.1 joerg case EK_Binding: 3344 1.1.1.2 joerg case EK_TemplateParameter: 3345 1.1 joerg return Variable.VariableOrMember; 3346 1.1 joerg 3347 1.1 joerg case EK_Parameter: 3348 1.1 joerg case EK_Parameter_CF_Audited: 3349 1.1.1.2 joerg return Parameter.getPointer(); 3350 1.1 joerg 3351 1.1 joerg case EK_Result: 3352 1.1 joerg case EK_StmtExprResult: 3353 1.1 joerg case EK_Exception: 3354 1.1 joerg case EK_New: 3355 1.1 joerg case EK_Temporary: 3356 1.1 joerg case EK_Base: 3357 1.1 joerg case EK_Delegating: 3358 1.1 joerg case EK_ArrayElement: 3359 1.1 joerg case EK_VectorElement: 3360 1.1 joerg case EK_ComplexElement: 3361 1.1 joerg case EK_BlockElement: 3362 1.1 joerg case EK_LambdaToBlockConversionBlockElement: 3363 1.1 joerg case EK_LambdaCapture: 3364 1.1 joerg case EK_CompoundLiteralInit: 3365 1.1 joerg case EK_RelatedResult: 3366 1.1 joerg return nullptr; 3367 1.1 joerg } 3368 1.1 joerg 3369 1.1 joerg llvm_unreachable("Invalid EntityKind!"); 3370 1.1 joerg } 3371 1.1 joerg 3372 1.1 joerg bool InitializedEntity::allowsNRVO() const { 3373 1.1 joerg switch (getKind()) { 3374 1.1 joerg case EK_Result: 3375 1.1 joerg case EK_Exception: 3376 1.1 joerg return LocAndNRVO.NRVO; 3377 1.1 joerg 3378 1.1 joerg case EK_StmtExprResult: 3379 1.1 joerg case EK_Variable: 3380 1.1 joerg case EK_Parameter: 3381 1.1 joerg case EK_Parameter_CF_Audited: 3382 1.1.1.2 joerg case EK_TemplateParameter: 3383 1.1 joerg case EK_Member: 3384 1.1 joerg case EK_Binding: 3385 1.1 joerg case EK_New: 3386 1.1 joerg case EK_Temporary: 3387 1.1 joerg case EK_CompoundLiteralInit: 3388 1.1 joerg case EK_Base: 3389 1.1 joerg case EK_Delegating: 3390 1.1 joerg case EK_ArrayElement: 3391 1.1 joerg case EK_VectorElement: 3392 1.1 joerg case EK_ComplexElement: 3393 1.1 joerg case EK_BlockElement: 3394 1.1 joerg case EK_LambdaToBlockConversionBlockElement: 3395 1.1 joerg case EK_LambdaCapture: 3396 1.1 joerg case EK_RelatedResult: 3397 1.1 joerg break; 3398 1.1 joerg } 3399 1.1 joerg 3400 1.1 joerg return false; 3401 1.1 joerg } 3402 1.1 joerg 3403 1.1 joerg unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const { 3404 1.1 joerg assert(getParent() != this); 3405 1.1 joerg unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0; 3406 1.1 joerg for (unsigned I = 0; I != Depth; ++I) 3407 1.1 joerg OS << "`-"; 3408 1.1 joerg 3409 1.1 joerg switch (getKind()) { 3410 1.1 joerg case EK_Variable: OS << "Variable"; break; 3411 1.1 joerg case EK_Parameter: OS << "Parameter"; break; 3412 1.1 joerg case EK_Parameter_CF_Audited: OS << "CF audited function Parameter"; 3413 1.1 joerg break; 3414 1.1.1.2 joerg case EK_TemplateParameter: OS << "TemplateParameter"; break; 3415 1.1 joerg case EK_Result: OS << "Result"; break; 3416 1.1 joerg case EK_StmtExprResult: OS << "StmtExprResult"; break; 3417 1.1 joerg case EK_Exception: OS << "Exception"; break; 3418 1.1 joerg case EK_Member: OS << "Member"; break; 3419 1.1 joerg case EK_Binding: OS << "Binding"; break; 3420 1.1 joerg case EK_New: OS << "New"; break; 3421 1.1 joerg case EK_Temporary: OS << "Temporary"; break; 3422 1.1 joerg case EK_CompoundLiteralInit: OS << "CompoundLiteral";break; 3423 1.1 joerg case EK_RelatedResult: OS << "RelatedResult"; break; 3424 1.1 joerg case EK_Base: OS << "Base"; break; 3425 1.1 joerg case EK_Delegating: OS << "Delegating"; break; 3426 1.1 joerg case EK_ArrayElement: OS << "ArrayElement " << Index; break; 3427 1.1 joerg case EK_VectorElement: OS << "VectorElement " << Index; break; 3428 1.1 joerg case EK_ComplexElement: OS << "ComplexElement " << Index; break; 3429 1.1 joerg case EK_BlockElement: OS << "Block"; break; 3430 1.1 joerg case EK_LambdaToBlockConversionBlockElement: 3431 1.1 joerg OS << "Block (lambda)"; 3432 1.1 joerg break; 3433 1.1 joerg case EK_LambdaCapture: 3434 1.1 joerg OS << "LambdaCapture "; 3435 1.1 joerg OS << DeclarationName(Capture.VarID); 3436 1.1 joerg break; 3437 1.1 joerg } 3438 1.1 joerg 3439 1.1 joerg if (auto *D = getDecl()) { 3440 1.1 joerg OS << " "; 3441 1.1 joerg D->printQualifiedName(OS); 3442 1.1 joerg } 3443 1.1 joerg 3444 1.1 joerg OS << " '" << getType().getAsString() << "'\n"; 3445 1.1 joerg 3446 1.1 joerg return Depth + 1; 3447 1.1 joerg } 3448 1.1 joerg 3449 1.1 joerg LLVM_DUMP_METHOD void InitializedEntity::dump() const { 3450 1.1 joerg dumpImpl(llvm::errs()); 3451 1.1 joerg } 3452 1.1 joerg 3453 1.1 joerg //===----------------------------------------------------------------------===// 3454 1.1 joerg // Initialization sequence 3455 1.1 joerg //===----------------------------------------------------------------------===// 3456 1.1 joerg 3457 1.1 joerg void InitializationSequence::Step::Destroy() { 3458 1.1 joerg switch (Kind) { 3459 1.1 joerg case SK_ResolveAddressOfOverloadedFunction: 3460 1.1 joerg case SK_CastDerivedToBaseRValue: 3461 1.1 joerg case SK_CastDerivedToBaseXValue: 3462 1.1 joerg case SK_CastDerivedToBaseLValue: 3463 1.1 joerg case SK_BindReference: 3464 1.1 joerg case SK_BindReferenceToTemporary: 3465 1.1 joerg case SK_FinalCopy: 3466 1.1 joerg case SK_ExtraneousCopyToTemporary: 3467 1.1 joerg case SK_UserConversion: 3468 1.1 joerg case SK_QualificationConversionRValue: 3469 1.1 joerg case SK_QualificationConversionXValue: 3470 1.1 joerg case SK_QualificationConversionLValue: 3471 1.1.1.2 joerg case SK_FunctionReferenceConversion: 3472 1.1 joerg case SK_AtomicConversion: 3473 1.1 joerg case SK_ListInitialization: 3474 1.1 joerg case SK_UnwrapInitList: 3475 1.1 joerg case SK_RewrapInitList: 3476 1.1 joerg case SK_ConstructorInitialization: 3477 1.1 joerg case SK_ConstructorInitializationFromList: 3478 1.1 joerg case SK_ZeroInitialization: 3479 1.1 joerg case SK_CAssignment: 3480 1.1 joerg case SK_StringInit: 3481 1.1 joerg case SK_ObjCObjectConversion: 3482 1.1 joerg case SK_ArrayLoopIndex: 3483 1.1 joerg case SK_ArrayLoopInit: 3484 1.1 joerg case SK_ArrayInit: 3485 1.1 joerg case SK_GNUArrayInit: 3486 1.1 joerg case SK_ParenthesizedArrayInit: 3487 1.1 joerg case SK_PassByIndirectCopyRestore: 3488 1.1 joerg case SK_PassByIndirectRestore: 3489 1.1 joerg case SK_ProduceObjCObject: 3490 1.1 joerg case SK_StdInitializerList: 3491 1.1 joerg case SK_StdInitializerListConstructorCall: 3492 1.1 joerg case SK_OCLSamplerInit: 3493 1.1 joerg case SK_OCLZeroOpaqueType: 3494 1.1 joerg break; 3495 1.1 joerg 3496 1.1 joerg case SK_ConversionSequence: 3497 1.1 joerg case SK_ConversionSequenceNoNarrowing: 3498 1.1 joerg delete ICS; 3499 1.1 joerg } 3500 1.1 joerg } 3501 1.1 joerg 3502 1.1 joerg bool InitializationSequence::isDirectReferenceBinding() const { 3503 1.1 joerg // There can be some lvalue adjustments after the SK_BindReference step. 3504 1.1 joerg for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) { 3505 1.1 joerg if (I->Kind == SK_BindReference) 3506 1.1 joerg return true; 3507 1.1 joerg if (I->Kind == SK_BindReferenceToTemporary) 3508 1.1 joerg return false; 3509 1.1 joerg } 3510 1.1 joerg return false; 3511 1.1 joerg } 3512 1.1 joerg 3513 1.1 joerg bool InitializationSequence::isAmbiguous() const { 3514 1.1 joerg if (!Failed()) 3515 1.1 joerg return false; 3516 1.1 joerg 3517 1.1 joerg switch (getFailureKind()) { 3518 1.1 joerg case FK_TooManyInitsForReference: 3519 1.1 joerg case FK_ParenthesizedListInitForReference: 3520 1.1 joerg case FK_ArrayNeedsInitList: 3521 1.1 joerg case FK_ArrayNeedsInitListOrStringLiteral: 3522 1.1 joerg case FK_ArrayNeedsInitListOrWideStringLiteral: 3523 1.1 joerg case FK_NarrowStringIntoWideCharArray: 3524 1.1 joerg case FK_WideStringIntoCharArray: 3525 1.1 joerg case FK_IncompatWideStringIntoWideChar: 3526 1.1 joerg case FK_PlainStringIntoUTF8Char: 3527 1.1 joerg case FK_UTF8StringIntoPlainChar: 3528 1.1 joerg case FK_AddressOfOverloadFailed: // FIXME: Could do better 3529 1.1 joerg case FK_NonConstLValueReferenceBindingToTemporary: 3530 1.1 joerg case FK_NonConstLValueReferenceBindingToBitfield: 3531 1.1 joerg case FK_NonConstLValueReferenceBindingToVectorElement: 3532 1.1.1.2 joerg case FK_NonConstLValueReferenceBindingToMatrixElement: 3533 1.1 joerg case FK_NonConstLValueReferenceBindingToUnrelated: 3534 1.1 joerg case FK_RValueReferenceBindingToLValue: 3535 1.1 joerg case FK_ReferenceAddrspaceMismatchTemporary: 3536 1.1 joerg case FK_ReferenceInitDropsQualifiers: 3537 1.1 joerg case FK_ReferenceInitFailed: 3538 1.1 joerg case FK_ConversionFailed: 3539 1.1 joerg case FK_ConversionFromPropertyFailed: 3540 1.1 joerg case FK_TooManyInitsForScalar: 3541 1.1 joerg case FK_ParenthesizedListInitForScalar: 3542 1.1 joerg case FK_ReferenceBindingToInitList: 3543 1.1 joerg case FK_InitListBadDestinationType: 3544 1.1 joerg case FK_DefaultInitOfConst: 3545 1.1 joerg case FK_Incomplete: 3546 1.1 joerg case FK_ArrayTypeMismatch: 3547 1.1 joerg case FK_NonConstantArrayInit: 3548 1.1 joerg case FK_ListInitializationFailed: 3549 1.1 joerg case FK_VariableLengthArrayHasInitializer: 3550 1.1 joerg case FK_PlaceholderType: 3551 1.1 joerg case FK_ExplicitConstructor: 3552 1.1 joerg case FK_AddressOfUnaddressableFunction: 3553 1.1 joerg return false; 3554 1.1 joerg 3555 1.1 joerg case FK_ReferenceInitOverloadFailed: 3556 1.1 joerg case FK_UserConversionOverloadFailed: 3557 1.1 joerg case FK_ConstructorOverloadFailed: 3558 1.1 joerg case FK_ListConstructorOverloadFailed: 3559 1.1 joerg return FailedOverloadResult == OR_Ambiguous; 3560 1.1 joerg } 3561 1.1 joerg 3562 1.1 joerg llvm_unreachable("Invalid EntityKind!"); 3563 1.1 joerg } 3564 1.1 joerg 3565 1.1 joerg bool InitializationSequence::isConstructorInitialization() const { 3566 1.1 joerg return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; 3567 1.1 joerg } 3568 1.1 joerg 3569 1.1 joerg void 3570 1.1 joerg InitializationSequence 3571 1.1 joerg ::AddAddressOverloadResolutionStep(FunctionDecl *Function, 3572 1.1 joerg DeclAccessPair Found, 3573 1.1 joerg bool HadMultipleCandidates) { 3574 1.1 joerg Step S; 3575 1.1 joerg S.Kind = SK_ResolveAddressOfOverloadedFunction; 3576 1.1 joerg S.Type = Function->getType(); 3577 1.1 joerg S.Function.HadMultipleCandidates = HadMultipleCandidates; 3578 1.1 joerg S.Function.Function = Function; 3579 1.1 joerg S.Function.FoundDecl = Found; 3580 1.1 joerg Steps.push_back(S); 3581 1.1 joerg } 3582 1.1 joerg 3583 1.1 joerg void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, 3584 1.1 joerg ExprValueKind VK) { 3585 1.1 joerg Step S; 3586 1.1 joerg switch (VK) { 3587 1.1 joerg case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break; 3588 1.1 joerg case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; 3589 1.1 joerg case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; 3590 1.1 joerg } 3591 1.1 joerg S.Type = BaseType; 3592 1.1 joerg Steps.push_back(S); 3593 1.1 joerg } 3594 1.1 joerg 3595 1.1 joerg void InitializationSequence::AddReferenceBindingStep(QualType T, 3596 1.1 joerg bool BindingTemporary) { 3597 1.1 joerg Step S; 3598 1.1 joerg S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; 3599 1.1 joerg S.Type = T; 3600 1.1 joerg Steps.push_back(S); 3601 1.1 joerg } 3602 1.1 joerg 3603 1.1 joerg void InitializationSequence::AddFinalCopy(QualType T) { 3604 1.1 joerg Step S; 3605 1.1 joerg S.Kind = SK_FinalCopy; 3606 1.1 joerg S.Type = T; 3607 1.1 joerg Steps.push_back(S); 3608 1.1 joerg } 3609 1.1 joerg 3610 1.1 joerg void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) { 3611 1.1 joerg Step S; 3612 1.1 joerg S.Kind = SK_ExtraneousCopyToTemporary; 3613 1.1 joerg S.Type = T; 3614 1.1 joerg Steps.push_back(S); 3615 1.1 joerg } 3616 1.1 joerg 3617 1.1 joerg void 3618 1.1 joerg InitializationSequence::AddUserConversionStep(FunctionDecl *Function, 3619 1.1 joerg DeclAccessPair FoundDecl, 3620 1.1 joerg QualType T, 3621 1.1 joerg bool HadMultipleCandidates) { 3622 1.1 joerg Step S; 3623 1.1 joerg S.Kind = SK_UserConversion; 3624 1.1 joerg S.Type = T; 3625 1.1 joerg S.Function.HadMultipleCandidates = HadMultipleCandidates; 3626 1.1 joerg S.Function.Function = Function; 3627 1.1 joerg S.Function.FoundDecl = FoundDecl; 3628 1.1 joerg Steps.push_back(S); 3629 1.1 joerg } 3630 1.1 joerg 3631 1.1 joerg void InitializationSequence::AddQualificationConversionStep(QualType Ty, 3632 1.1 joerg ExprValueKind VK) { 3633 1.1 joerg Step S; 3634 1.1 joerg S.Kind = SK_QualificationConversionRValue; // work around a gcc warning 3635 1.1 joerg switch (VK) { 3636 1.1 joerg case VK_RValue: 3637 1.1 joerg S.Kind = SK_QualificationConversionRValue; 3638 1.1 joerg break; 3639 1.1 joerg case VK_XValue: 3640 1.1 joerg S.Kind = SK_QualificationConversionXValue; 3641 1.1 joerg break; 3642 1.1 joerg case VK_LValue: 3643 1.1 joerg S.Kind = SK_QualificationConversionLValue; 3644 1.1 joerg break; 3645 1.1 joerg } 3646 1.1 joerg S.Type = Ty; 3647 1.1 joerg Steps.push_back(S); 3648 1.1 joerg } 3649 1.1 joerg 3650 1.1.1.2 joerg void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) { 3651 1.1.1.2 joerg Step S; 3652 1.1.1.2 joerg S.Kind = SK_FunctionReferenceConversion; 3653 1.1.1.2 joerg S.Type = Ty; 3654 1.1.1.2 joerg Steps.push_back(S); 3655 1.1.1.2 joerg } 3656 1.1.1.2 joerg 3657 1.1 joerg void InitializationSequence::AddAtomicConversionStep(QualType Ty) { 3658 1.1 joerg Step S; 3659 1.1 joerg S.Kind = SK_AtomicConversion; 3660 1.1 joerg S.Type = Ty; 3661 1.1 joerg Steps.push_back(S); 3662 1.1 joerg } 3663 1.1 joerg 3664 1.1 joerg void InitializationSequence::AddConversionSequenceStep( 3665 1.1 joerg const ImplicitConversionSequence &ICS, QualType T, 3666 1.1 joerg bool TopLevelOfInitList) { 3667 1.1 joerg Step S; 3668 1.1 joerg S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing 3669 1.1 joerg : SK_ConversionSequence; 3670 1.1 joerg S.Type = T; 3671 1.1 joerg S.ICS = new ImplicitConversionSequence(ICS); 3672 1.1 joerg Steps.push_back(S); 3673 1.1 joerg } 3674 1.1 joerg 3675 1.1 joerg void InitializationSequence::AddListInitializationStep(QualType T) { 3676 1.1 joerg Step S; 3677 1.1 joerg S.Kind = SK_ListInitialization; 3678 1.1 joerg S.Type = T; 3679 1.1 joerg Steps.push_back(S); 3680 1.1 joerg } 3681 1.1 joerg 3682 1.1 joerg void InitializationSequence::AddConstructorInitializationStep( 3683 1.1 joerg DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, 3684 1.1 joerg bool HadMultipleCandidates, bool FromInitList, bool AsInitList) { 3685 1.1 joerg Step S; 3686 1.1 joerg S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall 3687 1.1 joerg : SK_ConstructorInitializationFromList 3688 1.1 joerg : SK_ConstructorInitialization; 3689 1.1 joerg S.Type = T; 3690 1.1 joerg S.Function.HadMultipleCandidates = HadMultipleCandidates; 3691 1.1 joerg S.Function.Function = Constructor; 3692 1.1 joerg S.Function.FoundDecl = FoundDecl; 3693 1.1 joerg Steps.push_back(S); 3694 1.1 joerg } 3695 1.1 joerg 3696 1.1 joerg void InitializationSequence::AddZeroInitializationStep(QualType T) { 3697 1.1 joerg Step S; 3698 1.1 joerg S.Kind = SK_ZeroInitialization; 3699 1.1 joerg S.Type = T; 3700 1.1 joerg Steps.push_back(S); 3701 1.1 joerg } 3702 1.1 joerg 3703 1.1 joerg void InitializationSequence::AddCAssignmentStep(QualType T) { 3704 1.1 joerg Step S; 3705 1.1 joerg S.Kind = SK_CAssignment; 3706 1.1 joerg S.Type = T; 3707 1.1 joerg Steps.push_back(S); 3708 1.1 joerg } 3709 1.1 joerg 3710 1.1 joerg void InitializationSequence::AddStringInitStep(QualType T) { 3711 1.1 joerg Step S; 3712 1.1 joerg S.Kind = SK_StringInit; 3713 1.1 joerg S.Type = T; 3714 1.1 joerg Steps.push_back(S); 3715 1.1 joerg } 3716 1.1 joerg 3717 1.1 joerg void InitializationSequence::AddObjCObjectConversionStep(QualType T) { 3718 1.1 joerg Step S; 3719 1.1 joerg S.Kind = SK_ObjCObjectConversion; 3720 1.1 joerg S.Type = T; 3721 1.1 joerg Steps.push_back(S); 3722 1.1 joerg } 3723 1.1 joerg 3724 1.1 joerg void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) { 3725 1.1 joerg Step S; 3726 1.1 joerg S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit; 3727 1.1 joerg S.Type = T; 3728 1.1 joerg Steps.push_back(S); 3729 1.1 joerg } 3730 1.1 joerg 3731 1.1 joerg void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) { 3732 1.1 joerg Step S; 3733 1.1 joerg S.Kind = SK_ArrayLoopIndex; 3734 1.1 joerg S.Type = EltT; 3735 1.1 joerg Steps.insert(Steps.begin(), S); 3736 1.1 joerg 3737 1.1 joerg S.Kind = SK_ArrayLoopInit; 3738 1.1 joerg S.Type = T; 3739 1.1 joerg Steps.push_back(S); 3740 1.1 joerg } 3741 1.1 joerg 3742 1.1 joerg void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) { 3743 1.1 joerg Step S; 3744 1.1 joerg S.Kind = SK_ParenthesizedArrayInit; 3745 1.1 joerg S.Type = T; 3746 1.1 joerg Steps.push_back(S); 3747 1.1 joerg } 3748 1.1 joerg 3749 1.1 joerg void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, 3750 1.1 joerg bool shouldCopy) { 3751 1.1 joerg Step s; 3752 1.1 joerg s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore 3753 1.1 joerg : SK_PassByIndirectRestore); 3754 1.1 joerg s.Type = type; 3755 1.1 joerg Steps.push_back(s); 3756 1.1 joerg } 3757 1.1 joerg 3758 1.1 joerg void InitializationSequence::AddProduceObjCObjectStep(QualType T) { 3759 1.1 joerg Step S; 3760 1.1 joerg S.Kind = SK_ProduceObjCObject; 3761 1.1 joerg S.Type = T; 3762 1.1 joerg Steps.push_back(S); 3763 1.1 joerg } 3764 1.1 joerg 3765 1.1 joerg void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) { 3766 1.1 joerg Step S; 3767 1.1 joerg S.Kind = SK_StdInitializerList; 3768 1.1 joerg S.Type = T; 3769 1.1 joerg Steps.push_back(S); 3770 1.1 joerg } 3771 1.1 joerg 3772 1.1 joerg void InitializationSequence::AddOCLSamplerInitStep(QualType T) { 3773 1.1 joerg Step S; 3774 1.1 joerg S.Kind = SK_OCLSamplerInit; 3775 1.1 joerg S.Type = T; 3776 1.1 joerg Steps.push_back(S); 3777 1.1 joerg } 3778 1.1 joerg 3779 1.1 joerg void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) { 3780 1.1 joerg Step S; 3781 1.1 joerg S.Kind = SK_OCLZeroOpaqueType; 3782 1.1 joerg S.Type = T; 3783 1.1 joerg Steps.push_back(S); 3784 1.1 joerg } 3785 1.1 joerg 3786 1.1 joerg void InitializationSequence::RewrapReferenceInitList(QualType T, 3787 1.1 joerg InitListExpr *Syntactic) { 3788 1.1 joerg assert(Syntactic->getNumInits() == 1 && 3789 1.1 joerg "Can only rewrap trivial init lists."); 3790 1.1 joerg Step S; 3791 1.1 joerg S.Kind = SK_UnwrapInitList; 3792 1.1 joerg S.Type = Syntactic->getInit(0)->getType(); 3793 1.1 joerg Steps.insert(Steps.begin(), S); 3794 1.1 joerg 3795 1.1 joerg S.Kind = SK_RewrapInitList; 3796 1.1 joerg S.Type = T; 3797 1.1 joerg S.WrappingSyntacticList = Syntactic; 3798 1.1 joerg Steps.push_back(S); 3799 1.1 joerg } 3800 1.1 joerg 3801 1.1 joerg void InitializationSequence::SetOverloadFailure(FailureKind Failure, 3802 1.1 joerg OverloadingResult Result) { 3803 1.1 joerg setSequenceKind(FailedSequence); 3804 1.1 joerg this->Failure = Failure; 3805 1.1 joerg this->FailedOverloadResult = Result; 3806 1.1 joerg } 3807 1.1 joerg 3808 1.1 joerg //===----------------------------------------------------------------------===// 3809 1.1 joerg // Attempt initialization 3810 1.1 joerg //===----------------------------------------------------------------------===// 3811 1.1 joerg 3812 1.1 joerg /// Tries to add a zero initializer. Returns true if that worked. 3813 1.1 joerg static bool 3814 1.1 joerg maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, 3815 1.1 joerg const InitializedEntity &Entity) { 3816 1.1 joerg if (Entity.getKind() != InitializedEntity::EK_Variable) 3817 1.1 joerg return false; 3818 1.1 joerg 3819 1.1 joerg VarDecl *VD = cast<VarDecl>(Entity.getDecl()); 3820 1.1 joerg if (VD->getInit() || VD->getEndLoc().isMacroID()) 3821 1.1 joerg return false; 3822 1.1 joerg 3823 1.1 joerg QualType VariableTy = VD->getType().getCanonicalType(); 3824 1.1 joerg SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc()); 3825 1.1 joerg std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc); 3826 1.1 joerg if (!Init.empty()) { 3827 1.1 joerg Sequence.AddZeroInitializationStep(Entity.getType()); 3828 1.1 joerg Sequence.SetZeroInitializationFixit(Init, Loc); 3829 1.1 joerg return true; 3830 1.1 joerg } 3831 1.1 joerg return false; 3832 1.1 joerg } 3833 1.1 joerg 3834 1.1 joerg static void MaybeProduceObjCObject(Sema &S, 3835 1.1 joerg InitializationSequence &Sequence, 3836 1.1 joerg const InitializedEntity &Entity) { 3837 1.1 joerg if (!S.getLangOpts().ObjCAutoRefCount) return; 3838 1.1 joerg 3839 1.1 joerg /// When initializing a parameter, produce the value if it's marked 3840 1.1 joerg /// __attribute__((ns_consumed)). 3841 1.1 joerg if (Entity.isParameterKind()) { 3842 1.1 joerg if (!Entity.isParameterConsumed()) 3843 1.1 joerg return; 3844 1.1 joerg 3845 1.1 joerg assert(Entity.getType()->isObjCRetainableType() && 3846 1.1 joerg "consuming an object of unretainable type?"); 3847 1.1 joerg Sequence.AddProduceObjCObjectStep(Entity.getType()); 3848 1.1 joerg 3849 1.1 joerg /// When initializing a return value, if the return type is a 3850 1.1 joerg /// retainable type, then returns need to immediately retain the 3851 1.1 joerg /// object. If an autorelease is required, it will be done at the 3852 1.1 joerg /// last instant. 3853 1.1 joerg } else if (Entity.getKind() == InitializedEntity::EK_Result || 3854 1.1 joerg Entity.getKind() == InitializedEntity::EK_StmtExprResult) { 3855 1.1 joerg if (!Entity.getType()->isObjCRetainableType()) 3856 1.1 joerg return; 3857 1.1 joerg 3858 1.1 joerg Sequence.AddProduceObjCObjectStep(Entity.getType()); 3859 1.1 joerg } 3860 1.1 joerg } 3861 1.1 joerg 3862 1.1 joerg static void TryListInitialization(Sema &S, 3863 1.1 joerg const InitializedEntity &Entity, 3864 1.1 joerg const InitializationKind &Kind, 3865 1.1 joerg InitListExpr *InitList, 3866 1.1 joerg InitializationSequence &Sequence, 3867 1.1 joerg bool TreatUnavailableAsInvalid); 3868 1.1 joerg 3869 1.1 joerg /// When initializing from init list via constructor, handle 3870 1.1 joerg /// initialization of an object of type std::initializer_list<T>. 3871 1.1 joerg /// 3872 1.1 joerg /// \return true if we have handled initialization of an object of type 3873 1.1 joerg /// std::initializer_list<T>, false otherwise. 3874 1.1 joerg static bool TryInitializerListConstruction(Sema &S, 3875 1.1 joerg InitListExpr *List, 3876 1.1 joerg QualType DestType, 3877 1.1 joerg InitializationSequence &Sequence, 3878 1.1 joerg bool TreatUnavailableAsInvalid) { 3879 1.1 joerg QualType E; 3880 1.1 joerg if (!S.isStdInitializerList(DestType, &E)) 3881 1.1 joerg return false; 3882 1.1 joerg 3883 1.1 joerg if (!S.isCompleteType(List->getExprLoc(), E)) { 3884 1.1 joerg Sequence.setIncompleteTypeFailure(E); 3885 1.1 joerg return true; 3886 1.1 joerg } 3887 1.1 joerg 3888 1.1 joerg // Try initializing a temporary array from the init list. 3889 1.1 joerg QualType ArrayType = S.Context.getConstantArrayType( 3890 1.1 joerg E.withConst(), 3891 1.1 joerg llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), 3892 1.1 joerg List->getNumInits()), 3893 1.1 joerg nullptr, clang::ArrayType::Normal, 0); 3894 1.1 joerg InitializedEntity HiddenArray = 3895 1.1 joerg InitializedEntity::InitializeTemporary(ArrayType); 3896 1.1 joerg InitializationKind Kind = InitializationKind::CreateDirectList( 3897 1.1 joerg List->getExprLoc(), List->getBeginLoc(), List->getEndLoc()); 3898 1.1 joerg TryListInitialization(S, HiddenArray, Kind, List, Sequence, 3899 1.1 joerg TreatUnavailableAsInvalid); 3900 1.1 joerg if (Sequence) 3901 1.1 joerg Sequence.AddStdInitializerListConstructionStep(DestType); 3902 1.1 joerg return true; 3903 1.1 joerg } 3904 1.1 joerg 3905 1.1 joerg /// Determine if the constructor has the signature of a copy or move 3906 1.1 joerg /// constructor for the type T of the class in which it was found. That is, 3907 1.1 joerg /// determine if its first parameter is of type T or reference to (possibly 3908 1.1 joerg /// cv-qualified) T. 3909 1.1 joerg static bool hasCopyOrMoveCtorParam(ASTContext &Ctx, 3910 1.1 joerg const ConstructorInfo &Info) { 3911 1.1 joerg if (Info.Constructor->getNumParams() == 0) 3912 1.1 joerg return false; 3913 1.1 joerg 3914 1.1 joerg QualType ParmT = 3915 1.1 joerg Info.Constructor->getParamDecl(0)->getType().getNonReferenceType(); 3916 1.1 joerg QualType ClassT = 3917 1.1 joerg Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext())); 3918 1.1 joerg 3919 1.1 joerg return Ctx.hasSameUnqualifiedType(ParmT, ClassT); 3920 1.1 joerg } 3921 1.1 joerg 3922 1.1 joerg static OverloadingResult 3923 1.1 joerg ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, 3924 1.1 joerg MultiExprArg Args, 3925 1.1 joerg OverloadCandidateSet &CandidateSet, 3926 1.1 joerg QualType DestType, 3927 1.1 joerg DeclContext::lookup_result Ctors, 3928 1.1 joerg OverloadCandidateSet::iterator &Best, 3929 1.1 joerg bool CopyInitializing, bool AllowExplicit, 3930 1.1 joerg bool OnlyListConstructors, bool IsListInit, 3931 1.1 joerg bool SecondStepOfCopyInit = false) { 3932 1.1 joerg CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor); 3933 1.1 joerg CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); 3934 1.1 joerg 3935 1.1 joerg for (NamedDecl *D : Ctors) { 3936 1.1 joerg auto Info = getConstructorInfo(D); 3937 1.1 joerg if (!Info.Constructor || Info.Constructor->isInvalidDecl()) 3938 1.1 joerg continue; 3939 1.1 joerg 3940 1.1 joerg if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor)) 3941 1.1 joerg continue; 3942 1.1 joerg 3943 1.1 joerg // C++11 [over.best.ics]p4: 3944 1.1 joerg // ... and the constructor or user-defined conversion function is a 3945 1.1 joerg // candidate by 3946 1.1 joerg // - 13.3.1.3, when the argument is the temporary in the second step 3947 1.1 joerg // of a class copy-initialization, or 3948 1.1 joerg // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here] 3949 1.1 joerg // - the second phase of 13.3.1.7 when the initializer list has exactly 3950 1.1 joerg // one element that is itself an initializer list, and the target is 3951 1.1 joerg // the first parameter of a constructor of class X, and the conversion 3952 1.1 joerg // is to X or reference to (possibly cv-qualified X), 3953 1.1 joerg // user-defined conversion sequences are not considered. 3954 1.1 joerg bool SuppressUserConversions = 3955 1.1 joerg SecondStepOfCopyInit || 3956 1.1 joerg (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) && 3957 1.1 joerg hasCopyOrMoveCtorParam(S.Context, Info)); 3958 1.1 joerg 3959 1.1 joerg if (Info.ConstructorTmpl) 3960 1.1 joerg S.AddTemplateOverloadCandidate( 3961 1.1 joerg Info.ConstructorTmpl, Info.FoundDecl, 3962 1.1 joerg /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions, 3963 1.1 joerg /*PartialOverloading=*/false, AllowExplicit); 3964 1.1 joerg else { 3965 1.1 joerg // C++ [over.match.copy]p1: 3966 1.1 joerg // - When initializing a temporary to be bound to the first parameter 3967 1.1 joerg // of a constructor [for type T] that takes a reference to possibly 3968 1.1 joerg // cv-qualified T as its first argument, called with a single 3969 1.1 joerg // argument in the context of direct-initialization, explicit 3970 1.1 joerg // conversion functions are also considered. 3971 1.1 joerg // FIXME: What if a constructor template instantiates to such a signature? 3972 1.1 joerg bool AllowExplicitConv = AllowExplicit && !CopyInitializing && 3973 1.1 joerg Args.size() == 1 && 3974 1.1 joerg hasCopyOrMoveCtorParam(S.Context, Info); 3975 1.1 joerg S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args, 3976 1.1 joerg CandidateSet, SuppressUserConversions, 3977 1.1 joerg /*PartialOverloading=*/false, AllowExplicit, 3978 1.1 joerg AllowExplicitConv); 3979 1.1 joerg } 3980 1.1 joerg } 3981 1.1 joerg 3982 1.1 joerg // FIXME: Work around a bug in C++17 guaranteed copy elision. 3983 1.1 joerg // 3984 1.1 joerg // When initializing an object of class type T by constructor 3985 1.1 joerg // ([over.match.ctor]) or by list-initialization ([over.match.list]) 3986 1.1 joerg // from a single expression of class type U, conversion functions of 3987 1.1 joerg // U that convert to the non-reference type cv T are candidates. 3988 1.1 joerg // Explicit conversion functions are only candidates during 3989 1.1 joerg // direct-initialization. 3990 1.1 joerg // 3991 1.1 joerg // Note: SecondStepOfCopyInit is only ever true in this case when 3992 1.1 joerg // evaluating whether to produce a C++98 compatibility warning. 3993 1.1 joerg if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 && 3994 1.1 joerg !SecondStepOfCopyInit) { 3995 1.1 joerg Expr *Initializer = Args[0]; 3996 1.1 joerg auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl(); 3997 1.1 joerg if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) { 3998 1.1 joerg const auto &Conversions = SourceRD->getVisibleConversionFunctions(); 3999 1.1 joerg for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4000 1.1 joerg NamedDecl *D = *I; 4001 1.1 joerg CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4002 1.1 joerg D = D->getUnderlyingDecl(); 4003 1.1 joerg 4004 1.1 joerg FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 4005 1.1 joerg CXXConversionDecl *Conv; 4006 1.1 joerg if (ConvTemplate) 4007 1.1 joerg Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4008 1.1 joerg else 4009 1.1 joerg Conv = cast<CXXConversionDecl>(D); 4010 1.1 joerg 4011 1.1.1.2 joerg if (ConvTemplate) 4012 1.1.1.2 joerg S.AddTemplateConversionCandidate( 4013 1.1.1.2 joerg ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, 4014 1.1.1.2 joerg CandidateSet, AllowExplicit, AllowExplicit, 4015 1.1.1.2 joerg /*AllowResultConversion*/ false); 4016 1.1.1.2 joerg else 4017 1.1.1.2 joerg S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, 4018 1.1.1.2 joerg DestType, CandidateSet, AllowExplicit, 4019 1.1.1.2 joerg AllowExplicit, 4020 1.1.1.2 joerg /*AllowResultConversion*/ false); 4021 1.1 joerg } 4022 1.1 joerg } 4023 1.1 joerg } 4024 1.1 joerg 4025 1.1 joerg // Perform overload resolution and return the result. 4026 1.1 joerg return CandidateSet.BestViableFunction(S, DeclLoc, Best); 4027 1.1 joerg } 4028 1.1 joerg 4029 1.1 joerg /// Attempt initialization by constructor (C++ [dcl.init]), which 4030 1.1 joerg /// enumerates the constructors of the initialized entity and performs overload 4031 1.1 joerg /// resolution to select the best. 4032 1.1 joerg /// \param DestType The destination class type. 4033 1.1 joerg /// \param DestArrayType The destination type, which is either DestType or 4034 1.1 joerg /// a (possibly multidimensional) array of DestType. 4035 1.1 joerg /// \param IsListInit Is this list-initialization? 4036 1.1 joerg /// \param IsInitListCopy Is this non-list-initialization resulting from a 4037 1.1 joerg /// list-initialization from {x} where x is the same 4038 1.1 joerg /// type as the entity? 4039 1.1 joerg static void TryConstructorInitialization(Sema &S, 4040 1.1 joerg const InitializedEntity &Entity, 4041 1.1 joerg const InitializationKind &Kind, 4042 1.1 joerg MultiExprArg Args, QualType DestType, 4043 1.1 joerg QualType DestArrayType, 4044 1.1 joerg InitializationSequence &Sequence, 4045 1.1 joerg bool IsListInit = false, 4046 1.1 joerg bool IsInitListCopy = false) { 4047 1.1 joerg assert(((!IsListInit && !IsInitListCopy) || 4048 1.1 joerg (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && 4049 1.1 joerg "IsListInit/IsInitListCopy must come with a single initializer list " 4050 1.1 joerg "argument."); 4051 1.1 joerg InitListExpr *ILE = 4052 1.1 joerg (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr; 4053 1.1 joerg MultiExprArg UnwrappedArgs = 4054 1.1 joerg ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args; 4055 1.1 joerg 4056 1.1 joerg // The type we're constructing needs to be complete. 4057 1.1 joerg if (!S.isCompleteType(Kind.getLocation(), DestType)) { 4058 1.1 joerg Sequence.setIncompleteTypeFailure(DestType); 4059 1.1 joerg return; 4060 1.1 joerg } 4061 1.1 joerg 4062 1.1 joerg // C++17 [dcl.init]p17: 4063 1.1 joerg // - If the initializer expression is a prvalue and the cv-unqualified 4064 1.1 joerg // version of the source type is the same class as the class of the 4065 1.1 joerg // destination, the initializer expression is used to initialize the 4066 1.1 joerg // destination object. 4067 1.1 joerg // Per DR (no number yet), this does not apply when initializing a base 4068 1.1 joerg // class or delegating to another constructor from a mem-initializer. 4069 1.1 joerg // ObjC++: Lambda captured by the block in the lambda to block conversion 4070 1.1 joerg // should avoid copy elision. 4071 1.1 joerg if (S.getLangOpts().CPlusPlus17 && 4072 1.1 joerg Entity.getKind() != InitializedEntity::EK_Base && 4073 1.1 joerg Entity.getKind() != InitializedEntity::EK_Delegating && 4074 1.1 joerg Entity.getKind() != 4075 1.1 joerg InitializedEntity::EK_LambdaToBlockConversionBlockElement && 4076 1.1 joerg UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() && 4077 1.1 joerg S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) { 4078 1.1 joerg // Convert qualifications if necessary. 4079 1.1 joerg Sequence.AddQualificationConversionStep(DestType, VK_RValue); 4080 1.1 joerg if (ILE) 4081 1.1 joerg Sequence.RewrapReferenceInitList(DestType, ILE); 4082 1.1 joerg return; 4083 1.1 joerg } 4084 1.1 joerg 4085 1.1 joerg const RecordType *DestRecordType = DestType->getAs<RecordType>(); 4086 1.1 joerg assert(DestRecordType && "Constructor initialization requires record type"); 4087 1.1 joerg CXXRecordDecl *DestRecordDecl 4088 1.1 joerg = cast<CXXRecordDecl>(DestRecordType->getDecl()); 4089 1.1 joerg 4090 1.1 joerg // Build the candidate set directly in the initialization sequence 4091 1.1 joerg // structure, so that it will persist if we fail. 4092 1.1 joerg OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 4093 1.1 joerg 4094 1.1 joerg // Determine whether we are allowed to call explicit constructors or 4095 1.1 joerg // explicit conversion operators. 4096 1.1 joerg bool AllowExplicit = Kind.AllowExplicit() || IsListInit; 4097 1.1 joerg bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy; 4098 1.1 joerg 4099 1.1 joerg // - Otherwise, if T is a class type, constructors are considered. The 4100 1.1 joerg // applicable constructors are enumerated, and the best one is chosen 4101 1.1 joerg // through overload resolution. 4102 1.1 joerg DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl); 4103 1.1 joerg 4104 1.1 joerg OverloadingResult Result = OR_No_Viable_Function; 4105 1.1 joerg OverloadCandidateSet::iterator Best; 4106 1.1 joerg bool AsInitializerList = false; 4107 1.1 joerg 4108 1.1 joerg // C++11 [over.match.list]p1, per DR1467: 4109 1.1 joerg // When objects of non-aggregate type T are list-initialized, such that 4110 1.1 joerg // 8.5.4 [dcl.init.list] specifies that overload resolution is performed 4111 1.1 joerg // according to the rules in this section, overload resolution selects 4112 1.1 joerg // the constructor in two phases: 4113 1.1 joerg // 4114 1.1 joerg // - Initially, the candidate functions are the initializer-list 4115 1.1 joerg // constructors of the class T and the argument list consists of the 4116 1.1 joerg // initializer list as a single argument. 4117 1.1 joerg if (IsListInit) { 4118 1.1 joerg AsInitializerList = true; 4119 1.1 joerg 4120 1.1 joerg // If the initializer list has no elements and T has a default constructor, 4121 1.1 joerg // the first phase is omitted. 4122 1.1.1.2 joerg if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl))) 4123 1.1 joerg Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, 4124 1.1 joerg CandidateSet, DestType, Ctors, Best, 4125 1.1 joerg CopyInitialization, AllowExplicit, 4126 1.1 joerg /*OnlyListConstructors=*/true, 4127 1.1 joerg IsListInit); 4128 1.1 joerg } 4129 1.1 joerg 4130 1.1 joerg // C++11 [over.match.list]p1: 4131 1.1 joerg // - If no viable initializer-list constructor is found, overload resolution 4132 1.1 joerg // is performed again, where the candidate functions are all the 4133 1.1 joerg // constructors of the class T and the argument list consists of the 4134 1.1 joerg // elements of the initializer list. 4135 1.1 joerg if (Result == OR_No_Viable_Function) { 4136 1.1 joerg AsInitializerList = false; 4137 1.1 joerg Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs, 4138 1.1 joerg CandidateSet, DestType, Ctors, Best, 4139 1.1 joerg CopyInitialization, AllowExplicit, 4140 1.1 joerg /*OnlyListConstructors=*/false, 4141 1.1 joerg IsListInit); 4142 1.1 joerg } 4143 1.1 joerg if (Result) { 4144 1.1.1.2 joerg Sequence.SetOverloadFailure( 4145 1.1.1.2 joerg IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed 4146 1.1.1.2 joerg : InitializationSequence::FK_ConstructorOverloadFailed, 4147 1.1.1.2 joerg Result); 4148 1.1.1.2 joerg 4149 1.1.1.2 joerg if (Result != OR_Deleted) 4150 1.1.1.2 joerg return; 4151 1.1 joerg } 4152 1.1 joerg 4153 1.1 joerg bool HadMultipleCandidates = (CandidateSet.size() > 1); 4154 1.1 joerg 4155 1.1 joerg // In C++17, ResolveConstructorOverload can select a conversion function 4156 1.1 joerg // instead of a constructor. 4157 1.1 joerg if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) { 4158 1.1 joerg // Add the user-defined conversion step that calls the conversion function. 4159 1.1 joerg QualType ConvType = CD->getConversionType(); 4160 1.1 joerg assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) && 4161 1.1 joerg "should not have selected this conversion function"); 4162 1.1 joerg Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType, 4163 1.1 joerg HadMultipleCandidates); 4164 1.1 joerg if (!S.Context.hasSameType(ConvType, DestType)) 4165 1.1 joerg Sequence.AddQualificationConversionStep(DestType, VK_RValue); 4166 1.1 joerg if (IsListInit) 4167 1.1 joerg Sequence.RewrapReferenceInitList(Entity.getType(), ILE); 4168 1.1 joerg return; 4169 1.1 joerg } 4170 1.1 joerg 4171 1.1 joerg CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 4172 1.1.1.2 joerg if (Result != OR_Deleted) { 4173 1.1.1.2 joerg // C++11 [dcl.init]p6: 4174 1.1.1.2 joerg // If a program calls for the default initialization of an object 4175 1.1.1.2 joerg // of a const-qualified type T, T shall be a class type with a 4176 1.1.1.2 joerg // user-provided default constructor. 4177 1.1.1.2 joerg // C++ core issue 253 proposal: 4178 1.1.1.2 joerg // If the implicit default constructor initializes all subobjects, no 4179 1.1.1.2 joerg // initializer should be required. 4180 1.1.1.2 joerg // The 253 proposal is for example needed to process libstdc++ headers 4181 1.1.1.2 joerg // in 5.x. 4182 1.1.1.2 joerg if (Kind.getKind() == InitializationKind::IK_Default && 4183 1.1.1.2 joerg Entity.getType().isConstQualified()) { 4184 1.1.1.2 joerg if (!CtorDecl->getParent()->allowConstDefaultInit()) { 4185 1.1.1.2 joerg if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) 4186 1.1.1.2 joerg Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 4187 1.1.1.2 joerg return; 4188 1.1.1.2 joerg } 4189 1.1.1.2 joerg } 4190 1.1.1.2 joerg 4191 1.1.1.2 joerg // C++11 [over.match.list]p1: 4192 1.1.1.2 joerg // In copy-list-initialization, if an explicit constructor is chosen, the 4193 1.1.1.2 joerg // initializer is ill-formed. 4194 1.1.1.2 joerg if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) { 4195 1.1.1.2 joerg Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor); 4196 1.1 joerg return; 4197 1.1 joerg } 4198 1.1 joerg } 4199 1.1 joerg 4200 1.1.1.2 joerg // [class.copy.elision]p3: 4201 1.1.1.2 joerg // In some copy-initialization contexts, a two-stage overload resolution 4202 1.1.1.2 joerg // is performed. 4203 1.1.1.2 joerg // If the first overload resolution selects a deleted function, we also 4204 1.1.1.2 joerg // need the initialization sequence to decide whether to perform the second 4205 1.1.1.2 joerg // overload resolution. 4206 1.1.1.2 joerg // For deleted functions in other contexts, there is no need to get the 4207 1.1.1.2 joerg // initialization sequence. 4208 1.1.1.2 joerg if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy) 4209 1.1 joerg return; 4210 1.1 joerg 4211 1.1 joerg // Add the constructor initialization step. Any cv-qualification conversion is 4212 1.1 joerg // subsumed by the initialization. 4213 1.1 joerg Sequence.AddConstructorInitializationStep( 4214 1.1 joerg Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates, 4215 1.1 joerg IsListInit | IsInitListCopy, AsInitializerList); 4216 1.1 joerg } 4217 1.1 joerg 4218 1.1 joerg static bool 4219 1.1 joerg ResolveOverloadedFunctionForReferenceBinding(Sema &S, 4220 1.1 joerg Expr *Initializer, 4221 1.1 joerg QualType &SourceType, 4222 1.1 joerg QualType &UnqualifiedSourceType, 4223 1.1 joerg QualType UnqualifiedTargetType, 4224 1.1 joerg InitializationSequence &Sequence) { 4225 1.1 joerg if (S.Context.getCanonicalType(UnqualifiedSourceType) == 4226 1.1 joerg S.Context.OverloadTy) { 4227 1.1 joerg DeclAccessPair Found; 4228 1.1 joerg bool HadMultipleCandidates = false; 4229 1.1 joerg if (FunctionDecl *Fn 4230 1.1 joerg = S.ResolveAddressOfOverloadedFunction(Initializer, 4231 1.1 joerg UnqualifiedTargetType, 4232 1.1 joerg false, Found, 4233 1.1 joerg &HadMultipleCandidates)) { 4234 1.1 joerg Sequence.AddAddressOverloadResolutionStep(Fn, Found, 4235 1.1 joerg HadMultipleCandidates); 4236 1.1 joerg SourceType = Fn->getType(); 4237 1.1 joerg UnqualifiedSourceType = SourceType.getUnqualifiedType(); 4238 1.1 joerg } else if (!UnqualifiedTargetType->isRecordType()) { 4239 1.1 joerg Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 4240 1.1 joerg return true; 4241 1.1 joerg } 4242 1.1 joerg } 4243 1.1 joerg return false; 4244 1.1 joerg } 4245 1.1 joerg 4246 1.1 joerg static void TryReferenceInitializationCore(Sema &S, 4247 1.1 joerg const InitializedEntity &Entity, 4248 1.1 joerg const InitializationKind &Kind, 4249 1.1 joerg Expr *Initializer, 4250 1.1 joerg QualType cv1T1, QualType T1, 4251 1.1 joerg Qualifiers T1Quals, 4252 1.1 joerg QualType cv2T2, QualType T2, 4253 1.1 joerg Qualifiers T2Quals, 4254 1.1 joerg InitializationSequence &Sequence); 4255 1.1 joerg 4256 1.1 joerg static void TryValueInitialization(Sema &S, 4257 1.1 joerg const InitializedEntity &Entity, 4258 1.1 joerg const InitializationKind &Kind, 4259 1.1 joerg InitializationSequence &Sequence, 4260 1.1 joerg InitListExpr *InitList = nullptr); 4261 1.1 joerg 4262 1.1 joerg /// Attempt list initialization of a reference. 4263 1.1 joerg static void TryReferenceListInitialization(Sema &S, 4264 1.1 joerg const InitializedEntity &Entity, 4265 1.1 joerg const InitializationKind &Kind, 4266 1.1 joerg InitListExpr *InitList, 4267 1.1 joerg InitializationSequence &Sequence, 4268 1.1 joerg bool TreatUnavailableAsInvalid) { 4269 1.1 joerg // First, catch C++03 where this isn't possible. 4270 1.1 joerg if (!S.getLangOpts().CPlusPlus11) { 4271 1.1 joerg Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 4272 1.1 joerg return; 4273 1.1 joerg } 4274 1.1 joerg // Can't reference initialize a compound literal. 4275 1.1 joerg if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) { 4276 1.1 joerg Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 4277 1.1 joerg return; 4278 1.1 joerg } 4279 1.1 joerg 4280 1.1 joerg QualType DestType = Entity.getType(); 4281 1.1 joerg QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); 4282 1.1 joerg Qualifiers T1Quals; 4283 1.1 joerg QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 4284 1.1 joerg 4285 1.1 joerg // Reference initialization via an initializer list works thus: 4286 1.1 joerg // If the initializer list consists of a single element that is 4287 1.1 joerg // reference-related to the referenced type, bind directly to that element 4288 1.1 joerg // (possibly creating temporaries). 4289 1.1 joerg // Otherwise, initialize a temporary with the initializer list and 4290 1.1 joerg // bind to that. 4291 1.1 joerg if (InitList->getNumInits() == 1) { 4292 1.1 joerg Expr *Initializer = InitList->getInit(0); 4293 1.1.1.2 joerg QualType cv2T2 = S.getCompletedType(Initializer); 4294 1.1 joerg Qualifiers T2Quals; 4295 1.1 joerg QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 4296 1.1 joerg 4297 1.1 joerg // If this fails, creating a temporary wouldn't work either. 4298 1.1 joerg if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, 4299 1.1 joerg T1, Sequence)) 4300 1.1 joerg return; 4301 1.1 joerg 4302 1.1 joerg SourceLocation DeclLoc = Initializer->getBeginLoc(); 4303 1.1 joerg Sema::ReferenceCompareResult RefRelationship 4304 1.1.1.2 joerg = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2); 4305 1.1 joerg if (RefRelationship >= Sema::Ref_Related) { 4306 1.1 joerg // Try to bind the reference here. 4307 1.1 joerg TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, 4308 1.1 joerg T1Quals, cv2T2, T2, T2Quals, Sequence); 4309 1.1 joerg if (Sequence) 4310 1.1 joerg Sequence.RewrapReferenceInitList(cv1T1, InitList); 4311 1.1 joerg return; 4312 1.1 joerg } 4313 1.1 joerg 4314 1.1 joerg // Update the initializer if we've resolved an overloaded function. 4315 1.1 joerg if (Sequence.step_begin() != Sequence.step_end()) 4316 1.1 joerg Sequence.RewrapReferenceInitList(cv1T1, InitList); 4317 1.1 joerg } 4318 1.1.1.2 joerg // Perform address space compatibility check. 4319 1.1.1.2 joerg QualType cv1T1IgnoreAS = cv1T1; 4320 1.1.1.2 joerg if (T1Quals.hasAddressSpace()) { 4321 1.1.1.2 joerg Qualifiers T2Quals; 4322 1.1.1.2 joerg (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals); 4323 1.1.1.2 joerg if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) { 4324 1.1.1.2 joerg Sequence.SetFailed( 4325 1.1.1.2 joerg InitializationSequence::FK_ReferenceInitDropsQualifiers); 4326 1.1.1.2 joerg return; 4327 1.1.1.2 joerg } 4328 1.1.1.2 joerg // Ignore address space of reference type at this point and perform address 4329 1.1.1.2 joerg // space conversion after the reference binding step. 4330 1.1.1.2 joerg cv1T1IgnoreAS = 4331 1.1.1.2 joerg S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace()); 4332 1.1.1.2 joerg } 4333 1.1 joerg // Not reference-related. Create a temporary and bind to that. 4334 1.1.1.2 joerg InitializedEntity TempEntity = 4335 1.1.1.2 joerg InitializedEntity::InitializeTemporary(cv1T1IgnoreAS); 4336 1.1 joerg 4337 1.1 joerg TryListInitialization(S, TempEntity, Kind, InitList, Sequence, 4338 1.1 joerg TreatUnavailableAsInvalid); 4339 1.1 joerg if (Sequence) { 4340 1.1 joerg if (DestType->isRValueReferenceType() || 4341 1.1.1.2 joerg (T1Quals.hasConst() && !T1Quals.hasVolatile())) { 4342 1.1.1.2 joerg Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, 4343 1.1.1.2 joerg /*BindingTemporary=*/true); 4344 1.1.1.2 joerg if (T1Quals.hasAddressSpace()) 4345 1.1.1.2 joerg Sequence.AddQualificationConversionStep( 4346 1.1.1.2 joerg cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue); 4347 1.1.1.2 joerg } else 4348 1.1 joerg Sequence.SetFailed( 4349 1.1 joerg InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); 4350 1.1 joerg } 4351 1.1 joerg } 4352 1.1 joerg 4353 1.1 joerg /// Attempt list initialization (C++0x [dcl.init.list]) 4354 1.1 joerg static void TryListInitialization(Sema &S, 4355 1.1 joerg const InitializedEntity &Entity, 4356 1.1 joerg const InitializationKind &Kind, 4357 1.1 joerg InitListExpr *InitList, 4358 1.1 joerg InitializationSequence &Sequence, 4359 1.1 joerg bool TreatUnavailableAsInvalid) { 4360 1.1 joerg QualType DestType = Entity.getType(); 4361 1.1 joerg 4362 1.1 joerg // C++ doesn't allow scalar initialization with more than one argument. 4363 1.1 joerg // But C99 complex numbers are scalars and it makes sense there. 4364 1.1 joerg if (S.getLangOpts().CPlusPlus && DestType->isScalarType() && 4365 1.1 joerg !DestType->isAnyComplexType() && InitList->getNumInits() > 1) { 4366 1.1 joerg Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); 4367 1.1 joerg return; 4368 1.1 joerg } 4369 1.1 joerg if (DestType->isReferenceType()) { 4370 1.1 joerg TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence, 4371 1.1 joerg TreatUnavailableAsInvalid); 4372 1.1 joerg return; 4373 1.1 joerg } 4374 1.1 joerg 4375 1.1 joerg if (DestType->isRecordType() && 4376 1.1 joerg !S.isCompleteType(InitList->getBeginLoc(), DestType)) { 4377 1.1 joerg Sequence.setIncompleteTypeFailure(DestType); 4378 1.1 joerg return; 4379 1.1 joerg } 4380 1.1 joerg 4381 1.1 joerg // C++11 [dcl.init.list]p3, per DR1467: 4382 1.1 joerg // - If T is a class type and the initializer list has a single element of 4383 1.1 joerg // type cv U, where U is T or a class derived from T, the object is 4384 1.1 joerg // initialized from that element (by copy-initialization for 4385 1.1 joerg // copy-list-initialization, or by direct-initialization for 4386 1.1 joerg // direct-list-initialization). 4387 1.1 joerg // - Otherwise, if T is a character array and the initializer list has a 4388 1.1 joerg // single element that is an appropriately-typed string literal 4389 1.1 joerg // (8.5.2 [dcl.init.string]), initialization is performed as described 4390 1.1 joerg // in that section. 4391 1.1 joerg // - Otherwise, if T is an aggregate, [...] (continue below). 4392 1.1 joerg if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) { 4393 1.1 joerg if (DestType->isRecordType()) { 4394 1.1 joerg QualType InitType = InitList->getInit(0)->getType(); 4395 1.1 joerg if (S.Context.hasSameUnqualifiedType(InitType, DestType) || 4396 1.1 joerg S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) { 4397 1.1 joerg Expr *InitListAsExpr = InitList; 4398 1.1 joerg TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, 4399 1.1 joerg DestType, Sequence, 4400 1.1 joerg /*InitListSyntax*/false, 4401 1.1 joerg /*IsInitListCopy*/true); 4402 1.1 joerg return; 4403 1.1 joerg } 4404 1.1 joerg } 4405 1.1 joerg if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) { 4406 1.1 joerg Expr *SubInit[1] = {InitList->getInit(0)}; 4407 1.1 joerg if (!isa<VariableArrayType>(DestAT) && 4408 1.1 joerg IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) { 4409 1.1 joerg InitializationKind SubKind = 4410 1.1 joerg Kind.getKind() == InitializationKind::IK_DirectList 4411 1.1 joerg ? InitializationKind::CreateDirect(Kind.getLocation(), 4412 1.1 joerg InitList->getLBraceLoc(), 4413 1.1 joerg InitList->getRBraceLoc()) 4414 1.1 joerg : Kind; 4415 1.1 joerg Sequence.InitializeFrom(S, Entity, SubKind, SubInit, 4416 1.1 joerg /*TopLevelOfInitList*/ true, 4417 1.1 joerg TreatUnavailableAsInvalid); 4418 1.1 joerg 4419 1.1 joerg // TryStringLiteralInitialization() (in InitializeFrom()) will fail if 4420 1.1 joerg // the element is not an appropriately-typed string literal, in which 4421 1.1 joerg // case we should proceed as in C++11 (below). 4422 1.1 joerg if (Sequence) { 4423 1.1 joerg Sequence.RewrapReferenceInitList(Entity.getType(), InitList); 4424 1.1 joerg return; 4425 1.1 joerg } 4426 1.1 joerg } 4427 1.1 joerg } 4428 1.1 joerg } 4429 1.1 joerg 4430 1.1 joerg // C++11 [dcl.init.list]p3: 4431 1.1 joerg // - If T is an aggregate, aggregate initialization is performed. 4432 1.1 joerg if ((DestType->isRecordType() && !DestType->isAggregateType()) || 4433 1.1 joerg (S.getLangOpts().CPlusPlus11 && 4434 1.1 joerg S.isStdInitializerList(DestType, nullptr))) { 4435 1.1 joerg if (S.getLangOpts().CPlusPlus11) { 4436 1.1 joerg // - Otherwise, if the initializer list has no elements and T is a 4437 1.1 joerg // class type with a default constructor, the object is 4438 1.1 joerg // value-initialized. 4439 1.1 joerg if (InitList->getNumInits() == 0) { 4440 1.1 joerg CXXRecordDecl *RD = DestType->getAsCXXRecordDecl(); 4441 1.1.1.2 joerg if (S.LookupDefaultConstructor(RD)) { 4442 1.1 joerg TryValueInitialization(S, Entity, Kind, Sequence, InitList); 4443 1.1 joerg return; 4444 1.1 joerg } 4445 1.1 joerg } 4446 1.1 joerg 4447 1.1 joerg // - Otherwise, if T is a specialization of std::initializer_list<E>, 4448 1.1 joerg // an initializer_list object constructed [...] 4449 1.1 joerg if (TryInitializerListConstruction(S, InitList, DestType, Sequence, 4450 1.1 joerg TreatUnavailableAsInvalid)) 4451 1.1 joerg return; 4452 1.1 joerg 4453 1.1 joerg // - Otherwise, if T is a class type, constructors are considered. 4454 1.1 joerg Expr *InitListAsExpr = InitList; 4455 1.1 joerg TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, 4456 1.1 joerg DestType, Sequence, /*InitListSyntax*/true); 4457 1.1 joerg } else 4458 1.1 joerg Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); 4459 1.1 joerg return; 4460 1.1 joerg } 4461 1.1 joerg 4462 1.1 joerg if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() && 4463 1.1 joerg InitList->getNumInits() == 1) { 4464 1.1 joerg Expr *E = InitList->getInit(0); 4465 1.1 joerg 4466 1.1 joerg // - Otherwise, if T is an enumeration with a fixed underlying type, 4467 1.1 joerg // the initializer-list has a single element v, and the initialization 4468 1.1 joerg // is direct-list-initialization, the object is initialized with the 4469 1.1 joerg // value T(v); if a narrowing conversion is required to convert v to 4470 1.1 joerg // the underlying type of T, the program is ill-formed. 4471 1.1 joerg auto *ET = DestType->getAs<EnumType>(); 4472 1.1 joerg if (S.getLangOpts().CPlusPlus17 && 4473 1.1 joerg Kind.getKind() == InitializationKind::IK_DirectList && 4474 1.1 joerg ET && ET->getDecl()->isFixed() && 4475 1.1 joerg !S.Context.hasSameUnqualifiedType(E->getType(), DestType) && 4476 1.1 joerg (E->getType()->isIntegralOrEnumerationType() || 4477 1.1 joerg E->getType()->isFloatingType())) { 4478 1.1 joerg // There are two ways that T(v) can work when T is an enumeration type. 4479 1.1 joerg // If there is either an implicit conversion sequence from v to T or 4480 1.1 joerg // a conversion function that can convert from v to T, then we use that. 4481 1.1 joerg // Otherwise, if v is of integral, enumeration, or floating-point type, 4482 1.1 joerg // it is converted to the enumeration type via its underlying type. 4483 1.1 joerg // There is no overlap possible between these two cases (except when the 4484 1.1 joerg // source value is already of the destination type), and the first 4485 1.1 joerg // case is handled by the general case for single-element lists below. 4486 1.1 joerg ImplicitConversionSequence ICS; 4487 1.1 joerg ICS.setStandard(); 4488 1.1 joerg ICS.Standard.setAsIdentityConversion(); 4489 1.1 joerg if (!E->isRValue()) 4490 1.1 joerg ICS.Standard.First = ICK_Lvalue_To_Rvalue; 4491 1.1 joerg // If E is of a floating-point type, then the conversion is ill-formed 4492 1.1 joerg // due to narrowing, but go through the motions in order to produce the 4493 1.1 joerg // right diagnostic. 4494 1.1 joerg ICS.Standard.Second = E->getType()->isFloatingType() 4495 1.1 joerg ? ICK_Floating_Integral 4496 1.1 joerg : ICK_Integral_Conversion; 4497 1.1 joerg ICS.Standard.setFromType(E->getType()); 4498 1.1 joerg ICS.Standard.setToType(0, E->getType()); 4499 1.1 joerg ICS.Standard.setToType(1, DestType); 4500 1.1 joerg ICS.Standard.setToType(2, DestType); 4501 1.1 joerg Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2), 4502 1.1 joerg /*TopLevelOfInitList*/true); 4503 1.1 joerg Sequence.RewrapReferenceInitList(Entity.getType(), InitList); 4504 1.1 joerg return; 4505 1.1 joerg } 4506 1.1 joerg 4507 1.1 joerg // - Otherwise, if the initializer list has a single element of type E 4508 1.1 joerg // [...references are handled above...], the object or reference is 4509 1.1 joerg // initialized from that element (by copy-initialization for 4510 1.1 joerg // copy-list-initialization, or by direct-initialization for 4511 1.1 joerg // direct-list-initialization); if a narrowing conversion is required 4512 1.1 joerg // to convert the element to T, the program is ill-formed. 4513 1.1 joerg // 4514 1.1 joerg // Per core-24034, this is direct-initialization if we were performing 4515 1.1 joerg // direct-list-initialization and copy-initialization otherwise. 4516 1.1 joerg // We can't use InitListChecker for this, because it always performs 4517 1.1 joerg // copy-initialization. This only matters if we might use an 'explicit' 4518 1.1.1.2 joerg // conversion operator, or for the special case conversion of nullptr_t to 4519 1.1.1.2 joerg // bool, so we only need to handle those cases. 4520 1.1.1.2 joerg // 4521 1.1.1.2 joerg // FIXME: Why not do this in all cases? 4522 1.1.1.2 joerg Expr *Init = InitList->getInit(0); 4523 1.1.1.2 joerg if (Init->getType()->isRecordType() || 4524 1.1.1.2 joerg (Init->getType()->isNullPtrType() && DestType->isBooleanType())) { 4525 1.1 joerg InitializationKind SubKind = 4526 1.1 joerg Kind.getKind() == InitializationKind::IK_DirectList 4527 1.1 joerg ? InitializationKind::CreateDirect(Kind.getLocation(), 4528 1.1 joerg InitList->getLBraceLoc(), 4529 1.1 joerg InitList->getRBraceLoc()) 4530 1.1 joerg : Kind; 4531 1.1.1.2 joerg Expr *SubInit[1] = { Init }; 4532 1.1 joerg Sequence.InitializeFrom(S, Entity, SubKind, SubInit, 4533 1.1 joerg /*TopLevelOfInitList*/true, 4534 1.1 joerg TreatUnavailableAsInvalid); 4535 1.1 joerg if (Sequence) 4536 1.1 joerg Sequence.RewrapReferenceInitList(Entity.getType(), InitList); 4537 1.1 joerg return; 4538 1.1 joerg } 4539 1.1 joerg } 4540 1.1 joerg 4541 1.1 joerg InitListChecker CheckInitList(S, Entity, InitList, 4542 1.1 joerg DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid); 4543 1.1 joerg if (CheckInitList.HadError()) { 4544 1.1 joerg Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed); 4545 1.1 joerg return; 4546 1.1 joerg } 4547 1.1 joerg 4548 1.1 joerg // Add the list initialization step with the built init list. 4549 1.1 joerg Sequence.AddListInitializationStep(DestType); 4550 1.1 joerg } 4551 1.1 joerg 4552 1.1 joerg /// Try a reference initialization that involves calling a conversion 4553 1.1 joerg /// function. 4554 1.1 joerg static OverloadingResult TryRefInitWithConversionFunction( 4555 1.1 joerg Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, 4556 1.1 joerg Expr *Initializer, bool AllowRValues, bool IsLValueRef, 4557 1.1 joerg InitializationSequence &Sequence) { 4558 1.1 joerg QualType DestType = Entity.getType(); 4559 1.1 joerg QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); 4560 1.1 joerg QualType T1 = cv1T1.getUnqualifiedType(); 4561 1.1 joerg QualType cv2T2 = Initializer->getType(); 4562 1.1 joerg QualType T2 = cv2T2.getUnqualifiedType(); 4563 1.1 joerg 4564 1.1.1.2 joerg assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && 4565 1.1 joerg "Must have incompatible references when binding via conversion"); 4566 1.1 joerg 4567 1.1 joerg // Build the candidate set directly in the initialization sequence 4568 1.1 joerg // structure, so that it will persist if we fail. 4569 1.1 joerg OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 4570 1.1 joerg CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4571 1.1 joerg 4572 1.1 joerg // Determine whether we are allowed to call explicit conversion operators. 4573 1.1 joerg // Note that none of [over.match.copy], [over.match.conv], nor 4574 1.1 joerg // [over.match.ref] permit an explicit constructor to be chosen when 4575 1.1 joerg // initializing a reference, not even for direct-initialization. 4576 1.1 joerg bool AllowExplicitCtors = false; 4577 1.1 joerg bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding(); 4578 1.1 joerg 4579 1.1 joerg const RecordType *T1RecordType = nullptr; 4580 1.1 joerg if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) && 4581 1.1 joerg S.isCompleteType(Kind.getLocation(), T1)) { 4582 1.1 joerg // The type we're converting to is a class type. Enumerate its constructors 4583 1.1 joerg // to see if there is a suitable conversion. 4584 1.1 joerg CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); 4585 1.1 joerg 4586 1.1 joerg for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) { 4587 1.1 joerg auto Info = getConstructorInfo(D); 4588 1.1 joerg if (!Info.Constructor) 4589 1.1 joerg continue; 4590 1.1 joerg 4591 1.1 joerg if (!Info.Constructor->isInvalidDecl() && 4592 1.1.1.2 joerg Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { 4593 1.1 joerg if (Info.ConstructorTmpl) 4594 1.1 joerg S.AddTemplateOverloadCandidate( 4595 1.1 joerg Info.ConstructorTmpl, Info.FoundDecl, 4596 1.1 joerg /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, 4597 1.1 joerg /*SuppressUserConversions=*/true, 4598 1.1 joerg /*PartialOverloading*/ false, AllowExplicitCtors); 4599 1.1 joerg else 4600 1.1 joerg S.AddOverloadCandidate( 4601 1.1 joerg Info.Constructor, Info.FoundDecl, Initializer, CandidateSet, 4602 1.1 joerg /*SuppressUserConversions=*/true, 4603 1.1 joerg /*PartialOverloading*/ false, AllowExplicitCtors); 4604 1.1 joerg } 4605 1.1 joerg } 4606 1.1 joerg } 4607 1.1 joerg if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) 4608 1.1 joerg return OR_No_Viable_Function; 4609 1.1 joerg 4610 1.1 joerg const RecordType *T2RecordType = nullptr; 4611 1.1 joerg if ((T2RecordType = T2->getAs<RecordType>()) && 4612 1.1 joerg S.isCompleteType(Kind.getLocation(), T2)) { 4613 1.1 joerg // The type we're converting from is a class type, enumerate its conversion 4614 1.1 joerg // functions. 4615 1.1 joerg CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); 4616 1.1 joerg 4617 1.1 joerg const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4618 1.1 joerg for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4619 1.1 joerg NamedDecl *D = *I; 4620 1.1 joerg CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4621 1.1 joerg if (isa<UsingShadowDecl>(D)) 4622 1.1 joerg D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4623 1.1 joerg 4624 1.1 joerg FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 4625 1.1 joerg CXXConversionDecl *Conv; 4626 1.1 joerg if (ConvTemplate) 4627 1.1 joerg Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4628 1.1 joerg else 4629 1.1 joerg Conv = cast<CXXConversionDecl>(D); 4630 1.1 joerg 4631 1.1 joerg // If the conversion function doesn't return a reference type, 4632 1.1 joerg // it can't be considered for this conversion unless we're allowed to 4633 1.1 joerg // consider rvalues. 4634 1.1 joerg // FIXME: Do we need to make sure that we only consider conversion 4635 1.1 joerg // candidates with reference-compatible results? That might be needed to 4636 1.1 joerg // break recursion. 4637 1.1.1.2 joerg if ((AllowRValues || 4638 1.1 joerg Conv->getConversionType()->isLValueReferenceType())) { 4639 1.1 joerg if (ConvTemplate) 4640 1.1 joerg S.AddTemplateConversionCandidate( 4641 1.1 joerg ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, 4642 1.1 joerg CandidateSet, 4643 1.1 joerg /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs); 4644 1.1 joerg else 4645 1.1 joerg S.AddConversionCandidate( 4646 1.1 joerg Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet, 4647 1.1 joerg /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs); 4648 1.1 joerg } 4649 1.1 joerg } 4650 1.1 joerg } 4651 1.1 joerg if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) 4652 1.1 joerg return OR_No_Viable_Function; 4653 1.1 joerg 4654 1.1 joerg SourceLocation DeclLoc = Initializer->getBeginLoc(); 4655 1.1 joerg 4656 1.1 joerg // Perform overload resolution. If it fails, return the failed result. 4657 1.1 joerg OverloadCandidateSet::iterator Best; 4658 1.1 joerg if (OverloadingResult Result 4659 1.1 joerg = CandidateSet.BestViableFunction(S, DeclLoc, Best)) 4660 1.1 joerg return Result; 4661 1.1 joerg 4662 1.1 joerg FunctionDecl *Function = Best->Function; 4663 1.1 joerg // This is the overload that will be used for this initialization step if we 4664 1.1 joerg // use this initialization. Mark it as referenced. 4665 1.1 joerg Function->setReferenced(); 4666 1.1 joerg 4667 1.1 joerg // Compute the returned type and value kind of the conversion. 4668 1.1 joerg QualType cv3T3; 4669 1.1 joerg if (isa<CXXConversionDecl>(Function)) 4670 1.1 joerg cv3T3 = Function->getReturnType(); 4671 1.1 joerg else 4672 1.1 joerg cv3T3 = T1; 4673 1.1 joerg 4674 1.1 joerg ExprValueKind VK = VK_RValue; 4675 1.1 joerg if (cv3T3->isLValueReferenceType()) 4676 1.1 joerg VK = VK_LValue; 4677 1.1 joerg else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>()) 4678 1.1 joerg VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; 4679 1.1 joerg cv3T3 = cv3T3.getNonLValueExprType(S.Context); 4680 1.1 joerg 4681 1.1 joerg // Add the user-defined conversion step. 4682 1.1 joerg bool HadMultipleCandidates = (CandidateSet.size() > 1); 4683 1.1 joerg Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3, 4684 1.1 joerg HadMultipleCandidates); 4685 1.1 joerg 4686 1.1 joerg // Determine whether we'll need to perform derived-to-base adjustments or 4687 1.1 joerg // other conversions. 4688 1.1.1.2 joerg Sema::ReferenceConversions RefConv; 4689 1.1 joerg Sema::ReferenceCompareResult NewRefRelationship = 4690 1.1.1.2 joerg S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv); 4691 1.1 joerg 4692 1.1 joerg // Add the final conversion sequence, if necessary. 4693 1.1 joerg if (NewRefRelationship == Sema::Ref_Incompatible) { 4694 1.1 joerg assert(!isa<CXXConstructorDecl>(Function) && 4695 1.1 joerg "should not have conversion after constructor"); 4696 1.1 joerg 4697 1.1 joerg ImplicitConversionSequence ICS; 4698 1.1 joerg ICS.setStandard(); 4699 1.1 joerg ICS.Standard = Best->FinalConversion; 4700 1.1 joerg Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2)); 4701 1.1 joerg 4702 1.1 joerg // Every implicit conversion results in a prvalue, except for a glvalue 4703 1.1 joerg // derived-to-base conversion, which we handle below. 4704 1.1 joerg cv3T3 = ICS.Standard.getToType(2); 4705 1.1 joerg VK = VK_RValue; 4706 1.1 joerg } 4707 1.1 joerg 4708 1.1 joerg // If the converted initializer is a prvalue, its type T4 is adjusted to 4709 1.1 joerg // type "cv1 T4" and the temporary materialization conversion is applied. 4710 1.1 joerg // 4711 1.1 joerg // We adjust the cv-qualifications to match the reference regardless of 4712 1.1 joerg // whether we have a prvalue so that the AST records the change. In this 4713 1.1 joerg // case, T4 is "cv3 T3". 4714 1.1 joerg QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers()); 4715 1.1 joerg if (cv1T4.getQualifiers() != cv3T3.getQualifiers()) 4716 1.1 joerg Sequence.AddQualificationConversionStep(cv1T4, VK); 4717 1.1 joerg Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue); 4718 1.1 joerg VK = IsLValueRef ? VK_LValue : VK_XValue; 4719 1.1 joerg 4720 1.1.1.2 joerg if (RefConv & Sema::ReferenceConversions::DerivedToBase) 4721 1.1 joerg Sequence.AddDerivedToBaseCastStep(cv1T1, VK); 4722 1.1.1.2 joerg else if (RefConv & Sema::ReferenceConversions::ObjC) 4723 1.1 joerg Sequence.AddObjCObjectConversionStep(cv1T1); 4724 1.1.1.2 joerg else if (RefConv & Sema::ReferenceConversions::Function) 4725 1.1.1.2 joerg Sequence.AddFunctionReferenceConversionStep(cv1T1); 4726 1.1.1.2 joerg else if (RefConv & Sema::ReferenceConversions::Qualification) { 4727 1.1.1.2 joerg if (!S.Context.hasSameType(cv1T4, cv1T1)) 4728 1.1.1.2 joerg Sequence.AddQualificationConversionStep(cv1T1, VK); 4729 1.1.1.2 joerg } 4730 1.1 joerg 4731 1.1 joerg return OR_Success; 4732 1.1 joerg } 4733 1.1 joerg 4734 1.1 joerg static void CheckCXX98CompatAccessibleCopy(Sema &S, 4735 1.1 joerg const InitializedEntity &Entity, 4736 1.1 joerg Expr *CurInitExpr); 4737 1.1 joerg 4738 1.1 joerg /// Attempt reference initialization (C++0x [dcl.init.ref]) 4739 1.1 joerg static void TryReferenceInitialization(Sema &S, 4740 1.1 joerg const InitializedEntity &Entity, 4741 1.1 joerg const InitializationKind &Kind, 4742 1.1 joerg Expr *Initializer, 4743 1.1 joerg InitializationSequence &Sequence) { 4744 1.1 joerg QualType DestType = Entity.getType(); 4745 1.1 joerg QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); 4746 1.1 joerg Qualifiers T1Quals; 4747 1.1 joerg QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 4748 1.1.1.2 joerg QualType cv2T2 = S.getCompletedType(Initializer); 4749 1.1 joerg Qualifiers T2Quals; 4750 1.1 joerg QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 4751 1.1 joerg 4752 1.1 joerg // If the initializer is the address of an overloaded function, try 4753 1.1 joerg // to resolve the overloaded function. If all goes well, T2 is the 4754 1.1 joerg // type of the resulting function. 4755 1.1 joerg if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, 4756 1.1 joerg T1, Sequence)) 4757 1.1 joerg return; 4758 1.1 joerg 4759 1.1 joerg // Delegate everything else to a subfunction. 4760 1.1 joerg TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, 4761 1.1 joerg T1Quals, cv2T2, T2, T2Quals, Sequence); 4762 1.1 joerg } 4763 1.1 joerg 4764 1.1 joerg /// Determine whether an expression is a non-referenceable glvalue (one to 4765 1.1 joerg /// which a reference can never bind). Attempting to bind a reference to 4766 1.1 joerg /// such a glvalue will always create a temporary. 4767 1.1 joerg static bool isNonReferenceableGLValue(Expr *E) { 4768 1.1.1.2 joerg return E->refersToBitField() || E->refersToVectorElement() || 4769 1.1.1.2 joerg E->refersToMatrixElement(); 4770 1.1 joerg } 4771 1.1 joerg 4772 1.1 joerg /// Reference initialization without resolving overloaded functions. 4773 1.1.1.2 joerg /// 4774 1.1.1.2 joerg /// We also can get here in C if we call a builtin which is declared as 4775 1.1.1.2 joerg /// a function with a parameter of reference type (such as __builtin_va_end()). 4776 1.1 joerg static void TryReferenceInitializationCore(Sema &S, 4777 1.1 joerg const InitializedEntity &Entity, 4778 1.1 joerg const InitializationKind &Kind, 4779 1.1 joerg Expr *Initializer, 4780 1.1 joerg QualType cv1T1, QualType T1, 4781 1.1 joerg Qualifiers T1Quals, 4782 1.1 joerg QualType cv2T2, QualType T2, 4783 1.1 joerg Qualifiers T2Quals, 4784 1.1 joerg InitializationSequence &Sequence) { 4785 1.1 joerg QualType DestType = Entity.getType(); 4786 1.1 joerg SourceLocation DeclLoc = Initializer->getBeginLoc(); 4787 1.1.1.2 joerg 4788 1.1 joerg // Compute some basic properties of the types and the initializer. 4789 1.1 joerg bool isLValueRef = DestType->isLValueReferenceType(); 4790 1.1 joerg bool isRValueRef = !isLValueRef; 4791 1.1 joerg Expr::Classification InitCategory = Initializer->Classify(S.Context); 4792 1.1.1.2 joerg 4793 1.1.1.2 joerg Sema::ReferenceConversions RefConv; 4794 1.1.1.2 joerg Sema::ReferenceCompareResult RefRelationship = 4795 1.1.1.2 joerg S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv); 4796 1.1 joerg 4797 1.1 joerg // C++0x [dcl.init.ref]p5: 4798 1.1 joerg // A reference to type "cv1 T1" is initialized by an expression of type 4799 1.1 joerg // "cv2 T2" as follows: 4800 1.1 joerg // 4801 1.1 joerg // - If the reference is an lvalue reference and the initializer 4802 1.1 joerg // expression 4803 1.1 joerg // Note the analogous bullet points for rvalue refs to functions. Because 4804 1.1 joerg // there are no function rvalues in C++, rvalue refs to functions are treated 4805 1.1 joerg // like lvalue refs. 4806 1.1 joerg OverloadingResult ConvOvlResult = OR_Success; 4807 1.1 joerg bool T1Function = T1->isFunctionType(); 4808 1.1 joerg if (isLValueRef || T1Function) { 4809 1.1 joerg if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) && 4810 1.1 joerg (RefRelationship == Sema::Ref_Compatible || 4811 1.1 joerg (Kind.isCStyleOrFunctionalCast() && 4812 1.1 joerg RefRelationship == Sema::Ref_Related))) { 4813 1.1 joerg // - is an lvalue (but is not a bit-field), and "cv1 T1" is 4814 1.1 joerg // reference-compatible with "cv2 T2," or 4815 1.1.1.2 joerg if (RefConv & (Sema::ReferenceConversions::DerivedToBase | 4816 1.1.1.2 joerg Sema::ReferenceConversions::ObjC)) { 4817 1.1.1.2 joerg // If we're converting the pointee, add any qualifiers first; 4818 1.1.1.2 joerg // these qualifiers must all be top-level, so just convert to "cv1 T2". 4819 1.1.1.2 joerg if (RefConv & (Sema::ReferenceConversions::Qualification)) 4820 1.1.1.2 joerg Sequence.AddQualificationConversionStep( 4821 1.1.1.2 joerg S.Context.getQualifiedType(T2, T1Quals), 4822 1.1.1.2 joerg Initializer->getValueKind()); 4823 1.1.1.2 joerg if (RefConv & Sema::ReferenceConversions::DerivedToBase) 4824 1.1.1.2 joerg Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue); 4825 1.1.1.2 joerg else 4826 1.1.1.2 joerg Sequence.AddObjCObjectConversionStep(cv1T1); 4827 1.1.1.2 joerg } else if (RefConv & Sema::ReferenceConversions::Qualification) { 4828 1.1.1.2 joerg // Perform a (possibly multi-level) qualification conversion. 4829 1.1.1.2 joerg Sequence.AddQualificationConversionStep(cv1T1, 4830 1.1.1.2 joerg Initializer->getValueKind()); 4831 1.1.1.2 joerg } else if (RefConv & Sema::ReferenceConversions::Function) { 4832 1.1.1.2 joerg Sequence.AddFunctionReferenceConversionStep(cv1T1); 4833 1.1.1.2 joerg } 4834 1.1 joerg 4835 1.1 joerg // We only create a temporary here when binding a reference to a 4836 1.1 joerg // bit-field or vector element. Those cases are't supposed to be 4837 1.1 joerg // handled by this bullet, but the outcome is the same either way. 4838 1.1 joerg Sequence.AddReferenceBindingStep(cv1T1, false); 4839 1.1 joerg return; 4840 1.1 joerg } 4841 1.1 joerg 4842 1.1 joerg // - has a class type (i.e., T2 is a class type), where T1 is not 4843 1.1 joerg // reference-related to T2, and can be implicitly converted to an 4844 1.1 joerg // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible 4845 1.1 joerg // with "cv3 T3" (this conversion is selected by enumerating the 4846 1.1 joerg // applicable conversion functions (13.3.1.6) and choosing the best 4847 1.1 joerg // one through overload resolution (13.3)), 4848 1.1 joerg // If we have an rvalue ref to function type here, the rhs must be 4849 1.1 joerg // an rvalue. DR1287 removed the "implicitly" here. 4850 1.1 joerg if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && 4851 1.1 joerg (isLValueRef || InitCategory.isRValue())) { 4852 1.1.1.2 joerg if (S.getLangOpts().CPlusPlus) { 4853 1.1.1.2 joerg // Try conversion functions only for C++. 4854 1.1.1.2 joerg ConvOvlResult = TryRefInitWithConversionFunction( 4855 1.1.1.2 joerg S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef, 4856 1.1.1.2 joerg /*IsLValueRef*/ isLValueRef, Sequence); 4857 1.1.1.2 joerg if (ConvOvlResult == OR_Success) 4858 1.1.1.2 joerg return; 4859 1.1.1.2 joerg if (ConvOvlResult != OR_No_Viable_Function) 4860 1.1.1.2 joerg Sequence.SetOverloadFailure( 4861 1.1.1.2 joerg InitializationSequence::FK_ReferenceInitOverloadFailed, 4862 1.1.1.2 joerg ConvOvlResult); 4863 1.1.1.2 joerg } else { 4864 1.1.1.2 joerg ConvOvlResult = OR_No_Viable_Function; 4865 1.1.1.2 joerg } 4866 1.1 joerg } 4867 1.1 joerg } 4868 1.1 joerg 4869 1.1 joerg // - Otherwise, the reference shall be an lvalue reference to a 4870 1.1 joerg // non-volatile const type (i.e., cv1 shall be const), or the reference 4871 1.1 joerg // shall be an rvalue reference. 4872 1.1 joerg // For address spaces, we interpret this to mean that an addr space 4873 1.1 joerg // of a reference "cv1 T1" is a superset of addr space of "cv2 T2". 4874 1.1 joerg if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() && 4875 1.1 joerg T1Quals.isAddressSpaceSupersetOf(T2Quals))) { 4876 1.1 joerg if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 4877 1.1 joerg Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 4878 1.1 joerg else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 4879 1.1 joerg Sequence.SetOverloadFailure( 4880 1.1 joerg InitializationSequence::FK_ReferenceInitOverloadFailed, 4881 1.1 joerg ConvOvlResult); 4882 1.1 joerg else if (!InitCategory.isLValue()) 4883 1.1 joerg Sequence.SetFailed( 4884 1.1 joerg T1Quals.isAddressSpaceSupersetOf(T2Quals) 4885 1.1 joerg ? InitializationSequence:: 4886 1.1 joerg FK_NonConstLValueReferenceBindingToTemporary 4887 1.1 joerg : InitializationSequence::FK_ReferenceInitDropsQualifiers); 4888 1.1 joerg else { 4889 1.1 joerg InitializationSequence::FailureKind FK; 4890 1.1 joerg switch (RefRelationship) { 4891 1.1 joerg case Sema::Ref_Compatible: 4892 1.1 joerg if (Initializer->refersToBitField()) 4893 1.1 joerg FK = InitializationSequence:: 4894 1.1 joerg FK_NonConstLValueReferenceBindingToBitfield; 4895 1.1 joerg else if (Initializer->refersToVectorElement()) 4896 1.1 joerg FK = InitializationSequence:: 4897 1.1 joerg FK_NonConstLValueReferenceBindingToVectorElement; 4898 1.1.1.2 joerg else if (Initializer->refersToMatrixElement()) 4899 1.1.1.2 joerg FK = InitializationSequence:: 4900 1.1.1.2 joerg FK_NonConstLValueReferenceBindingToMatrixElement; 4901 1.1 joerg else 4902 1.1 joerg llvm_unreachable("unexpected kind of compatible initializer"); 4903 1.1 joerg break; 4904 1.1 joerg case Sema::Ref_Related: 4905 1.1 joerg FK = InitializationSequence::FK_ReferenceInitDropsQualifiers; 4906 1.1 joerg break; 4907 1.1 joerg case Sema::Ref_Incompatible: 4908 1.1 joerg FK = InitializationSequence:: 4909 1.1 joerg FK_NonConstLValueReferenceBindingToUnrelated; 4910 1.1 joerg break; 4911 1.1 joerg } 4912 1.1 joerg Sequence.SetFailed(FK); 4913 1.1 joerg } 4914 1.1 joerg return; 4915 1.1 joerg } 4916 1.1 joerg 4917 1.1 joerg // - If the initializer expression 4918 1.1 joerg // - is an 4919 1.1 joerg // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or 4920 1.1 joerg // [1z] rvalue (but not a bit-field) or 4921 1.1 joerg // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2" 4922 1.1 joerg // 4923 1.1 joerg // Note: functions are handled above and below rather than here... 4924 1.1 joerg if (!T1Function && 4925 1.1 joerg (RefRelationship == Sema::Ref_Compatible || 4926 1.1 joerg (Kind.isCStyleOrFunctionalCast() && 4927 1.1 joerg RefRelationship == Sema::Ref_Related)) && 4928 1.1 joerg ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) || 4929 1.1 joerg (InitCategory.isPRValue() && 4930 1.1 joerg (S.getLangOpts().CPlusPlus17 || T2->isRecordType() || 4931 1.1 joerg T2->isArrayType())))) { 4932 1.1 joerg ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue; 4933 1.1 joerg if (InitCategory.isPRValue() && T2->isRecordType()) { 4934 1.1 joerg // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the 4935 1.1 joerg // compiler the freedom to perform a copy here or bind to the 4936 1.1 joerg // object, while C++0x requires that we bind directly to the 4937 1.1 joerg // object. Hence, we always bind to the object without making an 4938 1.1 joerg // extra copy. However, in C++03 requires that we check for the 4939 1.1 joerg // presence of a suitable copy constructor: 4940 1.1 joerg // 4941 1.1 joerg // The constructor that would be used to make the copy shall 4942 1.1 joerg // be callable whether or not the copy is actually done. 4943 1.1 joerg if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt) 4944 1.1 joerg Sequence.AddExtraneousCopyToTemporary(cv2T2); 4945 1.1 joerg else if (S.getLangOpts().CPlusPlus11) 4946 1.1 joerg CheckCXX98CompatAccessibleCopy(S, Entity, Initializer); 4947 1.1 joerg } 4948 1.1 joerg 4949 1.1 joerg // C++1z [dcl.init.ref]/5.2.1.2: 4950 1.1 joerg // If the converted initializer is a prvalue, its type T4 is adjusted 4951 1.1 joerg // to type "cv1 T4" and the temporary materialization conversion is 4952 1.1 joerg // applied. 4953 1.1 joerg // Postpone address space conversions to after the temporary materialization 4954 1.1 joerg // conversion to allow creating temporaries in the alloca address space. 4955 1.1 joerg auto T1QualsIgnoreAS = T1Quals; 4956 1.1 joerg auto T2QualsIgnoreAS = T2Quals; 4957 1.1 joerg if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { 4958 1.1 joerg T1QualsIgnoreAS.removeAddressSpace(); 4959 1.1 joerg T2QualsIgnoreAS.removeAddressSpace(); 4960 1.1 joerg } 4961 1.1 joerg QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS); 4962 1.1 joerg if (T1QualsIgnoreAS != T2QualsIgnoreAS) 4963 1.1 joerg Sequence.AddQualificationConversionStep(cv1T4, ValueKind); 4964 1.1 joerg Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue); 4965 1.1 joerg ValueKind = isLValueRef ? VK_LValue : VK_XValue; 4966 1.1 joerg // Add addr space conversion if required. 4967 1.1 joerg if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { 4968 1.1 joerg auto T4Quals = cv1T4.getQualifiers(); 4969 1.1 joerg T4Quals.addAddressSpace(T1Quals.getAddressSpace()); 4970 1.1 joerg QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals); 4971 1.1 joerg Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind); 4972 1.1.1.2 joerg cv1T4 = cv1T4WithAS; 4973 1.1 joerg } 4974 1.1 joerg 4975 1.1 joerg // In any case, the reference is bound to the resulting glvalue (or to 4976 1.1 joerg // an appropriate base class subobject). 4977 1.1.1.2 joerg if (RefConv & Sema::ReferenceConversions::DerivedToBase) 4978 1.1 joerg Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind); 4979 1.1.1.2 joerg else if (RefConv & Sema::ReferenceConversions::ObjC) 4980 1.1 joerg Sequence.AddObjCObjectConversionStep(cv1T1); 4981 1.1.1.2 joerg else if (RefConv & Sema::ReferenceConversions::Qualification) { 4982 1.1.1.2 joerg if (!S.Context.hasSameType(cv1T4, cv1T1)) 4983 1.1.1.2 joerg Sequence.AddQualificationConversionStep(cv1T1, ValueKind); 4984 1.1.1.2 joerg } 4985 1.1 joerg return; 4986 1.1 joerg } 4987 1.1 joerg 4988 1.1 joerg // - has a class type (i.e., T2 is a class type), where T1 is not 4989 1.1 joerg // reference-related to T2, and can be implicitly converted to an 4990 1.1 joerg // xvalue, class prvalue, or function lvalue of type "cv3 T3", 4991 1.1 joerg // where "cv1 T1" is reference-compatible with "cv3 T3", 4992 1.1 joerg // 4993 1.1 joerg // DR1287 removes the "implicitly" here. 4994 1.1 joerg if (T2->isRecordType()) { 4995 1.1 joerg if (RefRelationship == Sema::Ref_Incompatible) { 4996 1.1 joerg ConvOvlResult = TryRefInitWithConversionFunction( 4997 1.1 joerg S, Entity, Kind, Initializer, /*AllowRValues*/ true, 4998 1.1 joerg /*IsLValueRef*/ isLValueRef, Sequence); 4999 1.1 joerg if (ConvOvlResult) 5000 1.1 joerg Sequence.SetOverloadFailure( 5001 1.1 joerg InitializationSequence::FK_ReferenceInitOverloadFailed, 5002 1.1 joerg ConvOvlResult); 5003 1.1 joerg 5004 1.1 joerg return; 5005 1.1 joerg } 5006 1.1 joerg 5007 1.1 joerg if (RefRelationship == Sema::Ref_Compatible && 5008 1.1 joerg isRValueRef && InitCategory.isLValue()) { 5009 1.1 joerg Sequence.SetFailed( 5010 1.1 joerg InitializationSequence::FK_RValueReferenceBindingToLValue); 5011 1.1 joerg return; 5012 1.1 joerg } 5013 1.1 joerg 5014 1.1 joerg Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 5015 1.1 joerg return; 5016 1.1 joerg } 5017 1.1 joerg 5018 1.1 joerg // - Otherwise, a temporary of type "cv1 T1" is created and initialized 5019 1.1 joerg // from the initializer expression using the rules for a non-reference 5020 1.1 joerg // copy-initialization (8.5). The reference is then bound to the 5021 1.1 joerg // temporary. [...] 5022 1.1 joerg 5023 1.1 joerg // Ignore address space of reference type at this point and perform address 5024 1.1 joerg // space conversion after the reference binding step. 5025 1.1 joerg QualType cv1T1IgnoreAS = 5026 1.1 joerg T1Quals.hasAddressSpace() 5027 1.1 joerg ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace()) 5028 1.1 joerg : cv1T1; 5029 1.1 joerg 5030 1.1 joerg InitializedEntity TempEntity = 5031 1.1 joerg InitializedEntity::InitializeTemporary(cv1T1IgnoreAS); 5032 1.1 joerg 5033 1.1 joerg // FIXME: Why do we use an implicit conversion here rather than trying 5034 1.1 joerg // copy-initialization? 5035 1.1 joerg ImplicitConversionSequence ICS 5036 1.1 joerg = S.TryImplicitConversion(Initializer, TempEntity.getType(), 5037 1.1 joerg /*SuppressUserConversions=*/false, 5038 1.1.1.2 joerg Sema::AllowedExplicit::None, 5039 1.1 joerg /*FIXME:InOverloadResolution=*/false, 5040 1.1 joerg /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 5041 1.1 joerg /*AllowObjCWritebackConversion=*/false); 5042 1.1 joerg 5043 1.1 joerg if (ICS.isBad()) { 5044 1.1 joerg // FIXME: Use the conversion function set stored in ICS to turn 5045 1.1 joerg // this into an overloading ambiguity diagnostic. However, we need 5046 1.1 joerg // to keep that set as an OverloadCandidateSet rather than as some 5047 1.1 joerg // other kind of set. 5048 1.1 joerg if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 5049 1.1 joerg Sequence.SetOverloadFailure( 5050 1.1 joerg InitializationSequence::FK_ReferenceInitOverloadFailed, 5051 1.1 joerg ConvOvlResult); 5052 1.1 joerg else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 5053 1.1 joerg Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 5054 1.1 joerg else 5055 1.1 joerg Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); 5056 1.1 joerg return; 5057 1.1 joerg } else { 5058 1.1 joerg Sequence.AddConversionSequenceStep(ICS, TempEntity.getType()); 5059 1.1 joerg } 5060 1.1 joerg 5061 1.1 joerg // [...] If T1 is reference-related to T2, cv1 must be the 5062 1.1 joerg // same cv-qualification as, or greater cv-qualification 5063 1.1 joerg // than, cv2; otherwise, the program is ill-formed. 5064 1.1 joerg unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); 5065 1.1 joerg unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); 5066 1.1 joerg if ((RefRelationship == Sema::Ref_Related && 5067 1.1 joerg (T1CVRQuals | T2CVRQuals) != T1CVRQuals) || 5068 1.1 joerg !T1Quals.isAddressSpaceSupersetOf(T2Quals)) { 5069 1.1 joerg Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 5070 1.1 joerg return; 5071 1.1 joerg } 5072 1.1 joerg 5073 1.1 joerg // [...] If T1 is reference-related to T2 and the reference is an rvalue 5074 1.1 joerg // reference, the initializer expression shall not be an lvalue. 5075 1.1 joerg if (RefRelationship >= Sema::Ref_Related && !isLValueRef && 5076 1.1 joerg InitCategory.isLValue()) { 5077 1.1 joerg Sequence.SetFailed( 5078 1.1 joerg InitializationSequence::FK_RValueReferenceBindingToLValue); 5079 1.1 joerg return; 5080 1.1 joerg } 5081 1.1 joerg 5082 1.1 joerg Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true); 5083 1.1 joerg 5084 1.1 joerg if (T1Quals.hasAddressSpace()) { 5085 1.1 joerg if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(), 5086 1.1 joerg LangAS::Default)) { 5087 1.1 joerg Sequence.SetFailed( 5088 1.1 joerg InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary); 5089 1.1 joerg return; 5090 1.1 joerg } 5091 1.1 joerg Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue 5092 1.1 joerg : VK_XValue); 5093 1.1 joerg } 5094 1.1 joerg } 5095 1.1 joerg 5096 1.1 joerg /// Attempt character array initialization from a string literal 5097 1.1 joerg /// (C++ [dcl.init.string], C99 6.7.8). 5098 1.1 joerg static void TryStringLiteralInitialization(Sema &S, 5099 1.1 joerg const InitializedEntity &Entity, 5100 1.1 joerg const InitializationKind &Kind, 5101 1.1 joerg Expr *Initializer, 5102 1.1 joerg InitializationSequence &Sequence) { 5103 1.1 joerg Sequence.AddStringInitStep(Entity.getType()); 5104 1.1 joerg } 5105 1.1 joerg 5106 1.1 joerg /// Attempt value initialization (C++ [dcl.init]p7). 5107 1.1 joerg static void TryValueInitialization(Sema &S, 5108 1.1 joerg const InitializedEntity &Entity, 5109 1.1 joerg const InitializationKind &Kind, 5110 1.1 joerg InitializationSequence &Sequence, 5111 1.1 joerg InitListExpr *InitList) { 5112 1.1 joerg assert((!InitList || InitList->getNumInits() == 0) && 5113 1.1 joerg "Shouldn't use value-init for non-empty init lists"); 5114 1.1 joerg 5115 1.1 joerg // C++98 [dcl.init]p5, C++11 [dcl.init]p7: 5116 1.1 joerg // 5117 1.1 joerg // To value-initialize an object of type T means: 5118 1.1 joerg QualType T = Entity.getType(); 5119 1.1 joerg 5120 1.1 joerg // -- if T is an array type, then each element is value-initialized; 5121 1.1 joerg T = S.Context.getBaseElementType(T); 5122 1.1 joerg 5123 1.1 joerg if (const RecordType *RT = T->getAs<RecordType>()) { 5124 1.1 joerg if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 5125 1.1 joerg bool NeedZeroInitialization = true; 5126 1.1 joerg // C++98: 5127 1.1 joerg // -- if T is a class type (clause 9) with a user-declared constructor 5128 1.1 joerg // (12.1), then the default constructor for T is called (and the 5129 1.1 joerg // initialization is ill-formed if T has no accessible default 5130 1.1 joerg // constructor); 5131 1.1 joerg // C++11: 5132 1.1 joerg // -- if T is a class type (clause 9) with either no default constructor 5133 1.1 joerg // (12.1 [class.ctor]) or a default constructor that is user-provided 5134 1.1 joerg // or deleted, then the object is default-initialized; 5135 1.1 joerg // 5136 1.1 joerg // Note that the C++11 rule is the same as the C++98 rule if there are no 5137 1.1 joerg // defaulted or deleted constructors, so we just use it unconditionally. 5138 1.1 joerg CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl); 5139 1.1 joerg if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted()) 5140 1.1 joerg NeedZeroInitialization = false; 5141 1.1 joerg 5142 1.1 joerg // -- if T is a (possibly cv-qualified) non-union class type without a 5143 1.1 joerg // user-provided or deleted default constructor, then the object is 5144 1.1 joerg // zero-initialized and, if T has a non-trivial default constructor, 5145 1.1 joerg // default-initialized; 5146 1.1 joerg // The 'non-union' here was removed by DR1502. The 'non-trivial default 5147 1.1 joerg // constructor' part was removed by DR1507. 5148 1.1 joerg if (NeedZeroInitialization) 5149 1.1 joerg Sequence.AddZeroInitializationStep(Entity.getType()); 5150 1.1 joerg 5151 1.1 joerg // C++03: 5152 1.1 joerg // -- if T is a non-union class type without a user-declared constructor, 5153 1.1 joerg // then every non-static data member and base class component of T is 5154 1.1 joerg // value-initialized; 5155 1.1 joerg // [...] A program that calls for [...] value-initialization of an 5156 1.1 joerg // entity of reference type is ill-formed. 5157 1.1 joerg // 5158 1.1 joerg // C++11 doesn't need this handling, because value-initialization does not 5159 1.1 joerg // occur recursively there, and the implicit default constructor is 5160 1.1 joerg // defined as deleted in the problematic cases. 5161 1.1 joerg if (!S.getLangOpts().CPlusPlus11 && 5162 1.1 joerg ClassDecl->hasUninitializedReferenceMember()) { 5163 1.1 joerg Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference); 5164 1.1 joerg return; 5165 1.1 joerg } 5166 1.1 joerg 5167 1.1 joerg // If this is list-value-initialization, pass the empty init list on when 5168 1.1 joerg // building the constructor call. This affects the semantics of a few 5169 1.1 joerg // things (such as whether an explicit default constructor can be called). 5170 1.1 joerg Expr *InitListAsExpr = InitList; 5171 1.1 joerg MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0); 5172 1.1 joerg bool InitListSyntax = InitList; 5173 1.1 joerg 5174 1.1 joerg // FIXME: Instead of creating a CXXConstructExpr of array type here, 5175 1.1 joerg // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr. 5176 1.1 joerg return TryConstructorInitialization( 5177 1.1 joerg S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax); 5178 1.1 joerg } 5179 1.1 joerg } 5180 1.1 joerg 5181 1.1 joerg Sequence.AddZeroInitializationStep(Entity.getType()); 5182 1.1 joerg } 5183 1.1 joerg 5184 1.1 joerg /// Attempt default initialization (C++ [dcl.init]p6). 5185 1.1 joerg static void TryDefaultInitialization(Sema &S, 5186 1.1 joerg const InitializedEntity &Entity, 5187 1.1 joerg const InitializationKind &Kind, 5188 1.1 joerg InitializationSequence &Sequence) { 5189 1.1 joerg assert(Kind.getKind() == InitializationKind::IK_Default); 5190 1.1 joerg 5191 1.1 joerg // C++ [dcl.init]p6: 5192 1.1 joerg // To default-initialize an object of type T means: 5193 1.1 joerg // - if T is an array type, each element is default-initialized; 5194 1.1 joerg QualType DestType = S.Context.getBaseElementType(Entity.getType()); 5195 1.1 joerg 5196 1.1 joerg // - if T is a (possibly cv-qualified) class type (Clause 9), the default 5197 1.1 joerg // constructor for T is called (and the initialization is ill-formed if 5198 1.1 joerg // T has no accessible default constructor); 5199 1.1 joerg if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) { 5200 1.1 joerg TryConstructorInitialization(S, Entity, Kind, None, DestType, 5201 1.1 joerg Entity.getType(), Sequence); 5202 1.1 joerg return; 5203 1.1 joerg } 5204 1.1 joerg 5205 1.1 joerg // - otherwise, no initialization is performed. 5206 1.1 joerg 5207 1.1 joerg // If a program calls for the default initialization of an object of 5208 1.1 joerg // a const-qualified type T, T shall be a class type with a user-provided 5209 1.1 joerg // default constructor. 5210 1.1 joerg if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) { 5211 1.1 joerg if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) 5212 1.1 joerg Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 5213 1.1 joerg return; 5214 1.1 joerg } 5215 1.1 joerg 5216 1.1 joerg // If the destination type has a lifetime property, zero-initialize it. 5217 1.1 joerg if (DestType.getQualifiers().hasObjCLifetime()) { 5218 1.1 joerg Sequence.AddZeroInitializationStep(Entity.getType()); 5219 1.1 joerg return; 5220 1.1 joerg } 5221 1.1 joerg } 5222 1.1 joerg 5223 1.1 joerg /// Attempt a user-defined conversion between two types (C++ [dcl.init]), 5224 1.1 joerg /// which enumerates all conversion functions and performs overload resolution 5225 1.1 joerg /// to select the best. 5226 1.1 joerg static void TryUserDefinedConversion(Sema &S, 5227 1.1 joerg QualType DestType, 5228 1.1 joerg const InitializationKind &Kind, 5229 1.1 joerg Expr *Initializer, 5230 1.1 joerg InitializationSequence &Sequence, 5231 1.1 joerg bool TopLevelOfInitList) { 5232 1.1 joerg assert(!DestType->isReferenceType() && "References are handled elsewhere"); 5233 1.1 joerg QualType SourceType = Initializer->getType(); 5234 1.1 joerg assert((DestType->isRecordType() || SourceType->isRecordType()) && 5235 1.1 joerg "Must have a class type to perform a user-defined conversion"); 5236 1.1 joerg 5237 1.1 joerg // Build the candidate set directly in the initialization sequence 5238 1.1 joerg // structure, so that it will persist if we fail. 5239 1.1 joerg OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 5240 1.1 joerg CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 5241 1.1 joerg CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); 5242 1.1 joerg 5243 1.1 joerg // Determine whether we are allowed to call explicit constructors or 5244 1.1 joerg // explicit conversion operators. 5245 1.1 joerg bool AllowExplicit = Kind.AllowExplicit(); 5246 1.1 joerg 5247 1.1 joerg if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { 5248 1.1 joerg // The type we're converting to is a class type. Enumerate its constructors 5249 1.1 joerg // to see if there is a suitable conversion. 5250 1.1 joerg CXXRecordDecl *DestRecordDecl 5251 1.1 joerg = cast<CXXRecordDecl>(DestRecordType->getDecl()); 5252 1.1 joerg 5253 1.1 joerg // Try to complete the type we're converting to. 5254 1.1 joerg if (S.isCompleteType(Kind.getLocation(), DestType)) { 5255 1.1 joerg for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) { 5256 1.1 joerg auto Info = getConstructorInfo(D); 5257 1.1 joerg if (!Info.Constructor) 5258 1.1 joerg continue; 5259 1.1 joerg 5260 1.1 joerg if (!Info.Constructor->isInvalidDecl() && 5261 1.1.1.2 joerg Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { 5262 1.1 joerg if (Info.ConstructorTmpl) 5263 1.1 joerg S.AddTemplateOverloadCandidate( 5264 1.1 joerg Info.ConstructorTmpl, Info.FoundDecl, 5265 1.1 joerg /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, 5266 1.1 joerg /*SuppressUserConversions=*/true, 5267 1.1 joerg /*PartialOverloading*/ false, AllowExplicit); 5268 1.1 joerg else 5269 1.1 joerg S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 5270 1.1 joerg Initializer, CandidateSet, 5271 1.1 joerg /*SuppressUserConversions=*/true, 5272 1.1 joerg /*PartialOverloading*/ false, AllowExplicit); 5273 1.1 joerg } 5274 1.1 joerg } 5275 1.1 joerg } 5276 1.1 joerg } 5277 1.1 joerg 5278 1.1 joerg SourceLocation DeclLoc = Initializer->getBeginLoc(); 5279 1.1 joerg 5280 1.1 joerg if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { 5281 1.1 joerg // The type we're converting from is a class type, enumerate its conversion 5282 1.1 joerg // functions. 5283 1.1 joerg 5284 1.1 joerg // We can only enumerate the conversion functions for a complete type; if 5285 1.1 joerg // the type isn't complete, simply skip this step. 5286 1.1 joerg if (S.isCompleteType(DeclLoc, SourceType)) { 5287 1.1 joerg CXXRecordDecl *SourceRecordDecl 5288 1.1 joerg = cast<CXXRecordDecl>(SourceRecordType->getDecl()); 5289 1.1 joerg 5290 1.1 joerg const auto &Conversions = 5291 1.1 joerg SourceRecordDecl->getVisibleConversionFunctions(); 5292 1.1 joerg for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5293 1.1 joerg NamedDecl *D = *I; 5294 1.1 joerg CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 5295 1.1 joerg if (isa<UsingShadowDecl>(D)) 5296 1.1 joerg D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5297 1.1 joerg 5298 1.1 joerg FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5299 1.1 joerg CXXConversionDecl *Conv; 5300 1.1 joerg if (ConvTemplate) 5301 1.1 joerg Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5302 1.1 joerg else 5303 1.1 joerg Conv = cast<CXXConversionDecl>(D); 5304 1.1 joerg 5305 1.1.1.2 joerg if (ConvTemplate) 5306 1.1.1.2 joerg S.AddTemplateConversionCandidate( 5307 1.1.1.2 joerg ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, 5308 1.1.1.2 joerg CandidateSet, AllowExplicit, AllowExplicit); 5309 1.1.1.2 joerg else 5310 1.1.1.2 joerg S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, 5311 1.1.1.2 joerg DestType, CandidateSet, AllowExplicit, 5312 1.1.1.2 joerg AllowExplicit); 5313 1.1 joerg } 5314 1.1 joerg } 5315 1.1 joerg } 5316 1.1 joerg 5317 1.1 joerg // Perform overload resolution. If it fails, return the failed result. 5318 1.1 joerg OverloadCandidateSet::iterator Best; 5319 1.1 joerg if (OverloadingResult Result 5320 1.1 joerg = CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 5321 1.1 joerg Sequence.SetOverloadFailure( 5322 1.1.1.2 joerg InitializationSequence::FK_UserConversionOverloadFailed, Result); 5323 1.1.1.2 joerg 5324 1.1.1.2 joerg // [class.copy.elision]p3: 5325 1.1.1.2 joerg // In some copy-initialization contexts, a two-stage overload resolution 5326 1.1.1.2 joerg // is performed. 5327 1.1.1.2 joerg // If the first overload resolution selects a deleted function, we also 5328 1.1.1.2 joerg // need the initialization sequence to decide whether to perform the second 5329 1.1.1.2 joerg // overload resolution. 5330 1.1.1.2 joerg if (!(Result == OR_Deleted && 5331 1.1.1.2 joerg Kind.getKind() == InitializationKind::IK_Copy)) 5332 1.1.1.2 joerg return; 5333 1.1 joerg } 5334 1.1 joerg 5335 1.1 joerg FunctionDecl *Function = Best->Function; 5336 1.1 joerg Function->setReferenced(); 5337 1.1 joerg bool HadMultipleCandidates = (CandidateSet.size() > 1); 5338 1.1 joerg 5339 1.1 joerg if (isa<CXXConstructorDecl>(Function)) { 5340 1.1 joerg // Add the user-defined conversion step. Any cv-qualification conversion is 5341 1.1 joerg // subsumed by the initialization. Per DR5, the created temporary is of the 5342 1.1 joerg // cv-unqualified type of the destination. 5343 1.1 joerg Sequence.AddUserConversionStep(Function, Best->FoundDecl, 5344 1.1 joerg DestType.getUnqualifiedType(), 5345 1.1 joerg HadMultipleCandidates); 5346 1.1 joerg 5347 1.1 joerg // C++14 and before: 5348 1.1 joerg // - if the function is a constructor, the call initializes a temporary 5349 1.1 joerg // of the cv-unqualified version of the destination type. The [...] 5350 1.1 joerg // temporary [...] is then used to direct-initialize, according to the 5351 1.1 joerg // rules above, the object that is the destination of the 5352 1.1 joerg // copy-initialization. 5353 1.1 joerg // Note that this just performs a simple object copy from the temporary. 5354 1.1 joerg // 5355 1.1 joerg // C++17: 5356 1.1 joerg // - if the function is a constructor, the call is a prvalue of the 5357 1.1 joerg // cv-unqualified version of the destination type whose return object 5358 1.1 joerg // is initialized by the constructor. The call is used to 5359 1.1 joerg // direct-initialize, according to the rules above, the object that 5360 1.1 joerg // is the destination of the copy-initialization. 5361 1.1 joerg // Therefore we need to do nothing further. 5362 1.1 joerg // 5363 1.1 joerg // FIXME: Mark this copy as extraneous. 5364 1.1 joerg if (!S.getLangOpts().CPlusPlus17) 5365 1.1 joerg Sequence.AddFinalCopy(DestType); 5366 1.1 joerg else if (DestType.hasQualifiers()) 5367 1.1 joerg Sequence.AddQualificationConversionStep(DestType, VK_RValue); 5368 1.1 joerg return; 5369 1.1 joerg } 5370 1.1 joerg 5371 1.1 joerg // Add the user-defined conversion step that calls the conversion function. 5372 1.1 joerg QualType ConvType = Function->getCallResultType(); 5373 1.1 joerg Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType, 5374 1.1 joerg HadMultipleCandidates); 5375 1.1 joerg 5376 1.1 joerg if (ConvType->getAs<RecordType>()) { 5377 1.1 joerg // The call is used to direct-initialize [...] the object that is the 5378 1.1 joerg // destination of the copy-initialization. 5379 1.1 joerg // 5380 1.1 joerg // In C++17, this does not call a constructor if we enter /17.6.1: 5381 1.1 joerg // - If the initializer expression is a prvalue and the cv-unqualified 5382 1.1 joerg // version of the source type is the same as the class of the 5383 1.1 joerg // destination [... do not make an extra copy] 5384 1.1 joerg // 5385 1.1 joerg // FIXME: Mark this copy as extraneous. 5386 1.1 joerg if (!S.getLangOpts().CPlusPlus17 || 5387 1.1 joerg Function->getReturnType()->isReferenceType() || 5388 1.1 joerg !S.Context.hasSameUnqualifiedType(ConvType, DestType)) 5389 1.1 joerg Sequence.AddFinalCopy(DestType); 5390 1.1 joerg else if (!S.Context.hasSameType(ConvType, DestType)) 5391 1.1 joerg Sequence.AddQualificationConversionStep(DestType, VK_RValue); 5392 1.1 joerg return; 5393 1.1 joerg } 5394 1.1 joerg 5395 1.1 joerg // If the conversion following the call to the conversion function 5396 1.1 joerg // is interesting, add it as a separate step. 5397 1.1 joerg if (Best->FinalConversion.First || Best->FinalConversion.Second || 5398 1.1 joerg Best->FinalConversion.Third) { 5399 1.1 joerg ImplicitConversionSequence ICS; 5400 1.1 joerg ICS.setStandard(); 5401 1.1 joerg ICS.Standard = Best->FinalConversion; 5402 1.1 joerg Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); 5403 1.1 joerg } 5404 1.1 joerg } 5405 1.1 joerg 5406 1.1 joerg /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>, 5407 1.1 joerg /// a function with a pointer return type contains a 'return false;' statement. 5408 1.1 joerg /// In C++11, 'false' is not a null pointer, so this breaks the build of any 5409 1.1 joerg /// code using that header. 5410 1.1 joerg /// 5411 1.1 joerg /// Work around this by treating 'return false;' as zero-initializing the result 5412 1.1 joerg /// if it's used in a pointer-returning function in a system header. 5413 1.1 joerg static bool isLibstdcxxPointerReturnFalseHack(Sema &S, 5414 1.1 joerg const InitializedEntity &Entity, 5415 1.1 joerg const Expr *Init) { 5416 1.1 joerg return S.getLangOpts().CPlusPlus11 && 5417 1.1 joerg Entity.getKind() == InitializedEntity::EK_Result && 5418 1.1 joerg Entity.getType()->isPointerType() && 5419 1.1 joerg isa<CXXBoolLiteralExpr>(Init) && 5420 1.1 joerg !cast<CXXBoolLiteralExpr>(Init)->getValue() && 5421 1.1 joerg S.getSourceManager().isInSystemHeader(Init->getExprLoc()); 5422 1.1 joerg } 5423 1.1 joerg 5424 1.1 joerg /// The non-zero enum values here are indexes into diagnostic alternatives. 5425 1.1 joerg enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; 5426 1.1 joerg 5427 1.1 joerg /// Determines whether this expression is an acceptable ICR source. 5428 1.1 joerg static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, 5429 1.1 joerg bool isAddressOf, bool &isWeakAccess) { 5430 1.1 joerg // Skip parens. 5431 1.1 joerg e = e->IgnoreParens(); 5432 1.1 joerg 5433 1.1 joerg // Skip address-of nodes. 5434 1.1 joerg if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { 5435 1.1 joerg if (op->getOpcode() == UO_AddrOf) 5436 1.1 joerg return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true, 5437 1.1 joerg isWeakAccess); 5438 1.1 joerg 5439 1.1 joerg // Skip certain casts. 5440 1.1 joerg } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) { 5441 1.1 joerg switch (ce->getCastKind()) { 5442 1.1 joerg case CK_Dependent: 5443 1.1 joerg case CK_BitCast: 5444 1.1 joerg case CK_LValueBitCast: 5445 1.1 joerg case CK_NoOp: 5446 1.1 joerg return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess); 5447 1.1 joerg 5448 1.1 joerg case CK_ArrayToPointerDecay: 5449 1.1 joerg return IIK_nonscalar; 5450 1.1 joerg 5451 1.1 joerg case CK_NullToPointer: 5452 1.1 joerg return IIK_okay; 5453 1.1 joerg 5454 1.1 joerg default: 5455 1.1 joerg break; 5456 1.1 joerg } 5457 1.1 joerg 5458 1.1 joerg // If we have a declaration reference, it had better be a local variable. 5459 1.1 joerg } else if (isa<DeclRefExpr>(e)) { 5460 1.1 joerg // set isWeakAccess to true, to mean that there will be an implicit 5461 1.1 joerg // load which requires a cleanup. 5462 1.1 joerg if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 5463 1.1 joerg isWeakAccess = true; 5464 1.1 joerg 5465 1.1 joerg if (!isAddressOf) return IIK_nonlocal; 5466 1.1 joerg 5467 1.1 joerg VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl()); 5468 1.1 joerg if (!var) return IIK_nonlocal; 5469 1.1 joerg 5470 1.1 joerg return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); 5471 1.1 joerg 5472 1.1 joerg // If we have a conditional operator, check both sides. 5473 1.1 joerg } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) { 5474 1.1 joerg if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf, 5475 1.1 joerg isWeakAccess)) 5476 1.1 joerg return iik; 5477 1.1 joerg 5478 1.1 joerg return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess); 5479 1.1 joerg 5480 1.1 joerg // These are never scalar. 5481 1.1 joerg } else if (isa<ArraySubscriptExpr>(e)) { 5482 1.1 joerg return IIK_nonscalar; 5483 1.1 joerg 5484 1.1 joerg // Otherwise, it needs to be a null pointer constant. 5485 1.1 joerg } else { 5486 1.1 joerg return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull) 5487 1.1 joerg ? IIK_okay : IIK_nonlocal); 5488 1.1 joerg } 5489 1.1 joerg 5490 1.1 joerg return IIK_nonlocal; 5491 1.1 joerg } 5492 1.1 joerg 5493 1.1 joerg /// Check whether the given expression is a valid operand for an 5494 1.1 joerg /// indirect copy/restore. 5495 1.1 joerg static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { 5496 1.1 joerg assert(src->isRValue()); 5497 1.1 joerg bool isWeakAccess = false; 5498 1.1 joerg InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess); 5499 1.1 joerg // If isWeakAccess to true, there will be an implicit 5500 1.1 joerg // load which requires a cleanup. 5501 1.1 joerg if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess) 5502 1.1 joerg S.Cleanup.setExprNeedsCleanups(true); 5503 1.1 joerg 5504 1.1 joerg if (iik == IIK_okay) return; 5505 1.1 joerg 5506 1.1 joerg S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback) 5507 1.1 joerg << ((unsigned) iik - 1) // shift index into diagnostic explanations 5508 1.1 joerg << src->getSourceRange(); 5509 1.1 joerg } 5510 1.1 joerg 5511 1.1 joerg /// Determine whether we have compatible array types for the 5512 1.1 joerg /// purposes of GNU by-copy array initialization. 5513 1.1 joerg static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, 5514 1.1 joerg const ArrayType *Source) { 5515 1.1 joerg // If the source and destination array types are equivalent, we're 5516 1.1 joerg // done. 5517 1.1 joerg if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0))) 5518 1.1 joerg return true; 5519 1.1 joerg 5520 1.1 joerg // Make sure that the element types are the same. 5521 1.1 joerg if (!Context.hasSameType(Dest->getElementType(), Source->getElementType())) 5522 1.1 joerg return false; 5523 1.1 joerg 5524 1.1 joerg // The only mismatch we allow is when the destination is an 5525 1.1 joerg // incomplete array type and the source is a constant array type. 5526 1.1 joerg return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); 5527 1.1 joerg } 5528 1.1 joerg 5529 1.1 joerg static bool tryObjCWritebackConversion(Sema &S, 5530 1.1 joerg InitializationSequence &Sequence, 5531 1.1 joerg const InitializedEntity &Entity, 5532 1.1 joerg Expr *Initializer) { 5533 1.1 joerg bool ArrayDecay = false; 5534 1.1 joerg QualType ArgType = Initializer->getType(); 5535 1.1 joerg QualType ArgPointee; 5536 1.1 joerg if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) { 5537 1.1 joerg ArrayDecay = true; 5538 1.1 joerg ArgPointee = ArgArrayType->getElementType(); 5539 1.1 joerg ArgType = S.Context.getPointerType(ArgPointee); 5540 1.1 joerg } 5541 1.1 joerg 5542 1.1 joerg // Handle write-back conversion. 5543 1.1 joerg QualType ConvertedArgType; 5544 1.1 joerg if (!S.isObjCWritebackConversion(ArgType, Entity.getType(), 5545 1.1 joerg ConvertedArgType)) 5546 1.1 joerg return false; 5547 1.1 joerg 5548 1.1 joerg // We should copy unless we're passing to an argument explicitly 5549 1.1 joerg // marked 'out'. 5550 1.1 joerg bool ShouldCopy = true; 5551 1.1 joerg if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 5552 1.1 joerg ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 5553 1.1 joerg 5554 1.1 joerg // Do we need an lvalue conversion? 5555 1.1 joerg if (ArrayDecay || Initializer->isGLValue()) { 5556 1.1 joerg ImplicitConversionSequence ICS; 5557 1.1 joerg ICS.setStandard(); 5558 1.1 joerg ICS.Standard.setAsIdentityConversion(); 5559 1.1 joerg 5560 1.1 joerg QualType ResultType; 5561 1.1 joerg if (ArrayDecay) { 5562 1.1 joerg ICS.Standard.First = ICK_Array_To_Pointer; 5563 1.1 joerg ResultType = S.Context.getPointerType(ArgPointee); 5564 1.1 joerg } else { 5565 1.1 joerg ICS.Standard.First = ICK_Lvalue_To_Rvalue; 5566 1.1 joerg ResultType = Initializer->getType().getNonLValueExprType(S.Context); 5567 1.1 joerg } 5568 1.1 joerg 5569 1.1 joerg Sequence.AddConversionSequenceStep(ICS, ResultType); 5570 1.1 joerg } 5571 1.1 joerg 5572 1.1 joerg Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); 5573 1.1 joerg return true; 5574 1.1 joerg } 5575 1.1 joerg 5576 1.1 joerg static bool TryOCLSamplerInitialization(Sema &S, 5577 1.1 joerg InitializationSequence &Sequence, 5578 1.1 joerg QualType DestType, 5579 1.1 joerg Expr *Initializer) { 5580 1.1 joerg if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() || 5581 1.1 joerg (!Initializer->isIntegerConstantExpr(S.Context) && 5582 1.1 joerg !Initializer->getType()->isSamplerT())) 5583 1.1 joerg return false; 5584 1.1 joerg 5585 1.1 joerg Sequence.AddOCLSamplerInitStep(DestType); 5586 1.1 joerg return true; 5587 1.1 joerg } 5588 1.1 joerg 5589 1.1 joerg static bool IsZeroInitializer(Expr *Initializer, Sema &S) { 5590 1.1 joerg return Initializer->isIntegerConstantExpr(S.getASTContext()) && 5591 1.1 joerg (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0); 5592 1.1 joerg } 5593 1.1 joerg 5594 1.1 joerg static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, 5595 1.1 joerg InitializationSequence &Sequence, 5596 1.1 joerg QualType DestType, 5597 1.1 joerg Expr *Initializer) { 5598 1.1 joerg if (!S.getLangOpts().OpenCL) 5599 1.1 joerg return false; 5600 1.1 joerg 5601 1.1 joerg // 5602 1.1 joerg // OpenCL 1.2 spec, s6.12.10 5603 1.1 joerg // 5604 1.1 joerg // The event argument can also be used to associate the 5605 1.1 joerg // async_work_group_copy with a previous async copy allowing 5606 1.1 joerg // an event to be shared by multiple async copies; otherwise 5607 1.1 joerg // event should be zero. 5608 1.1 joerg // 5609 1.1 joerg if (DestType->isEventT() || DestType->isQueueT()) { 5610 1.1 joerg if (!IsZeroInitializer(Initializer, S)) 5611 1.1 joerg return false; 5612 1.1 joerg 5613 1.1 joerg Sequence.AddOCLZeroOpaqueTypeStep(DestType); 5614 1.1 joerg return true; 5615 1.1 joerg } 5616 1.1 joerg 5617 1.1 joerg // We should allow zero initialization for all types defined in the 5618 1.1 joerg // cl_intel_device_side_avc_motion_estimation extension, except 5619 1.1 joerg // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t. 5620 1.1.1.2 joerg if (S.getOpenCLOptions().isAvailableOption( 5621 1.1.1.2 joerg "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) && 5622 1.1 joerg DestType->isOCLIntelSubgroupAVCType()) { 5623 1.1 joerg if (DestType->isOCLIntelSubgroupAVCMcePayloadType() || 5624 1.1 joerg DestType->isOCLIntelSubgroupAVCMceResultType()) 5625 1.1 joerg return false; 5626 1.1 joerg if (!IsZeroInitializer(Initializer, S)) 5627 1.1 joerg return false; 5628 1.1 joerg 5629 1.1 joerg Sequence.AddOCLZeroOpaqueTypeStep(DestType); 5630 1.1 joerg return true; 5631 1.1 joerg } 5632 1.1 joerg 5633 1.1 joerg return false; 5634 1.1 joerg } 5635 1.1 joerg 5636 1.1.1.2 joerg InitializationSequence::InitializationSequence( 5637 1.1.1.2 joerg Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, 5638 1.1.1.2 joerg MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid) 5639 1.1.1.2 joerg : FailedOverloadResult(OR_Success), 5640 1.1.1.2 joerg FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) { 5641 1.1 joerg InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList, 5642 1.1 joerg TreatUnavailableAsInvalid); 5643 1.1 joerg } 5644 1.1 joerg 5645 1.1 joerg /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the 5646 1.1 joerg /// address of that function, this returns true. Otherwise, it returns false. 5647 1.1 joerg static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) { 5648 1.1 joerg auto *DRE = dyn_cast<DeclRefExpr>(E); 5649 1.1 joerg if (!DRE || !isa<FunctionDecl>(DRE->getDecl())) 5650 1.1 joerg return false; 5651 1.1 joerg 5652 1.1 joerg return !S.checkAddressOfFunctionIsAvailable( 5653 1.1 joerg cast<FunctionDecl>(DRE->getDecl())); 5654 1.1 joerg } 5655 1.1 joerg 5656 1.1 joerg /// Determine whether we can perform an elementwise array copy for this kind 5657 1.1 joerg /// of entity. 5658 1.1 joerg static bool canPerformArrayCopy(const InitializedEntity &Entity) { 5659 1.1 joerg switch (Entity.getKind()) { 5660 1.1 joerg case InitializedEntity::EK_LambdaCapture: 5661 1.1 joerg // C++ [expr.prim.lambda]p24: 5662 1.1 joerg // For array members, the array elements are direct-initialized in 5663 1.1 joerg // increasing subscript order. 5664 1.1 joerg return true; 5665 1.1 joerg 5666 1.1 joerg case InitializedEntity::EK_Variable: 5667 1.1 joerg // C++ [dcl.decomp]p1: 5668 1.1 joerg // [...] each element is copy-initialized or direct-initialized from the 5669 1.1 joerg // corresponding element of the assignment-expression [...] 5670 1.1 joerg return isa<DecompositionDecl>(Entity.getDecl()); 5671 1.1 joerg 5672 1.1 joerg case InitializedEntity::EK_Member: 5673 1.1 joerg // C++ [class.copy.ctor]p14: 5674 1.1 joerg // - if the member is an array, each element is direct-initialized with 5675 1.1 joerg // the corresponding subobject of x 5676 1.1 joerg return Entity.isImplicitMemberInitializer(); 5677 1.1 joerg 5678 1.1 joerg case InitializedEntity::EK_ArrayElement: 5679 1.1 joerg // All the above cases are intended to apply recursively, even though none 5680 1.1 joerg // of them actually say that. 5681 1.1 joerg if (auto *E = Entity.getParent()) 5682 1.1 joerg return canPerformArrayCopy(*E); 5683 1.1 joerg break; 5684 1.1 joerg 5685 1.1 joerg default: 5686 1.1 joerg break; 5687 1.1 joerg } 5688 1.1 joerg 5689 1.1 joerg return false; 5690 1.1 joerg } 5691 1.1 joerg 5692 1.1 joerg void InitializationSequence::InitializeFrom(Sema &S, 5693 1.1 joerg const InitializedEntity &Entity, 5694 1.1 joerg const InitializationKind &Kind, 5695 1.1 joerg MultiExprArg Args, 5696 1.1 joerg bool TopLevelOfInitList, 5697 1.1 joerg bool TreatUnavailableAsInvalid) { 5698 1.1 joerg ASTContext &Context = S.Context; 5699 1.1 joerg 5700 1.1 joerg // Eliminate non-overload placeholder types in the arguments. We 5701 1.1 joerg // need to do this before checking whether types are dependent 5702 1.1 joerg // because lowering a pseudo-object expression might well give us 5703 1.1 joerg // something of dependent type. 5704 1.1 joerg for (unsigned I = 0, E = Args.size(); I != E; ++I) 5705 1.1 joerg if (Args[I]->getType()->isNonOverloadPlaceholderType()) { 5706 1.1 joerg // FIXME: should we be doing this here? 5707 1.1 joerg ExprResult result = S.CheckPlaceholderExpr(Args[I]); 5708 1.1 joerg if (result.isInvalid()) { 5709 1.1 joerg SetFailed(FK_PlaceholderType); 5710 1.1 joerg return; 5711 1.1 joerg } 5712 1.1 joerg Args[I] = result.get(); 5713 1.1 joerg } 5714 1.1 joerg 5715 1.1 joerg // C++0x [dcl.init]p16: 5716 1.1 joerg // The semantics of initializers are as follows. The destination type is 5717 1.1 joerg // the type of the object or reference being initialized and the source 5718 1.1 joerg // type is the type of the initializer expression. The source type is not 5719 1.1 joerg // defined when the initializer is a braced-init-list or when it is a 5720 1.1 joerg // parenthesized list of expressions. 5721 1.1 joerg QualType DestType = Entity.getType(); 5722 1.1 joerg 5723 1.1 joerg if (DestType->isDependentType() || 5724 1.1 joerg Expr::hasAnyTypeDependentArguments(Args)) { 5725 1.1 joerg SequenceKind = DependentSequence; 5726 1.1 joerg return; 5727 1.1 joerg } 5728 1.1 joerg 5729 1.1 joerg // Almost everything is a normal sequence. 5730 1.1 joerg setSequenceKind(NormalSequence); 5731 1.1 joerg 5732 1.1 joerg QualType SourceType; 5733 1.1 joerg Expr *Initializer = nullptr; 5734 1.1 joerg if (Args.size() == 1) { 5735 1.1 joerg Initializer = Args[0]; 5736 1.1 joerg if (S.getLangOpts().ObjC) { 5737 1.1 joerg if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(), 5738 1.1 joerg DestType, Initializer->getType(), 5739 1.1 joerg Initializer) || 5740 1.1.1.2 joerg S.CheckConversionToObjCLiteral(DestType, Initializer)) 5741 1.1 joerg Args[0] = Initializer; 5742 1.1 joerg } 5743 1.1 joerg if (!isa<InitListExpr>(Initializer)) 5744 1.1 joerg SourceType = Initializer->getType(); 5745 1.1 joerg } 5746 1.1 joerg 5747 1.1 joerg // - If the initializer is a (non-parenthesized) braced-init-list, the 5748 1.1 joerg // object is list-initialized (8.5.4). 5749 1.1 joerg if (Kind.getKind() != InitializationKind::IK_Direct) { 5750 1.1 joerg if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { 5751 1.1 joerg TryListInitialization(S, Entity, Kind, InitList, *this, 5752 1.1 joerg TreatUnavailableAsInvalid); 5753 1.1 joerg return; 5754 1.1 joerg } 5755 1.1 joerg } 5756 1.1 joerg 5757 1.1 joerg // - If the destination type is a reference type, see 8.5.3. 5758 1.1 joerg if (DestType->isReferenceType()) { 5759 1.1 joerg // C++0x [dcl.init.ref]p1: 5760 1.1 joerg // A variable declared to be a T& or T&&, that is, "reference to type T" 5761 1.1 joerg // (8.3.2), shall be initialized by an object, or function, of type T or 5762 1.1 joerg // by an object that can be converted into a T. 5763 1.1 joerg // (Therefore, multiple arguments are not permitted.) 5764 1.1 joerg if (Args.size() != 1) 5765 1.1 joerg SetFailed(FK_TooManyInitsForReference); 5766 1.1 joerg // C++17 [dcl.init.ref]p5: 5767 1.1 joerg // A reference [...] is initialized by an expression [...] as follows: 5768 1.1 joerg // If the initializer is not an expression, presumably we should reject, 5769 1.1 joerg // but the standard fails to actually say so. 5770 1.1 joerg else if (isa<InitListExpr>(Args[0])) 5771 1.1 joerg SetFailed(FK_ParenthesizedListInitForReference); 5772 1.1 joerg else 5773 1.1 joerg TryReferenceInitialization(S, Entity, Kind, Args[0], *this); 5774 1.1 joerg return; 5775 1.1 joerg } 5776 1.1 joerg 5777 1.1 joerg // - If the initializer is (), the object is value-initialized. 5778 1.1 joerg if (Kind.getKind() == InitializationKind::IK_Value || 5779 1.1 joerg (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) { 5780 1.1 joerg TryValueInitialization(S, Entity, Kind, *this); 5781 1.1 joerg return; 5782 1.1 joerg } 5783 1.1 joerg 5784 1.1 joerg // Handle default initialization. 5785 1.1 joerg if (Kind.getKind() == InitializationKind::IK_Default) { 5786 1.1 joerg TryDefaultInitialization(S, Entity, Kind, *this); 5787 1.1 joerg return; 5788 1.1 joerg } 5789 1.1 joerg 5790 1.1 joerg // - If the destination type is an array of characters, an array of 5791 1.1 joerg // char16_t, an array of char32_t, or an array of wchar_t, and the 5792 1.1 joerg // initializer is a string literal, see 8.5.2. 5793 1.1 joerg // - Otherwise, if the destination type is an array, the program is 5794 1.1 joerg // ill-formed. 5795 1.1 joerg if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) { 5796 1.1 joerg if (Initializer && isa<VariableArrayType>(DestAT)) { 5797 1.1 joerg SetFailed(FK_VariableLengthArrayHasInitializer); 5798 1.1 joerg return; 5799 1.1 joerg } 5800 1.1 joerg 5801 1.1 joerg if (Initializer) { 5802 1.1 joerg switch (IsStringInit(Initializer, DestAT, Context)) { 5803 1.1 joerg case SIF_None: 5804 1.1 joerg TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); 5805 1.1 joerg return; 5806 1.1 joerg case SIF_NarrowStringIntoWideChar: 5807 1.1 joerg SetFailed(FK_NarrowStringIntoWideCharArray); 5808 1.1 joerg return; 5809 1.1 joerg case SIF_WideStringIntoChar: 5810 1.1 joerg SetFailed(FK_WideStringIntoCharArray); 5811 1.1 joerg return; 5812 1.1 joerg case SIF_IncompatWideStringIntoWideChar: 5813 1.1 joerg SetFailed(FK_IncompatWideStringIntoWideChar); 5814 1.1 joerg return; 5815 1.1 joerg case SIF_PlainStringIntoUTF8Char: 5816 1.1 joerg SetFailed(FK_PlainStringIntoUTF8Char); 5817 1.1 joerg return; 5818 1.1 joerg case SIF_UTF8StringIntoPlainChar: 5819 1.1 joerg SetFailed(FK_UTF8StringIntoPlainChar); 5820 1.1 joerg return; 5821 1.1 joerg case SIF_Other: 5822 1.1 joerg break; 5823 1.1 joerg } 5824 1.1 joerg } 5825 1.1 joerg 5826 1.1 joerg // Some kinds of initialization permit an array to be initialized from 5827 1.1 joerg // another array of the same type, and perform elementwise initialization. 5828 1.1 joerg if (Initializer && isa<ConstantArrayType>(DestAT) && 5829 1.1 joerg S.Context.hasSameUnqualifiedType(Initializer->getType(), 5830 1.1 joerg Entity.getType()) && 5831 1.1 joerg canPerformArrayCopy(Entity)) { 5832 1.1 joerg // If source is a prvalue, use it directly. 5833 1.1 joerg if (Initializer->getValueKind() == VK_RValue) { 5834 1.1 joerg AddArrayInitStep(DestType, /*IsGNUExtension*/false); 5835 1.1 joerg return; 5836 1.1 joerg } 5837 1.1 joerg 5838 1.1 joerg // Emit element-at-a-time copy loop. 5839 1.1 joerg InitializedEntity Element = 5840 1.1 joerg InitializedEntity::InitializeElement(S.Context, 0, Entity); 5841 1.1 joerg QualType InitEltT = 5842 1.1 joerg Context.getAsArrayType(Initializer->getType())->getElementType(); 5843 1.1 joerg OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT, 5844 1.1 joerg Initializer->getValueKind(), 5845 1.1 joerg Initializer->getObjectKind()); 5846 1.1 joerg Expr *OVEAsExpr = &OVE; 5847 1.1 joerg InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList, 5848 1.1 joerg TreatUnavailableAsInvalid); 5849 1.1 joerg if (!Failed()) 5850 1.1 joerg AddArrayInitLoopStep(Entity.getType(), InitEltT); 5851 1.1 joerg return; 5852 1.1 joerg } 5853 1.1 joerg 5854 1.1 joerg // Note: as an GNU C extension, we allow initialization of an 5855 1.1 joerg // array from a compound literal that creates an array of the same 5856 1.1 joerg // type, so long as the initializer has no side effects. 5857 1.1 joerg if (!S.getLangOpts().CPlusPlus && Initializer && 5858 1.1 joerg isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) && 5859 1.1 joerg Initializer->getType()->isArrayType()) { 5860 1.1 joerg const ArrayType *SourceAT 5861 1.1 joerg = Context.getAsArrayType(Initializer->getType()); 5862 1.1 joerg if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT)) 5863 1.1 joerg SetFailed(FK_ArrayTypeMismatch); 5864 1.1 joerg else if (Initializer->HasSideEffects(S.Context)) 5865 1.1 joerg SetFailed(FK_NonConstantArrayInit); 5866 1.1 joerg else { 5867 1.1 joerg AddArrayInitStep(DestType, /*IsGNUExtension*/true); 5868 1.1 joerg } 5869 1.1 joerg } 5870 1.1 joerg // Note: as a GNU C++ extension, we allow list-initialization of a 5871 1.1 joerg // class member of array type from a parenthesized initializer list. 5872 1.1 joerg else if (S.getLangOpts().CPlusPlus && 5873 1.1 joerg Entity.getKind() == InitializedEntity::EK_Member && 5874 1.1 joerg Initializer && isa<InitListExpr>(Initializer)) { 5875 1.1 joerg TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer), 5876 1.1 joerg *this, TreatUnavailableAsInvalid); 5877 1.1 joerg AddParenthesizedArrayInitStep(DestType); 5878 1.1 joerg } else if (DestAT->getElementType()->isCharType()) 5879 1.1 joerg SetFailed(FK_ArrayNeedsInitListOrStringLiteral); 5880 1.1 joerg else if (IsWideCharCompatible(DestAT->getElementType(), Context)) 5881 1.1 joerg SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral); 5882 1.1 joerg else 5883 1.1 joerg SetFailed(FK_ArrayNeedsInitList); 5884 1.1 joerg 5885 1.1 joerg return; 5886 1.1 joerg } 5887 1.1 joerg 5888 1.1 joerg // Determine whether we should consider writeback conversions for 5889 1.1 joerg // Objective-C ARC. 5890 1.1 joerg bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount && 5891 1.1 joerg Entity.isParameterKind(); 5892 1.1 joerg 5893 1.1 joerg if (TryOCLSamplerInitialization(S, *this, DestType, Initializer)) 5894 1.1 joerg return; 5895 1.1 joerg 5896 1.1 joerg // We're at the end of the line for C: it's either a write-back conversion 5897 1.1 joerg // or it's a C assignment. There's no need to check anything else. 5898 1.1 joerg if (!S.getLangOpts().CPlusPlus) { 5899 1.1 joerg // If allowed, check whether this is an Objective-C writeback conversion. 5900 1.1 joerg if (allowObjCWritebackConversion && 5901 1.1 joerg tryObjCWritebackConversion(S, *this, Entity, Initializer)) { 5902 1.1 joerg return; 5903 1.1 joerg } 5904 1.1 joerg 5905 1.1 joerg if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer)) 5906 1.1 joerg return; 5907 1.1 joerg 5908 1.1 joerg // Handle initialization in C 5909 1.1 joerg AddCAssignmentStep(DestType); 5910 1.1 joerg MaybeProduceObjCObject(S, *this, Entity); 5911 1.1 joerg return; 5912 1.1 joerg } 5913 1.1 joerg 5914 1.1 joerg assert(S.getLangOpts().CPlusPlus); 5915 1.1 joerg 5916 1.1 joerg // - If the destination type is a (possibly cv-qualified) class type: 5917 1.1 joerg if (DestType->isRecordType()) { 5918 1.1 joerg // - If the initialization is direct-initialization, or if it is 5919 1.1 joerg // copy-initialization where the cv-unqualified version of the 5920 1.1 joerg // source type is the same class as, or a derived class of, the 5921 1.1 joerg // class of the destination, constructors are considered. [...] 5922 1.1 joerg if (Kind.getKind() == InitializationKind::IK_Direct || 5923 1.1 joerg (Kind.getKind() == InitializationKind::IK_Copy && 5924 1.1 joerg (Context.hasSameUnqualifiedType(SourceType, DestType) || 5925 1.1 joerg S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType)))) 5926 1.1 joerg TryConstructorInitialization(S, Entity, Kind, Args, 5927 1.1 joerg DestType, DestType, *this); 5928 1.1 joerg // - Otherwise (i.e., for the remaining copy-initialization cases), 5929 1.1 joerg // user-defined conversion sequences that can convert from the source 5930 1.1 joerg // type to the destination type or (when a conversion function is 5931 1.1 joerg // used) to a derived class thereof are enumerated as described in 5932 1.1 joerg // 13.3.1.4, and the best one is chosen through overload resolution 5933 1.1 joerg // (13.3). 5934 1.1 joerg else 5935 1.1 joerg TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, 5936 1.1 joerg TopLevelOfInitList); 5937 1.1 joerg return; 5938 1.1 joerg } 5939 1.1 joerg 5940 1.1 joerg assert(Args.size() >= 1 && "Zero-argument case handled above"); 5941 1.1 joerg 5942 1.1 joerg // The remaining cases all need a source type. 5943 1.1 joerg if (Args.size() > 1) { 5944 1.1 joerg SetFailed(FK_TooManyInitsForScalar); 5945 1.1 joerg return; 5946 1.1 joerg } else if (isa<InitListExpr>(Args[0])) { 5947 1.1 joerg SetFailed(FK_ParenthesizedListInitForScalar); 5948 1.1 joerg return; 5949 1.1 joerg } 5950 1.1 joerg 5951 1.1 joerg // - Otherwise, if the source type is a (possibly cv-qualified) class 5952 1.1 joerg // type, conversion functions are considered. 5953 1.1 joerg if (!SourceType.isNull() && SourceType->isRecordType()) { 5954 1.1 joerg // For a conversion to _Atomic(T) from either T or a class type derived 5955 1.1 joerg // from T, initialize the T object then convert to _Atomic type. 5956 1.1 joerg bool NeedAtomicConversion = false; 5957 1.1 joerg if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) { 5958 1.1 joerg if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) || 5959 1.1 joerg S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, 5960 1.1 joerg Atomic->getValueType())) { 5961 1.1 joerg DestType = Atomic->getValueType(); 5962 1.1 joerg NeedAtomicConversion = true; 5963 1.1 joerg } 5964 1.1 joerg } 5965 1.1 joerg 5966 1.1 joerg TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, 5967 1.1 joerg TopLevelOfInitList); 5968 1.1 joerg MaybeProduceObjCObject(S, *this, Entity); 5969 1.1 joerg if (!Failed() && NeedAtomicConversion) 5970 1.1 joerg AddAtomicConversionStep(Entity.getType()); 5971 1.1 joerg return; 5972 1.1 joerg } 5973 1.1 joerg 5974 1.1.1.2 joerg // - Otherwise, if the initialization is direct-initialization, the source 5975 1.1.1.2 joerg // type is std::nullptr_t, and the destination type is bool, the initial 5976 1.1.1.2 joerg // value of the object being initialized is false. 5977 1.1.1.2 joerg if (!SourceType.isNull() && SourceType->isNullPtrType() && 5978 1.1.1.2 joerg DestType->isBooleanType() && 5979 1.1.1.2 joerg Kind.getKind() == InitializationKind::IK_Direct) { 5980 1.1.1.2 joerg AddConversionSequenceStep( 5981 1.1.1.2 joerg ImplicitConversionSequence::getNullptrToBool(SourceType, DestType, 5982 1.1.1.2 joerg Initializer->isGLValue()), 5983 1.1.1.2 joerg DestType); 5984 1.1.1.2 joerg return; 5985 1.1.1.2 joerg } 5986 1.1.1.2 joerg 5987 1.1 joerg // - Otherwise, the initial value of the object being initialized is the 5988 1.1 joerg // (possibly converted) value of the initializer expression. Standard 5989 1.1 joerg // conversions (Clause 4) will be used, if necessary, to convert the 5990 1.1 joerg // initializer expression to the cv-unqualified version of the 5991 1.1 joerg // destination type; no user-defined conversions are considered. 5992 1.1 joerg 5993 1.1 joerg ImplicitConversionSequence ICS 5994 1.1 joerg = S.TryImplicitConversion(Initializer, DestType, 5995 1.1 joerg /*SuppressUserConversions*/true, 5996 1.1.1.2 joerg Sema::AllowedExplicit::None, 5997 1.1 joerg /*InOverloadResolution*/ false, 5998 1.1 joerg /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 5999 1.1 joerg allowObjCWritebackConversion); 6000 1.1 joerg 6001 1.1 joerg if (ICS.isStandard() && 6002 1.1 joerg ICS.Standard.Second == ICK_Writeback_Conversion) { 6003 1.1 joerg // Objective-C ARC writeback conversion. 6004 1.1 joerg 6005 1.1 joerg // We should copy unless we're passing to an argument explicitly 6006 1.1 joerg // marked 'out'. 6007 1.1 joerg bool ShouldCopy = true; 6008 1.1 joerg if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 6009 1.1 joerg ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 6010 1.1 joerg 6011 1.1 joerg // If there was an lvalue adjustment, add it as a separate conversion. 6012 1.1 joerg if (ICS.Standard.First == ICK_Array_To_Pointer || 6013 1.1 joerg ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6014 1.1 joerg ImplicitConversionSequence LvalueICS; 6015 1.1 joerg LvalueICS.setStandard(); 6016 1.1 joerg LvalueICS.Standard.setAsIdentityConversion(); 6017 1.1 joerg LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0)); 6018 1.1 joerg LvalueICS.Standard.First = ICS.Standard.First; 6019 1.1 joerg AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); 6020 1.1 joerg } 6021 1.1 joerg 6022 1.1 joerg AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy); 6023 1.1 joerg } else if (ICS.isBad()) { 6024 1.1 joerg DeclAccessPair dap; 6025 1.1 joerg if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) { 6026 1.1 joerg AddZeroInitializationStep(Entity.getType()); 6027 1.1 joerg } else if (Initializer->getType() == Context.OverloadTy && 6028 1.1 joerg !S.ResolveAddressOfOverloadedFunction(Initializer, DestType, 6029 1.1 joerg false, dap)) 6030 1.1 joerg SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 6031 1.1 joerg else if (Initializer->getType()->isFunctionType() && 6032 1.1 joerg isExprAnUnaddressableFunction(S, Initializer)) 6033 1.1 joerg SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction); 6034 1.1 joerg else 6035 1.1 joerg SetFailed(InitializationSequence::FK_ConversionFailed); 6036 1.1 joerg } else { 6037 1.1 joerg AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); 6038 1.1 joerg 6039 1.1 joerg MaybeProduceObjCObject(S, *this, Entity); 6040 1.1 joerg } 6041 1.1 joerg } 6042 1.1 joerg 6043 1.1 joerg InitializationSequence::~InitializationSequence() { 6044 1.1 joerg for (auto &S : Steps) 6045 1.1 joerg S.Destroy(); 6046 1.1 joerg } 6047 1.1 joerg 6048 1.1 joerg //===----------------------------------------------------------------------===// 6049 1.1 joerg // Perform initialization 6050 1.1 joerg //===----------------------------------------------------------------------===// 6051 1.1 joerg static Sema::AssignmentAction 6052 1.1 joerg getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) { 6053 1.1 joerg switch(Entity.getKind()) { 6054 1.1 joerg case InitializedEntity::EK_Variable: 6055 1.1 joerg case InitializedEntity::EK_New: 6056 1.1 joerg case InitializedEntity::EK_Exception: 6057 1.1 joerg case InitializedEntity::EK_Base: 6058 1.1 joerg case InitializedEntity::EK_Delegating: 6059 1.1 joerg return Sema::AA_Initializing; 6060 1.1 joerg 6061 1.1 joerg case InitializedEntity::EK_Parameter: 6062 1.1 joerg if (Entity.getDecl() && 6063 1.1 joerg isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 6064 1.1 joerg return Sema::AA_Sending; 6065 1.1 joerg 6066 1.1 joerg return Sema::AA_Passing; 6067 1.1 joerg 6068 1.1 joerg case InitializedEntity::EK_Parameter_CF_Audited: 6069 1.1 joerg if (Entity.getDecl() && 6070 1.1 joerg isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 6071 1.1 joerg return Sema::AA_Sending; 6072 1.1 joerg 6073 1.1 joerg return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited; 6074 1.1 joerg 6075 1.1 joerg case InitializedEntity::EK_Result: 6076 1.1 joerg case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right. 6077 1.1 joerg return Sema::AA_Returning; 6078 1.1 joerg 6079 1.1 joerg case InitializedEntity::EK_Temporary: 6080 1.1 joerg case InitializedEntity::EK_RelatedResult: 6081 1.1 joerg // FIXME: Can we tell apart casting vs. converting? 6082 1.1 joerg return Sema::AA_Casting; 6083 1.1 joerg 6084 1.1.1.2 joerg case InitializedEntity::EK_TemplateParameter: 6085 1.1.1.2 joerg // This is really initialization, but refer to it as conversion for 6086 1.1.1.2 joerg // consistency with CheckConvertedConstantExpression. 6087 1.1.1.2 joerg return Sema::AA_Converting; 6088 1.1.1.2 joerg 6089 1.1 joerg case InitializedEntity::EK_Member: 6090 1.1 joerg case InitializedEntity::EK_Binding: 6091 1.1 joerg case InitializedEntity::EK_ArrayElement: 6092 1.1 joerg case InitializedEntity::EK_VectorElement: 6093 1.1 joerg case InitializedEntity::EK_ComplexElement: 6094 1.1 joerg case InitializedEntity::EK_BlockElement: 6095 1.1 joerg case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6096 1.1 joerg case InitializedEntity::EK_LambdaCapture: 6097 1.1 joerg case InitializedEntity::EK_CompoundLiteralInit: 6098 1.1 joerg return Sema::AA_Initializing; 6099 1.1 joerg } 6100 1.1 joerg 6101 1.1 joerg llvm_unreachable("Invalid EntityKind!"); 6102 1.1 joerg } 6103 1.1 joerg 6104 1.1 joerg /// Whether we should bind a created object as a temporary when 6105 1.1 joerg /// initializing the given entity. 6106 1.1 joerg static bool shouldBindAsTemporary(const InitializedEntity &Entity) { 6107 1.1 joerg switch (Entity.getKind()) { 6108 1.1 joerg case InitializedEntity::EK_ArrayElement: 6109 1.1 joerg case InitializedEntity::EK_Member: 6110 1.1 joerg case InitializedEntity::EK_Result: 6111 1.1 joerg case InitializedEntity::EK_StmtExprResult: 6112 1.1 joerg case InitializedEntity::EK_New: 6113 1.1 joerg case InitializedEntity::EK_Variable: 6114 1.1 joerg case InitializedEntity::EK_Base: 6115 1.1 joerg case InitializedEntity::EK_Delegating: 6116 1.1 joerg case InitializedEntity::EK_VectorElement: 6117 1.1 joerg case InitializedEntity::EK_ComplexElement: 6118 1.1 joerg case InitializedEntity::EK_Exception: 6119 1.1 joerg case InitializedEntity::EK_BlockElement: 6120 1.1 joerg case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6121 1.1 joerg case InitializedEntity::EK_LambdaCapture: 6122 1.1 joerg case InitializedEntity::EK_CompoundLiteralInit: 6123 1.1.1.2 joerg case InitializedEntity::EK_TemplateParameter: 6124 1.1 joerg return false; 6125 1.1 joerg 6126 1.1 joerg case InitializedEntity::EK_Parameter: 6127 1.1 joerg case InitializedEntity::EK_Parameter_CF_Audited: 6128 1.1 joerg case InitializedEntity::EK_Temporary: 6129 1.1 joerg case InitializedEntity::EK_RelatedResult: 6130 1.1 joerg case InitializedEntity::EK_Binding: 6131 1.1 joerg return true; 6132 1.1 joerg } 6133 1.1 joerg 6134 1.1 joerg llvm_unreachable("missed an InitializedEntity kind?"); 6135 1.1 joerg } 6136 1.1 joerg 6137 1.1 joerg /// Whether the given entity, when initialized with an object 6138 1.1 joerg /// created for that initialization, requires destruction. 6139 1.1 joerg static bool shouldDestroyEntity(const InitializedEntity &Entity) { 6140 1.1 joerg switch (Entity.getKind()) { 6141 1.1 joerg case InitializedEntity::EK_Result: 6142 1.1 joerg case InitializedEntity::EK_StmtExprResult: 6143 1.1 joerg case InitializedEntity::EK_New: 6144 1.1 joerg case InitializedEntity::EK_Base: 6145 1.1 joerg case InitializedEntity::EK_Delegating: 6146 1.1 joerg case InitializedEntity::EK_VectorElement: 6147 1.1 joerg case InitializedEntity::EK_ComplexElement: 6148 1.1 joerg case InitializedEntity::EK_BlockElement: 6149 1.1 joerg case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6150 1.1 joerg case InitializedEntity::EK_LambdaCapture: 6151 1.1 joerg return false; 6152 1.1 joerg 6153 1.1 joerg case InitializedEntity::EK_Member: 6154 1.1 joerg case InitializedEntity::EK_Binding: 6155 1.1 joerg case InitializedEntity::EK_Variable: 6156 1.1 joerg case InitializedEntity::EK_Parameter: 6157 1.1 joerg case InitializedEntity::EK_Parameter_CF_Audited: 6158 1.1.1.2 joerg case InitializedEntity::EK_TemplateParameter: 6159 1.1 joerg case InitializedEntity::EK_Temporary: 6160 1.1 joerg case InitializedEntity::EK_ArrayElement: 6161 1.1 joerg case InitializedEntity::EK_Exception: 6162 1.1 joerg case InitializedEntity::EK_CompoundLiteralInit: 6163 1.1 joerg case InitializedEntity::EK_RelatedResult: 6164 1.1 joerg return true; 6165 1.1 joerg } 6166 1.1 joerg 6167 1.1 joerg llvm_unreachable("missed an InitializedEntity kind?"); 6168 1.1 joerg } 6169 1.1 joerg 6170 1.1 joerg /// Get the location at which initialization diagnostics should appear. 6171 1.1 joerg static SourceLocation getInitializationLoc(const InitializedEntity &Entity, 6172 1.1 joerg Expr *Initializer) { 6173 1.1 joerg switch (Entity.getKind()) { 6174 1.1 joerg case InitializedEntity::EK_Result: 6175 1.1 joerg case InitializedEntity::EK_StmtExprResult: 6176 1.1 joerg return Entity.getReturnLoc(); 6177 1.1 joerg 6178 1.1 joerg case InitializedEntity::EK_Exception: 6179 1.1 joerg return Entity.getThrowLoc(); 6180 1.1 joerg 6181 1.1 joerg case InitializedEntity::EK_Variable: 6182 1.1 joerg case InitializedEntity::EK_Binding: 6183 1.1 joerg return Entity.getDecl()->getLocation(); 6184 1.1 joerg 6185 1.1 joerg case InitializedEntity::EK_LambdaCapture: 6186 1.1 joerg return Entity.getCaptureLoc(); 6187 1.1 joerg 6188 1.1 joerg case InitializedEntity::EK_ArrayElement: 6189 1.1 joerg case InitializedEntity::EK_Member: 6190 1.1 joerg case InitializedEntity::EK_Parameter: 6191 1.1 joerg case InitializedEntity::EK_Parameter_CF_Audited: 6192 1.1.1.2 joerg case InitializedEntity::EK_TemplateParameter: 6193 1.1 joerg case InitializedEntity::EK_Temporary: 6194 1.1 joerg case InitializedEntity::EK_New: 6195 1.1 joerg case InitializedEntity::EK_Base: 6196 1.1 joerg case InitializedEntity::EK_Delegating: 6197 1.1 joerg case InitializedEntity::EK_VectorElement: 6198 1.1 joerg case InitializedEntity::EK_ComplexElement: 6199 1.1 joerg case InitializedEntity::EK_BlockElement: 6200 1.1 joerg case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6201 1.1 joerg case InitializedEntity::EK_CompoundLiteralInit: 6202 1.1 joerg case InitializedEntity::EK_RelatedResult: 6203 1.1 joerg return Initializer->getBeginLoc(); 6204 1.1 joerg } 6205 1.1 joerg llvm_unreachable("missed an InitializedEntity kind?"); 6206 1.1 joerg } 6207 1.1 joerg 6208 1.1 joerg /// Make a (potentially elidable) temporary copy of the object 6209 1.1 joerg /// provided by the given initializer by calling the appropriate copy 6210 1.1 joerg /// constructor. 6211 1.1 joerg /// 6212 1.1 joerg /// \param S The Sema object used for type-checking. 6213 1.1 joerg /// 6214 1.1 joerg /// \param T The type of the temporary object, which must either be 6215 1.1 joerg /// the type of the initializer expression or a superclass thereof. 6216 1.1 joerg /// 6217 1.1 joerg /// \param Entity The entity being initialized. 6218 1.1 joerg /// 6219 1.1 joerg /// \param CurInit The initializer expression. 6220 1.1 joerg /// 6221 1.1 joerg /// \param IsExtraneousCopy Whether this is an "extraneous" copy that 6222 1.1 joerg /// is permitted in C++03 (but not C++0x) when binding a reference to 6223 1.1 joerg /// an rvalue. 6224 1.1 joerg /// 6225 1.1 joerg /// \returns An expression that copies the initializer expression into 6226 1.1 joerg /// a temporary object, or an error expression if a copy could not be 6227 1.1 joerg /// created. 6228 1.1 joerg static ExprResult CopyObject(Sema &S, 6229 1.1 joerg QualType T, 6230 1.1 joerg const InitializedEntity &Entity, 6231 1.1 joerg ExprResult CurInit, 6232 1.1 joerg bool IsExtraneousCopy) { 6233 1.1 joerg if (CurInit.isInvalid()) 6234 1.1 joerg return CurInit; 6235 1.1 joerg // Determine which class type we're copying to. 6236 1.1 joerg Expr *CurInitExpr = (Expr *)CurInit.get(); 6237 1.1 joerg CXXRecordDecl *Class = nullptr; 6238 1.1 joerg if (const RecordType *Record = T->getAs<RecordType>()) 6239 1.1 joerg Class = cast<CXXRecordDecl>(Record->getDecl()); 6240 1.1 joerg if (!Class) 6241 1.1 joerg return CurInit; 6242 1.1 joerg 6243 1.1 joerg SourceLocation Loc = getInitializationLoc(Entity, CurInit.get()); 6244 1.1 joerg 6245 1.1 joerg // Make sure that the type we are copying is complete. 6246 1.1 joerg if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete)) 6247 1.1 joerg return CurInit; 6248 1.1 joerg 6249 1.1 joerg // Perform overload resolution using the class's constructors. Per 6250 1.1 joerg // C++11 [dcl.init]p16, second bullet for class types, this initialization 6251 1.1 joerg // is direct-initialization. 6252 1.1 joerg OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6253 1.1 joerg DeclContext::lookup_result Ctors = S.LookupConstructors(Class); 6254 1.1 joerg 6255 1.1 joerg OverloadCandidateSet::iterator Best; 6256 1.1 joerg switch (ResolveConstructorOverload( 6257 1.1 joerg S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best, 6258 1.1 joerg /*CopyInitializing=*/false, /*AllowExplicit=*/true, 6259 1.1 joerg /*OnlyListConstructors=*/false, /*IsListInit=*/false, 6260 1.1 joerg /*SecondStepOfCopyInit=*/true)) { 6261 1.1 joerg case OR_Success: 6262 1.1 joerg break; 6263 1.1 joerg 6264 1.1 joerg case OR_No_Viable_Function: 6265 1.1 joerg CandidateSet.NoteCandidates( 6266 1.1 joerg PartialDiagnosticAt( 6267 1.1 joerg Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext() 6268 1.1 joerg ? diag::ext_rvalue_to_reference_temp_copy_no_viable 6269 1.1 joerg : diag::err_temp_copy_no_viable) 6270 1.1 joerg << (int)Entity.getKind() << CurInitExpr->getType() 6271 1.1 joerg << CurInitExpr->getSourceRange()), 6272 1.1 joerg S, OCD_AllCandidates, CurInitExpr); 6273 1.1 joerg if (!IsExtraneousCopy || S.isSFINAEContext()) 6274 1.1 joerg return ExprError(); 6275 1.1 joerg return CurInit; 6276 1.1 joerg 6277 1.1 joerg case OR_Ambiguous: 6278 1.1 joerg CandidateSet.NoteCandidates( 6279 1.1 joerg PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous) 6280 1.1 joerg << (int)Entity.getKind() 6281 1.1 joerg << CurInitExpr->getType() 6282 1.1 joerg << CurInitExpr->getSourceRange()), 6283 1.1 joerg S, OCD_AmbiguousCandidates, CurInitExpr); 6284 1.1 joerg return ExprError(); 6285 1.1 joerg 6286 1.1 joerg case OR_Deleted: 6287 1.1 joerg S.Diag(Loc, diag::err_temp_copy_deleted) 6288 1.1 joerg << (int)Entity.getKind() << CurInitExpr->getType() 6289 1.1 joerg << CurInitExpr->getSourceRange(); 6290 1.1 joerg S.NoteDeletedFunction(Best->Function); 6291 1.1 joerg return ExprError(); 6292 1.1 joerg } 6293 1.1 joerg 6294 1.1 joerg bool HadMultipleCandidates = CandidateSet.size() > 1; 6295 1.1 joerg 6296 1.1 joerg CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 6297 1.1 joerg SmallVector<Expr*, 8> ConstructorArgs; 6298 1.1 joerg CurInit.get(); // Ownership transferred into MultiExprArg, below. 6299 1.1 joerg 6300 1.1 joerg S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity, 6301 1.1 joerg IsExtraneousCopy); 6302 1.1 joerg 6303 1.1 joerg if (IsExtraneousCopy) { 6304 1.1 joerg // If this is a totally extraneous copy for C++03 reference 6305 1.1 joerg // binding purposes, just return the original initialization 6306 1.1 joerg // expression. We don't generate an (elided) copy operation here 6307 1.1 joerg // because doing so would require us to pass down a flag to avoid 6308 1.1 joerg // infinite recursion, where each step adds another extraneous, 6309 1.1 joerg // elidable copy. 6310 1.1 joerg 6311 1.1 joerg // Instantiate the default arguments of any extra parameters in 6312 1.1 joerg // the selected copy constructor, as if we were going to create a 6313 1.1 joerg // proper call to the copy constructor. 6314 1.1 joerg for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { 6315 1.1 joerg ParmVarDecl *Parm = Constructor->getParamDecl(I); 6316 1.1 joerg if (S.RequireCompleteType(Loc, Parm->getType(), 6317 1.1 joerg diag::err_call_incomplete_argument)) 6318 1.1 joerg break; 6319 1.1 joerg 6320 1.1 joerg // Build the default argument expression; we don't actually care 6321 1.1 joerg // if this succeeds or not, because this routine will complain 6322 1.1 joerg // if there was a problem. 6323 1.1 joerg S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); 6324 1.1 joerg } 6325 1.1 joerg 6326 1.1 joerg return CurInitExpr; 6327 1.1 joerg } 6328 1.1 joerg 6329 1.1 joerg // Determine the arguments required to actually perform the 6330 1.1 joerg // constructor call (we might have derived-to-base conversions, or 6331 1.1 joerg // the copy constructor may have default arguments). 6332 1.1.1.2 joerg if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc, 6333 1.1.1.2 joerg ConstructorArgs)) 6334 1.1 joerg return ExprError(); 6335 1.1 joerg 6336 1.1 joerg // C++0x [class.copy]p32: 6337 1.1 joerg // When certain criteria are met, an implementation is allowed to 6338 1.1 joerg // omit the copy/move construction of a class object, even if the 6339 1.1 joerg // copy/move constructor and/or destructor for the object have 6340 1.1 joerg // side effects. [...] 6341 1.1 joerg // - when a temporary class object that has not been bound to a 6342 1.1 joerg // reference (12.2) would be copied/moved to a class object 6343 1.1 joerg // with the same cv-unqualified type, the copy/move operation 6344 1.1 joerg // can be omitted by constructing the temporary object 6345 1.1 joerg // directly into the target of the omitted copy/move 6346 1.1 joerg // 6347 1.1 joerg // Note that the other three bullets are handled elsewhere. Copy 6348 1.1 joerg // elision for return statements and throw expressions are handled as part 6349 1.1 joerg // of constructor initialization, while copy elision for exception handlers 6350 1.1 joerg // is handled by the run-time. 6351 1.1 joerg // 6352 1.1 joerg // FIXME: If the function parameter is not the same type as the temporary, we 6353 1.1 joerg // should still be able to elide the copy, but we don't have a way to 6354 1.1 joerg // represent in the AST how much should be elided in this case. 6355 1.1 joerg bool Elidable = 6356 1.1 joerg CurInitExpr->isTemporaryObject(S.Context, Class) && 6357 1.1 joerg S.Context.hasSameUnqualifiedType( 6358 1.1 joerg Best->Function->getParamDecl(0)->getType().getNonReferenceType(), 6359 1.1 joerg CurInitExpr->getType()); 6360 1.1 joerg 6361 1.1 joerg // Actually perform the constructor call. 6362 1.1 joerg CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor, 6363 1.1 joerg Elidable, 6364 1.1 joerg ConstructorArgs, 6365 1.1 joerg HadMultipleCandidates, 6366 1.1 joerg /*ListInit*/ false, 6367 1.1 joerg /*StdInitListInit*/ false, 6368 1.1 joerg /*ZeroInit*/ false, 6369 1.1 joerg CXXConstructExpr::CK_Complete, 6370 1.1 joerg SourceRange()); 6371 1.1 joerg 6372 1.1 joerg // If we're supposed to bind temporaries, do so. 6373 1.1 joerg if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) 6374 1.1 joerg CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); 6375 1.1 joerg return CurInit; 6376 1.1 joerg } 6377 1.1 joerg 6378 1.1 joerg /// Check whether elidable copy construction for binding a reference to 6379 1.1 joerg /// a temporary would have succeeded if we were building in C++98 mode, for 6380 1.1 joerg /// -Wc++98-compat. 6381 1.1 joerg static void CheckCXX98CompatAccessibleCopy(Sema &S, 6382 1.1 joerg const InitializedEntity &Entity, 6383 1.1 joerg Expr *CurInitExpr) { 6384 1.1 joerg assert(S.getLangOpts().CPlusPlus11); 6385 1.1 joerg 6386 1.1 joerg const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>(); 6387 1.1 joerg if (!Record) 6388 1.1 joerg return; 6389 1.1 joerg 6390 1.1 joerg SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr); 6391 1.1 joerg if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc)) 6392 1.1 joerg return; 6393 1.1 joerg 6394 1.1 joerg // Find constructors which would have been considered. 6395 1.1 joerg OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6396 1.1 joerg DeclContext::lookup_result Ctors = 6397 1.1 joerg S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl())); 6398 1.1 joerg 6399 1.1 joerg // Perform overload resolution. 6400 1.1 joerg OverloadCandidateSet::iterator Best; 6401 1.1 joerg OverloadingResult OR = ResolveConstructorOverload( 6402 1.1 joerg S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best, 6403 1.1 joerg /*CopyInitializing=*/false, /*AllowExplicit=*/true, 6404 1.1 joerg /*OnlyListConstructors=*/false, /*IsListInit=*/false, 6405 1.1 joerg /*SecondStepOfCopyInit=*/true); 6406 1.1 joerg 6407 1.1 joerg PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy) 6408 1.1 joerg << OR << (int)Entity.getKind() << CurInitExpr->getType() 6409 1.1 joerg << CurInitExpr->getSourceRange(); 6410 1.1 joerg 6411 1.1 joerg switch (OR) { 6412 1.1 joerg case OR_Success: 6413 1.1 joerg S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function), 6414 1.1 joerg Best->FoundDecl, Entity, Diag); 6415 1.1 joerg // FIXME: Check default arguments as far as that's possible. 6416 1.1 joerg break; 6417 1.1 joerg 6418 1.1 joerg case OR_No_Viable_Function: 6419 1.1 joerg CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, 6420 1.1 joerg OCD_AllCandidates, CurInitExpr); 6421 1.1 joerg break; 6422 1.1 joerg 6423 1.1 joerg case OR_Ambiguous: 6424 1.1 joerg CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, 6425 1.1 joerg OCD_AmbiguousCandidates, CurInitExpr); 6426 1.1 joerg break; 6427 1.1 joerg 6428 1.1 joerg case OR_Deleted: 6429 1.1 joerg S.Diag(Loc, Diag); 6430 1.1 joerg S.NoteDeletedFunction(Best->Function); 6431 1.1 joerg break; 6432 1.1 joerg } 6433 1.1 joerg } 6434 1.1 joerg 6435 1.1 joerg void InitializationSequence::PrintInitLocationNote(Sema &S, 6436 1.1 joerg const InitializedEntity &Entity) { 6437 1.1.1.2 joerg if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) { 6438 1.1 joerg if (Entity.getDecl()->getLocation().isInvalid()) 6439 1.1 joerg return; 6440 1.1 joerg 6441 1.1 joerg if (Entity.getDecl()->getDeclName()) 6442 1.1 joerg S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) 6443 1.1 joerg << Entity.getDecl()->getDeclName(); 6444 1.1 joerg else 6445 1.1 joerg S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); 6446 1.1 joerg } 6447 1.1 joerg else if (Entity.getKind() == InitializedEntity::EK_RelatedResult && 6448 1.1 joerg Entity.getMethodDecl()) 6449 1.1 joerg S.Diag(Entity.getMethodDecl()->getLocation(), 6450 1.1 joerg diag::note_method_return_type_change) 6451 1.1 joerg << Entity.getMethodDecl()->getDeclName(); 6452 1.1 joerg } 6453 1.1 joerg 6454 1.1 joerg /// Returns true if the parameters describe a constructor initialization of 6455 1.1 joerg /// an explicit temporary object, e.g. "Point(x, y)". 6456 1.1 joerg static bool isExplicitTemporary(const InitializedEntity &Entity, 6457 1.1 joerg const InitializationKind &Kind, 6458 1.1 joerg unsigned NumArgs) { 6459 1.1 joerg switch (Entity.getKind()) { 6460 1.1 joerg case InitializedEntity::EK_Temporary: 6461 1.1 joerg case InitializedEntity::EK_CompoundLiteralInit: 6462 1.1 joerg case InitializedEntity::EK_RelatedResult: 6463 1.1 joerg break; 6464 1.1 joerg default: 6465 1.1 joerg return false; 6466 1.1 joerg } 6467 1.1 joerg 6468 1.1 joerg switch (Kind.getKind()) { 6469 1.1 joerg case InitializationKind::IK_DirectList: 6470 1.1 joerg return true; 6471 1.1 joerg // FIXME: Hack to work around cast weirdness. 6472 1.1 joerg case InitializationKind::IK_Direct: 6473 1.1 joerg case InitializationKind::IK_Value: 6474 1.1 joerg return NumArgs != 1; 6475 1.1 joerg default: 6476 1.1 joerg return false; 6477 1.1 joerg } 6478 1.1 joerg } 6479 1.1 joerg 6480 1.1 joerg static ExprResult 6481 1.1 joerg PerformConstructorInitialization(Sema &S, 6482 1.1 joerg const InitializedEntity &Entity, 6483 1.1 joerg const InitializationKind &Kind, 6484 1.1 joerg MultiExprArg Args, 6485 1.1 joerg const InitializationSequence::Step& Step, 6486 1.1 joerg bool &ConstructorInitRequiresZeroInit, 6487 1.1 joerg bool IsListInitialization, 6488 1.1 joerg bool IsStdInitListInitialization, 6489 1.1 joerg SourceLocation LBraceLoc, 6490 1.1 joerg SourceLocation RBraceLoc) { 6491 1.1 joerg unsigned NumArgs = Args.size(); 6492 1.1 joerg CXXConstructorDecl *Constructor 6493 1.1 joerg = cast<CXXConstructorDecl>(Step.Function.Function); 6494 1.1 joerg bool HadMultipleCandidates = Step.Function.HadMultipleCandidates; 6495 1.1 joerg 6496 1.1 joerg // Build a call to the selected constructor. 6497 1.1 joerg SmallVector<Expr*, 8> ConstructorArgs; 6498 1.1 joerg SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) 6499 1.1 joerg ? Kind.getEqualLoc() 6500 1.1 joerg : Kind.getLocation(); 6501 1.1 joerg 6502 1.1 joerg if (Kind.getKind() == InitializationKind::IK_Default) { 6503 1.1 joerg // Force even a trivial, implicit default constructor to be 6504 1.1 joerg // semantically checked. We do this explicitly because we don't build 6505 1.1 joerg // the definition for completely trivial constructors. 6506 1.1 joerg assert(Constructor->getParent() && "No parent class for constructor."); 6507 1.1 joerg if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 6508 1.1 joerg Constructor->isTrivial() && !Constructor->isUsed(false)) { 6509 1.1 joerg S.runWithSufficientStackSpace(Loc, [&] { 6510 1.1 joerg S.DefineImplicitDefaultConstructor(Loc, Constructor); 6511 1.1 joerg }); 6512 1.1 joerg } 6513 1.1 joerg } 6514 1.1 joerg 6515 1.1 joerg ExprResult CurInit((Expr *)nullptr); 6516 1.1 joerg 6517 1.1 joerg // C++ [over.match.copy]p1: 6518 1.1 joerg // - When initializing a temporary to be bound to the first parameter 6519 1.1 joerg // of a constructor that takes a reference to possibly cv-qualified 6520 1.1 joerg // T as its first argument, called with a single argument in the 6521 1.1 joerg // context of direct-initialization, explicit conversion functions 6522 1.1 joerg // are also considered. 6523 1.1 joerg bool AllowExplicitConv = 6524 1.1 joerg Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 && 6525 1.1 joerg hasCopyOrMoveCtorParam(S.Context, 6526 1.1 joerg getConstructorInfo(Step.Function.FoundDecl)); 6527 1.1 joerg 6528 1.1 joerg // Determine the arguments required to actually perform the constructor 6529 1.1 joerg // call. 6530 1.1.1.2 joerg if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc, 6531 1.1.1.2 joerg ConstructorArgs, AllowExplicitConv, 6532 1.1 joerg IsListInitialization)) 6533 1.1 joerg return ExprError(); 6534 1.1 joerg 6535 1.1 joerg if (isExplicitTemporary(Entity, Kind, NumArgs)) { 6536 1.1 joerg // An explicitly-constructed temporary, e.g., X(1, 2). 6537 1.1 joerg if (S.DiagnoseUseOfDecl(Constructor, Loc)) 6538 1.1 joerg return ExprError(); 6539 1.1 joerg 6540 1.1 joerg TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 6541 1.1 joerg if (!TSInfo) 6542 1.1 joerg TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc); 6543 1.1 joerg SourceRange ParenOrBraceRange = 6544 1.1 joerg (Kind.getKind() == InitializationKind::IK_DirectList) 6545 1.1 joerg ? SourceRange(LBraceLoc, RBraceLoc) 6546 1.1 joerg : Kind.getParenOrBraceRange(); 6547 1.1 joerg 6548 1.1.1.2 joerg CXXConstructorDecl *CalleeDecl = Constructor; 6549 1.1 joerg if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>( 6550 1.1 joerg Step.Function.FoundDecl.getDecl())) { 6551 1.1.1.2 joerg CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow); 6552 1.1.1.2 joerg if (S.DiagnoseUseOfDecl(CalleeDecl, Loc)) 6553 1.1 joerg return ExprError(); 6554 1.1 joerg } 6555 1.1.1.2 joerg S.MarkFunctionReferenced(Loc, CalleeDecl); 6556 1.1 joerg 6557 1.1.1.2 joerg CurInit = S.CheckForImmediateInvocation( 6558 1.1.1.2 joerg CXXTemporaryObjectExpr::Create( 6559 1.1.1.2 joerg S.Context, CalleeDecl, 6560 1.1.1.2 joerg Entity.getType().getNonLValueExprType(S.Context), TSInfo, 6561 1.1.1.2 joerg ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates, 6562 1.1.1.2 joerg IsListInitialization, IsStdInitListInitialization, 6563 1.1.1.2 joerg ConstructorInitRequiresZeroInit), 6564 1.1.1.2 joerg CalleeDecl); 6565 1.1 joerg } else { 6566 1.1 joerg CXXConstructExpr::ConstructionKind ConstructKind = 6567 1.1 joerg CXXConstructExpr::CK_Complete; 6568 1.1 joerg 6569 1.1 joerg if (Entity.getKind() == InitializedEntity::EK_Base) { 6570 1.1 joerg ConstructKind = Entity.getBaseSpecifier()->isVirtual() ? 6571 1.1 joerg CXXConstructExpr::CK_VirtualBase : 6572 1.1 joerg CXXConstructExpr::CK_NonVirtualBase; 6573 1.1 joerg } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { 6574 1.1 joerg ConstructKind = CXXConstructExpr::CK_Delegating; 6575 1.1 joerg } 6576 1.1 joerg 6577 1.1 joerg // Only get the parenthesis or brace range if it is a list initialization or 6578 1.1 joerg // direct construction. 6579 1.1 joerg SourceRange ParenOrBraceRange; 6580 1.1 joerg if (IsListInitialization) 6581 1.1 joerg ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc); 6582 1.1 joerg else if (Kind.getKind() == InitializationKind::IK_Direct) 6583 1.1 joerg ParenOrBraceRange = Kind.getParenOrBraceRange(); 6584 1.1 joerg 6585 1.1 joerg // If the entity allows NRVO, mark the construction as elidable 6586 1.1 joerg // unconditionally. 6587 1.1 joerg if (Entity.allowsNRVO()) 6588 1.1 joerg CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, 6589 1.1 joerg Step.Function.FoundDecl, 6590 1.1 joerg Constructor, /*Elidable=*/true, 6591 1.1 joerg ConstructorArgs, 6592 1.1 joerg HadMultipleCandidates, 6593 1.1 joerg IsListInitialization, 6594 1.1 joerg IsStdInitListInitialization, 6595 1.1 joerg ConstructorInitRequiresZeroInit, 6596 1.1 joerg ConstructKind, 6597 1.1 joerg ParenOrBraceRange); 6598 1.1 joerg else 6599 1.1 joerg CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, 6600 1.1 joerg Step.Function.FoundDecl, 6601 1.1 joerg Constructor, 6602 1.1 joerg ConstructorArgs, 6603 1.1 joerg HadMultipleCandidates, 6604 1.1 joerg IsListInitialization, 6605 1.1 joerg IsStdInitListInitialization, 6606 1.1 joerg ConstructorInitRequiresZeroInit, 6607 1.1 joerg ConstructKind, 6608 1.1 joerg ParenOrBraceRange); 6609 1.1 joerg } 6610 1.1 joerg if (CurInit.isInvalid()) 6611 1.1 joerg return ExprError(); 6612 1.1 joerg 6613 1.1 joerg // Only check access if all of that succeeded. 6614 1.1 joerg S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity); 6615 1.1 joerg if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc)) 6616 1.1 joerg return ExprError(); 6617 1.1 joerg 6618 1.1 joerg if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType())) 6619 1.1 joerg if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S)) 6620 1.1 joerg return ExprError(); 6621 1.1 joerg 6622 1.1 joerg if (shouldBindAsTemporary(Entity)) 6623 1.1 joerg CurInit = S.MaybeBindToTemporary(CurInit.get()); 6624 1.1 joerg 6625 1.1 joerg return CurInit; 6626 1.1 joerg } 6627 1.1 joerg 6628 1.1 joerg namespace { 6629 1.1 joerg enum LifetimeKind { 6630 1.1 joerg /// The lifetime of a temporary bound to this entity ends at the end of the 6631 1.1 joerg /// full-expression, and that's (probably) fine. 6632 1.1 joerg LK_FullExpression, 6633 1.1 joerg 6634 1.1 joerg /// The lifetime of a temporary bound to this entity is extended to the 6635 1.1 joerg /// lifeitme of the entity itself. 6636 1.1 joerg LK_Extended, 6637 1.1 joerg 6638 1.1 joerg /// The lifetime of a temporary bound to this entity probably ends too soon, 6639 1.1 joerg /// because the entity is allocated in a new-expression. 6640 1.1 joerg LK_New, 6641 1.1 joerg 6642 1.1 joerg /// The lifetime of a temporary bound to this entity ends too soon, because 6643 1.1 joerg /// the entity is a return object. 6644 1.1 joerg LK_Return, 6645 1.1 joerg 6646 1.1 joerg /// The lifetime of a temporary bound to this entity ends too soon, because 6647 1.1 joerg /// the entity is the result of a statement expression. 6648 1.1 joerg LK_StmtExprResult, 6649 1.1 joerg 6650 1.1 joerg /// This is a mem-initializer: if it would extend a temporary (other than via 6651 1.1 joerg /// a default member initializer), the program is ill-formed. 6652 1.1 joerg LK_MemInitializer, 6653 1.1 joerg }; 6654 1.1 joerg using LifetimeResult = 6655 1.1 joerg llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>; 6656 1.1 joerg } 6657 1.1 joerg 6658 1.1 joerg /// Determine the declaration which an initialized entity ultimately refers to, 6659 1.1 joerg /// for the purpose of lifetime-extending a temporary bound to a reference in 6660 1.1 joerg /// the initialization of \p Entity. 6661 1.1 joerg static LifetimeResult getEntityLifetime( 6662 1.1 joerg const InitializedEntity *Entity, 6663 1.1 joerg const InitializedEntity *InitField = nullptr) { 6664 1.1 joerg // C++11 [class.temporary]p5: 6665 1.1 joerg switch (Entity->getKind()) { 6666 1.1 joerg case InitializedEntity::EK_Variable: 6667 1.1 joerg // The temporary [...] persists for the lifetime of the reference 6668 1.1 joerg return {Entity, LK_Extended}; 6669 1.1 joerg 6670 1.1 joerg case InitializedEntity::EK_Member: 6671 1.1 joerg // For subobjects, we look at the complete object. 6672 1.1 joerg if (Entity->getParent()) 6673 1.1 joerg return getEntityLifetime(Entity->getParent(), Entity); 6674 1.1 joerg 6675 1.1 joerg // except: 6676 1.1 joerg // C++17 [class.base.init]p8: 6677 1.1 joerg // A temporary expression bound to a reference member in a 6678 1.1 joerg // mem-initializer is ill-formed. 6679 1.1 joerg // C++17 [class.base.init]p11: 6680 1.1 joerg // A temporary expression bound to a reference member from a 6681 1.1 joerg // default member initializer is ill-formed. 6682 1.1 joerg // 6683 1.1 joerg // The context of p11 and its example suggest that it's only the use of a 6684 1.1 joerg // default member initializer from a constructor that makes the program 6685 1.1 joerg // ill-formed, not its mere existence, and that it can even be used by 6686 1.1 joerg // aggregate initialization. 6687 1.1 joerg return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended 6688 1.1 joerg : LK_MemInitializer}; 6689 1.1 joerg 6690 1.1 joerg case InitializedEntity::EK_Binding: 6691 1.1 joerg // Per [dcl.decomp]p3, the binding is treated as a variable of reference 6692 1.1 joerg // type. 6693 1.1 joerg return {Entity, LK_Extended}; 6694 1.1 joerg 6695 1.1 joerg case InitializedEntity::EK_Parameter: 6696 1.1 joerg case InitializedEntity::EK_Parameter_CF_Audited: 6697 1.1 joerg // -- A temporary bound to a reference parameter in a function call 6698 1.1 joerg // persists until the completion of the full-expression containing 6699 1.1 joerg // the call. 6700 1.1 joerg return {nullptr, LK_FullExpression}; 6701 1.1 joerg 6702 1.1.1.2 joerg case InitializedEntity::EK_TemplateParameter: 6703 1.1.1.2 joerg // FIXME: This will always be ill-formed; should we eagerly diagnose it here? 6704 1.1.1.2 joerg return {nullptr, LK_FullExpression}; 6705 1.1.1.2 joerg 6706 1.1 joerg case InitializedEntity::EK_Result: 6707 1.1 joerg // -- The lifetime of a temporary bound to the returned value in a 6708 1.1 joerg // function return statement is not extended; the temporary is 6709 1.1 joerg // destroyed at the end of the full-expression in the return statement. 6710 1.1 joerg return {nullptr, LK_Return}; 6711 1.1 joerg 6712 1.1 joerg case InitializedEntity::EK_StmtExprResult: 6713 1.1 joerg // FIXME: Should we lifetime-extend through the result of a statement 6714 1.1 joerg // expression? 6715 1.1 joerg return {nullptr, LK_StmtExprResult}; 6716 1.1 joerg 6717 1.1 joerg case InitializedEntity::EK_New: 6718 1.1 joerg // -- A temporary bound to a reference in a new-initializer persists 6719 1.1 joerg // until the completion of the full-expression containing the 6720 1.1 joerg // new-initializer. 6721 1.1 joerg return {nullptr, LK_New}; 6722 1.1 joerg 6723 1.1 joerg case InitializedEntity::EK_Temporary: 6724 1.1 joerg case InitializedEntity::EK_CompoundLiteralInit: 6725 1.1 joerg case InitializedEntity::EK_RelatedResult: 6726 1.1 joerg // We don't yet know the storage duration of the surrounding temporary. 6727 1.1 joerg // Assume it's got full-expression duration for now, it will patch up our 6728 1.1 joerg // storage duration if that's not correct. 6729 1.1 joerg return {nullptr, LK_FullExpression}; 6730 1.1 joerg 6731 1.1 joerg case InitializedEntity::EK_ArrayElement: 6732 1.1 joerg // For subobjects, we look at the complete object. 6733 1.1 joerg return getEntityLifetime(Entity->getParent(), InitField); 6734 1.1 joerg 6735 1.1 joerg case InitializedEntity::EK_Base: 6736 1.1 joerg // For subobjects, we look at the complete object. 6737 1.1 joerg if (Entity->getParent()) 6738 1.1 joerg return getEntityLifetime(Entity->getParent(), InitField); 6739 1.1 joerg return {InitField, LK_MemInitializer}; 6740 1.1 joerg 6741 1.1 joerg case InitializedEntity::EK_Delegating: 6742 1.1 joerg // We can reach this case for aggregate initialization in a constructor: 6743 1.1 joerg // struct A { int &&r; }; 6744 1.1 joerg // struct B : A { B() : A{0} {} }; 6745 1.1 joerg // In this case, use the outermost field decl as the context. 6746 1.1 joerg return {InitField, LK_MemInitializer}; 6747 1.1 joerg 6748 1.1 joerg case InitializedEntity::EK_BlockElement: 6749 1.1 joerg case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6750 1.1 joerg case InitializedEntity::EK_LambdaCapture: 6751 1.1 joerg case InitializedEntity::EK_VectorElement: 6752 1.1 joerg case InitializedEntity::EK_ComplexElement: 6753 1.1 joerg return {nullptr, LK_FullExpression}; 6754 1.1 joerg 6755 1.1 joerg case InitializedEntity::EK_Exception: 6756 1.1 joerg // FIXME: Can we diagnose lifetime problems with exceptions? 6757 1.1 joerg return {nullptr, LK_FullExpression}; 6758 1.1 joerg } 6759 1.1 joerg llvm_unreachable("unknown entity kind"); 6760 1.1 joerg } 6761 1.1 joerg 6762 1.1 joerg namespace { 6763 1.1 joerg enum ReferenceKind { 6764 1.1 joerg /// Lifetime would be extended by a reference binding to a temporary. 6765 1.1 joerg RK_ReferenceBinding, 6766 1.1 joerg /// Lifetime would be extended by a std::initializer_list object binding to 6767 1.1 joerg /// its backing array. 6768 1.1 joerg RK_StdInitializerList, 6769 1.1 joerg }; 6770 1.1 joerg 6771 1.1 joerg /// A temporary or local variable. This will be one of: 6772 1.1 joerg /// * A MaterializeTemporaryExpr. 6773 1.1 joerg /// * A DeclRefExpr whose declaration is a local. 6774 1.1 joerg /// * An AddrLabelExpr. 6775 1.1 joerg /// * A BlockExpr for a block with captures. 6776 1.1 joerg using Local = Expr*; 6777 1.1 joerg 6778 1.1 joerg /// Expressions we stepped over when looking for the local state. Any steps 6779 1.1 joerg /// that would inhibit lifetime extension or take us out of subexpressions of 6780 1.1 joerg /// the initializer are included. 6781 1.1 joerg struct IndirectLocalPathEntry { 6782 1.1 joerg enum EntryKind { 6783 1.1 joerg DefaultInit, 6784 1.1 joerg AddressOf, 6785 1.1 joerg VarInit, 6786 1.1 joerg LValToRVal, 6787 1.1 joerg LifetimeBoundCall, 6788 1.1.1.2 joerg TemporaryCopy, 6789 1.1.1.2 joerg LambdaCaptureInit, 6790 1.1.1.2 joerg GslReferenceInit, 6791 1.1 joerg GslPointerInit 6792 1.1 joerg } Kind; 6793 1.1 joerg Expr *E; 6794 1.1.1.2 joerg union { 6795 1.1.1.2 joerg const Decl *D = nullptr; 6796 1.1.1.2 joerg const LambdaCapture *Capture; 6797 1.1.1.2 joerg }; 6798 1.1 joerg IndirectLocalPathEntry() {} 6799 1.1 joerg IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {} 6800 1.1 joerg IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D) 6801 1.1 joerg : Kind(K), E(E), D(D) {} 6802 1.1.1.2 joerg IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture) 6803 1.1.1.2 joerg : Kind(K), E(E), Capture(Capture) {} 6804 1.1 joerg }; 6805 1.1 joerg 6806 1.1 joerg using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>; 6807 1.1 joerg 6808 1.1 joerg struct RevertToOldSizeRAII { 6809 1.1 joerg IndirectLocalPath &Path; 6810 1.1 joerg unsigned OldSize = Path.size(); 6811 1.1 joerg RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {} 6812 1.1 joerg ~RevertToOldSizeRAII() { Path.resize(OldSize); } 6813 1.1 joerg }; 6814 1.1 joerg 6815 1.1 joerg using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L, 6816 1.1 joerg ReferenceKind RK)>; 6817 1.1 joerg } 6818 1.1 joerg 6819 1.1 joerg static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) { 6820 1.1 joerg for (auto E : Path) 6821 1.1 joerg if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD) 6822 1.1 joerg return true; 6823 1.1 joerg return false; 6824 1.1 joerg } 6825 1.1 joerg 6826 1.1 joerg static bool pathContainsInit(IndirectLocalPath &Path) { 6827 1.1 joerg return llvm::any_of(Path, [=](IndirectLocalPathEntry E) { 6828 1.1 joerg return E.Kind == IndirectLocalPathEntry::DefaultInit || 6829 1.1 joerg E.Kind == IndirectLocalPathEntry::VarInit; 6830 1.1 joerg }); 6831 1.1 joerg } 6832 1.1 joerg 6833 1.1 joerg static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, 6834 1.1 joerg Expr *Init, LocalVisitor Visit, 6835 1.1 joerg bool RevisitSubinits, 6836 1.1 joerg bool EnableLifetimeWarnings); 6837 1.1 joerg 6838 1.1 joerg static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, 6839 1.1 joerg Expr *Init, ReferenceKind RK, 6840 1.1 joerg LocalVisitor Visit, 6841 1.1 joerg bool EnableLifetimeWarnings); 6842 1.1 joerg 6843 1.1 joerg template <typename T> static bool isRecordWithAttr(QualType Type) { 6844 1.1 joerg if (auto *RD = Type->getAsCXXRecordDecl()) 6845 1.1 joerg return RD->hasAttr<T>(); 6846 1.1 joerg return false; 6847 1.1 joerg } 6848 1.1 joerg 6849 1.1 joerg // Decl::isInStdNamespace will return false for iterators in some STL 6850 1.1 joerg // implementations due to them being defined in a namespace outside of the std 6851 1.1 joerg // namespace. 6852 1.1 joerg static bool isInStlNamespace(const Decl *D) { 6853 1.1 joerg const DeclContext *DC = D->getDeclContext(); 6854 1.1 joerg if (!DC) 6855 1.1 joerg return false; 6856 1.1 joerg if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) 6857 1.1 joerg if (const IdentifierInfo *II = ND->getIdentifier()) { 6858 1.1 joerg StringRef Name = II->getName(); 6859 1.1 joerg if (Name.size() >= 2 && Name.front() == '_' && 6860 1.1 joerg (Name[1] == '_' || isUppercase(Name[1]))) 6861 1.1 joerg return true; 6862 1.1 joerg } 6863 1.1 joerg 6864 1.1 joerg return DC->isStdNamespace(); 6865 1.1 joerg } 6866 1.1 joerg 6867 1.1 joerg static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) { 6868 1.1 joerg if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee)) 6869 1.1 joerg if (isRecordWithAttr<PointerAttr>(Conv->getConversionType())) 6870 1.1 joerg return true; 6871 1.1 joerg if (!isInStlNamespace(Callee->getParent())) 6872 1.1 joerg return false; 6873 1.1 joerg if (!isRecordWithAttr<PointerAttr>(Callee->getThisObjectType()) && 6874 1.1 joerg !isRecordWithAttr<OwnerAttr>(Callee->getThisObjectType())) 6875 1.1 joerg return false; 6876 1.1 joerg if (Callee->getReturnType()->isPointerType() || 6877 1.1 joerg isRecordWithAttr<PointerAttr>(Callee->getReturnType())) { 6878 1.1 joerg if (!Callee->getIdentifier()) 6879 1.1 joerg return false; 6880 1.1 joerg return llvm::StringSwitch<bool>(Callee->getName()) 6881 1.1 joerg .Cases("begin", "rbegin", "cbegin", "crbegin", true) 6882 1.1 joerg .Cases("end", "rend", "cend", "crend", true) 6883 1.1 joerg .Cases("c_str", "data", "get", true) 6884 1.1 joerg // Map and set types. 6885 1.1 joerg .Cases("find", "equal_range", "lower_bound", "upper_bound", true) 6886 1.1 joerg .Default(false); 6887 1.1 joerg } else if (Callee->getReturnType()->isReferenceType()) { 6888 1.1 joerg if (!Callee->getIdentifier()) { 6889 1.1 joerg auto OO = Callee->getOverloadedOperator(); 6890 1.1 joerg return OO == OverloadedOperatorKind::OO_Subscript || 6891 1.1 joerg OO == OverloadedOperatorKind::OO_Star; 6892 1.1 joerg } 6893 1.1 joerg return llvm::StringSwitch<bool>(Callee->getName()) 6894 1.1 joerg .Cases("front", "back", "at", "top", "value", true) 6895 1.1 joerg .Default(false); 6896 1.1 joerg } 6897 1.1 joerg return false; 6898 1.1 joerg } 6899 1.1 joerg 6900 1.1 joerg static bool shouldTrackFirstArgument(const FunctionDecl *FD) { 6901 1.1 joerg if (!FD->getIdentifier() || FD->getNumParams() != 1) 6902 1.1 joerg return false; 6903 1.1 joerg const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl(); 6904 1.1 joerg if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace()) 6905 1.1 joerg return false; 6906 1.1 joerg if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) && 6907 1.1 joerg !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0))) 6908 1.1 joerg return false; 6909 1.1 joerg if (FD->getReturnType()->isPointerType() || 6910 1.1 joerg isRecordWithAttr<PointerAttr>(FD->getReturnType())) { 6911 1.1 joerg return llvm::StringSwitch<bool>(FD->getName()) 6912 1.1 joerg .Cases("begin", "rbegin", "cbegin", "crbegin", true) 6913 1.1 joerg .Cases("end", "rend", "cend", "crend", true) 6914 1.1 joerg .Case("data", true) 6915 1.1 joerg .Default(false); 6916 1.1 joerg } else if (FD->getReturnType()->isReferenceType()) { 6917 1.1 joerg return llvm::StringSwitch<bool>(FD->getName()) 6918 1.1 joerg .Cases("get", "any_cast", true) 6919 1.1 joerg .Default(false); 6920 1.1 joerg } 6921 1.1 joerg return false; 6922 1.1 joerg } 6923 1.1 joerg 6924 1.1 joerg static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call, 6925 1.1 joerg LocalVisitor Visit) { 6926 1.1.1.2 joerg auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) { 6927 1.1 joerg // We are not interested in the temporary base objects of gsl Pointers: 6928 1.1 joerg // Temp().ptr; // Here ptr might not dangle. 6929 1.1 joerg if (isa<MemberExpr>(Arg->IgnoreImpCasts())) 6930 1.1 joerg return; 6931 1.1.1.2 joerg // Once we initialized a value with a reference, it can no longer dangle. 6932 1.1.1.2 joerg if (!Value) { 6933 1.1.1.2 joerg for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) { 6934 1.1.1.2 joerg if (It->Kind == IndirectLocalPathEntry::GslReferenceInit) 6935 1.1.1.2 joerg continue; 6936 1.1.1.2 joerg if (It->Kind == IndirectLocalPathEntry::GslPointerInit) 6937 1.1.1.2 joerg return; 6938 1.1.1.2 joerg break; 6939 1.1.1.2 joerg } 6940 1.1.1.2 joerg } 6941 1.1.1.2 joerg Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit 6942 1.1.1.2 joerg : IndirectLocalPathEntry::GslReferenceInit, 6943 1.1.1.2 joerg Arg, D}); 6944 1.1 joerg if (Arg->isGLValue()) 6945 1.1 joerg visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, 6946 1.1 joerg Visit, 6947 1.1 joerg /*EnableLifetimeWarnings=*/true); 6948 1.1 joerg else 6949 1.1 joerg visitLocalsRetainedByInitializer(Path, Arg, Visit, true, 6950 1.1 joerg /*EnableLifetimeWarnings=*/true); 6951 1.1 joerg Path.pop_back(); 6952 1.1 joerg }; 6953 1.1 joerg 6954 1.1 joerg if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { 6955 1.1 joerg const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee()); 6956 1.1 joerg if (MD && shouldTrackImplicitObjectArg(MD)) 6957 1.1.1.2 joerg VisitPointerArg(MD, MCE->getImplicitObjectArgument(), 6958 1.1.1.2 joerg !MD->getReturnType()->isReferenceType()); 6959 1.1 joerg return; 6960 1.1 joerg } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) { 6961 1.1 joerg FunctionDecl *Callee = OCE->getDirectCallee(); 6962 1.1 joerg if (Callee && Callee->isCXXInstanceMember() && 6963 1.1 joerg shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee))) 6964 1.1.1.2 joerg VisitPointerArg(Callee, OCE->getArg(0), 6965 1.1.1.2 joerg !Callee->getReturnType()->isReferenceType()); 6966 1.1 joerg return; 6967 1.1 joerg } else if (auto *CE = dyn_cast<CallExpr>(Call)) { 6968 1.1 joerg FunctionDecl *Callee = CE->getDirectCallee(); 6969 1.1 joerg if (Callee && shouldTrackFirstArgument(Callee)) 6970 1.1.1.2 joerg VisitPointerArg(Callee, CE->getArg(0), 6971 1.1.1.2 joerg !Callee->getReturnType()->isReferenceType()); 6972 1.1 joerg return; 6973 1.1 joerg } 6974 1.1 joerg 6975 1.1 joerg if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) { 6976 1.1 joerg const auto *Ctor = CCE->getConstructor(); 6977 1.1 joerg const CXXRecordDecl *RD = Ctor->getParent(); 6978 1.1 joerg if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>()) 6979 1.1.1.2 joerg VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true); 6980 1.1 joerg } 6981 1.1 joerg } 6982 1.1 joerg 6983 1.1 joerg static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) { 6984 1.1 joerg const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 6985 1.1 joerg if (!TSI) 6986 1.1 joerg return false; 6987 1.1 joerg // Don't declare this variable in the second operand of the for-statement; 6988 1.1 joerg // GCC miscompiles that by ending its lifetime before evaluating the 6989 1.1 joerg // third operand. See gcc.gnu.org/PR86769. 6990 1.1 joerg AttributedTypeLoc ATL; 6991 1.1 joerg for (TypeLoc TL = TSI->getTypeLoc(); 6992 1.1 joerg (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6993 1.1 joerg TL = ATL.getModifiedLoc()) { 6994 1.1 joerg if (ATL.getAttrAs<LifetimeBoundAttr>()) 6995 1.1 joerg return true; 6996 1.1 joerg } 6997 1.1.1.2 joerg 6998 1.1.1.2 joerg // Assume that all assignment operators with a "normal" return type return 6999 1.1.1.2 joerg // *this, that is, an lvalue reference that is the same type as the implicit 7000 1.1.1.2 joerg // object parameter (or the LHS for a non-member operator$=). 7001 1.1.1.2 joerg OverloadedOperatorKind OO = FD->getDeclName().getCXXOverloadedOperator(); 7002 1.1.1.2 joerg if (OO == OO_Equal || isCompoundAssignmentOperator(OO)) { 7003 1.1.1.2 joerg QualType RetT = FD->getReturnType(); 7004 1.1.1.2 joerg if (RetT->isLValueReferenceType()) { 7005 1.1.1.2 joerg ASTContext &Ctx = FD->getASTContext(); 7006 1.1.1.2 joerg QualType LHST; 7007 1.1.1.2 joerg auto *MD = dyn_cast<CXXMethodDecl>(FD); 7008 1.1.1.2 joerg if (MD && MD->isCXXInstanceMember()) 7009 1.1.1.2 joerg LHST = Ctx.getLValueReferenceType(MD->getThisObjectType()); 7010 1.1.1.2 joerg else 7011 1.1.1.2 joerg LHST = MD->getParamDecl(0)->getType(); 7012 1.1.1.2 joerg if (Ctx.hasSameType(RetT, LHST)) 7013 1.1.1.2 joerg return true; 7014 1.1.1.2 joerg } 7015 1.1.1.2 joerg } 7016 1.1.1.2 joerg 7017 1.1 joerg return false; 7018 1.1 joerg } 7019 1.1 joerg 7020 1.1 joerg static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call, 7021 1.1 joerg LocalVisitor Visit) { 7022 1.1 joerg const FunctionDecl *Callee; 7023 1.1 joerg ArrayRef<Expr*> Args; 7024 1.1 joerg 7025 1.1 joerg if (auto *CE = dyn_cast<CallExpr>(Call)) { 7026 1.1 joerg Callee = CE->getDirectCallee(); 7027 1.1 joerg Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs()); 7028 1.1 joerg } else { 7029 1.1 joerg auto *CCE = cast<CXXConstructExpr>(Call); 7030 1.1 joerg Callee = CCE->getConstructor(); 7031 1.1 joerg Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs()); 7032 1.1 joerg } 7033 1.1 joerg if (!Callee) 7034 1.1 joerg return; 7035 1.1 joerg 7036 1.1 joerg Expr *ObjectArg = nullptr; 7037 1.1 joerg if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) { 7038 1.1 joerg ObjectArg = Args[0]; 7039 1.1 joerg Args = Args.slice(1); 7040 1.1 joerg } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { 7041 1.1 joerg ObjectArg = MCE->getImplicitObjectArgument(); 7042 1.1 joerg } 7043 1.1 joerg 7044 1.1 joerg auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) { 7045 1.1 joerg Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D}); 7046 1.1 joerg if (Arg->isGLValue()) 7047 1.1 joerg visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, 7048 1.1 joerg Visit, 7049 1.1 joerg /*EnableLifetimeWarnings=*/false); 7050 1.1 joerg else 7051 1.1 joerg visitLocalsRetainedByInitializer(Path, Arg, Visit, true, 7052 1.1 joerg /*EnableLifetimeWarnings=*/false); 7053 1.1 joerg Path.pop_back(); 7054 1.1 joerg }; 7055 1.1 joerg 7056 1.1 joerg if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee)) 7057 1.1 joerg VisitLifetimeBoundArg(Callee, ObjectArg); 7058 1.1 joerg 7059 1.1 joerg for (unsigned I = 0, 7060 1.1 joerg N = std::min<unsigned>(Callee->getNumParams(), Args.size()); 7061 1.1 joerg I != N; ++I) { 7062 1.1 joerg if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>()) 7063 1.1 joerg VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]); 7064 1.1 joerg } 7065 1.1 joerg } 7066 1.1 joerg 7067 1.1 joerg /// Visit the locals that would be reachable through a reference bound to the 7068 1.1 joerg /// glvalue expression \c Init. 7069 1.1 joerg static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, 7070 1.1 joerg Expr *Init, ReferenceKind RK, 7071 1.1 joerg LocalVisitor Visit, 7072 1.1 joerg bool EnableLifetimeWarnings) { 7073 1.1 joerg RevertToOldSizeRAII RAII(Path); 7074 1.1 joerg 7075 1.1 joerg // Walk past any constructs which we can lifetime-extend across. 7076 1.1 joerg Expr *Old; 7077 1.1 joerg do { 7078 1.1 joerg Old = Init; 7079 1.1 joerg 7080 1.1 joerg if (auto *FE = dyn_cast<FullExpr>(Init)) 7081 1.1 joerg Init = FE->getSubExpr(); 7082 1.1 joerg 7083 1.1 joerg if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 7084 1.1 joerg // If this is just redundant braces around an initializer, step over it. 7085 1.1 joerg if (ILE->isTransparent()) 7086 1.1 joerg Init = ILE->getInit(0); 7087 1.1 joerg } 7088 1.1 joerg 7089 1.1 joerg // Step over any subobject adjustments; we may have a materialized 7090 1.1 joerg // temporary inside them. 7091 1.1 joerg Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); 7092 1.1 joerg 7093 1.1 joerg // Per current approach for DR1376, look through casts to reference type 7094 1.1 joerg // when performing lifetime extension. 7095 1.1 joerg if (CastExpr *CE = dyn_cast<CastExpr>(Init)) 7096 1.1 joerg if (CE->getSubExpr()->isGLValue()) 7097 1.1 joerg Init = CE->getSubExpr(); 7098 1.1 joerg 7099 1.1 joerg // Per the current approach for DR1299, look through array element access 7100 1.1 joerg // on array glvalues when performing lifetime extension. 7101 1.1 joerg if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) { 7102 1.1 joerg Init = ASE->getBase(); 7103 1.1 joerg auto *ICE = dyn_cast<ImplicitCastExpr>(Init); 7104 1.1 joerg if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay) 7105 1.1 joerg Init = ICE->getSubExpr(); 7106 1.1 joerg else 7107 1.1 joerg // We can't lifetime extend through this but we might still find some 7108 1.1 joerg // retained temporaries. 7109 1.1 joerg return visitLocalsRetainedByInitializer(Path, Init, Visit, true, 7110 1.1 joerg EnableLifetimeWarnings); 7111 1.1 joerg } 7112 1.1 joerg 7113 1.1 joerg // Step into CXXDefaultInitExprs so we can diagnose cases where a 7114 1.1 joerg // constructor inherits one as an implicit mem-initializer. 7115 1.1 joerg if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { 7116 1.1 joerg Path.push_back( 7117 1.1 joerg {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); 7118 1.1 joerg Init = DIE->getExpr(); 7119 1.1 joerg } 7120 1.1 joerg } while (Init != Old); 7121 1.1 joerg 7122 1.1 joerg if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) { 7123 1.1 joerg if (Visit(Path, Local(MTE), RK)) 7124 1.1.1.2 joerg visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true, 7125 1.1.1.2 joerg EnableLifetimeWarnings); 7126 1.1 joerg } 7127 1.1 joerg 7128 1.1 joerg if (isa<CallExpr>(Init)) { 7129 1.1 joerg if (EnableLifetimeWarnings) 7130 1.1 joerg handleGslAnnotatedTypes(Path, Init, Visit); 7131 1.1 joerg return visitLifetimeBoundArguments(Path, Init, Visit); 7132 1.1 joerg } 7133 1.1 joerg 7134 1.1 joerg switch (Init->getStmtClass()) { 7135 1.1 joerg case Stmt::DeclRefExprClass: { 7136 1.1 joerg // If we find the name of a local non-reference parameter, we could have a 7137 1.1 joerg // lifetime problem. 7138 1.1 joerg auto *DRE = cast<DeclRefExpr>(Init); 7139 1.1 joerg auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); 7140 1.1 joerg if (VD && VD->hasLocalStorage() && 7141 1.1 joerg !DRE->refersToEnclosingVariableOrCapture()) { 7142 1.1 joerg if (!VD->getType()->isReferenceType()) { 7143 1.1 joerg Visit(Path, Local(DRE), RK); 7144 1.1 joerg } else if (isa<ParmVarDecl>(DRE->getDecl())) { 7145 1.1 joerg // The lifetime of a reference parameter is unknown; assume it's OK 7146 1.1 joerg // for now. 7147 1.1 joerg break; 7148 1.1 joerg } else if (VD->getInit() && !isVarOnPath(Path, VD)) { 7149 1.1 joerg Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); 7150 1.1 joerg visitLocalsRetainedByReferenceBinding(Path, VD->getInit(), 7151 1.1 joerg RK_ReferenceBinding, Visit, 7152 1.1 joerg EnableLifetimeWarnings); 7153 1.1 joerg } 7154 1.1 joerg } 7155 1.1 joerg break; 7156 1.1 joerg } 7157 1.1 joerg 7158 1.1 joerg case Stmt::UnaryOperatorClass: { 7159 1.1 joerg // The only unary operator that make sense to handle here 7160 1.1 joerg // is Deref. All others don't resolve to a "name." This includes 7161 1.1 joerg // handling all sorts of rvalues passed to a unary operator. 7162 1.1 joerg const UnaryOperator *U = cast<UnaryOperator>(Init); 7163 1.1 joerg if (U->getOpcode() == UO_Deref) 7164 1.1 joerg visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true, 7165 1.1 joerg EnableLifetimeWarnings); 7166 1.1 joerg break; 7167 1.1 joerg } 7168 1.1 joerg 7169 1.1 joerg case Stmt::OMPArraySectionExprClass: { 7170 1.1 joerg visitLocalsRetainedByInitializer(Path, 7171 1.1 joerg cast<OMPArraySectionExpr>(Init)->getBase(), 7172 1.1 joerg Visit, true, EnableLifetimeWarnings); 7173 1.1 joerg break; 7174 1.1 joerg } 7175 1.1 joerg 7176 1.1 joerg case Stmt::ConditionalOperatorClass: 7177 1.1 joerg case Stmt::BinaryConditionalOperatorClass: { 7178 1.1 joerg auto *C = cast<AbstractConditionalOperator>(Init); 7179 1.1 joerg if (!C->getTrueExpr()->getType()->isVoidType()) 7180 1.1 joerg visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit, 7181 1.1 joerg EnableLifetimeWarnings); 7182 1.1 joerg if (!C->getFalseExpr()->getType()->isVoidType()) 7183 1.1 joerg visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit, 7184 1.1 joerg EnableLifetimeWarnings); 7185 1.1 joerg break; 7186 1.1 joerg } 7187 1.1 joerg 7188 1.1 joerg // FIXME: Visit the left-hand side of an -> or ->*. 7189 1.1 joerg 7190 1.1 joerg default: 7191 1.1 joerg break; 7192 1.1 joerg } 7193 1.1 joerg } 7194 1.1 joerg 7195 1.1 joerg /// Visit the locals that would be reachable through an object initialized by 7196 1.1 joerg /// the prvalue expression \c Init. 7197 1.1 joerg static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, 7198 1.1 joerg Expr *Init, LocalVisitor Visit, 7199 1.1 joerg bool RevisitSubinits, 7200 1.1 joerg bool EnableLifetimeWarnings) { 7201 1.1 joerg RevertToOldSizeRAII RAII(Path); 7202 1.1 joerg 7203 1.1 joerg Expr *Old; 7204 1.1 joerg do { 7205 1.1 joerg Old = Init; 7206 1.1 joerg 7207 1.1 joerg // Step into CXXDefaultInitExprs so we can diagnose cases where a 7208 1.1 joerg // constructor inherits one as an implicit mem-initializer. 7209 1.1 joerg if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { 7210 1.1 joerg Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); 7211 1.1 joerg Init = DIE->getExpr(); 7212 1.1 joerg } 7213 1.1 joerg 7214 1.1 joerg if (auto *FE = dyn_cast<FullExpr>(Init)) 7215 1.1 joerg Init = FE->getSubExpr(); 7216 1.1 joerg 7217 1.1 joerg // Dig out the expression which constructs the extended temporary. 7218 1.1 joerg Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); 7219 1.1 joerg 7220 1.1 joerg if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init)) 7221 1.1 joerg Init = BTE->getSubExpr(); 7222 1.1 joerg 7223 1.1 joerg Init = Init->IgnoreParens(); 7224 1.1 joerg 7225 1.1 joerg // Step over value-preserving rvalue casts. 7226 1.1 joerg if (auto *CE = dyn_cast<CastExpr>(Init)) { 7227 1.1 joerg switch (CE->getCastKind()) { 7228 1.1 joerg case CK_LValueToRValue: 7229 1.1 joerg // If we can match the lvalue to a const object, we can look at its 7230 1.1 joerg // initializer. 7231 1.1 joerg Path.push_back({IndirectLocalPathEntry::LValToRVal, CE}); 7232 1.1 joerg return visitLocalsRetainedByReferenceBinding( 7233 1.1 joerg Path, Init, RK_ReferenceBinding, 7234 1.1 joerg [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool { 7235 1.1 joerg if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { 7236 1.1 joerg auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); 7237 1.1 joerg if (VD && VD->getType().isConstQualified() && VD->getInit() && 7238 1.1 joerg !isVarOnPath(Path, VD)) { 7239 1.1 joerg Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); 7240 1.1 joerg visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true, 7241 1.1 joerg EnableLifetimeWarnings); 7242 1.1 joerg } 7243 1.1 joerg } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) { 7244 1.1 joerg if (MTE->getType().isConstQualified()) 7245 1.1.1.2 joerg visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, 7246 1.1.1.2 joerg true, EnableLifetimeWarnings); 7247 1.1 joerg } 7248 1.1 joerg return false; 7249 1.1 joerg }, EnableLifetimeWarnings); 7250 1.1 joerg 7251 1.1 joerg // We assume that objects can be retained by pointers cast to integers, 7252 1.1 joerg // but not if the integer is cast to floating-point type or to _Complex. 7253 1.1 joerg // We assume that casts to 'bool' do not preserve enough information to 7254 1.1 joerg // retain a local object. 7255 1.1 joerg case CK_NoOp: 7256 1.1 joerg case CK_BitCast: 7257 1.1 joerg case CK_BaseToDerived: 7258 1.1 joerg case CK_DerivedToBase: 7259 1.1 joerg case CK_UncheckedDerivedToBase: 7260 1.1 joerg case CK_Dynamic: 7261 1.1 joerg case CK_ToUnion: 7262 1.1 joerg case CK_UserDefinedConversion: 7263 1.1 joerg case CK_ConstructorConversion: 7264 1.1 joerg case CK_IntegralToPointer: 7265 1.1 joerg case CK_PointerToIntegral: 7266 1.1 joerg case CK_VectorSplat: 7267 1.1 joerg case CK_IntegralCast: 7268 1.1 joerg case CK_CPointerToObjCPointerCast: 7269 1.1 joerg case CK_BlockPointerToObjCPointerCast: 7270 1.1 joerg case CK_AnyPointerToBlockPointerCast: 7271 1.1 joerg case CK_AddressSpaceConversion: 7272 1.1 joerg break; 7273 1.1 joerg 7274 1.1 joerg case CK_ArrayToPointerDecay: 7275 1.1 joerg // Model array-to-pointer decay as taking the address of the array 7276 1.1 joerg // lvalue. 7277 1.1 joerg Path.push_back({IndirectLocalPathEntry::AddressOf, CE}); 7278 1.1 joerg return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(), 7279 1.1 joerg RK_ReferenceBinding, Visit, 7280 1.1 joerg EnableLifetimeWarnings); 7281 1.1 joerg 7282 1.1 joerg default: 7283 1.1 joerg return; 7284 1.1 joerg } 7285 1.1 joerg 7286 1.1 joerg Init = CE->getSubExpr(); 7287 1.1 joerg } 7288 1.1 joerg } while (Old != Init); 7289 1.1 joerg 7290 1.1 joerg // C++17 [dcl.init.list]p6: 7291 1.1 joerg // initializing an initializer_list object from the array extends the 7292 1.1 joerg // lifetime of the array exactly like binding a reference to a temporary. 7293 1.1 joerg if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init)) 7294 1.1 joerg return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(), 7295 1.1 joerg RK_StdInitializerList, Visit, 7296 1.1 joerg EnableLifetimeWarnings); 7297 1.1 joerg 7298 1.1 joerg if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 7299 1.1 joerg // We already visited the elements of this initializer list while 7300 1.1 joerg // performing the initialization. Don't visit them again unless we've 7301 1.1 joerg // changed the lifetime of the initialized entity. 7302 1.1 joerg if (!RevisitSubinits) 7303 1.1 joerg return; 7304 1.1 joerg 7305 1.1 joerg if (ILE->isTransparent()) 7306 1.1 joerg return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit, 7307 1.1 joerg RevisitSubinits, 7308 1.1 joerg EnableLifetimeWarnings); 7309 1.1 joerg 7310 1.1 joerg if (ILE->getType()->isArrayType()) { 7311 1.1 joerg for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I) 7312 1.1 joerg visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit, 7313 1.1 joerg RevisitSubinits, 7314 1.1 joerg EnableLifetimeWarnings); 7315 1.1 joerg return; 7316 1.1 joerg } 7317 1.1 joerg 7318 1.1 joerg if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) { 7319 1.1 joerg assert(RD->isAggregate() && "aggregate init on non-aggregate"); 7320 1.1 joerg 7321 1.1 joerg // If we lifetime-extend a braced initializer which is initializing an 7322 1.1 joerg // aggregate, and that aggregate contains reference members which are 7323 1.1 joerg // bound to temporaries, those temporaries are also lifetime-extended. 7324 1.1 joerg if (RD->isUnion() && ILE->getInitializedFieldInUnion() && 7325 1.1 joerg ILE->getInitializedFieldInUnion()->getType()->isReferenceType()) 7326 1.1 joerg visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0), 7327 1.1 joerg RK_ReferenceBinding, Visit, 7328 1.1 joerg EnableLifetimeWarnings); 7329 1.1 joerg else { 7330 1.1 joerg unsigned Index = 0; 7331 1.1 joerg for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index) 7332 1.1 joerg visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit, 7333 1.1 joerg RevisitSubinits, 7334 1.1 joerg EnableLifetimeWarnings); 7335 1.1 joerg for (const auto *I : RD->fields()) { 7336 1.1 joerg if (Index >= ILE->getNumInits()) 7337 1.1 joerg break; 7338 1.1 joerg if (I->isUnnamedBitfield()) 7339 1.1 joerg continue; 7340 1.1 joerg Expr *SubInit = ILE->getInit(Index); 7341 1.1 joerg if (I->getType()->isReferenceType()) 7342 1.1 joerg visitLocalsRetainedByReferenceBinding(Path, SubInit, 7343 1.1 joerg RK_ReferenceBinding, Visit, 7344 1.1 joerg EnableLifetimeWarnings); 7345 1.1 joerg else 7346 1.1 joerg // This might be either aggregate-initialization of a member or 7347 1.1 joerg // initialization of a std::initializer_list object. Regardless, 7348 1.1 joerg // we should recursively lifetime-extend that initializer. 7349 1.1 joerg visitLocalsRetainedByInitializer(Path, SubInit, Visit, 7350 1.1 joerg RevisitSubinits, 7351 1.1 joerg EnableLifetimeWarnings); 7352 1.1 joerg ++Index; 7353 1.1 joerg } 7354 1.1 joerg } 7355 1.1 joerg } 7356 1.1 joerg return; 7357 1.1 joerg } 7358 1.1 joerg 7359 1.1 joerg // The lifetime of an init-capture is that of the closure object constructed 7360 1.1 joerg // by a lambda-expression. 7361 1.1 joerg if (auto *LE = dyn_cast<LambdaExpr>(Init)) { 7362 1.1.1.2 joerg LambdaExpr::capture_iterator CapI = LE->capture_begin(); 7363 1.1 joerg for (Expr *E : LE->capture_inits()) { 7364 1.1.1.2 joerg assert(CapI != LE->capture_end()); 7365 1.1.1.2 joerg const LambdaCapture &Cap = *CapI++; 7366 1.1 joerg if (!E) 7367 1.1 joerg continue; 7368 1.1.1.2 joerg if (Cap.capturesVariable()) 7369 1.1.1.2 joerg Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap}); 7370 1.1 joerg if (E->isGLValue()) 7371 1.1 joerg visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding, 7372 1.1 joerg Visit, EnableLifetimeWarnings); 7373 1.1 joerg else 7374 1.1 joerg visitLocalsRetainedByInitializer(Path, E, Visit, true, 7375 1.1 joerg EnableLifetimeWarnings); 7376 1.1.1.2 joerg if (Cap.capturesVariable()) 7377 1.1.1.2 joerg Path.pop_back(); 7378 1.1.1.2 joerg } 7379 1.1.1.2 joerg } 7380 1.1.1.2 joerg 7381 1.1.1.2 joerg // Assume that a copy or move from a temporary references the same objects 7382 1.1.1.2 joerg // that the temporary does. 7383 1.1.1.2 joerg if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 7384 1.1.1.2 joerg if (CCE->getConstructor()->isCopyOrMoveConstructor()) { 7385 1.1.1.2 joerg if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) { 7386 1.1.1.2 joerg Expr *Arg = MTE->getSubExpr(); 7387 1.1.1.2 joerg Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg, 7388 1.1.1.2 joerg CCE->getConstructor()}); 7389 1.1.1.2 joerg visitLocalsRetainedByInitializer(Path, Arg, Visit, true, 7390 1.1.1.2 joerg /*EnableLifetimeWarnings*/false); 7391 1.1.1.2 joerg Path.pop_back(); 7392 1.1.1.2 joerg } 7393 1.1 joerg } 7394 1.1 joerg } 7395 1.1 joerg 7396 1.1 joerg if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) { 7397 1.1 joerg if (EnableLifetimeWarnings) 7398 1.1 joerg handleGslAnnotatedTypes(Path, Init, Visit); 7399 1.1 joerg return visitLifetimeBoundArguments(Path, Init, Visit); 7400 1.1 joerg } 7401 1.1 joerg 7402 1.1 joerg switch (Init->getStmtClass()) { 7403 1.1 joerg case Stmt::UnaryOperatorClass: { 7404 1.1 joerg auto *UO = cast<UnaryOperator>(Init); 7405 1.1 joerg // If the initializer is the address of a local, we could have a lifetime 7406 1.1 joerg // problem. 7407 1.1 joerg if (UO->getOpcode() == UO_AddrOf) { 7408 1.1 joerg // If this is &rvalue, then it's ill-formed and we have already diagnosed 7409 1.1 joerg // it. Don't produce a redundant warning about the lifetime of the 7410 1.1 joerg // temporary. 7411 1.1 joerg if (isa<MaterializeTemporaryExpr>(UO->getSubExpr())) 7412 1.1 joerg return; 7413 1.1 joerg 7414 1.1 joerg Path.push_back({IndirectLocalPathEntry::AddressOf, UO}); 7415 1.1 joerg visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(), 7416 1.1 joerg RK_ReferenceBinding, Visit, 7417 1.1 joerg EnableLifetimeWarnings); 7418 1.1 joerg } 7419 1.1 joerg break; 7420 1.1 joerg } 7421 1.1 joerg 7422 1.1 joerg case Stmt::BinaryOperatorClass: { 7423 1.1 joerg // Handle pointer arithmetic. 7424 1.1 joerg auto *BO = cast<BinaryOperator>(Init); 7425 1.1 joerg BinaryOperatorKind BOK = BO->getOpcode(); 7426 1.1 joerg if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub)) 7427 1.1 joerg break; 7428 1.1 joerg 7429 1.1 joerg if (BO->getLHS()->getType()->isPointerType()) 7430 1.1 joerg visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true, 7431 1.1 joerg EnableLifetimeWarnings); 7432 1.1 joerg else if (BO->getRHS()->getType()->isPointerType()) 7433 1.1 joerg visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true, 7434 1.1 joerg EnableLifetimeWarnings); 7435 1.1 joerg break; 7436 1.1 joerg } 7437 1.1 joerg 7438 1.1 joerg case Stmt::ConditionalOperatorClass: 7439 1.1 joerg case Stmt::BinaryConditionalOperatorClass: { 7440 1.1 joerg auto *C = cast<AbstractConditionalOperator>(Init); 7441 1.1 joerg // In C++, we can have a throw-expression operand, which has 'void' type 7442 1.1 joerg // and isn't interesting from a lifetime perspective. 7443 1.1 joerg if (!C->getTrueExpr()->getType()->isVoidType()) 7444 1.1 joerg visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true, 7445 1.1 joerg EnableLifetimeWarnings); 7446 1.1 joerg if (!C->getFalseExpr()->getType()->isVoidType()) 7447 1.1 joerg visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true, 7448 1.1 joerg EnableLifetimeWarnings); 7449 1.1 joerg break; 7450 1.1 joerg } 7451 1.1 joerg 7452 1.1 joerg case Stmt::BlockExprClass: 7453 1.1 joerg if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) { 7454 1.1 joerg // This is a local block, whose lifetime is that of the function. 7455 1.1 joerg Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding); 7456 1.1 joerg } 7457 1.1 joerg break; 7458 1.1 joerg 7459 1.1 joerg case Stmt::AddrLabelExprClass: 7460 1.1 joerg // We want to warn if the address of a label would escape the function. 7461 1.1 joerg Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding); 7462 1.1 joerg break; 7463 1.1 joerg 7464 1.1 joerg default: 7465 1.1 joerg break; 7466 1.1 joerg } 7467 1.1 joerg } 7468 1.1 joerg 7469 1.1.1.2 joerg /// Whether a path to an object supports lifetime extension. 7470 1.1.1.2 joerg enum PathLifetimeKind { 7471 1.1.1.2 joerg /// Lifetime-extend along this path. 7472 1.1.1.2 joerg Extend, 7473 1.1.1.2 joerg /// We should lifetime-extend, but we don't because (due to technical 7474 1.1.1.2 joerg /// limitations) we can't. This happens for default member initializers, 7475 1.1.1.2 joerg /// which we don't clone for every use, so we don't have a unique 7476 1.1.1.2 joerg /// MaterializeTemporaryExpr to update. 7477 1.1.1.2 joerg ShouldExtend, 7478 1.1.1.2 joerg /// Do not lifetime extend along this path. 7479 1.1.1.2 joerg NoExtend 7480 1.1.1.2 joerg }; 7481 1.1.1.2 joerg 7482 1.1 joerg /// Determine whether this is an indirect path to a temporary that we are 7483 1.1.1.2 joerg /// supposed to lifetime-extend along. 7484 1.1.1.2 joerg static PathLifetimeKind 7485 1.1.1.2 joerg shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) { 7486 1.1.1.2 joerg PathLifetimeKind Kind = PathLifetimeKind::Extend; 7487 1.1 joerg for (auto Elem : Path) { 7488 1.1.1.2 joerg if (Elem.Kind == IndirectLocalPathEntry::DefaultInit) 7489 1.1.1.2 joerg Kind = PathLifetimeKind::ShouldExtend; 7490 1.1.1.2 joerg else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit) 7491 1.1.1.2 joerg return PathLifetimeKind::NoExtend; 7492 1.1 joerg } 7493 1.1.1.2 joerg return Kind; 7494 1.1 joerg } 7495 1.1 joerg 7496 1.1 joerg /// Find the range for the first interesting entry in the path at or after I. 7497 1.1 joerg static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I, 7498 1.1 joerg Expr *E) { 7499 1.1 joerg for (unsigned N = Path.size(); I != N; ++I) { 7500 1.1 joerg switch (Path[I].Kind) { 7501 1.1 joerg case IndirectLocalPathEntry::AddressOf: 7502 1.1 joerg case IndirectLocalPathEntry::LValToRVal: 7503 1.1 joerg case IndirectLocalPathEntry::LifetimeBoundCall: 7504 1.1.1.2 joerg case IndirectLocalPathEntry::TemporaryCopy: 7505 1.1.1.2 joerg case IndirectLocalPathEntry::GslReferenceInit: 7506 1.1 joerg case IndirectLocalPathEntry::GslPointerInit: 7507 1.1 joerg // These exist primarily to mark the path as not permitting or 7508 1.1 joerg // supporting lifetime extension. 7509 1.1 joerg break; 7510 1.1 joerg 7511 1.1 joerg case IndirectLocalPathEntry::VarInit: 7512 1.1 joerg if (cast<VarDecl>(Path[I].D)->isImplicit()) 7513 1.1 joerg return SourceRange(); 7514 1.1 joerg LLVM_FALLTHROUGH; 7515 1.1 joerg case IndirectLocalPathEntry::DefaultInit: 7516 1.1 joerg return Path[I].E->getSourceRange(); 7517 1.1.1.2 joerg 7518 1.1.1.2 joerg case IndirectLocalPathEntry::LambdaCaptureInit: 7519 1.1.1.2 joerg if (!Path[I].Capture->capturesVariable()) 7520 1.1.1.2 joerg continue; 7521 1.1.1.2 joerg return Path[I].E->getSourceRange(); 7522 1.1 joerg } 7523 1.1 joerg } 7524 1.1 joerg return E->getSourceRange(); 7525 1.1 joerg } 7526 1.1 joerg 7527 1.1 joerg static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) { 7528 1.1 joerg for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) { 7529 1.1 joerg if (It->Kind == IndirectLocalPathEntry::VarInit) 7530 1.1 joerg continue; 7531 1.1 joerg if (It->Kind == IndirectLocalPathEntry::AddressOf) 7532 1.1 joerg continue; 7533 1.1.1.2 joerg if (It->Kind == IndirectLocalPathEntry::LifetimeBoundCall) 7534 1.1.1.2 joerg continue; 7535 1.1.1.2 joerg return It->Kind == IndirectLocalPathEntry::GslPointerInit || 7536 1.1.1.2 joerg It->Kind == IndirectLocalPathEntry::GslReferenceInit; 7537 1.1 joerg } 7538 1.1 joerg return false; 7539 1.1 joerg } 7540 1.1 joerg 7541 1.1 joerg void Sema::checkInitializerLifetime(const InitializedEntity &Entity, 7542 1.1 joerg Expr *Init) { 7543 1.1 joerg LifetimeResult LR = getEntityLifetime(&Entity); 7544 1.1 joerg LifetimeKind LK = LR.getInt(); 7545 1.1 joerg const InitializedEntity *ExtendingEntity = LR.getPointer(); 7546 1.1 joerg 7547 1.1 joerg // If this entity doesn't have an interesting lifetime, don't bother looking 7548 1.1 joerg // for temporaries within its initializer. 7549 1.1 joerg if (LK == LK_FullExpression) 7550 1.1 joerg return; 7551 1.1 joerg 7552 1.1 joerg auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L, 7553 1.1 joerg ReferenceKind RK) -> bool { 7554 1.1 joerg SourceRange DiagRange = nextPathEntryRange(Path, 0, L); 7555 1.1 joerg SourceLocation DiagLoc = DiagRange.getBegin(); 7556 1.1 joerg 7557 1.1 joerg auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L); 7558 1.1 joerg 7559 1.1 joerg bool IsGslPtrInitWithGslTempOwner = false; 7560 1.1 joerg bool IsLocalGslOwner = false; 7561 1.1 joerg if (pathOnlyInitializesGslPointer(Path)) { 7562 1.1 joerg if (isa<DeclRefExpr>(L)) { 7563 1.1 joerg // We do not want to follow the references when returning a pointer originating 7564 1.1 joerg // from a local owner to avoid the following false positive: 7565 1.1 joerg // int &p = *localUniquePtr; 7566 1.1 joerg // someContainer.add(std::move(localUniquePtr)); 7567 1.1 joerg // return p; 7568 1.1 joerg IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType()); 7569 1.1 joerg if (pathContainsInit(Path) || !IsLocalGslOwner) 7570 1.1 joerg return false; 7571 1.1 joerg } else { 7572 1.1 joerg IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() && 7573 1.1 joerg isRecordWithAttr<OwnerAttr>(MTE->getType()); 7574 1.1 joerg // Skipping a chain of initializing gsl::Pointer annotated objects. 7575 1.1 joerg // We are looking only for the final source to find out if it was 7576 1.1 joerg // a local or temporary owner or the address of a local variable/param. 7577 1.1 joerg if (!IsGslPtrInitWithGslTempOwner) 7578 1.1 joerg return true; 7579 1.1 joerg } 7580 1.1 joerg } 7581 1.1 joerg 7582 1.1 joerg switch (LK) { 7583 1.1 joerg case LK_FullExpression: 7584 1.1 joerg llvm_unreachable("already handled this"); 7585 1.1 joerg 7586 1.1 joerg case LK_Extended: { 7587 1.1 joerg if (!MTE) { 7588 1.1 joerg // The initialized entity has lifetime beyond the full-expression, 7589 1.1 joerg // and the local entity does too, so don't warn. 7590 1.1 joerg // 7591 1.1 joerg // FIXME: We should consider warning if a static / thread storage 7592 1.1 joerg // duration variable retains an automatic storage duration local. 7593 1.1 joerg return false; 7594 1.1 joerg } 7595 1.1 joerg 7596 1.1 joerg if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) { 7597 1.1 joerg Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange; 7598 1.1 joerg return false; 7599 1.1 joerg } 7600 1.1 joerg 7601 1.1.1.2 joerg switch (shouldLifetimeExtendThroughPath(Path)) { 7602 1.1.1.2 joerg case PathLifetimeKind::Extend: 7603 1.1 joerg // Update the storage duration of the materialized temporary. 7604 1.1 joerg // FIXME: Rebuild the expression instead of mutating it. 7605 1.1 joerg MTE->setExtendingDecl(ExtendingEntity->getDecl(), 7606 1.1 joerg ExtendingEntity->allocateManglingNumber()); 7607 1.1 joerg // Also visit the temporaries lifetime-extended by this initializer. 7608 1.1 joerg return true; 7609 1.1 joerg 7610 1.1.1.2 joerg case PathLifetimeKind::ShouldExtend: 7611 1.1 joerg // We're supposed to lifetime-extend the temporary along this path (per 7612 1.1 joerg // the resolution of DR1815), but we don't support that yet. 7613 1.1 joerg // 7614 1.1 joerg // FIXME: Properly handle this situation. Perhaps the easiest approach 7615 1.1 joerg // would be to clone the initializer expression on each use that would 7616 1.1 joerg // lifetime extend its temporaries. 7617 1.1 joerg Diag(DiagLoc, diag::warn_unsupported_lifetime_extension) 7618 1.1 joerg << RK << DiagRange; 7619 1.1.1.2 joerg break; 7620 1.1.1.2 joerg 7621 1.1.1.2 joerg case PathLifetimeKind::NoExtend: 7622 1.1 joerg // If the path goes through the initialization of a variable or field, 7623 1.1 joerg // it can't possibly reach a temporary created in this full-expression. 7624 1.1 joerg // We will have already diagnosed any problems with the initializer. 7625 1.1 joerg if (pathContainsInit(Path)) 7626 1.1 joerg return false; 7627 1.1 joerg 7628 1.1 joerg Diag(DiagLoc, diag::warn_dangling_variable) 7629 1.1 joerg << RK << !Entity.getParent() 7630 1.1 joerg << ExtendingEntity->getDecl()->isImplicit() 7631 1.1 joerg << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange; 7632 1.1.1.2 joerg break; 7633 1.1 joerg } 7634 1.1 joerg break; 7635 1.1 joerg } 7636 1.1 joerg 7637 1.1 joerg case LK_MemInitializer: { 7638 1.1 joerg if (isa<MaterializeTemporaryExpr>(L)) { 7639 1.1 joerg // Under C++ DR1696, if a mem-initializer (or a default member 7640 1.1 joerg // initializer used by the absence of one) would lifetime-extend a 7641 1.1 joerg // temporary, the program is ill-formed. 7642 1.1 joerg if (auto *ExtendingDecl = 7643 1.1 joerg ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { 7644 1.1 joerg if (IsGslPtrInitWithGslTempOwner) { 7645 1.1 joerg Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member) 7646 1.1 joerg << ExtendingDecl << DiagRange; 7647 1.1 joerg Diag(ExtendingDecl->getLocation(), 7648 1.1 joerg diag::note_ref_or_ptr_member_declared_here) 7649 1.1 joerg << true; 7650 1.1 joerg return false; 7651 1.1 joerg } 7652 1.1 joerg bool IsSubobjectMember = ExtendingEntity != &Entity; 7653 1.1.1.2 joerg Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) != 7654 1.1.1.2 joerg PathLifetimeKind::NoExtend 7655 1.1 joerg ? diag::err_dangling_member 7656 1.1 joerg : diag::warn_dangling_member) 7657 1.1 joerg << ExtendingDecl << IsSubobjectMember << RK << DiagRange; 7658 1.1 joerg // Don't bother adding a note pointing to the field if we're inside 7659 1.1 joerg // its default member initializer; our primary diagnostic points to 7660 1.1 joerg // the same place in that case. 7661 1.1 joerg if (Path.empty() || 7662 1.1 joerg Path.back().Kind != IndirectLocalPathEntry::DefaultInit) { 7663 1.1 joerg Diag(ExtendingDecl->getLocation(), 7664 1.1 joerg diag::note_lifetime_extending_member_declared_here) 7665 1.1 joerg << RK << IsSubobjectMember; 7666 1.1 joerg } 7667 1.1 joerg } else { 7668 1.1 joerg // We have a mem-initializer but no particular field within it; this 7669 1.1 joerg // is either a base class or a delegating initializer directly 7670 1.1 joerg // initializing the base-class from something that doesn't live long 7671 1.1 joerg // enough. 7672 1.1 joerg // 7673 1.1 joerg // FIXME: Warn on this. 7674 1.1 joerg return false; 7675 1.1 joerg } 7676 1.1 joerg } else { 7677 1.1 joerg // Paths via a default initializer can only occur during error recovery 7678 1.1 joerg // (there's no other way that a default initializer can refer to a 7679 1.1 joerg // local). Don't produce a bogus warning on those cases. 7680 1.1 joerg if (pathContainsInit(Path)) 7681 1.1 joerg return false; 7682 1.1 joerg 7683 1.1 joerg // Suppress false positives for code like the one below: 7684 1.1 joerg // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {} 7685 1.1 joerg if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path)) 7686 1.1 joerg return false; 7687 1.1 joerg 7688 1.1 joerg auto *DRE = dyn_cast<DeclRefExpr>(L); 7689 1.1 joerg auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr; 7690 1.1 joerg if (!VD) { 7691 1.1 joerg // A member was initialized to a local block. 7692 1.1 joerg // FIXME: Warn on this. 7693 1.1 joerg return false; 7694 1.1 joerg } 7695 1.1 joerg 7696 1.1 joerg if (auto *Member = 7697 1.1 joerg ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { 7698 1.1 joerg bool IsPointer = !Member->getType()->isReferenceType(); 7699 1.1 joerg Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 7700 1.1 joerg : diag::warn_bind_ref_member_to_parameter) 7701 1.1 joerg << Member << VD << isa<ParmVarDecl>(VD) << DiagRange; 7702 1.1 joerg Diag(Member->getLocation(), 7703 1.1 joerg diag::note_ref_or_ptr_member_declared_here) 7704 1.1 joerg << (unsigned)IsPointer; 7705 1.1 joerg } 7706 1.1 joerg } 7707 1.1 joerg break; 7708 1.1 joerg } 7709 1.1 joerg 7710 1.1 joerg case LK_New: 7711 1.1 joerg if (isa<MaterializeTemporaryExpr>(L)) { 7712 1.1 joerg if (IsGslPtrInitWithGslTempOwner) 7713 1.1 joerg Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange; 7714 1.1 joerg else 7715 1.1 joerg Diag(DiagLoc, RK == RK_ReferenceBinding 7716 1.1 joerg ? diag::warn_new_dangling_reference 7717 1.1 joerg : diag::warn_new_dangling_initializer_list) 7718 1.1 joerg << !Entity.getParent() << DiagRange; 7719 1.1 joerg } else { 7720 1.1 joerg // We can't determine if the allocation outlives the local declaration. 7721 1.1 joerg return false; 7722 1.1 joerg } 7723 1.1 joerg break; 7724 1.1 joerg 7725 1.1 joerg case LK_Return: 7726 1.1 joerg case LK_StmtExprResult: 7727 1.1 joerg if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { 7728 1.1 joerg // We can't determine if the local variable outlives the statement 7729 1.1 joerg // expression. 7730 1.1 joerg if (LK == LK_StmtExprResult) 7731 1.1 joerg return false; 7732 1.1 joerg Diag(DiagLoc, diag::warn_ret_stack_addr_ref) 7733 1.1 joerg << Entity.getType()->isReferenceType() << DRE->getDecl() 7734 1.1 joerg << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange; 7735 1.1 joerg } else if (isa<BlockExpr>(L)) { 7736 1.1 joerg Diag(DiagLoc, diag::err_ret_local_block) << DiagRange; 7737 1.1 joerg } else if (isa<AddrLabelExpr>(L)) { 7738 1.1 joerg // Don't warn when returning a label from a statement expression. 7739 1.1 joerg // Leaving the scope doesn't end its lifetime. 7740 1.1 joerg if (LK == LK_StmtExprResult) 7741 1.1 joerg return false; 7742 1.1 joerg Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange; 7743 1.1 joerg } else { 7744 1.1 joerg Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref) 7745 1.1 joerg << Entity.getType()->isReferenceType() << DiagRange; 7746 1.1 joerg } 7747 1.1 joerg break; 7748 1.1 joerg } 7749 1.1 joerg 7750 1.1 joerg for (unsigned I = 0; I != Path.size(); ++I) { 7751 1.1 joerg auto Elem = Path[I]; 7752 1.1 joerg 7753 1.1 joerg switch (Elem.Kind) { 7754 1.1 joerg case IndirectLocalPathEntry::AddressOf: 7755 1.1 joerg case IndirectLocalPathEntry::LValToRVal: 7756 1.1 joerg // These exist primarily to mark the path as not permitting or 7757 1.1 joerg // supporting lifetime extension. 7758 1.1 joerg break; 7759 1.1 joerg 7760 1.1 joerg case IndirectLocalPathEntry::LifetimeBoundCall: 7761 1.1.1.2 joerg case IndirectLocalPathEntry::TemporaryCopy: 7762 1.1 joerg case IndirectLocalPathEntry::GslPointerInit: 7763 1.1.1.2 joerg case IndirectLocalPathEntry::GslReferenceInit: 7764 1.1 joerg // FIXME: Consider adding a note for these. 7765 1.1 joerg break; 7766 1.1 joerg 7767 1.1 joerg case IndirectLocalPathEntry::DefaultInit: { 7768 1.1 joerg auto *FD = cast<FieldDecl>(Elem.D); 7769 1.1 joerg Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer) 7770 1.1 joerg << FD << nextPathEntryRange(Path, I + 1, L); 7771 1.1 joerg break; 7772 1.1 joerg } 7773 1.1 joerg 7774 1.1.1.2 joerg case IndirectLocalPathEntry::VarInit: { 7775 1.1 joerg const VarDecl *VD = cast<VarDecl>(Elem.D); 7776 1.1 joerg Diag(VD->getLocation(), diag::note_local_var_initializer) 7777 1.1 joerg << VD->getType()->isReferenceType() 7778 1.1 joerg << VD->isImplicit() << VD->getDeclName() 7779 1.1 joerg << nextPathEntryRange(Path, I + 1, L); 7780 1.1 joerg break; 7781 1.1 joerg } 7782 1.1.1.2 joerg 7783 1.1.1.2 joerg case IndirectLocalPathEntry::LambdaCaptureInit: 7784 1.1.1.2 joerg if (!Elem.Capture->capturesVariable()) 7785 1.1.1.2 joerg break; 7786 1.1.1.2 joerg // FIXME: We can't easily tell apart an init-capture from a nested 7787 1.1.1.2 joerg // capture of an init-capture. 7788 1.1.1.2 joerg const VarDecl *VD = Elem.Capture->getCapturedVar(); 7789 1.1.1.2 joerg Diag(Elem.Capture->getLocation(), diag::note_lambda_capture_initializer) 7790 1.1.1.2 joerg << VD << VD->isInitCapture() << Elem.Capture->isExplicit() 7791 1.1.1.2 joerg << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD 7792 1.1.1.2 joerg << nextPathEntryRange(Path, I + 1, L); 7793 1.1.1.2 joerg break; 7794 1.1.1.2 joerg } 7795 1.1 joerg } 7796 1.1 joerg 7797 1.1 joerg // We didn't lifetime-extend, so don't go any further; we don't need more 7798 1.1 joerg // warnings or errors on inner temporaries within this one's initializer. 7799 1.1 joerg return false; 7800 1.1 joerg }; 7801 1.1 joerg 7802 1.1 joerg bool EnableLifetimeWarnings = !getDiagnostics().isIgnored( 7803 1.1 joerg diag::warn_dangling_lifetime_pointer, SourceLocation()); 7804 1.1 joerg llvm::SmallVector<IndirectLocalPathEntry, 8> Path; 7805 1.1 joerg if (Init->isGLValue()) 7806 1.1 joerg visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding, 7807 1.1 joerg TemporaryVisitor, 7808 1.1 joerg EnableLifetimeWarnings); 7809 1.1 joerg else 7810 1.1 joerg visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false, 7811 1.1 joerg EnableLifetimeWarnings); 7812 1.1 joerg } 7813 1.1 joerg 7814 1.1 joerg static void DiagnoseNarrowingInInitList(Sema &S, 7815 1.1 joerg const ImplicitConversionSequence &ICS, 7816 1.1 joerg QualType PreNarrowingType, 7817 1.1 joerg QualType EntityType, 7818 1.1 joerg const Expr *PostInit); 7819 1.1 joerg 7820 1.1 joerg /// Provide warnings when std::move is used on construction. 7821 1.1 joerg static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, 7822 1.1 joerg bool IsReturnStmt) { 7823 1.1 joerg if (!InitExpr) 7824 1.1 joerg return; 7825 1.1 joerg 7826 1.1 joerg if (S.inTemplateInstantiation()) 7827 1.1 joerg return; 7828 1.1 joerg 7829 1.1 joerg QualType DestType = InitExpr->getType(); 7830 1.1 joerg if (!DestType->isRecordType()) 7831 1.1 joerg return; 7832 1.1 joerg 7833 1.1 joerg unsigned DiagID = 0; 7834 1.1 joerg if (IsReturnStmt) { 7835 1.1 joerg const CXXConstructExpr *CCE = 7836 1.1 joerg dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens()); 7837 1.1 joerg if (!CCE || CCE->getNumArgs() != 1) 7838 1.1 joerg return; 7839 1.1 joerg 7840 1.1 joerg if (!CCE->getConstructor()->isCopyOrMoveConstructor()) 7841 1.1 joerg return; 7842 1.1 joerg 7843 1.1 joerg InitExpr = CCE->getArg(0)->IgnoreImpCasts(); 7844 1.1 joerg } 7845 1.1 joerg 7846 1.1 joerg // Find the std::move call and get the argument. 7847 1.1 joerg const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens()); 7848 1.1 joerg if (!CE || !CE->isCallToStdMove()) 7849 1.1 joerg return; 7850 1.1 joerg 7851 1.1 joerg const Expr *Arg = CE->getArg(0)->IgnoreImplicit(); 7852 1.1 joerg 7853 1.1 joerg if (IsReturnStmt) { 7854 1.1 joerg const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts()); 7855 1.1 joerg if (!DRE || DRE->refersToEnclosingVariableOrCapture()) 7856 1.1 joerg return; 7857 1.1 joerg 7858 1.1 joerg const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()); 7859 1.1 joerg if (!VD || !VD->hasLocalStorage()) 7860 1.1 joerg return; 7861 1.1 joerg 7862 1.1 joerg // __block variables are not moved implicitly. 7863 1.1 joerg if (VD->hasAttr<BlocksAttr>()) 7864 1.1 joerg return; 7865 1.1 joerg 7866 1.1 joerg QualType SourceType = VD->getType(); 7867 1.1 joerg if (!SourceType->isRecordType()) 7868 1.1 joerg return; 7869 1.1 joerg 7870 1.1 joerg if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) { 7871 1.1 joerg return; 7872 1.1 joerg } 7873 1.1 joerg 7874 1.1 joerg // If we're returning a function parameter, copy elision 7875 1.1 joerg // is not possible. 7876 1.1 joerg if (isa<ParmVarDecl>(VD)) 7877 1.1 joerg DiagID = diag::warn_redundant_move_on_return; 7878 1.1 joerg else 7879 1.1 joerg DiagID = diag::warn_pessimizing_move_on_return; 7880 1.1 joerg } else { 7881 1.1 joerg DiagID = diag::warn_pessimizing_move_on_initialization; 7882 1.1 joerg const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens(); 7883 1.1 joerg if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType()) 7884 1.1 joerg return; 7885 1.1 joerg } 7886 1.1 joerg 7887 1.1 joerg S.Diag(CE->getBeginLoc(), DiagID); 7888 1.1 joerg 7889 1.1 joerg // Get all the locations for a fix-it. Don't emit the fix-it if any location 7890 1.1 joerg // is within a macro. 7891 1.1 joerg SourceLocation CallBegin = CE->getCallee()->getBeginLoc(); 7892 1.1 joerg if (CallBegin.isMacroID()) 7893 1.1 joerg return; 7894 1.1 joerg SourceLocation RParen = CE->getRParenLoc(); 7895 1.1 joerg if (RParen.isMacroID()) 7896 1.1 joerg return; 7897 1.1 joerg SourceLocation LParen; 7898 1.1 joerg SourceLocation ArgLoc = Arg->getBeginLoc(); 7899 1.1 joerg 7900 1.1 joerg // Special testing for the argument location. Since the fix-it needs the 7901 1.1 joerg // location right before the argument, the argument location can be in a 7902 1.1 joerg // macro only if it is at the beginning of the macro. 7903 1.1 joerg while (ArgLoc.isMacroID() && 7904 1.1 joerg S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) { 7905 1.1 joerg ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin(); 7906 1.1 joerg } 7907 1.1 joerg 7908 1.1 joerg if (LParen.isMacroID()) 7909 1.1 joerg return; 7910 1.1 joerg 7911 1.1 joerg LParen = ArgLoc.getLocWithOffset(-1); 7912 1.1 joerg 7913 1.1 joerg S.Diag(CE->getBeginLoc(), diag::note_remove_move) 7914 1.1 joerg << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen)) 7915 1.1 joerg << FixItHint::CreateRemoval(SourceRange(RParen, RParen)); 7916 1.1 joerg } 7917 1.1 joerg 7918 1.1 joerg static void CheckForNullPointerDereference(Sema &S, const Expr *E) { 7919 1.1 joerg // Check to see if we are dereferencing a null pointer. If so, this is 7920 1.1 joerg // undefined behavior, so warn about it. This only handles the pattern 7921 1.1 joerg // "*null", which is a very syntactic check. 7922 1.1 joerg if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 7923 1.1 joerg if (UO->getOpcode() == UO_Deref && 7924 1.1 joerg UO->getSubExpr()->IgnoreParenCasts()-> 7925 1.1 joerg isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) { 7926 1.1 joerg S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 7927 1.1 joerg S.PDiag(diag::warn_binding_null_to_reference) 7928 1.1 joerg << UO->getSubExpr()->getSourceRange()); 7929 1.1 joerg } 7930 1.1 joerg } 7931 1.1 joerg 7932 1.1 joerg MaterializeTemporaryExpr * 7933 1.1 joerg Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, 7934 1.1 joerg bool BoundToLvalueReference) { 7935 1.1 joerg auto MTE = new (Context) 7936 1.1 joerg MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference); 7937 1.1 joerg 7938 1.1 joerg // Order an ExprWithCleanups for lifetime marks. 7939 1.1 joerg // 7940 1.1 joerg // TODO: It'll be good to have a single place to check the access of the 7941 1.1 joerg // destructor and generate ExprWithCleanups for various uses. Currently these 7942 1.1 joerg // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary, 7943 1.1 joerg // but there may be a chance to merge them. 7944 1.1 joerg Cleanup.setExprNeedsCleanups(false); 7945 1.1 joerg return MTE; 7946 1.1 joerg } 7947 1.1 joerg 7948 1.1 joerg ExprResult Sema::TemporaryMaterializationConversion(Expr *E) { 7949 1.1 joerg // In C++98, we don't want to implicitly create an xvalue. 7950 1.1 joerg // FIXME: This means that AST consumers need to deal with "prvalues" that 7951 1.1 joerg // denote materialized temporaries. Maybe we should add another ValueKind 7952 1.1 joerg // for "xvalue pretending to be a prvalue" for C++98 support. 7953 1.1 joerg if (!E->isRValue() || !getLangOpts().CPlusPlus11) 7954 1.1 joerg return E; 7955 1.1 joerg 7956 1.1 joerg // C++1z [conv.rval]/1: T shall be a complete type. 7957 1.1 joerg // FIXME: Does this ever matter (can we form a prvalue of incomplete type)? 7958 1.1 joerg // If so, we should check for a non-abstract class type here too. 7959 1.1 joerg QualType T = E->getType(); 7960 1.1 joerg if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type)) 7961 1.1 joerg return ExprError(); 7962 1.1 joerg 7963 1.1 joerg return CreateMaterializeTemporaryExpr(E->getType(), E, false); 7964 1.1 joerg } 7965 1.1 joerg 7966 1.1 joerg ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty, 7967 1.1 joerg ExprValueKind VK, 7968 1.1 joerg CheckedConversionKind CCK) { 7969 1.1 joerg 7970 1.1 joerg CastKind CK = CK_NoOp; 7971 1.1 joerg 7972 1.1 joerg if (VK == VK_RValue) { 7973 1.1 joerg auto PointeeTy = Ty->getPointeeType(); 7974 1.1 joerg auto ExprPointeeTy = E->getType()->getPointeeType(); 7975 1.1 joerg if (!PointeeTy.isNull() && 7976 1.1 joerg PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace()) 7977 1.1 joerg CK = CK_AddressSpaceConversion; 7978 1.1 joerg } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) { 7979 1.1 joerg CK = CK_AddressSpaceConversion; 7980 1.1 joerg } 7981 1.1 joerg 7982 1.1 joerg return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK); 7983 1.1 joerg } 7984 1.1 joerg 7985 1.1 joerg ExprResult InitializationSequence::Perform(Sema &S, 7986 1.1 joerg const InitializedEntity &Entity, 7987 1.1 joerg const InitializationKind &Kind, 7988 1.1 joerg MultiExprArg Args, 7989 1.1 joerg QualType *ResultType) { 7990 1.1 joerg if (Failed()) { 7991 1.1 joerg Diagnose(S, Entity, Kind, Args); 7992 1.1 joerg return ExprError(); 7993 1.1 joerg } 7994 1.1 joerg if (!ZeroInitializationFixit.empty()) { 7995 1.1 joerg unsigned DiagID = diag::err_default_init_const; 7996 1.1 joerg if (Decl *D = Entity.getDecl()) 7997 1.1 joerg if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>()) 7998 1.1 joerg DiagID = diag::ext_default_init_const; 7999 1.1 joerg 8000 1.1 joerg // The initialization would have succeeded with this fixit. Since the fixit 8001 1.1 joerg // is on the error, we need to build a valid AST in this case, so this isn't 8002 1.1 joerg // handled in the Failed() branch above. 8003 1.1 joerg QualType DestType = Entity.getType(); 8004 1.1 joerg S.Diag(Kind.getLocation(), DiagID) 8005 1.1 joerg << DestType << (bool)DestType->getAs<RecordType>() 8006 1.1 joerg << FixItHint::CreateInsertion(ZeroInitializationFixitLoc, 8007 1.1 joerg ZeroInitializationFixit); 8008 1.1 joerg } 8009 1.1 joerg 8010 1.1 joerg if (getKind() == DependentSequence) { 8011 1.1 joerg // If the declaration is a non-dependent, incomplete array type 8012 1.1 joerg // that has an initializer, then its type will be completed once 8013 1.1 joerg // the initializer is instantiated. 8014 1.1 joerg if (ResultType && !Entity.getType()->isDependentType() && 8015 1.1 joerg Args.size() == 1) { 8016 1.1 joerg QualType DeclType = Entity.getType(); 8017 1.1 joerg if (const IncompleteArrayType *ArrayT 8018 1.1 joerg = S.Context.getAsIncompleteArrayType(DeclType)) { 8019 1.1 joerg // FIXME: We don't currently have the ability to accurately 8020 1.1 joerg // compute the length of an initializer list without 8021 1.1 joerg // performing full type-checking of the initializer list 8022 1.1 joerg // (since we have to determine where braces are implicitly 8023 1.1 joerg // introduced and such). So, we fall back to making the array 8024 1.1 joerg // type a dependently-sized array type with no specified 8025 1.1 joerg // bound. 8026 1.1 joerg if (isa<InitListExpr>((Expr *)Args[0])) { 8027 1.1 joerg SourceRange Brackets; 8028 1.1 joerg 8029 1.1 joerg // Scavange the location of the brackets from the entity, if we can. 8030 1.1 joerg if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) { 8031 1.1 joerg if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { 8032 1.1 joerg TypeLoc TL = TInfo->getTypeLoc(); 8033 1.1 joerg if (IncompleteArrayTypeLoc ArrayLoc = 8034 1.1 joerg TL.getAs<IncompleteArrayTypeLoc>()) 8035 1.1 joerg Brackets = ArrayLoc.getBracketsRange(); 8036 1.1 joerg } 8037 1.1 joerg } 8038 1.1 joerg 8039 1.1 joerg *ResultType 8040 1.1 joerg = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), 8041 1.1 joerg /*NumElts=*/nullptr, 8042 1.1 joerg ArrayT->getSizeModifier(), 8043 1.1 joerg ArrayT->getIndexTypeCVRQualifiers(), 8044 1.1 joerg Brackets); 8045 1.1 joerg } 8046 1.1 joerg 8047 1.1 joerg } 8048 1.1 joerg } 8049 1.1 joerg if (Kind.getKind() == InitializationKind::IK_Direct && 8050 1.1 joerg !Kind.isExplicitCast()) { 8051 1.1 joerg // Rebuild the ParenListExpr. 8052 1.1 joerg SourceRange ParenRange = Kind.getParenOrBraceRange(); 8053 1.1 joerg return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(), 8054 1.1 joerg Args); 8055 1.1 joerg } 8056 1.1 joerg assert(Kind.getKind() == InitializationKind::IK_Copy || 8057 1.1 joerg Kind.isExplicitCast() || 8058 1.1 joerg Kind.getKind() == InitializationKind::IK_DirectList); 8059 1.1 joerg return ExprResult(Args[0]); 8060 1.1 joerg } 8061 1.1 joerg 8062 1.1 joerg // No steps means no initialization. 8063 1.1 joerg if (Steps.empty()) 8064 1.1 joerg return ExprResult((Expr *)nullptr); 8065 1.1 joerg 8066 1.1 joerg if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() && 8067 1.1 joerg Args.size() == 1 && isa<InitListExpr>(Args[0]) && 8068 1.1.1.2 joerg !Entity.isParamOrTemplateParamKind()) { 8069 1.1 joerg // Produce a C++98 compatibility warning if we are initializing a reference 8070 1.1 joerg // from an initializer list. For parameters, we produce a better warning 8071 1.1 joerg // elsewhere. 8072 1.1 joerg Expr *Init = Args[0]; 8073 1.1 joerg S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init) 8074 1.1 joerg << Init->getSourceRange(); 8075 1.1 joerg } 8076 1.1 joerg 8077 1.1 joerg // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope 8078 1.1 joerg QualType ETy = Entity.getType(); 8079 1.1.1.2 joerg bool HasGlobalAS = ETy.hasAddressSpace() && 8080 1.1.1.2 joerg ETy.getAddressSpace() == LangAS::opencl_global; 8081 1.1 joerg 8082 1.1 joerg if (S.getLangOpts().OpenCLVersion >= 200 && 8083 1.1 joerg ETy->isAtomicType() && !HasGlobalAS && 8084 1.1 joerg Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) { 8085 1.1 joerg S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init) 8086 1.1 joerg << 1 8087 1.1 joerg << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc()); 8088 1.1 joerg return ExprError(); 8089 1.1 joerg } 8090 1.1 joerg 8091 1.1 joerg QualType DestType = Entity.getType().getNonReferenceType(); 8092 1.1 joerg // FIXME: Ugly hack around the fact that Entity.getType() is not 8093 1.1 joerg // the same as Entity.getDecl()->getType() in cases involving type merging, 8094 1.1 joerg // and we want latter when it makes sense. 8095 1.1 joerg if (ResultType) 8096 1.1 joerg *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : 8097 1.1 joerg Entity.getType(); 8098 1.1 joerg 8099 1.1 joerg ExprResult CurInit((Expr *)nullptr); 8100 1.1 joerg SmallVector<Expr*, 4> ArrayLoopCommonExprs; 8101 1.1 joerg 8102 1.1 joerg // For initialization steps that start with a single initializer, 8103 1.1 joerg // grab the only argument out the Args and place it into the "current" 8104 1.1 joerg // initializer. 8105 1.1 joerg switch (Steps.front().Kind) { 8106 1.1 joerg case SK_ResolveAddressOfOverloadedFunction: 8107 1.1 joerg case SK_CastDerivedToBaseRValue: 8108 1.1 joerg case SK_CastDerivedToBaseXValue: 8109 1.1 joerg case SK_CastDerivedToBaseLValue: 8110 1.1 joerg case SK_BindReference: 8111 1.1 joerg case SK_BindReferenceToTemporary: 8112 1.1 joerg case SK_FinalCopy: 8113 1.1 joerg case SK_ExtraneousCopyToTemporary: 8114 1.1 joerg case SK_UserConversion: 8115 1.1 joerg case SK_QualificationConversionLValue: 8116 1.1 joerg case SK_QualificationConversionXValue: 8117 1.1 joerg case SK_QualificationConversionRValue: 8118 1.1.1.2 joerg case SK_FunctionReferenceConversion: 8119 1.1 joerg case SK_AtomicConversion: 8120 1.1 joerg case SK_ConversionSequence: 8121 1.1 joerg case SK_ConversionSequenceNoNarrowing: 8122 1.1 joerg case SK_ListInitialization: 8123 1.1 joerg case SK_UnwrapInitList: 8124 1.1 joerg case SK_RewrapInitList: 8125 1.1 joerg case SK_CAssignment: 8126 1.1 joerg case SK_StringInit: 8127 1.1 joerg case SK_ObjCObjectConversion: 8128 1.1 joerg case SK_ArrayLoopIndex: 8129 1.1 joerg case SK_ArrayLoopInit: 8130 1.1 joerg case SK_ArrayInit: 8131 1.1 joerg case SK_GNUArrayInit: 8132 1.1 joerg case SK_ParenthesizedArrayInit: 8133 1.1 joerg case SK_PassByIndirectCopyRestore: 8134 1.1 joerg case SK_PassByIndirectRestore: 8135 1.1 joerg case SK_ProduceObjCObject: 8136 1.1 joerg case SK_StdInitializerList: 8137 1.1 joerg case SK_OCLSamplerInit: 8138 1.1 joerg case SK_OCLZeroOpaqueType: { 8139 1.1 joerg assert(Args.size() == 1); 8140 1.1 joerg CurInit = Args[0]; 8141 1.1 joerg if (!CurInit.get()) return ExprError(); 8142 1.1 joerg break; 8143 1.1 joerg } 8144 1.1 joerg 8145 1.1 joerg case SK_ConstructorInitialization: 8146 1.1 joerg case SK_ConstructorInitializationFromList: 8147 1.1 joerg case SK_StdInitializerListConstructorCall: 8148 1.1 joerg case SK_ZeroInitialization: 8149 1.1 joerg break; 8150 1.1 joerg } 8151 1.1 joerg 8152 1.1 joerg // Promote from an unevaluated context to an unevaluated list context in 8153 1.1 joerg // C++11 list-initialization; we need to instantiate entities usable in 8154 1.1 joerg // constant expressions here in order to perform narrowing checks =( 8155 1.1 joerg EnterExpressionEvaluationContext Evaluated( 8156 1.1 joerg S, EnterExpressionEvaluationContext::InitList, 8157 1.1 joerg CurInit.get() && isa<InitListExpr>(CurInit.get())); 8158 1.1 joerg 8159 1.1 joerg // C++ [class.abstract]p2: 8160 1.1 joerg // no objects of an abstract class can be created except as subobjects 8161 1.1 joerg // of a class derived from it 8162 1.1 joerg auto checkAbstractType = [&](QualType T) -> bool { 8163 1.1 joerg if (Entity.getKind() == InitializedEntity::EK_Base || 8164 1.1 joerg Entity.getKind() == InitializedEntity::EK_Delegating) 8165 1.1 joerg return false; 8166 1.1 joerg return S.RequireNonAbstractType(Kind.getLocation(), T, 8167 1.1 joerg diag::err_allocation_of_abstract_type); 8168 1.1 joerg }; 8169 1.1 joerg 8170 1.1 joerg // Walk through the computed steps for the initialization sequence, 8171 1.1 joerg // performing the specified conversions along the way. 8172 1.1 joerg bool ConstructorInitRequiresZeroInit = false; 8173 1.1 joerg for (step_iterator Step = step_begin(), StepEnd = step_end(); 8174 1.1 joerg Step != StepEnd; ++Step) { 8175 1.1 joerg if (CurInit.isInvalid()) 8176 1.1 joerg return ExprError(); 8177 1.1 joerg 8178 1.1 joerg QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); 8179 1.1 joerg 8180 1.1 joerg switch (Step->Kind) { 8181 1.1 joerg case SK_ResolveAddressOfOverloadedFunction: 8182 1.1 joerg // Overload resolution determined which function invoke; update the 8183 1.1 joerg // initializer to reflect that choice. 8184 1.1 joerg S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl); 8185 1.1 joerg if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation())) 8186 1.1 joerg return ExprError(); 8187 1.1 joerg CurInit = S.FixOverloadedFunctionReference(CurInit, 8188 1.1 joerg Step->Function.FoundDecl, 8189 1.1 joerg Step->Function.Function); 8190 1.1 joerg break; 8191 1.1 joerg 8192 1.1 joerg case SK_CastDerivedToBaseRValue: 8193 1.1 joerg case SK_CastDerivedToBaseXValue: 8194 1.1 joerg case SK_CastDerivedToBaseLValue: { 8195 1.1 joerg // We have a derived-to-base cast that produces either an rvalue or an 8196 1.1 joerg // lvalue. Perform that cast. 8197 1.1 joerg 8198 1.1 joerg CXXCastPath BasePath; 8199 1.1 joerg 8200 1.1 joerg // Casts to inaccessible base classes are allowed with C-style casts. 8201 1.1 joerg bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); 8202 1.1 joerg if (S.CheckDerivedToBaseConversion( 8203 1.1 joerg SourceType, Step->Type, CurInit.get()->getBeginLoc(), 8204 1.1 joerg CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess)) 8205 1.1 joerg return ExprError(); 8206 1.1 joerg 8207 1.1 joerg ExprValueKind VK = 8208 1.1 joerg Step->Kind == SK_CastDerivedToBaseLValue ? 8209 1.1 joerg VK_LValue : 8210 1.1 joerg (Step->Kind == SK_CastDerivedToBaseXValue ? 8211 1.1 joerg VK_XValue : 8212 1.1 joerg VK_RValue); 8213 1.1.1.2 joerg CurInit = ImplicitCastExpr::Create(S.Context, Step->Type, 8214 1.1.1.2 joerg CK_DerivedToBase, CurInit.get(), 8215 1.1.1.2 joerg &BasePath, VK, FPOptionsOverride()); 8216 1.1 joerg break; 8217 1.1 joerg } 8218 1.1 joerg 8219 1.1 joerg case SK_BindReference: 8220 1.1 joerg // Reference binding does not have any corresponding ASTs. 8221 1.1 joerg 8222 1.1 joerg // Check exception specifications 8223 1.1 joerg if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 8224 1.1 joerg return ExprError(); 8225 1.1 joerg 8226 1.1 joerg // We don't check for e.g. function pointers here, since address 8227 1.1 joerg // availability checks should only occur when the function first decays 8228 1.1 joerg // into a pointer or reference. 8229 1.1 joerg if (CurInit.get()->getType()->isFunctionProtoType()) { 8230 1.1 joerg if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) { 8231 1.1 joerg if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 8232 1.1 joerg if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 8233 1.1 joerg DRE->getBeginLoc())) 8234 1.1 joerg return ExprError(); 8235 1.1 joerg } 8236 1.1 joerg } 8237 1.1 joerg } 8238 1.1 joerg 8239 1.1 joerg CheckForNullPointerDereference(S, CurInit.get()); 8240 1.1 joerg break; 8241 1.1 joerg 8242 1.1 joerg case SK_BindReferenceToTemporary: { 8243 1.1 joerg // Make sure the "temporary" is actually an rvalue. 8244 1.1 joerg assert(CurInit.get()->isRValue() && "not a temporary"); 8245 1.1 joerg 8246 1.1 joerg // Check exception specifications 8247 1.1 joerg if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 8248 1.1 joerg return ExprError(); 8249 1.1 joerg 8250 1.1.1.2 joerg QualType MTETy = Step->Type; 8251 1.1.1.2 joerg 8252 1.1.1.2 joerg // When this is an incomplete array type (such as when this is 8253 1.1.1.2 joerg // initializing an array of unknown bounds from an init list), use THAT 8254 1.1.1.2 joerg // type instead so that we propogate the array bounds. 8255 1.1.1.2 joerg if (MTETy->isIncompleteArrayType() && 8256 1.1.1.2 joerg !CurInit.get()->getType()->isIncompleteArrayType() && 8257 1.1.1.2 joerg S.Context.hasSameType( 8258 1.1.1.2 joerg MTETy->getPointeeOrArrayElementType(), 8259 1.1.1.2 joerg CurInit.get()->getType()->getPointeeOrArrayElementType())) 8260 1.1.1.2 joerg MTETy = CurInit.get()->getType(); 8261 1.1.1.2 joerg 8262 1.1 joerg // Materialize the temporary into memory. 8263 1.1 joerg MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( 8264 1.1.1.2 joerg MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType()); 8265 1.1 joerg CurInit = MTE; 8266 1.1 joerg 8267 1.1 joerg // If we're extending this temporary to automatic storage duration -- we 8268 1.1 joerg // need to register its cleanup during the full-expression's cleanups. 8269 1.1 joerg if (MTE->getStorageDuration() == SD_Automatic && 8270 1.1 joerg MTE->getType().isDestructedType()) 8271 1.1 joerg S.Cleanup.setExprNeedsCleanups(true); 8272 1.1 joerg break; 8273 1.1 joerg } 8274 1.1 joerg 8275 1.1 joerg case SK_FinalCopy: 8276 1.1 joerg if (checkAbstractType(Step->Type)) 8277 1.1 joerg return ExprError(); 8278 1.1 joerg 8279 1.1 joerg // If the overall initialization is initializing a temporary, we already 8280 1.1 joerg // bound our argument if it was necessary to do so. If not (if we're 8281 1.1 joerg // ultimately initializing a non-temporary), our argument needs to be 8282 1.1 joerg // bound since it's initializing a function parameter. 8283 1.1 joerg // FIXME: This is a mess. Rationalize temporary destruction. 8284 1.1 joerg if (!shouldBindAsTemporary(Entity)) 8285 1.1 joerg CurInit = S.MaybeBindToTemporary(CurInit.get()); 8286 1.1 joerg CurInit = CopyObject(S, Step->Type, Entity, CurInit, 8287 1.1 joerg /*IsExtraneousCopy=*/false); 8288 1.1 joerg break; 8289 1.1 joerg 8290 1.1 joerg case SK_ExtraneousCopyToTemporary: 8291 1.1 joerg CurInit = CopyObject(S, Step->Type, Entity, CurInit, 8292 1.1 joerg /*IsExtraneousCopy=*/true); 8293 1.1 joerg break; 8294 1.1 joerg 8295 1.1 joerg case SK_UserConversion: { 8296 1.1 joerg // We have a user-defined conversion that invokes either a constructor 8297 1.1 joerg // or a conversion function. 8298 1.1 joerg CastKind CastKind; 8299 1.1 joerg FunctionDecl *Fn = Step->Function.Function; 8300 1.1 joerg DeclAccessPair FoundFn = Step->Function.FoundDecl; 8301 1.1 joerg bool HadMultipleCandidates = Step->Function.HadMultipleCandidates; 8302 1.1 joerg bool CreatedObject = false; 8303 1.1 joerg if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) { 8304 1.1 joerg // Build a call to the selected constructor. 8305 1.1 joerg SmallVector<Expr*, 8> ConstructorArgs; 8306 1.1 joerg SourceLocation Loc = CurInit.get()->getBeginLoc(); 8307 1.1 joerg 8308 1.1 joerg // Determine the arguments required to actually perform the constructor 8309 1.1 joerg // call. 8310 1.1 joerg Expr *Arg = CurInit.get(); 8311 1.1.1.2 joerg if (S.CompleteConstructorCall(Constructor, Step->Type, 8312 1.1.1.2 joerg MultiExprArg(&Arg, 1), Loc, 8313 1.1.1.2 joerg ConstructorArgs)) 8314 1.1 joerg return ExprError(); 8315 1.1 joerg 8316 1.1 joerg // Build an expression that constructs a temporary. 8317 1.1 joerg CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, 8318 1.1 joerg FoundFn, Constructor, 8319 1.1 joerg ConstructorArgs, 8320 1.1 joerg HadMultipleCandidates, 8321 1.1 joerg /*ListInit*/ false, 8322 1.1 joerg /*StdInitListInit*/ false, 8323 1.1 joerg /*ZeroInit*/ false, 8324 1.1 joerg CXXConstructExpr::CK_Complete, 8325 1.1 joerg SourceRange()); 8326 1.1 joerg if (CurInit.isInvalid()) 8327 1.1 joerg return ExprError(); 8328 1.1 joerg 8329 1.1 joerg S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn, 8330 1.1 joerg Entity); 8331 1.1 joerg if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) 8332 1.1 joerg return ExprError(); 8333 1.1 joerg 8334 1.1 joerg CastKind = CK_ConstructorConversion; 8335 1.1 joerg CreatedObject = true; 8336 1.1 joerg } else { 8337 1.1 joerg // Build a call to the conversion function. 8338 1.1 joerg CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn); 8339 1.1 joerg S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr, 8340 1.1 joerg FoundFn); 8341 1.1 joerg if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) 8342 1.1 joerg return ExprError(); 8343 1.1 joerg 8344 1.1 joerg CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion, 8345 1.1 joerg HadMultipleCandidates); 8346 1.1 joerg if (CurInit.isInvalid()) 8347 1.1 joerg return ExprError(); 8348 1.1 joerg 8349 1.1 joerg CastKind = CK_UserDefinedConversion; 8350 1.1 joerg CreatedObject = Conversion->getReturnType()->isRecordType(); 8351 1.1 joerg } 8352 1.1 joerg 8353 1.1 joerg if (CreatedObject && checkAbstractType(CurInit.get()->getType())) 8354 1.1 joerg return ExprError(); 8355 1.1 joerg 8356 1.1.1.2 joerg CurInit = ImplicitCastExpr::Create( 8357 1.1.1.2 joerg S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr, 8358 1.1.1.2 joerg CurInit.get()->getValueKind(), S.CurFPFeatureOverrides()); 8359 1.1 joerg 8360 1.1 joerg if (shouldBindAsTemporary(Entity)) 8361 1.1 joerg // The overall entity is temporary, so this expression should be 8362 1.1 joerg // destroyed at the end of its full-expression. 8363 1.1 joerg CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); 8364 1.1 joerg else if (CreatedObject && shouldDestroyEntity(Entity)) { 8365 1.1 joerg // The object outlasts the full-expression, but we need to prepare for 8366 1.1 joerg // a destructor being run on it. 8367 1.1 joerg // FIXME: It makes no sense to do this here. This should happen 8368 1.1 joerg // regardless of how we initialized the entity. 8369 1.1 joerg QualType T = CurInit.get()->getType(); 8370 1.1 joerg if (const RecordType *Record = T->getAs<RecordType>()) { 8371 1.1 joerg CXXDestructorDecl *Destructor 8372 1.1 joerg = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl())); 8373 1.1 joerg S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor, 8374 1.1 joerg S.PDiag(diag::err_access_dtor_temp) << T); 8375 1.1 joerg S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor); 8376 1.1 joerg if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc())) 8377 1.1 joerg return ExprError(); 8378 1.1 joerg } 8379 1.1 joerg } 8380 1.1 joerg break; 8381 1.1 joerg } 8382 1.1 joerg 8383 1.1 joerg case SK_QualificationConversionLValue: 8384 1.1 joerg case SK_QualificationConversionXValue: 8385 1.1 joerg case SK_QualificationConversionRValue: { 8386 1.1 joerg // Perform a qualification conversion; these can never go wrong. 8387 1.1 joerg ExprValueKind VK = 8388 1.1 joerg Step->Kind == SK_QualificationConversionLValue 8389 1.1 joerg ? VK_LValue 8390 1.1 joerg : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue 8391 1.1 joerg : VK_RValue); 8392 1.1 joerg CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK); 8393 1.1 joerg break; 8394 1.1 joerg } 8395 1.1 joerg 8396 1.1.1.2 joerg case SK_FunctionReferenceConversion: 8397 1.1.1.2 joerg assert(CurInit.get()->isLValue() && 8398 1.1.1.2 joerg "function reference should be lvalue"); 8399 1.1.1.2 joerg CurInit = 8400 1.1.1.2 joerg S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue); 8401 1.1.1.2 joerg break; 8402 1.1.1.2 joerg 8403 1.1 joerg case SK_AtomicConversion: { 8404 1.1 joerg assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic"); 8405 1.1 joerg CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, 8406 1.1 joerg CK_NonAtomicToAtomic, VK_RValue); 8407 1.1 joerg break; 8408 1.1 joerg } 8409 1.1 joerg 8410 1.1 joerg case SK_ConversionSequence: 8411 1.1 joerg case SK_ConversionSequenceNoNarrowing: { 8412 1.1 joerg if (const auto *FromPtrType = 8413 1.1 joerg CurInit.get()->getType()->getAs<PointerType>()) { 8414 1.1 joerg if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) { 8415 1.1 joerg if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8416 1.1 joerg !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8417 1.1.1.2 joerg // Do not check static casts here because they are checked earlier 8418 1.1.1.2 joerg // in Sema::ActOnCXXNamedCast() 8419 1.1.1.2 joerg if (!Kind.isStaticCast()) { 8420 1.1.1.2 joerg S.Diag(CurInit.get()->getExprLoc(), 8421 1.1.1.2 joerg diag::warn_noderef_to_dereferenceable_pointer) 8422 1.1.1.2 joerg << CurInit.get()->getSourceRange(); 8423 1.1.1.2 joerg } 8424 1.1 joerg } 8425 1.1 joerg } 8426 1.1 joerg } 8427 1.1 joerg 8428 1.1 joerg Sema::CheckedConversionKind CCK 8429 1.1 joerg = Kind.isCStyleCast()? Sema::CCK_CStyleCast 8430 1.1 joerg : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast 8431 1.1 joerg : Kind.isExplicitCast()? Sema::CCK_OtherCast 8432 1.1 joerg : Sema::CCK_ImplicitConversion; 8433 1.1 joerg ExprResult CurInitExprRes = 8434 1.1 joerg S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS, 8435 1.1 joerg getAssignmentAction(Entity), CCK); 8436 1.1 joerg if (CurInitExprRes.isInvalid()) 8437 1.1 joerg return ExprError(); 8438 1.1 joerg 8439 1.1 joerg S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get()); 8440 1.1 joerg 8441 1.1 joerg CurInit = CurInitExprRes; 8442 1.1 joerg 8443 1.1 joerg if (Step->Kind == SK_ConversionSequenceNoNarrowing && 8444 1.1 joerg S.getLangOpts().CPlusPlus) 8445 1.1 joerg DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(), 8446 1.1 joerg CurInit.get()); 8447 1.1 joerg 8448 1.1 joerg break; 8449 1.1 joerg } 8450 1.1 joerg 8451 1.1 joerg case SK_ListInitialization: { 8452 1.1 joerg if (checkAbstractType(Step->Type)) 8453 1.1 joerg return ExprError(); 8454 1.1 joerg 8455 1.1 joerg InitListExpr *InitList = cast<InitListExpr>(CurInit.get()); 8456 1.1 joerg // If we're not initializing the top-level entity, we need to create an 8457 1.1 joerg // InitializeTemporary entity for our target type. 8458 1.1 joerg QualType Ty = Step->Type; 8459 1.1 joerg bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty); 8460 1.1 joerg InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty); 8461 1.1 joerg InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity; 8462 1.1 joerg InitListChecker PerformInitList(S, InitEntity, 8463 1.1 joerg InitList, Ty, /*VerifyOnly=*/false, 8464 1.1 joerg /*TreatUnavailableAsInvalid=*/false); 8465 1.1 joerg if (PerformInitList.HadError()) 8466 1.1 joerg return ExprError(); 8467 1.1 joerg 8468 1.1 joerg // Hack: We must update *ResultType if available in order to set the 8469 1.1 joerg // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'. 8470 1.1 joerg // Worst case: 'const int (&arref)[] = {1, 2, 3};'. 8471 1.1 joerg if (ResultType && 8472 1.1 joerg ResultType->getNonReferenceType()->isIncompleteArrayType()) { 8473 1.1 joerg if ((*ResultType)->isRValueReferenceType()) 8474 1.1 joerg Ty = S.Context.getRValueReferenceType(Ty); 8475 1.1 joerg else if ((*ResultType)->isLValueReferenceType()) 8476 1.1 joerg Ty = S.Context.getLValueReferenceType(Ty, 8477 1.1 joerg (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue()); 8478 1.1 joerg *ResultType = Ty; 8479 1.1 joerg } 8480 1.1 joerg 8481 1.1 joerg InitListExpr *StructuredInitList = 8482 1.1 joerg PerformInitList.getFullyStructuredList(); 8483 1.1 joerg CurInit.get(); 8484 1.1 joerg CurInit = shouldBindAsTemporary(InitEntity) 8485 1.1 joerg ? S.MaybeBindToTemporary(StructuredInitList) 8486 1.1 joerg : StructuredInitList; 8487 1.1 joerg break; 8488 1.1 joerg } 8489 1.1 joerg 8490 1.1 joerg case SK_ConstructorInitializationFromList: { 8491 1.1 joerg if (checkAbstractType(Step->Type)) 8492 1.1 joerg return ExprError(); 8493 1.1 joerg 8494 1.1 joerg // When an initializer list is passed for a parameter of type "reference 8495 1.1 joerg // to object", we don't get an EK_Temporary entity, but instead an 8496 1.1 joerg // EK_Parameter entity with reference type. 8497 1.1 joerg // FIXME: This is a hack. What we really should do is create a user 8498 1.1 joerg // conversion step for this case, but this makes it considerably more 8499 1.1 joerg // complicated. For now, this will do. 8500 1.1 joerg InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( 8501 1.1 joerg Entity.getType().getNonReferenceType()); 8502 1.1 joerg bool UseTemporary = Entity.getType()->isReferenceType(); 8503 1.1 joerg assert(Args.size() == 1 && "expected a single argument for list init"); 8504 1.1 joerg InitListExpr *InitList = cast<InitListExpr>(Args[0]); 8505 1.1 joerg S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init) 8506 1.1 joerg << InitList->getSourceRange(); 8507 1.1 joerg MultiExprArg Arg(InitList->getInits(), InitList->getNumInits()); 8508 1.1 joerg CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity : 8509 1.1 joerg Entity, 8510 1.1 joerg Kind, Arg, *Step, 8511 1.1 joerg ConstructorInitRequiresZeroInit, 8512 1.1 joerg /*IsListInitialization*/true, 8513 1.1 joerg /*IsStdInitListInit*/false, 8514 1.1 joerg InitList->getLBraceLoc(), 8515 1.1 joerg InitList->getRBraceLoc()); 8516 1.1 joerg break; 8517 1.1 joerg } 8518 1.1 joerg 8519 1.1 joerg case SK_UnwrapInitList: 8520 1.1 joerg CurInit = cast<InitListExpr>(CurInit.get())->getInit(0); 8521 1.1 joerg break; 8522 1.1 joerg 8523 1.1 joerg case SK_RewrapInitList: { 8524 1.1 joerg Expr *E = CurInit.get(); 8525 1.1 joerg InitListExpr *Syntactic = Step->WrappingSyntacticList; 8526 1.1 joerg InitListExpr *ILE = new (S.Context) InitListExpr(S.Context, 8527 1.1 joerg Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc()); 8528 1.1 joerg ILE->setSyntacticForm(Syntactic); 8529 1.1 joerg ILE->setType(E->getType()); 8530 1.1 joerg ILE->setValueKind(E->getValueKind()); 8531 1.1 joerg CurInit = ILE; 8532 1.1 joerg break; 8533 1.1 joerg } 8534 1.1 joerg 8535 1.1 joerg case SK_ConstructorInitialization: 8536 1.1 joerg case SK_StdInitializerListConstructorCall: { 8537 1.1 joerg if (checkAbstractType(Step->Type)) 8538 1.1 joerg return ExprError(); 8539 1.1 joerg 8540 1.1 joerg // When an initializer list is passed for a parameter of type "reference 8541 1.1 joerg // to object", we don't get an EK_Temporary entity, but instead an 8542 1.1 joerg // EK_Parameter entity with reference type. 8543 1.1 joerg // FIXME: This is a hack. What we really should do is create a user 8544 1.1 joerg // conversion step for this case, but this makes it considerably more 8545 1.1 joerg // complicated. For now, this will do. 8546 1.1 joerg InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( 8547 1.1 joerg Entity.getType().getNonReferenceType()); 8548 1.1 joerg bool UseTemporary = Entity.getType()->isReferenceType(); 8549 1.1 joerg bool IsStdInitListInit = 8550 1.1 joerg Step->Kind == SK_StdInitializerListConstructorCall; 8551 1.1 joerg Expr *Source = CurInit.get(); 8552 1.1 joerg SourceRange Range = Kind.hasParenOrBraceRange() 8553 1.1 joerg ? Kind.getParenOrBraceRange() 8554 1.1 joerg : SourceRange(); 8555 1.1 joerg CurInit = PerformConstructorInitialization( 8556 1.1 joerg S, UseTemporary ? TempEntity : Entity, Kind, 8557 1.1 joerg Source ? MultiExprArg(Source) : Args, *Step, 8558 1.1 joerg ConstructorInitRequiresZeroInit, 8559 1.1 joerg /*IsListInitialization*/ IsStdInitListInit, 8560 1.1 joerg /*IsStdInitListInitialization*/ IsStdInitListInit, 8561 1.1 joerg /*LBraceLoc*/ Range.getBegin(), 8562 1.1 joerg /*RBraceLoc*/ Range.getEnd()); 8563 1.1 joerg break; 8564 1.1 joerg } 8565 1.1 joerg 8566 1.1 joerg case SK_ZeroInitialization: { 8567 1.1 joerg step_iterator NextStep = Step; 8568 1.1 joerg ++NextStep; 8569 1.1 joerg if (NextStep != StepEnd && 8570 1.1 joerg (NextStep->Kind == SK_ConstructorInitialization || 8571 1.1 joerg NextStep->Kind == SK_ConstructorInitializationFromList)) { 8572 1.1 joerg // The need for zero-initialization is recorded directly into 8573 1.1 joerg // the call to the object's constructor within the next step. 8574 1.1 joerg ConstructorInitRequiresZeroInit = true; 8575 1.1 joerg } else if (Kind.getKind() == InitializationKind::IK_Value && 8576 1.1 joerg S.getLangOpts().CPlusPlus && 8577 1.1 joerg !Kind.isImplicitValueInit()) { 8578 1.1 joerg TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 8579 1.1 joerg if (!TSInfo) 8580 1.1 joerg TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type, 8581 1.1 joerg Kind.getRange().getBegin()); 8582 1.1 joerg 8583 1.1 joerg CurInit = new (S.Context) CXXScalarValueInitExpr( 8584 1.1 joerg Entity.getType().getNonLValueExprType(S.Context), TSInfo, 8585 1.1 joerg Kind.getRange().getEnd()); 8586 1.1 joerg } else { 8587 1.1 joerg CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type); 8588 1.1 joerg } 8589 1.1 joerg break; 8590 1.1 joerg } 8591 1.1 joerg 8592 1.1 joerg case SK_CAssignment: { 8593 1.1 joerg QualType SourceType = CurInit.get()->getType(); 8594 1.1 joerg 8595 1.1 joerg // Save off the initial CurInit in case we need to emit a diagnostic 8596 1.1 joerg ExprResult InitialCurInit = CurInit; 8597 1.1 joerg ExprResult Result = CurInit; 8598 1.1 joerg Sema::AssignConvertType ConvTy = 8599 1.1 joerg S.CheckSingleAssignmentConstraints(Step->Type, Result, true, 8600 1.1 joerg Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited); 8601 1.1 joerg if (Result.isInvalid()) 8602 1.1 joerg return ExprError(); 8603 1.1 joerg CurInit = Result; 8604 1.1 joerg 8605 1.1 joerg // If this is a call, allow conversion to a transparent union. 8606 1.1 joerg ExprResult CurInitExprRes = CurInit; 8607 1.1 joerg if (ConvTy != Sema::Compatible && 8608 1.1 joerg Entity.isParameterKind() && 8609 1.1 joerg S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes) 8610 1.1 joerg == Sema::Compatible) 8611 1.1 joerg ConvTy = Sema::Compatible; 8612 1.1 joerg if (CurInitExprRes.isInvalid()) 8613 1.1 joerg return ExprError(); 8614 1.1 joerg CurInit = CurInitExprRes; 8615 1.1 joerg 8616 1.1 joerg bool Complained; 8617 1.1 joerg if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), 8618 1.1 joerg Step->Type, SourceType, 8619 1.1 joerg InitialCurInit.get(), 8620 1.1 joerg getAssignmentAction(Entity, true), 8621 1.1 joerg &Complained)) { 8622 1.1 joerg PrintInitLocationNote(S, Entity); 8623 1.1 joerg return ExprError(); 8624 1.1 joerg } else if (Complained) 8625 1.1 joerg PrintInitLocationNote(S, Entity); 8626 1.1 joerg break; 8627 1.1 joerg } 8628 1.1 joerg 8629 1.1 joerg case SK_StringInit: { 8630 1.1 joerg QualType Ty = Step->Type; 8631 1.1.1.2 joerg bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType(); 8632 1.1.1.2 joerg CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty, 8633 1.1 joerg S.Context.getAsArrayType(Ty), S); 8634 1.1 joerg break; 8635 1.1 joerg } 8636 1.1 joerg 8637 1.1 joerg case SK_ObjCObjectConversion: 8638 1.1 joerg CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, 8639 1.1 joerg CK_ObjCObjectLValueCast, 8640 1.1 joerg CurInit.get()->getValueKind()); 8641 1.1 joerg break; 8642 1.1 joerg 8643 1.1 joerg case SK_ArrayLoopIndex: { 8644 1.1 joerg Expr *Cur = CurInit.get(); 8645 1.1 joerg Expr *BaseExpr = new (S.Context) 8646 1.1 joerg OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(), 8647 1.1 joerg Cur->getValueKind(), Cur->getObjectKind(), Cur); 8648 1.1 joerg Expr *IndexExpr = 8649 1.1 joerg new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType()); 8650 1.1 joerg CurInit = S.CreateBuiltinArraySubscriptExpr( 8651 1.1 joerg BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation()); 8652 1.1 joerg ArrayLoopCommonExprs.push_back(BaseExpr); 8653 1.1 joerg break; 8654 1.1 joerg } 8655 1.1 joerg 8656 1.1 joerg case SK_ArrayLoopInit: { 8657 1.1 joerg assert(!ArrayLoopCommonExprs.empty() && 8658 1.1 joerg "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit"); 8659 1.1 joerg Expr *Common = ArrayLoopCommonExprs.pop_back_val(); 8660 1.1 joerg CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common, 8661 1.1 joerg CurInit.get()); 8662 1.1 joerg break; 8663 1.1 joerg } 8664 1.1 joerg 8665 1.1 joerg case SK_GNUArrayInit: 8666 1.1 joerg // Okay: we checked everything before creating this step. Note that 8667 1.1 joerg // this is a GNU extension. 8668 1.1 joerg S.Diag(Kind.getLocation(), diag::ext_array_init_copy) 8669 1.1 joerg << Step->Type << CurInit.get()->getType() 8670 1.1 joerg << CurInit.get()->getSourceRange(); 8671 1.1 joerg updateGNUCompoundLiteralRValue(CurInit.get()); 8672 1.1 joerg LLVM_FALLTHROUGH; 8673 1.1 joerg case SK_ArrayInit: 8674 1.1 joerg // If the destination type is an incomplete array type, update the 8675 1.1 joerg // type accordingly. 8676 1.1 joerg if (ResultType) { 8677 1.1 joerg if (const IncompleteArrayType *IncompleteDest 8678 1.1 joerg = S.Context.getAsIncompleteArrayType(Step->Type)) { 8679 1.1 joerg if (const ConstantArrayType *ConstantSource 8680 1.1 joerg = S.Context.getAsConstantArrayType(CurInit.get()->getType())) { 8681 1.1 joerg *ResultType = S.Context.getConstantArrayType( 8682 1.1 joerg IncompleteDest->getElementType(), 8683 1.1 joerg ConstantSource->getSize(), 8684 1.1 joerg ConstantSource->getSizeExpr(), 8685 1.1 joerg ArrayType::Normal, 0); 8686 1.1 joerg } 8687 1.1 joerg } 8688 1.1 joerg } 8689 1.1 joerg break; 8690 1.1 joerg 8691 1.1 joerg case SK_ParenthesizedArrayInit: 8692 1.1 joerg // Okay: we checked everything before creating this step. Note that 8693 1.1 joerg // this is a GNU extension. 8694 1.1 joerg S.Diag(Kind.getLocation(), diag::ext_array_init_parens) 8695 1.1 joerg << CurInit.get()->getSourceRange(); 8696 1.1 joerg break; 8697 1.1 joerg 8698 1.1 joerg case SK_PassByIndirectCopyRestore: 8699 1.1 joerg case SK_PassByIndirectRestore: 8700 1.1 joerg checkIndirectCopyRestoreSource(S, CurInit.get()); 8701 1.1 joerg CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr( 8702 1.1 joerg CurInit.get(), Step->Type, 8703 1.1 joerg Step->Kind == SK_PassByIndirectCopyRestore); 8704 1.1 joerg break; 8705 1.1 joerg 8706 1.1 joerg case SK_ProduceObjCObject: 8707 1.1.1.2 joerg CurInit = ImplicitCastExpr::Create( 8708 1.1.1.2 joerg S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr, 8709 1.1.1.2 joerg VK_RValue, FPOptionsOverride()); 8710 1.1 joerg break; 8711 1.1 joerg 8712 1.1 joerg case SK_StdInitializerList: { 8713 1.1 joerg S.Diag(CurInit.get()->getExprLoc(), 8714 1.1 joerg diag::warn_cxx98_compat_initializer_list_init) 8715 1.1 joerg << CurInit.get()->getSourceRange(); 8716 1.1 joerg 8717 1.1 joerg // Materialize the temporary into memory. 8718 1.1 joerg MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( 8719 1.1 joerg CurInit.get()->getType(), CurInit.get(), 8720 1.1 joerg /*BoundToLvalueReference=*/false); 8721 1.1 joerg 8722 1.1 joerg // Wrap it in a construction of a std::initializer_list<T>. 8723 1.1 joerg CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE); 8724 1.1 joerg 8725 1.1 joerg // Bind the result, in case the library has given initializer_list a 8726 1.1 joerg // non-trivial destructor. 8727 1.1 joerg if (shouldBindAsTemporary(Entity)) 8728 1.1 joerg CurInit = S.MaybeBindToTemporary(CurInit.get()); 8729 1.1 joerg break; 8730 1.1 joerg } 8731 1.1 joerg 8732 1.1 joerg case SK_OCLSamplerInit: { 8733 1.1 joerg // Sampler initialization have 5 cases: 8734 1.1 joerg // 1. function argument passing 8735 1.1 joerg // 1a. argument is a file-scope variable 8736 1.1 joerg // 1b. argument is a function-scope variable 8737 1.1 joerg // 1c. argument is one of caller function's parameters 8738 1.1 joerg // 2. variable initialization 8739 1.1 joerg // 2a. initializing a file-scope variable 8740 1.1 joerg // 2b. initializing a function-scope variable 8741 1.1 joerg // 8742 1.1 joerg // For file-scope variables, since they cannot be initialized by function 8743 1.1 joerg // call of __translate_sampler_initializer in LLVM IR, their references 8744 1.1 joerg // need to be replaced by a cast from their literal initializers to 8745 1.1 joerg // sampler type. Since sampler variables can only be used in function 8746 1.1 joerg // calls as arguments, we only need to replace them when handling the 8747 1.1 joerg // argument passing. 8748 1.1 joerg assert(Step->Type->isSamplerT() && 8749 1.1 joerg "Sampler initialization on non-sampler type."); 8750 1.1 joerg Expr *Init = CurInit.get()->IgnoreParens(); 8751 1.1 joerg QualType SourceType = Init->getType(); 8752 1.1 joerg // Case 1 8753 1.1 joerg if (Entity.isParameterKind()) { 8754 1.1 joerg if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) { 8755 1.1 joerg S.Diag(Kind.getLocation(), diag::err_sampler_argument_required) 8756 1.1 joerg << SourceType; 8757 1.1 joerg break; 8758 1.1 joerg } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) { 8759 1.1 joerg auto Var = cast<VarDecl>(DRE->getDecl()); 8760 1.1 joerg // Case 1b and 1c 8761 1.1 joerg // No cast from integer to sampler is needed. 8762 1.1 joerg if (!Var->hasGlobalStorage()) { 8763 1.1.1.2 joerg CurInit = ImplicitCastExpr::Create( 8764 1.1.1.2 joerg S.Context, Step->Type, CK_LValueToRValue, Init, 8765 1.1.1.2 joerg /*BasePath=*/nullptr, VK_RValue, FPOptionsOverride()); 8766 1.1 joerg break; 8767 1.1 joerg } 8768 1.1 joerg // Case 1a 8769 1.1 joerg // For function call with a file-scope sampler variable as argument, 8770 1.1 joerg // get the integer literal. 8771 1.1 joerg // Do not diagnose if the file-scope variable does not have initializer 8772 1.1 joerg // since this has already been diagnosed when parsing the variable 8773 1.1 joerg // declaration. 8774 1.1 joerg if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit())) 8775 1.1 joerg break; 8776 1.1 joerg Init = cast<ImplicitCastExpr>(const_cast<Expr*>( 8777 1.1 joerg Var->getInit()))->getSubExpr(); 8778 1.1 joerg SourceType = Init->getType(); 8779 1.1 joerg } 8780 1.1 joerg } else { 8781 1.1 joerg // Case 2 8782 1.1 joerg // Check initializer is 32 bit integer constant. 8783 1.1 joerg // If the initializer is taken from global variable, do not diagnose since 8784 1.1 joerg // this has already been done when parsing the variable declaration. 8785 1.1 joerg if (!Init->isConstantInitializer(S.Context, false)) 8786 1.1 joerg break; 8787 1.1 joerg 8788 1.1 joerg if (!SourceType->isIntegerType() || 8789 1.1 joerg 32 != S.Context.getIntWidth(SourceType)) { 8790 1.1 joerg S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer) 8791 1.1 joerg << SourceType; 8792 1.1 joerg break; 8793 1.1 joerg } 8794 1.1 joerg 8795 1.1 joerg Expr::EvalResult EVResult; 8796 1.1 joerg Init->EvaluateAsInt(EVResult, S.Context); 8797 1.1 joerg llvm::APSInt Result = EVResult.Val.getInt(); 8798 1.1 joerg const uint64_t SamplerValue = Result.getLimitedValue(); 8799 1.1 joerg // 32-bit value of sampler's initializer is interpreted as 8800 1.1 joerg // bit-field with the following structure: 8801 1.1 joerg // |unspecified|Filter|Addressing Mode| Normalized Coords| 8802 1.1 joerg // |31 6|5 4|3 1| 0| 8803 1.1 joerg // This structure corresponds to enum values of sampler properties 8804 1.1 joerg // defined in SPIR spec v1.2 and also opencl-c.h 8805 1.1 joerg unsigned AddressingMode = (0x0E & SamplerValue) >> 1; 8806 1.1 joerg unsigned FilterMode = (0x30 & SamplerValue) >> 4; 8807 1.1 joerg if (FilterMode != 1 && FilterMode != 2 && 8808 1.1.1.2 joerg !S.getOpenCLOptions().isAvailableOption( 8809 1.1.1.2 joerg "cl_intel_device_side_avc_motion_estimation", S.getLangOpts())) 8810 1.1 joerg S.Diag(Kind.getLocation(), 8811 1.1 joerg diag::warn_sampler_initializer_invalid_bits) 8812 1.1 joerg << "Filter Mode"; 8813 1.1 joerg if (AddressingMode > 4) 8814 1.1 joerg S.Diag(Kind.getLocation(), 8815 1.1 joerg diag::warn_sampler_initializer_invalid_bits) 8816 1.1 joerg << "Addressing Mode"; 8817 1.1 joerg } 8818 1.1 joerg 8819 1.1 joerg // Cases 1a, 2a and 2b 8820 1.1 joerg // Insert cast from integer to sampler. 8821 1.1 joerg CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy, 8822 1.1 joerg CK_IntToOCLSampler); 8823 1.1 joerg break; 8824 1.1 joerg } 8825 1.1 joerg case SK_OCLZeroOpaqueType: { 8826 1.1 joerg assert((Step->Type->isEventT() || Step->Type->isQueueT() || 8827 1.1 joerg Step->Type->isOCLIntelSubgroupAVCType()) && 8828 1.1 joerg "Wrong type for initialization of OpenCL opaque type."); 8829 1.1 joerg 8830 1.1 joerg CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, 8831 1.1 joerg CK_ZeroToOCLOpaqueType, 8832 1.1 joerg CurInit.get()->getValueKind()); 8833 1.1 joerg break; 8834 1.1 joerg } 8835 1.1 joerg } 8836 1.1 joerg } 8837 1.1 joerg 8838 1.1 joerg // Check whether the initializer has a shorter lifetime than the initialized 8839 1.1 joerg // entity, and if not, either lifetime-extend or warn as appropriate. 8840 1.1 joerg if (auto *Init = CurInit.get()) 8841 1.1 joerg S.checkInitializerLifetime(Entity, Init); 8842 1.1 joerg 8843 1.1 joerg // Diagnose non-fatal problems with the completed initialization. 8844 1.1 joerg if (Entity.getKind() == InitializedEntity::EK_Member && 8845 1.1 joerg cast<FieldDecl>(Entity.getDecl())->isBitField()) 8846 1.1 joerg S.CheckBitFieldInitialization(Kind.getLocation(), 8847 1.1 joerg cast<FieldDecl>(Entity.getDecl()), 8848 1.1 joerg CurInit.get()); 8849 1.1 joerg 8850 1.1 joerg // Check for std::move on construction. 8851 1.1 joerg if (const Expr *E = CurInit.get()) { 8852 1.1 joerg CheckMoveOnConstruction(S, E, 8853 1.1 joerg Entity.getKind() == InitializedEntity::EK_Result); 8854 1.1 joerg } 8855 1.1 joerg 8856 1.1 joerg return CurInit; 8857 1.1 joerg } 8858 1.1 joerg 8859 1.1 joerg /// Somewhere within T there is an uninitialized reference subobject. 8860 1.1 joerg /// Dig it out and diagnose it. 8861 1.1 joerg static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, 8862 1.1 joerg QualType T) { 8863 1.1 joerg if (T->isReferenceType()) { 8864 1.1 joerg S.Diag(Loc, diag::err_reference_without_init) 8865 1.1 joerg << T.getNonReferenceType(); 8866 1.1 joerg return true; 8867 1.1 joerg } 8868 1.1 joerg 8869 1.1 joerg CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 8870 1.1 joerg if (!RD || !RD->hasUninitializedReferenceMember()) 8871 1.1 joerg return false; 8872 1.1 joerg 8873 1.1 joerg for (const auto *FI : RD->fields()) { 8874 1.1 joerg if (FI->isUnnamedBitfield()) 8875 1.1 joerg continue; 8876 1.1 joerg 8877 1.1 joerg if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) { 8878 1.1 joerg S.Diag(Loc, diag::note_value_initialization_here) << RD; 8879 1.1 joerg return true; 8880 1.1 joerg } 8881 1.1 joerg } 8882 1.1 joerg 8883 1.1 joerg for (const auto &BI : RD->bases()) { 8884 1.1 joerg if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) { 8885 1.1 joerg S.Diag(Loc, diag::note_value_initialization_here) << RD; 8886 1.1 joerg return true; 8887 1.1 joerg } 8888 1.1 joerg } 8889 1.1 joerg 8890 1.1 joerg return false; 8891 1.1 joerg } 8892 1.1 joerg 8893 1.1 joerg 8894 1.1 joerg //===----------------------------------------------------------------------===// 8895 1.1 joerg // Diagnose initialization failures 8896 1.1 joerg //===----------------------------------------------------------------------===// 8897 1.1 joerg 8898 1.1 joerg /// Emit notes associated with an initialization that failed due to a 8899 1.1 joerg /// "simple" conversion failure. 8900 1.1 joerg static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, 8901 1.1 joerg Expr *op) { 8902 1.1 joerg QualType destType = entity.getType(); 8903 1.1 joerg if (destType.getNonReferenceType()->isObjCObjectPointerType() && 8904 1.1 joerg op->getType()->isObjCObjectPointerType()) { 8905 1.1 joerg 8906 1.1 joerg // Emit a possible note about the conversion failing because the 8907 1.1 joerg // operand is a message send with a related result type. 8908 1.1 joerg S.EmitRelatedResultTypeNote(op); 8909 1.1 joerg 8910 1.1 joerg // Emit a possible note about a return failing because we're 8911 1.1 joerg // expecting a related result type. 8912 1.1 joerg if (entity.getKind() == InitializedEntity::EK_Result) 8913 1.1 joerg S.EmitRelatedResultTypeNoteForReturn(destType); 8914 1.1 joerg } 8915 1.1.1.2 joerg QualType fromType = op->getType(); 8916 1.1.1.2 joerg auto *fromDecl = fromType.getTypePtr()->getPointeeCXXRecordDecl(); 8917 1.1.1.2 joerg auto *destDecl = destType.getTypePtr()->getPointeeCXXRecordDecl(); 8918 1.1.1.2 joerg if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord && 8919 1.1.1.2 joerg destDecl->getDeclKind() == Decl::CXXRecord && 8920 1.1.1.2 joerg !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() && 8921 1.1.1.2 joerg !fromDecl->hasDefinition()) 8922 1.1.1.2 joerg S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion) 8923 1.1.1.2 joerg << S.getASTContext().getTagDeclType(fromDecl) 8924 1.1.1.2 joerg << S.getASTContext().getTagDeclType(destDecl); 8925 1.1 joerg } 8926 1.1 joerg 8927 1.1 joerg static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, 8928 1.1 joerg InitListExpr *InitList) { 8929 1.1 joerg QualType DestType = Entity.getType(); 8930 1.1 joerg 8931 1.1 joerg QualType E; 8932 1.1 joerg if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) { 8933 1.1 joerg QualType ArrayType = S.Context.getConstantArrayType( 8934 1.1 joerg E.withConst(), 8935 1.1 joerg llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), 8936 1.1 joerg InitList->getNumInits()), 8937 1.1 joerg nullptr, clang::ArrayType::Normal, 0); 8938 1.1 joerg InitializedEntity HiddenArray = 8939 1.1 joerg InitializedEntity::InitializeTemporary(ArrayType); 8940 1.1 joerg return diagnoseListInit(S, HiddenArray, InitList); 8941 1.1 joerg } 8942 1.1 joerg 8943 1.1 joerg if (DestType->isReferenceType()) { 8944 1.1 joerg // A list-initialization failure for a reference means that we tried to 8945 1.1 joerg // create a temporary of the inner type (per [dcl.init.list]p3.6) and the 8946 1.1 joerg // inner initialization failed. 8947 1.1 joerg QualType T = DestType->castAs<ReferenceType>()->getPointeeType(); 8948 1.1 joerg diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList); 8949 1.1 joerg SourceLocation Loc = InitList->getBeginLoc(); 8950 1.1 joerg if (auto *D = Entity.getDecl()) 8951 1.1 joerg Loc = D->getLocation(); 8952 1.1 joerg S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T; 8953 1.1 joerg return; 8954 1.1 joerg } 8955 1.1 joerg 8956 1.1 joerg InitListChecker DiagnoseInitList(S, Entity, InitList, DestType, 8957 1.1 joerg /*VerifyOnly=*/false, 8958 1.1 joerg /*TreatUnavailableAsInvalid=*/false); 8959 1.1 joerg assert(DiagnoseInitList.HadError() && 8960 1.1 joerg "Inconsistent init list check result."); 8961 1.1 joerg } 8962 1.1 joerg 8963 1.1 joerg bool InitializationSequence::Diagnose(Sema &S, 8964 1.1 joerg const InitializedEntity &Entity, 8965 1.1 joerg const InitializationKind &Kind, 8966 1.1 joerg ArrayRef<Expr *> Args) { 8967 1.1 joerg if (!Failed()) 8968 1.1 joerg return false; 8969 1.1 joerg 8970 1.1 joerg // When we want to diagnose only one element of a braced-init-list, 8971 1.1 joerg // we need to factor it out. 8972 1.1 joerg Expr *OnlyArg; 8973 1.1 joerg if (Args.size() == 1) { 8974 1.1 joerg auto *List = dyn_cast<InitListExpr>(Args[0]); 8975 1.1 joerg if (List && List->getNumInits() == 1) 8976 1.1 joerg OnlyArg = List->getInit(0); 8977 1.1 joerg else 8978 1.1 joerg OnlyArg = Args[0]; 8979 1.1 joerg } 8980 1.1 joerg else 8981 1.1 joerg OnlyArg = nullptr; 8982 1.1 joerg 8983 1.1 joerg QualType DestType = Entity.getType(); 8984 1.1 joerg switch (Failure) { 8985 1.1 joerg case FK_TooManyInitsForReference: 8986 1.1 joerg // FIXME: Customize for the initialized entity? 8987 1.1 joerg if (Args.empty()) { 8988 1.1 joerg // Dig out the reference subobject which is uninitialized and diagnose it. 8989 1.1 joerg // If this is value-initialization, this could be nested some way within 8990 1.1 joerg // the target type. 8991 1.1 joerg assert(Kind.getKind() == InitializationKind::IK_Value || 8992 1.1 joerg DestType->isReferenceType()); 8993 1.1 joerg bool Diagnosed = 8994 1.1 joerg DiagnoseUninitializedReference(S, Kind.getLocation(), DestType); 8995 1.1 joerg assert(Diagnosed && "couldn't find uninitialized reference to diagnose"); 8996 1.1 joerg (void)Diagnosed; 8997 1.1 joerg } else // FIXME: diagnostic below could be better! 8998 1.1 joerg S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) 8999 1.1 joerg << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); 9000 1.1 joerg break; 9001 1.1 joerg case FK_ParenthesizedListInitForReference: 9002 1.1 joerg S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) 9003 1.1 joerg << 1 << Entity.getType() << Args[0]->getSourceRange(); 9004 1.1 joerg break; 9005 1.1 joerg 9006 1.1 joerg case FK_ArrayNeedsInitList: 9007 1.1 joerg S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0; 9008 1.1 joerg break; 9009 1.1 joerg case FK_ArrayNeedsInitListOrStringLiteral: 9010 1.1 joerg S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1; 9011 1.1 joerg break; 9012 1.1 joerg case FK_ArrayNeedsInitListOrWideStringLiteral: 9013 1.1 joerg S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2; 9014 1.1 joerg break; 9015 1.1 joerg case FK_NarrowStringIntoWideCharArray: 9016 1.1 joerg S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar); 9017 1.1 joerg break; 9018 1.1 joerg case FK_WideStringIntoCharArray: 9019 1.1 joerg S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char); 9020 1.1 joerg break; 9021 1.1 joerg case FK_IncompatWideStringIntoWideChar: 9022 1.1 joerg S.Diag(Kind.getLocation(), 9023 1.1 joerg diag::err_array_init_incompat_wide_string_into_wchar); 9024 1.1 joerg break; 9025 1.1 joerg case FK_PlainStringIntoUTF8Char: 9026 1.1 joerg S.Diag(Kind.getLocation(), 9027 1.1 joerg diag::err_array_init_plain_string_into_char8_t); 9028 1.1 joerg S.Diag(Args.front()->getBeginLoc(), 9029 1.1 joerg diag::note_array_init_plain_string_into_char8_t) 9030 1.1 joerg << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8"); 9031 1.1 joerg break; 9032 1.1 joerg case FK_UTF8StringIntoPlainChar: 9033 1.1 joerg S.Diag(Kind.getLocation(), 9034 1.1 joerg diag::err_array_init_utf8_string_into_char) 9035 1.1.1.2 joerg << S.getLangOpts().CPlusPlus20; 9036 1.1 joerg break; 9037 1.1 joerg case FK_ArrayTypeMismatch: 9038 1.1 joerg case FK_NonConstantArrayInit: 9039 1.1 joerg S.Diag(Kind.getLocation(), 9040 1.1 joerg (Failure == FK_ArrayTypeMismatch 9041 1.1 joerg ? diag::err_array_init_different_type 9042 1.1 joerg : diag::err_array_init_non_constant_array)) 9043 1.1 joerg << DestType.getNonReferenceType() 9044 1.1 joerg << OnlyArg->getType() 9045 1.1 joerg << Args[0]->getSourceRange(); 9046 1.1 joerg break; 9047 1.1 joerg 9048 1.1 joerg case FK_VariableLengthArrayHasInitializer: 9049 1.1 joerg S.Diag(Kind.getLocation(), diag::err_variable_object_no_init) 9050 1.1 joerg << Args[0]->getSourceRange(); 9051 1.1 joerg break; 9052 1.1 joerg 9053 1.1 joerg case FK_AddressOfOverloadFailed: { 9054 1.1 joerg DeclAccessPair Found; 9055 1.1 joerg S.ResolveAddressOfOverloadedFunction(OnlyArg, 9056 1.1 joerg DestType.getNonReferenceType(), 9057 1.1 joerg true, 9058 1.1 joerg Found); 9059 1.1 joerg break; 9060 1.1 joerg } 9061 1.1 joerg 9062 1.1 joerg case FK_AddressOfUnaddressableFunction: { 9063 1.1 joerg auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl()); 9064 1.1 joerg S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 9065 1.1 joerg OnlyArg->getBeginLoc()); 9066 1.1 joerg break; 9067 1.1 joerg } 9068 1.1 joerg 9069 1.1 joerg case FK_ReferenceInitOverloadFailed: 9070 1.1 joerg case FK_UserConversionOverloadFailed: 9071 1.1 joerg switch (FailedOverloadResult) { 9072 1.1 joerg case OR_Ambiguous: 9073 1.1 joerg 9074 1.1 joerg FailedCandidateSet.NoteCandidates( 9075 1.1 joerg PartialDiagnosticAt( 9076 1.1 joerg Kind.getLocation(), 9077 1.1 joerg Failure == FK_UserConversionOverloadFailed 9078 1.1 joerg ? (S.PDiag(diag::err_typecheck_ambiguous_condition) 9079 1.1 joerg << OnlyArg->getType() << DestType 9080 1.1 joerg << Args[0]->getSourceRange()) 9081 1.1 joerg : (S.PDiag(diag::err_ref_init_ambiguous) 9082 1.1 joerg << DestType << OnlyArg->getType() 9083 1.1 joerg << Args[0]->getSourceRange())), 9084 1.1 joerg S, OCD_AmbiguousCandidates, Args); 9085 1.1 joerg break; 9086 1.1 joerg 9087 1.1 joerg case OR_No_Viable_Function: { 9088 1.1 joerg auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args); 9089 1.1 joerg if (!S.RequireCompleteType(Kind.getLocation(), 9090 1.1 joerg DestType.getNonReferenceType(), 9091 1.1 joerg diag::err_typecheck_nonviable_condition_incomplete, 9092 1.1 joerg OnlyArg->getType(), Args[0]->getSourceRange())) 9093 1.1 joerg S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) 9094 1.1 joerg << (Entity.getKind() == InitializedEntity::EK_Result) 9095 1.1 joerg << OnlyArg->getType() << Args[0]->getSourceRange() 9096 1.1 joerg << DestType.getNonReferenceType(); 9097 1.1 joerg 9098 1.1 joerg FailedCandidateSet.NoteCandidates(S, Args, Cands); 9099 1.1 joerg break; 9100 1.1 joerg } 9101 1.1 joerg case OR_Deleted: { 9102 1.1 joerg S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) 9103 1.1 joerg << OnlyArg->getType() << DestType.getNonReferenceType() 9104 1.1 joerg << Args[0]->getSourceRange(); 9105 1.1 joerg OverloadCandidateSet::iterator Best; 9106 1.1 joerg OverloadingResult Ovl 9107 1.1 joerg = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 9108 1.1 joerg if (Ovl == OR_Deleted) { 9109 1.1 joerg S.NoteDeletedFunction(Best->Function); 9110 1.1 joerg } else { 9111 1.1 joerg llvm_unreachable("Inconsistent overload resolution?"); 9112 1.1 joerg } 9113 1.1 joerg break; 9114 1.1 joerg } 9115 1.1 joerg 9116 1.1 joerg case OR_Success: 9117 1.1 joerg llvm_unreachable("Conversion did not fail!"); 9118 1.1 joerg } 9119 1.1 joerg break; 9120 1.1 joerg 9121 1.1 joerg case FK_NonConstLValueReferenceBindingToTemporary: 9122 1.1 joerg if (isa<InitListExpr>(Args[0])) { 9123 1.1 joerg S.Diag(Kind.getLocation(), 9124 1.1 joerg diag::err_lvalue_reference_bind_to_initlist) 9125 1.1 joerg << DestType.getNonReferenceType().isVolatileQualified() 9126 1.1 joerg << DestType.getNonReferenceType() 9127 1.1 joerg << Args[0]->getSourceRange(); 9128 1.1 joerg break; 9129 1.1 joerg } 9130 1.1 joerg LLVM_FALLTHROUGH; 9131 1.1 joerg 9132 1.1 joerg case FK_NonConstLValueReferenceBindingToUnrelated: 9133 1.1 joerg S.Diag(Kind.getLocation(), 9134 1.1 joerg Failure == FK_NonConstLValueReferenceBindingToTemporary 9135 1.1 joerg ? diag::err_lvalue_reference_bind_to_temporary 9136 1.1 joerg : diag::err_lvalue_reference_bind_to_unrelated) 9137 1.1 joerg << DestType.getNonReferenceType().isVolatileQualified() 9138 1.1 joerg << DestType.getNonReferenceType() 9139 1.1 joerg << OnlyArg->getType() 9140 1.1 joerg << Args[0]->getSourceRange(); 9141 1.1 joerg break; 9142 1.1 joerg 9143 1.1 joerg case FK_NonConstLValueReferenceBindingToBitfield: { 9144 1.1 joerg // We don't necessarily have an unambiguous source bit-field. 9145 1.1 joerg FieldDecl *BitField = Args[0]->getSourceBitField(); 9146 1.1 joerg S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) 9147 1.1 joerg << DestType.isVolatileQualified() 9148 1.1 joerg << (BitField ? BitField->getDeclName() : DeclarationName()) 9149 1.1 joerg << (BitField != nullptr) 9150 1.1 joerg << Args[0]->getSourceRange(); 9151 1.1 joerg if (BitField) 9152 1.1 joerg S.Diag(BitField->getLocation(), diag::note_bitfield_decl); 9153 1.1 joerg break; 9154 1.1 joerg } 9155 1.1 joerg 9156 1.1 joerg case FK_NonConstLValueReferenceBindingToVectorElement: 9157 1.1 joerg S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element) 9158 1.1 joerg << DestType.isVolatileQualified() 9159 1.1 joerg << Args[0]->getSourceRange(); 9160 1.1 joerg break; 9161 1.1 joerg 9162 1.1.1.2 joerg case FK_NonConstLValueReferenceBindingToMatrixElement: 9163 1.1.1.2 joerg S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element) 9164 1.1.1.2 joerg << DestType.isVolatileQualified() << Args[0]->getSourceRange(); 9165 1.1.1.2 joerg break; 9166 1.1.1.2 joerg 9167 1.1 joerg case FK_RValueReferenceBindingToLValue: 9168 1.1 joerg S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) 9169 1.1 joerg << DestType.getNonReferenceType() << OnlyArg->getType() 9170 1.1 joerg << Args[0]->getSourceRange(); 9171 1.1 joerg break; 9172 1.1 joerg 9173 1.1 joerg case FK_ReferenceAddrspaceMismatchTemporary: 9174 1.1 joerg S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace) 9175 1.1 joerg << DestType << Args[0]->getSourceRange(); 9176 1.1 joerg break; 9177 1.1 joerg 9178 1.1 joerg case FK_ReferenceInitDropsQualifiers: { 9179 1.1 joerg QualType SourceType = OnlyArg->getType(); 9180 1.1 joerg QualType NonRefType = DestType.getNonReferenceType(); 9181 1.1 joerg Qualifiers DroppedQualifiers = 9182 1.1 joerg SourceType.getQualifiers() - NonRefType.getQualifiers(); 9183 1.1 joerg 9184 1.1 joerg if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf( 9185 1.1 joerg SourceType.getQualifiers())) 9186 1.1 joerg S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 9187 1.1 joerg << NonRefType << SourceType << 1 /*addr space*/ 9188 1.1 joerg << Args[0]->getSourceRange(); 9189 1.1.1.2 joerg else if (DroppedQualifiers.hasQualifiers()) 9190 1.1 joerg S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 9191 1.1 joerg << NonRefType << SourceType << 0 /*cv quals*/ 9192 1.1 joerg << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers()) 9193 1.1 joerg << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange(); 9194 1.1.1.2 joerg else 9195 1.1.1.2 joerg // FIXME: Consider decomposing the type and explaining which qualifiers 9196 1.1.1.2 joerg // were dropped where, or on which level a 'const' is missing, etc. 9197 1.1.1.2 joerg S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 9198 1.1.1.2 joerg << NonRefType << SourceType << 2 /*incompatible quals*/ 9199 1.1.1.2 joerg << Args[0]->getSourceRange(); 9200 1.1 joerg break; 9201 1.1 joerg } 9202 1.1 joerg 9203 1.1 joerg case FK_ReferenceInitFailed: 9204 1.1 joerg S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) 9205 1.1 joerg << DestType.getNonReferenceType() 9206 1.1 joerg << DestType.getNonReferenceType()->isIncompleteType() 9207 1.1 joerg << OnlyArg->isLValue() 9208 1.1 joerg << OnlyArg->getType() 9209 1.1 joerg << Args[0]->getSourceRange(); 9210 1.1 joerg emitBadConversionNotes(S, Entity, Args[0]); 9211 1.1 joerg break; 9212 1.1 joerg 9213 1.1 joerg case FK_ConversionFailed: { 9214 1.1 joerg QualType FromType = OnlyArg->getType(); 9215 1.1 joerg PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed) 9216 1.1 joerg << (int)Entity.getKind() 9217 1.1 joerg << DestType 9218 1.1 joerg << OnlyArg->isLValue() 9219 1.1 joerg << FromType 9220 1.1 joerg << Args[0]->getSourceRange(); 9221 1.1 joerg S.HandleFunctionTypeMismatch(PDiag, FromType, DestType); 9222 1.1 joerg S.Diag(Kind.getLocation(), PDiag); 9223 1.1 joerg emitBadConversionNotes(S, Entity, Args[0]); 9224 1.1 joerg break; 9225 1.1 joerg } 9226 1.1 joerg 9227 1.1 joerg case FK_ConversionFromPropertyFailed: 9228 1.1 joerg // No-op. This error has already been reported. 9229 1.1 joerg break; 9230 1.1 joerg 9231 1.1 joerg case FK_TooManyInitsForScalar: { 9232 1.1 joerg SourceRange R; 9233 1.1 joerg 9234 1.1 joerg auto *InitList = dyn_cast<InitListExpr>(Args[0]); 9235 1.1 joerg if (InitList && InitList->getNumInits() >= 1) { 9236 1.1 joerg R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc()); 9237 1.1 joerg } else { 9238 1.1 joerg assert(Args.size() > 1 && "Expected multiple initializers!"); 9239 1.1 joerg R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc()); 9240 1.1 joerg } 9241 1.1 joerg 9242 1.1 joerg R.setBegin(S.getLocForEndOfToken(R.getBegin())); 9243 1.1 joerg if (Kind.isCStyleOrFunctionalCast()) 9244 1.1 joerg S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg) 9245 1.1 joerg << R; 9246 1.1 joerg else 9247 1.1 joerg S.Diag(Kind.getLocation(), diag::err_excess_initializers) 9248 1.1 joerg << /*scalar=*/2 << R; 9249 1.1 joerg break; 9250 1.1 joerg } 9251 1.1 joerg 9252 1.1 joerg case FK_ParenthesizedListInitForScalar: 9253 1.1 joerg S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) 9254 1.1 joerg << 0 << Entity.getType() << Args[0]->getSourceRange(); 9255 1.1 joerg break; 9256 1.1 joerg 9257 1.1 joerg case FK_ReferenceBindingToInitList: 9258 1.1 joerg S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) 9259 1.1 joerg << DestType.getNonReferenceType() << Args[0]->getSourceRange(); 9260 1.1 joerg break; 9261 1.1 joerg 9262 1.1 joerg case FK_InitListBadDestinationType: 9263 1.1 joerg S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) 9264 1.1 joerg << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); 9265 1.1 joerg break; 9266 1.1 joerg 9267 1.1 joerg case FK_ListConstructorOverloadFailed: 9268 1.1 joerg case FK_ConstructorOverloadFailed: { 9269 1.1 joerg SourceRange ArgsRange; 9270 1.1 joerg if (Args.size()) 9271 1.1 joerg ArgsRange = 9272 1.1 joerg SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); 9273 1.1 joerg 9274 1.1 joerg if (Failure == FK_ListConstructorOverloadFailed) { 9275 1.1 joerg assert(Args.size() == 1 && 9276 1.1 joerg "List construction from other than 1 argument."); 9277 1.1 joerg InitListExpr *InitList = cast<InitListExpr>(Args[0]); 9278 1.1 joerg Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 9279 1.1 joerg } 9280 1.1 joerg 9281 1.1 joerg // FIXME: Using "DestType" for the entity we're printing is probably 9282 1.1 joerg // bad. 9283 1.1 joerg switch (FailedOverloadResult) { 9284 1.1 joerg case OR_Ambiguous: 9285 1.1 joerg FailedCandidateSet.NoteCandidates( 9286 1.1 joerg PartialDiagnosticAt(Kind.getLocation(), 9287 1.1 joerg S.PDiag(diag::err_ovl_ambiguous_init) 9288 1.1 joerg << DestType << ArgsRange), 9289 1.1 joerg S, OCD_AmbiguousCandidates, Args); 9290 1.1 joerg break; 9291 1.1 joerg 9292 1.1 joerg case OR_No_Viable_Function: 9293 1.1 joerg if (Kind.getKind() == InitializationKind::IK_Default && 9294 1.1 joerg (Entity.getKind() == InitializedEntity::EK_Base || 9295 1.1 joerg Entity.getKind() == InitializedEntity::EK_Member) && 9296 1.1 joerg isa<CXXConstructorDecl>(S.CurContext)) { 9297 1.1 joerg // This is implicit default initialization of a member or 9298 1.1 joerg // base within a constructor. If no viable function was 9299 1.1 joerg // found, notify the user that they need to explicitly 9300 1.1 joerg // initialize this base/member. 9301 1.1 joerg CXXConstructorDecl *Constructor 9302 1.1 joerg = cast<CXXConstructorDecl>(S.CurContext); 9303 1.1 joerg const CXXRecordDecl *InheritedFrom = nullptr; 9304 1.1 joerg if (auto Inherited = Constructor->getInheritedConstructor()) 9305 1.1 joerg InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass(); 9306 1.1 joerg if (Entity.getKind() == InitializedEntity::EK_Base) { 9307 1.1 joerg S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 9308 1.1 joerg << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) 9309 1.1 joerg << S.Context.getTypeDeclType(Constructor->getParent()) 9310 1.1 joerg << /*base=*/0 9311 1.1 joerg << Entity.getType() 9312 1.1 joerg << InheritedFrom; 9313 1.1 joerg 9314 1.1 joerg RecordDecl *BaseDecl 9315 1.1 joerg = Entity.getBaseSpecifier()->getType()->castAs<RecordType>() 9316 1.1 joerg ->getDecl(); 9317 1.1 joerg S.Diag(BaseDecl->getLocation(), diag::note_previous_decl) 9318 1.1 joerg << S.Context.getTagDeclType(BaseDecl); 9319 1.1 joerg } else { 9320 1.1 joerg S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 9321 1.1 joerg << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) 9322 1.1 joerg << S.Context.getTypeDeclType(Constructor->getParent()) 9323 1.1 joerg << /*member=*/1 9324 1.1 joerg << Entity.getName() 9325 1.1 joerg << InheritedFrom; 9326 1.1 joerg S.Diag(Entity.getDecl()->getLocation(), 9327 1.1 joerg diag::note_member_declared_at); 9328 1.1 joerg 9329 1.1 joerg if (const RecordType *Record 9330 1.1 joerg = Entity.getType()->getAs<RecordType>()) 9331 1.1 joerg S.Diag(Record->getDecl()->getLocation(), 9332 1.1 joerg diag::note_previous_decl) 9333 1.1 joerg << S.Context.getTagDeclType(Record->getDecl()); 9334 1.1 joerg } 9335 1.1 joerg break; 9336 1.1 joerg } 9337 1.1 joerg 9338 1.1 joerg FailedCandidateSet.NoteCandidates( 9339 1.1 joerg PartialDiagnosticAt( 9340 1.1 joerg Kind.getLocation(), 9341 1.1 joerg S.PDiag(diag::err_ovl_no_viable_function_in_init) 9342 1.1 joerg << DestType << ArgsRange), 9343 1.1 joerg S, OCD_AllCandidates, Args); 9344 1.1 joerg break; 9345 1.1 joerg 9346 1.1 joerg case OR_Deleted: { 9347 1.1 joerg OverloadCandidateSet::iterator Best; 9348 1.1 joerg OverloadingResult Ovl 9349 1.1 joerg = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 9350 1.1 joerg if (Ovl != OR_Deleted) { 9351 1.1 joerg S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 9352 1.1 joerg << DestType << ArgsRange; 9353 1.1 joerg llvm_unreachable("Inconsistent overload resolution?"); 9354 1.1 joerg break; 9355 1.1 joerg } 9356 1.1 joerg 9357 1.1 joerg // If this is a defaulted or implicitly-declared function, then 9358 1.1 joerg // it was implicitly deleted. Make it clear that the deletion was 9359 1.1 joerg // implicit. 9360 1.1 joerg if (S.isImplicitlyDeleted(Best->Function)) 9361 1.1 joerg S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init) 9362 1.1 joerg << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)) 9363 1.1 joerg << DestType << ArgsRange; 9364 1.1 joerg else 9365 1.1 joerg S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 9366 1.1 joerg << DestType << ArgsRange; 9367 1.1 joerg 9368 1.1 joerg S.NoteDeletedFunction(Best->Function); 9369 1.1 joerg break; 9370 1.1 joerg } 9371 1.1 joerg 9372 1.1 joerg case OR_Success: 9373 1.1 joerg llvm_unreachable("Conversion did not fail!"); 9374 1.1 joerg } 9375 1.1 joerg } 9376 1.1 joerg break; 9377 1.1 joerg 9378 1.1 joerg case FK_DefaultInitOfConst: 9379 1.1 joerg if (Entity.getKind() == InitializedEntity::EK_Member && 9380 1.1 joerg isa<CXXConstructorDecl>(S.CurContext)) { 9381 1.1 joerg // This is implicit default-initialization of a const member in 9382 1.1 joerg // a constructor. Complain that it needs to be explicitly 9383 1.1 joerg // initialized. 9384 1.1 joerg CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext); 9385 1.1 joerg S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor) 9386 1.1 joerg << (Constructor->getInheritedConstructor() ? 2 : 9387 1.1 joerg Constructor->isImplicit() ? 1 : 0) 9388 1.1 joerg << S.Context.getTypeDeclType(Constructor->getParent()) 9389 1.1 joerg << /*const=*/1 9390 1.1 joerg << Entity.getName(); 9391 1.1 joerg S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl) 9392 1.1 joerg << Entity.getName(); 9393 1.1 joerg } else { 9394 1.1 joerg S.Diag(Kind.getLocation(), diag::err_default_init_const) 9395 1.1 joerg << DestType << (bool)DestType->getAs<RecordType>(); 9396 1.1 joerg } 9397 1.1 joerg break; 9398 1.1 joerg 9399 1.1 joerg case FK_Incomplete: 9400 1.1 joerg S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType, 9401 1.1 joerg diag::err_init_incomplete_type); 9402 1.1 joerg break; 9403 1.1 joerg 9404 1.1 joerg case FK_ListInitializationFailed: { 9405 1.1 joerg // Run the init list checker again to emit diagnostics. 9406 1.1 joerg InitListExpr *InitList = cast<InitListExpr>(Args[0]); 9407 1.1 joerg diagnoseListInit(S, Entity, InitList); 9408 1.1 joerg break; 9409 1.1 joerg } 9410 1.1 joerg 9411 1.1 joerg case FK_PlaceholderType: { 9412 1.1 joerg // FIXME: Already diagnosed! 9413 1.1 joerg break; 9414 1.1 joerg } 9415 1.1 joerg 9416 1.1 joerg case FK_ExplicitConstructor: { 9417 1.1 joerg S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor) 9418 1.1 joerg << Args[0]->getSourceRange(); 9419 1.1 joerg OverloadCandidateSet::iterator Best; 9420 1.1 joerg OverloadingResult Ovl 9421 1.1 joerg = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 9422 1.1 joerg (void)Ovl; 9423 1.1 joerg assert(Ovl == OR_Success && "Inconsistent overload resolution"); 9424 1.1 joerg CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 9425 1.1 joerg S.Diag(CtorDecl->getLocation(), 9426 1.1 joerg diag::note_explicit_ctor_deduction_guide_here) << false; 9427 1.1 joerg break; 9428 1.1 joerg } 9429 1.1 joerg } 9430 1.1 joerg 9431 1.1 joerg PrintInitLocationNote(S, Entity); 9432 1.1 joerg return true; 9433 1.1 joerg } 9434 1.1 joerg 9435 1.1 joerg void InitializationSequence::dump(raw_ostream &OS) const { 9436 1.1 joerg switch (SequenceKind) { 9437 1.1 joerg case FailedSequence: { 9438 1.1 joerg OS << "Failed sequence: "; 9439 1.1 joerg switch (Failure) { 9440 1.1 joerg case FK_TooManyInitsForReference: 9441 1.1 joerg OS << "too many initializers for reference"; 9442 1.1 joerg break; 9443 1.1 joerg 9444 1.1 joerg case FK_ParenthesizedListInitForReference: 9445 1.1 joerg OS << "parenthesized list init for reference"; 9446 1.1 joerg break; 9447 1.1 joerg 9448 1.1 joerg case FK_ArrayNeedsInitList: 9449 1.1 joerg OS << "array requires initializer list"; 9450 1.1 joerg break; 9451 1.1 joerg 9452 1.1 joerg case FK_AddressOfUnaddressableFunction: 9453 1.1 joerg OS << "address of unaddressable function was taken"; 9454 1.1 joerg break; 9455 1.1 joerg 9456 1.1 joerg case FK_ArrayNeedsInitListOrStringLiteral: 9457 1.1 joerg OS << "array requires initializer list or string literal"; 9458 1.1 joerg break; 9459 1.1 joerg 9460 1.1 joerg case FK_ArrayNeedsInitListOrWideStringLiteral: 9461 1.1 joerg OS << "array requires initializer list or wide string literal"; 9462 1.1 joerg break; 9463 1.1 joerg 9464 1.1 joerg case FK_NarrowStringIntoWideCharArray: 9465 1.1 joerg OS << "narrow string into wide char array"; 9466 1.1 joerg break; 9467 1.1 joerg 9468 1.1 joerg case FK_WideStringIntoCharArray: 9469 1.1 joerg OS << "wide string into char array"; 9470 1.1 joerg break; 9471 1.1 joerg 9472 1.1 joerg case FK_IncompatWideStringIntoWideChar: 9473 1.1 joerg OS << "incompatible wide string into wide char array"; 9474 1.1 joerg break; 9475 1.1 joerg 9476 1.1 joerg case FK_PlainStringIntoUTF8Char: 9477 1.1 joerg OS << "plain string literal into char8_t array"; 9478 1.1 joerg break; 9479 1.1 joerg 9480 1.1 joerg case FK_UTF8StringIntoPlainChar: 9481 1.1 joerg OS << "u8 string literal into char array"; 9482 1.1 joerg break; 9483 1.1 joerg 9484 1.1 joerg case FK_ArrayTypeMismatch: 9485 1.1 joerg OS << "array type mismatch"; 9486 1.1 joerg break; 9487 1.1 joerg 9488 1.1 joerg case FK_NonConstantArrayInit: 9489 1.1 joerg OS << "non-constant array initializer"; 9490 1.1 joerg break; 9491 1.1 joerg 9492 1.1 joerg case FK_AddressOfOverloadFailed: 9493 1.1 joerg OS << "address of overloaded function failed"; 9494 1.1 joerg break; 9495 1.1 joerg 9496 1.1 joerg case FK_ReferenceInitOverloadFailed: 9497 1.1 joerg OS << "overload resolution for reference initialization failed"; 9498 1.1 joerg break; 9499 1.1 joerg 9500 1.1 joerg case FK_NonConstLValueReferenceBindingToTemporary: 9501 1.1 joerg OS << "non-const lvalue reference bound to temporary"; 9502 1.1 joerg break; 9503 1.1 joerg 9504 1.1 joerg case FK_NonConstLValueReferenceBindingToBitfield: 9505 1.1 joerg OS << "non-const lvalue reference bound to bit-field"; 9506 1.1 joerg break; 9507 1.1 joerg 9508 1.1 joerg case FK_NonConstLValueReferenceBindingToVectorElement: 9509 1.1 joerg OS << "non-const lvalue reference bound to vector element"; 9510 1.1 joerg break; 9511 1.1 joerg 9512 1.1.1.2 joerg case FK_NonConstLValueReferenceBindingToMatrixElement: 9513 1.1.1.2 joerg OS << "non-const lvalue reference bound to matrix element"; 9514 1.1.1.2 joerg break; 9515 1.1.1.2 joerg 9516 1.1 joerg case FK_NonConstLValueReferenceBindingToUnrelated: 9517 1.1 joerg OS << "non-const lvalue reference bound to unrelated type"; 9518 1.1 joerg break; 9519 1.1 joerg 9520 1.1 joerg case FK_RValueReferenceBindingToLValue: 9521 1.1 joerg OS << "rvalue reference bound to an lvalue"; 9522 1.1 joerg break; 9523 1.1 joerg 9524 1.1 joerg case FK_ReferenceInitDropsQualifiers: 9525 1.1 joerg OS << "reference initialization drops qualifiers"; 9526 1.1 joerg break; 9527 1.1 joerg 9528 1.1 joerg case FK_ReferenceAddrspaceMismatchTemporary: 9529 1.1 joerg OS << "reference with mismatching address space bound to temporary"; 9530 1.1 joerg break; 9531 1.1 joerg 9532 1.1 joerg case FK_ReferenceInitFailed: 9533 1.1 joerg OS << "reference initialization failed"; 9534 1.1 joerg break; 9535 1.1 joerg 9536 1.1 joerg case FK_ConversionFailed: 9537 1.1 joerg OS << "conversion failed"; 9538 1.1 joerg break; 9539 1.1 joerg 9540 1.1 joerg case FK_ConversionFromPropertyFailed: 9541 1.1 joerg OS << "conversion from property failed"; 9542 1.1 joerg break; 9543 1.1 joerg 9544 1.1 joerg case FK_TooManyInitsForScalar: 9545 1.1 joerg OS << "too many initializers for scalar"; 9546 1.1 joerg break; 9547 1.1 joerg 9548 1.1 joerg case FK_ParenthesizedListInitForScalar: 9549 1.1 joerg OS << "parenthesized list init for reference"; 9550 1.1 joerg break; 9551 1.1 joerg 9552 1.1 joerg case FK_ReferenceBindingToInitList: 9553 1.1 joerg OS << "referencing binding to initializer list"; 9554 1.1 joerg break; 9555 1.1 joerg 9556 1.1 joerg case FK_InitListBadDestinationType: 9557 1.1 joerg OS << "initializer list for non-aggregate, non-scalar type"; 9558 1.1 joerg break; 9559 1.1 joerg 9560 1.1 joerg case FK_UserConversionOverloadFailed: 9561 1.1 joerg OS << "overloading failed for user-defined conversion"; 9562 1.1 joerg break; 9563 1.1 joerg 9564 1.1 joerg case FK_ConstructorOverloadFailed: 9565 1.1 joerg OS << "constructor overloading failed"; 9566 1.1 joerg break; 9567 1.1 joerg 9568 1.1 joerg case FK_DefaultInitOfConst: 9569 1.1 joerg OS << "default initialization of a const variable"; 9570 1.1 joerg break; 9571 1.1 joerg 9572 1.1 joerg case FK_Incomplete: 9573 1.1 joerg OS << "initialization of incomplete type"; 9574 1.1 joerg break; 9575 1.1 joerg 9576 1.1 joerg case FK_ListInitializationFailed: 9577 1.1 joerg OS << "list initialization checker failure"; 9578 1.1 joerg break; 9579 1.1 joerg 9580 1.1 joerg case FK_VariableLengthArrayHasInitializer: 9581 1.1 joerg OS << "variable length array has an initializer"; 9582 1.1 joerg break; 9583 1.1 joerg 9584 1.1 joerg case FK_PlaceholderType: 9585 1.1 joerg OS << "initializer expression isn't contextually valid"; 9586 1.1 joerg break; 9587 1.1 joerg 9588 1.1 joerg case FK_ListConstructorOverloadFailed: 9589 1.1 joerg OS << "list constructor overloading failed"; 9590 1.1 joerg break; 9591 1.1 joerg 9592 1.1 joerg case FK_ExplicitConstructor: 9593 1.1 joerg OS << "list copy initialization chose explicit constructor"; 9594 1.1 joerg break; 9595 1.1 joerg } 9596 1.1 joerg OS << '\n'; 9597 1.1 joerg return; 9598 1.1 joerg } 9599 1.1 joerg 9600 1.1 joerg case DependentSequence: 9601 1.1 joerg OS << "Dependent sequence\n"; 9602 1.1 joerg return; 9603 1.1 joerg 9604 1.1 joerg case NormalSequence: 9605 1.1 joerg OS << "Normal sequence: "; 9606 1.1 joerg break; 9607 1.1 joerg } 9608 1.1 joerg 9609 1.1 joerg for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { 9610 1.1 joerg if (S != step_begin()) { 9611 1.1 joerg OS << " -> "; 9612 1.1 joerg } 9613 1.1 joerg 9614 1.1 joerg switch (S->Kind) { 9615 1.1 joerg case SK_ResolveAddressOfOverloadedFunction: 9616 1.1 joerg OS << "resolve address of overloaded function"; 9617 1.1 joerg break; 9618 1.1 joerg 9619 1.1 joerg case SK_CastDerivedToBaseRValue: 9620 1.1 joerg OS << "derived-to-base (rvalue)"; 9621 1.1 joerg break; 9622 1.1 joerg 9623 1.1 joerg case SK_CastDerivedToBaseXValue: 9624 1.1 joerg OS << "derived-to-base (xvalue)"; 9625 1.1 joerg break; 9626 1.1 joerg 9627 1.1 joerg case SK_CastDerivedToBaseLValue: 9628 1.1 joerg OS << "derived-to-base (lvalue)"; 9629 1.1 joerg break; 9630 1.1 joerg 9631 1.1 joerg case SK_BindReference: 9632 1.1 joerg OS << "bind reference to lvalue"; 9633 1.1 joerg break; 9634 1.1 joerg 9635 1.1 joerg case SK_BindReferenceToTemporary: 9636 1.1 joerg OS << "bind reference to a temporary"; 9637 1.1 joerg break; 9638 1.1 joerg 9639 1.1 joerg case SK_FinalCopy: 9640 1.1 joerg OS << "final copy in class direct-initialization"; 9641 1.1 joerg break; 9642 1.1 joerg 9643 1.1 joerg case SK_ExtraneousCopyToTemporary: 9644 1.1 joerg OS << "extraneous C++03 copy to temporary"; 9645 1.1 joerg break; 9646 1.1 joerg 9647 1.1 joerg case SK_UserConversion: 9648 1.1 joerg OS << "user-defined conversion via " << *S->Function.Function; 9649 1.1 joerg break; 9650 1.1 joerg 9651 1.1 joerg case SK_QualificationConversionRValue: 9652 1.1 joerg OS << "qualification conversion (rvalue)"; 9653 1.1 joerg break; 9654 1.1 joerg 9655 1.1 joerg case SK_QualificationConversionXValue: 9656 1.1 joerg OS << "qualification conversion (xvalue)"; 9657 1.1 joerg break; 9658 1.1 joerg 9659 1.1 joerg case SK_QualificationConversionLValue: 9660 1.1 joerg OS << "qualification conversion (lvalue)"; 9661 1.1 joerg break; 9662 1.1 joerg 9663 1.1.1.2 joerg case SK_FunctionReferenceConversion: 9664 1.1.1.2 joerg OS << "function reference conversion"; 9665 1.1.1.2 joerg break; 9666 1.1.1.2 joerg 9667 1.1 joerg case SK_AtomicConversion: 9668 1.1 joerg OS << "non-atomic-to-atomic conversion"; 9669 1.1 joerg break; 9670 1.1 joerg 9671 1.1 joerg case SK_ConversionSequence: 9672 1.1 joerg OS << "implicit conversion sequence ("; 9673 1.1 joerg S->ICS->dump(); // FIXME: use OS 9674 1.1 joerg OS << ")"; 9675 1.1 joerg break; 9676 1.1 joerg 9677 1.1 joerg case SK_ConversionSequenceNoNarrowing: 9678 1.1 joerg OS << "implicit conversion sequence with narrowing prohibited ("; 9679 1.1 joerg S->ICS->dump(); // FIXME: use OS 9680 1.1 joerg OS << ")"; 9681 1.1 joerg break; 9682 1.1 joerg 9683 1.1 joerg case SK_ListInitialization: 9684 1.1 joerg OS << "list aggregate initialization"; 9685 1.1 joerg break; 9686 1.1 joerg 9687 1.1 joerg case SK_UnwrapInitList: 9688 1.1 joerg OS << "unwrap reference initializer list"; 9689 1.1 joerg break; 9690 1.1 joerg 9691 1.1 joerg case SK_RewrapInitList: 9692 1.1 joerg OS << "rewrap reference initializer list"; 9693 1.1 joerg break; 9694 1.1 joerg 9695 1.1 joerg case SK_ConstructorInitialization: 9696 1.1 joerg OS << "constructor initialization"; 9697 1.1 joerg break; 9698 1.1 joerg 9699 1.1 joerg case SK_ConstructorInitializationFromList: 9700 1.1 joerg OS << "list initialization via constructor"; 9701 1.1 joerg break; 9702 1.1 joerg 9703 1.1 joerg case SK_ZeroInitialization: 9704 1.1 joerg OS << "zero initialization"; 9705 1.1 joerg break; 9706 1.1 joerg 9707 1.1 joerg case SK_CAssignment: 9708 1.1 joerg OS << "C assignment"; 9709 1.1 joerg break; 9710 1.1 joerg 9711 1.1 joerg case SK_StringInit: 9712 1.1 joerg OS << "string initialization"; 9713 1.1 joerg break; 9714 1.1 joerg 9715 1.1 joerg case SK_ObjCObjectConversion: 9716 1.1 joerg OS << "Objective-C object conversion"; 9717 1.1 joerg break; 9718 1.1 joerg 9719 1.1 joerg case SK_ArrayLoopIndex: 9720 1.1 joerg OS << "indexing for array initialization loop"; 9721 1.1 joerg break; 9722 1.1 joerg 9723 1.1 joerg case SK_ArrayLoopInit: 9724 1.1 joerg OS << "array initialization loop"; 9725 1.1 joerg break; 9726 1.1 joerg 9727 1.1 joerg case SK_ArrayInit: 9728 1.1 joerg OS << "array initialization"; 9729 1.1 joerg break; 9730 1.1 joerg 9731 1.1 joerg case SK_GNUArrayInit: 9732 1.1 joerg OS << "array initialization (GNU extension)"; 9733 1.1 joerg break; 9734 1.1 joerg 9735 1.1 joerg case SK_ParenthesizedArrayInit: 9736 1.1 joerg OS << "parenthesized array initialization"; 9737 1.1 joerg break; 9738 1.1 joerg 9739 1.1 joerg case SK_PassByIndirectCopyRestore: 9740 1.1 joerg OS << "pass by indirect copy and restore"; 9741 1.1 joerg break; 9742 1.1 joerg 9743 1.1 joerg case SK_PassByIndirectRestore: 9744 1.1 joerg OS << "pass by indirect restore"; 9745 1.1 joerg break; 9746 1.1 joerg 9747 1.1 joerg case SK_ProduceObjCObject: 9748 1.1 joerg OS << "Objective-C object retension"; 9749 1.1 joerg break; 9750 1.1 joerg 9751 1.1 joerg case SK_StdInitializerList: 9752 1.1 joerg OS << "std::initializer_list from initializer list"; 9753 1.1 joerg break; 9754 1.1 joerg 9755 1.1 joerg case SK_StdInitializerListConstructorCall: 9756 1.1 joerg OS << "list initialization from std::initializer_list"; 9757 1.1 joerg break; 9758 1.1 joerg 9759 1.1 joerg case SK_OCLSamplerInit: 9760 1.1 joerg OS << "OpenCL sampler_t from integer constant"; 9761 1.1 joerg break; 9762 1.1 joerg 9763 1.1 joerg case SK_OCLZeroOpaqueType: 9764 1.1 joerg OS << "OpenCL opaque type from zero"; 9765 1.1 joerg break; 9766 1.1 joerg } 9767 1.1 joerg 9768 1.1 joerg OS << " [" << S->Type.getAsString() << ']'; 9769 1.1 joerg } 9770 1.1 joerg 9771 1.1 joerg OS << '\n'; 9772 1.1 joerg } 9773 1.1 joerg 9774 1.1 joerg void InitializationSequence::dump() const { 9775 1.1 joerg dump(llvm::errs()); 9776 1.1 joerg } 9777 1.1 joerg 9778 1.1 joerg static bool NarrowingErrs(const LangOptions &L) { 9779 1.1 joerg return L.CPlusPlus11 && 9780 1.1 joerg (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)); 9781 1.1 joerg } 9782 1.1 joerg 9783 1.1 joerg static void DiagnoseNarrowingInInitList(Sema &S, 9784 1.1 joerg const ImplicitConversionSequence &ICS, 9785 1.1 joerg QualType PreNarrowingType, 9786 1.1 joerg QualType EntityType, 9787 1.1 joerg const Expr *PostInit) { 9788 1.1 joerg const StandardConversionSequence *SCS = nullptr; 9789 1.1 joerg switch (ICS.getKind()) { 9790 1.1 joerg case ImplicitConversionSequence::StandardConversion: 9791 1.1 joerg SCS = &ICS.Standard; 9792 1.1 joerg break; 9793 1.1 joerg case ImplicitConversionSequence::UserDefinedConversion: 9794 1.1 joerg SCS = &ICS.UserDefined.After; 9795 1.1 joerg break; 9796 1.1 joerg case ImplicitConversionSequence::AmbiguousConversion: 9797 1.1 joerg case ImplicitConversionSequence::EllipsisConversion: 9798 1.1 joerg case ImplicitConversionSequence::BadConversion: 9799 1.1 joerg return; 9800 1.1 joerg } 9801 1.1 joerg 9802 1.1 joerg // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion. 9803 1.1 joerg APValue ConstantValue; 9804 1.1 joerg QualType ConstantType; 9805 1.1 joerg switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue, 9806 1.1 joerg ConstantType)) { 9807 1.1 joerg case NK_Not_Narrowing: 9808 1.1 joerg case NK_Dependent_Narrowing: 9809 1.1 joerg // No narrowing occurred. 9810 1.1 joerg return; 9811 1.1 joerg 9812 1.1 joerg case NK_Type_Narrowing: 9813 1.1 joerg // This was a floating-to-integer conversion, which is always considered a 9814 1.1 joerg // narrowing conversion even if the value is a constant and can be 9815 1.1 joerg // represented exactly as an integer. 9816 1.1 joerg S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts()) 9817 1.1 joerg ? diag::ext_init_list_type_narrowing 9818 1.1 joerg : diag::warn_init_list_type_narrowing) 9819 1.1 joerg << PostInit->getSourceRange() 9820 1.1 joerg << PreNarrowingType.getLocalUnqualifiedType() 9821 1.1 joerg << EntityType.getLocalUnqualifiedType(); 9822 1.1 joerg break; 9823 1.1 joerg 9824 1.1 joerg case NK_Constant_Narrowing: 9825 1.1 joerg // A constant value was narrowed. 9826 1.1 joerg S.Diag(PostInit->getBeginLoc(), 9827 1.1 joerg NarrowingErrs(S.getLangOpts()) 9828 1.1 joerg ? diag::ext_init_list_constant_narrowing 9829 1.1 joerg : diag::warn_init_list_constant_narrowing) 9830 1.1 joerg << PostInit->getSourceRange() 9831 1.1 joerg << ConstantValue.getAsString(S.getASTContext(), ConstantType) 9832 1.1 joerg << EntityType.getLocalUnqualifiedType(); 9833 1.1 joerg break; 9834 1.1 joerg 9835 1.1 joerg case NK_Variable_Narrowing: 9836 1.1 joerg // A variable's value may have been narrowed. 9837 1.1 joerg S.Diag(PostInit->getBeginLoc(), 9838 1.1 joerg NarrowingErrs(S.getLangOpts()) 9839 1.1 joerg ? diag::ext_init_list_variable_narrowing 9840 1.1 joerg : diag::warn_init_list_variable_narrowing) 9841 1.1 joerg << PostInit->getSourceRange() 9842 1.1 joerg << PreNarrowingType.getLocalUnqualifiedType() 9843 1.1 joerg << EntityType.getLocalUnqualifiedType(); 9844 1.1 joerg break; 9845 1.1 joerg } 9846 1.1 joerg 9847 1.1 joerg SmallString<128> StaticCast; 9848 1.1 joerg llvm::raw_svector_ostream OS(StaticCast); 9849 1.1 joerg OS << "static_cast<"; 9850 1.1 joerg if (const TypedefType *TT = EntityType->getAs<TypedefType>()) { 9851 1.1 joerg // It's important to use the typedef's name if there is one so that the 9852 1.1 joerg // fixit doesn't break code using types like int64_t. 9853 1.1 joerg // 9854 1.1 joerg // FIXME: This will break if the typedef requires qualification. But 9855 1.1 joerg // getQualifiedNameAsString() includes non-machine-parsable components. 9856 1.1 joerg OS << *TT->getDecl(); 9857 1.1 joerg } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>()) 9858 1.1 joerg OS << BT->getName(S.getLangOpts()); 9859 1.1 joerg else { 9860 1.1 joerg // Oops, we didn't find the actual type of the variable. Don't emit a fixit 9861 1.1 joerg // with a broken cast. 9862 1.1 joerg return; 9863 1.1 joerg } 9864 1.1 joerg OS << ">("; 9865 1.1 joerg S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence) 9866 1.1 joerg << PostInit->getSourceRange() 9867 1.1 joerg << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str()) 9868 1.1 joerg << FixItHint::CreateInsertion( 9869 1.1 joerg S.getLocForEndOfToken(PostInit->getEndLoc()), ")"); 9870 1.1 joerg } 9871 1.1 joerg 9872 1.1 joerg //===----------------------------------------------------------------------===// 9873 1.1 joerg // Initialization helper functions 9874 1.1 joerg //===----------------------------------------------------------------------===// 9875 1.1 joerg bool 9876 1.1 joerg Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, 9877 1.1 joerg ExprResult Init) { 9878 1.1 joerg if (Init.isInvalid()) 9879 1.1 joerg return false; 9880 1.1 joerg 9881 1.1 joerg Expr *InitE = Init.get(); 9882 1.1 joerg assert(InitE && "No initialization expression"); 9883 1.1 joerg 9884 1.1 joerg InitializationKind Kind = 9885 1.1 joerg InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation()); 9886 1.1 joerg InitializationSequence Seq(*this, Entity, Kind, InitE); 9887 1.1 joerg return !Seq.Failed(); 9888 1.1 joerg } 9889 1.1 joerg 9890 1.1 joerg ExprResult 9891 1.1 joerg Sema::PerformCopyInitialization(const InitializedEntity &Entity, 9892 1.1 joerg SourceLocation EqualLoc, 9893 1.1 joerg ExprResult Init, 9894 1.1 joerg bool TopLevelOfInitList, 9895 1.1 joerg bool AllowExplicit) { 9896 1.1 joerg if (Init.isInvalid()) 9897 1.1 joerg return ExprError(); 9898 1.1 joerg 9899 1.1 joerg Expr *InitE = Init.get(); 9900 1.1 joerg assert(InitE && "No initialization expression?"); 9901 1.1 joerg 9902 1.1 joerg if (EqualLoc.isInvalid()) 9903 1.1 joerg EqualLoc = InitE->getBeginLoc(); 9904 1.1 joerg 9905 1.1 joerg InitializationKind Kind = InitializationKind::CreateCopy( 9906 1.1 joerg InitE->getBeginLoc(), EqualLoc, AllowExplicit); 9907 1.1 joerg InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList); 9908 1.1 joerg 9909 1.1 joerg // Prevent infinite recursion when performing parameter copy-initialization. 9910 1.1 joerg const bool ShouldTrackCopy = 9911 1.1 joerg Entity.isParameterKind() && Seq.isConstructorInitialization(); 9912 1.1 joerg if (ShouldTrackCopy) { 9913 1.1 joerg if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) != 9914 1.1 joerg CurrentParameterCopyTypes.end()) { 9915 1.1 joerg Seq.SetOverloadFailure( 9916 1.1 joerg InitializationSequence::FK_ConstructorOverloadFailed, 9917 1.1 joerg OR_No_Viable_Function); 9918 1.1 joerg 9919 1.1 joerg // Try to give a meaningful diagnostic note for the problematic 9920 1.1 joerg // constructor. 9921 1.1 joerg const auto LastStep = Seq.step_end() - 1; 9922 1.1 joerg assert(LastStep->Kind == 9923 1.1 joerg InitializationSequence::SK_ConstructorInitialization); 9924 1.1 joerg const FunctionDecl *Function = LastStep->Function.Function; 9925 1.1 joerg auto Candidate = 9926 1.1 joerg llvm::find_if(Seq.getFailedCandidateSet(), 9927 1.1 joerg [Function](const OverloadCandidate &Candidate) -> bool { 9928 1.1 joerg return Candidate.Viable && 9929 1.1 joerg Candidate.Function == Function && 9930 1.1 joerg Candidate.Conversions.size() > 0; 9931 1.1 joerg }); 9932 1.1 joerg if (Candidate != Seq.getFailedCandidateSet().end() && 9933 1.1 joerg Function->getNumParams() > 0) { 9934 1.1 joerg Candidate->Viable = false; 9935 1.1 joerg Candidate->FailureKind = ovl_fail_bad_conversion; 9936 1.1 joerg Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion, 9937 1.1 joerg InitE, 9938 1.1 joerg Function->getParamDecl(0)->getType()); 9939 1.1 joerg } 9940 1.1 joerg } 9941 1.1 joerg CurrentParameterCopyTypes.push_back(Entity.getType()); 9942 1.1 joerg } 9943 1.1 joerg 9944 1.1 joerg ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE); 9945 1.1 joerg 9946 1.1 joerg if (ShouldTrackCopy) 9947 1.1 joerg CurrentParameterCopyTypes.pop_back(); 9948 1.1 joerg 9949 1.1 joerg return Result; 9950 1.1 joerg } 9951 1.1 joerg 9952 1.1 joerg /// Determine whether RD is, or is derived from, a specialization of CTD. 9953 1.1 joerg static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, 9954 1.1 joerg ClassTemplateDecl *CTD) { 9955 1.1 joerg auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) { 9956 1.1 joerg auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate); 9957 1.1 joerg return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD); 9958 1.1 joerg }; 9959 1.1 joerg return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization)); 9960 1.1 joerg } 9961 1.1 joerg 9962 1.1 joerg QualType Sema::DeduceTemplateSpecializationFromInitializer( 9963 1.1 joerg TypeSourceInfo *TSInfo, const InitializedEntity &Entity, 9964 1.1 joerg const InitializationKind &Kind, MultiExprArg Inits) { 9965 1.1 joerg auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>( 9966 1.1 joerg TSInfo->getType()->getContainedDeducedType()); 9967 1.1 joerg assert(DeducedTST && "not a deduced template specialization type"); 9968 1.1 joerg 9969 1.1 joerg auto TemplateName = DeducedTST->getTemplateName(); 9970 1.1 joerg if (TemplateName.isDependent()) 9971 1.1.1.2 joerg return SubstAutoType(TSInfo->getType(), Context.DependentTy); 9972 1.1 joerg 9973 1.1 joerg // We can only perform deduction for class templates. 9974 1.1 joerg auto *Template = 9975 1.1 joerg dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl()); 9976 1.1 joerg if (!Template) { 9977 1.1 joerg Diag(Kind.getLocation(), 9978 1.1 joerg diag::err_deduced_non_class_template_specialization_type) 9979 1.1 joerg << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName; 9980 1.1 joerg if (auto *TD = TemplateName.getAsTemplateDecl()) 9981 1.1 joerg Diag(TD->getLocation(), diag::note_template_decl_here); 9982 1.1 joerg return QualType(); 9983 1.1 joerg } 9984 1.1 joerg 9985 1.1 joerg // Can't deduce from dependent arguments. 9986 1.1 joerg if (Expr::hasAnyTypeDependentArguments(Inits)) { 9987 1.1 joerg Diag(TSInfo->getTypeLoc().getBeginLoc(), 9988 1.1 joerg diag::warn_cxx14_compat_class_template_argument_deduction) 9989 1.1 joerg << TSInfo->getTypeLoc().getSourceRange() << 0; 9990 1.1.1.2 joerg return SubstAutoType(TSInfo->getType(), Context.DependentTy); 9991 1.1 joerg } 9992 1.1 joerg 9993 1.1 joerg // FIXME: Perform "exact type" matching first, per CWG discussion? 9994 1.1 joerg // Or implement this via an implied 'T(T) -> T' deduction guide? 9995 1.1 joerg 9996 1.1 joerg // FIXME: Do we need/want a std::initializer_list<T> special case? 9997 1.1 joerg 9998 1.1 joerg // Look up deduction guides, including those synthesized from constructors. 9999 1.1 joerg // 10000 1.1 joerg // C++1z [over.match.class.deduct]p1: 10001 1.1 joerg // A set of functions and function templates is formed comprising: 10002 1.1 joerg // - For each constructor of the class template designated by the 10003 1.1 joerg // template-name, a function template [...] 10004 1.1 joerg // - For each deduction-guide, a function or function template [...] 10005 1.1 joerg DeclarationNameInfo NameInfo( 10006 1.1 joerg Context.DeclarationNames.getCXXDeductionGuideName(Template), 10007 1.1 joerg TSInfo->getTypeLoc().getEndLoc()); 10008 1.1 joerg LookupResult Guides(*this, NameInfo, LookupOrdinaryName); 10009 1.1 joerg LookupQualifiedName(Guides, Template->getDeclContext()); 10010 1.1 joerg 10011 1.1 joerg // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't 10012 1.1 joerg // clear on this, but they're not found by name so access does not apply. 10013 1.1 joerg Guides.suppressDiagnostics(); 10014 1.1 joerg 10015 1.1 joerg // Figure out if this is list-initialization. 10016 1.1 joerg InitListExpr *ListInit = 10017 1.1 joerg (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct) 10018 1.1 joerg ? dyn_cast<InitListExpr>(Inits[0]) 10019 1.1 joerg : nullptr; 10020 1.1 joerg 10021 1.1 joerg // C++1z [over.match.class.deduct]p1: 10022 1.1 joerg // Initialization and overload resolution are performed as described in 10023 1.1 joerg // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list] 10024 1.1 joerg // (as appropriate for the type of initialization performed) for an object 10025 1.1 joerg // of a hypothetical class type, where the selected functions and function 10026 1.1 joerg // templates are considered to be the constructors of that class type 10027 1.1 joerg // 10028 1.1 joerg // Since we know we're initializing a class type of a type unrelated to that 10029 1.1 joerg // of the initializer, this reduces to something fairly reasonable. 10030 1.1 joerg OverloadCandidateSet Candidates(Kind.getLocation(), 10031 1.1 joerg OverloadCandidateSet::CSK_Normal); 10032 1.1 joerg OverloadCandidateSet::iterator Best; 10033 1.1 joerg 10034 1.1 joerg bool HasAnyDeductionGuide = false; 10035 1.1 joerg bool AllowExplicit = !Kind.isCopyInit() || ListInit; 10036 1.1 joerg 10037 1.1 joerg auto tryToResolveOverload = 10038 1.1 joerg [&](bool OnlyListConstructors) -> OverloadingResult { 10039 1.1 joerg Candidates.clear(OverloadCandidateSet::CSK_Normal); 10040 1.1 joerg HasAnyDeductionGuide = false; 10041 1.1 joerg 10042 1.1 joerg for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) { 10043 1.1 joerg NamedDecl *D = (*I)->getUnderlyingDecl(); 10044 1.1 joerg if (D->isInvalidDecl()) 10045 1.1 joerg continue; 10046 1.1 joerg 10047 1.1 joerg auto *TD = dyn_cast<FunctionTemplateDecl>(D); 10048 1.1 joerg auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>( 10049 1.1 joerg TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D)); 10050 1.1 joerg if (!GD) 10051 1.1 joerg continue; 10052 1.1 joerg 10053 1.1 joerg if (!GD->isImplicit()) 10054 1.1 joerg HasAnyDeductionGuide = true; 10055 1.1 joerg 10056 1.1 joerg // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class) 10057 1.1 joerg // For copy-initialization, the candidate functions are all the 10058 1.1 joerg // converting constructors (12.3.1) of that class. 10059 1.1 joerg // C++ [over.match.copy]p1: (non-list copy-initialization from class) 10060 1.1 joerg // The converting constructors of T are candidate functions. 10061 1.1 joerg if (!AllowExplicit) { 10062 1.1.1.2 joerg // Overload resolution checks whether the deduction guide is declared 10063 1.1.1.2 joerg // explicit for us. 10064 1.1 joerg 10065 1.1 joerg // When looking for a converting constructor, deduction guides that 10066 1.1 joerg // could never be called with one argument are not interesting to 10067 1.1 joerg // check or note. 10068 1.1 joerg if (GD->getMinRequiredArguments() > 1 || 10069 1.1 joerg (GD->getNumParams() == 0 && !GD->isVariadic())) 10070 1.1 joerg continue; 10071 1.1 joerg } 10072 1.1 joerg 10073 1.1 joerg // C++ [over.match.list]p1.1: (first phase list initialization) 10074 1.1 joerg // Initially, the candidate functions are the initializer-list 10075 1.1 joerg // constructors of the class T 10076 1.1 joerg if (OnlyListConstructors && !isInitListConstructor(GD)) 10077 1.1 joerg continue; 10078 1.1 joerg 10079 1.1 joerg // C++ [over.match.list]p1.2: (second phase list initialization) 10080 1.1 joerg // the candidate functions are all the constructors of the class T 10081 1.1 joerg // C++ [over.match.ctor]p1: (all other cases) 10082 1.1 joerg // the candidate functions are all the constructors of the class of 10083 1.1 joerg // the object being initialized 10084 1.1 joerg 10085 1.1 joerg // C++ [over.best.ics]p4: 10086 1.1 joerg // When [...] the constructor [...] is a candidate by 10087 1.1 joerg // - [over.match.copy] (in all cases) 10088 1.1 joerg // FIXME: The "second phase of [over.match.list] case can also 10089 1.1 joerg // theoretically happen here, but it's not clear whether we can 10090 1.1 joerg // ever have a parameter of the right type. 10091 1.1 joerg bool SuppressUserConversions = Kind.isCopyInit(); 10092 1.1 joerg 10093 1.1 joerg if (TD) 10094 1.1 joerg AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr, 10095 1.1 joerg Inits, Candidates, SuppressUserConversions, 10096 1.1 joerg /*PartialOverloading*/ false, 10097 1.1 joerg AllowExplicit); 10098 1.1 joerg else 10099 1.1 joerg AddOverloadCandidate(GD, I.getPair(), Inits, Candidates, 10100 1.1 joerg SuppressUserConversions, 10101 1.1 joerg /*PartialOverloading*/ false, AllowExplicit); 10102 1.1 joerg } 10103 1.1 joerg return Candidates.BestViableFunction(*this, Kind.getLocation(), Best); 10104 1.1 joerg }; 10105 1.1 joerg 10106 1.1 joerg OverloadingResult Result = OR_No_Viable_Function; 10107 1.1 joerg 10108 1.1 joerg // C++11 [over.match.list]p1, per DR1467: for list-initialization, first 10109 1.1 joerg // try initializer-list constructors. 10110 1.1 joerg if (ListInit) { 10111 1.1 joerg bool TryListConstructors = true; 10112 1.1 joerg 10113 1.1 joerg // Try list constructors unless the list is empty and the class has one or 10114 1.1 joerg // more default constructors, in which case those constructors win. 10115 1.1 joerg if (!ListInit->getNumInits()) { 10116 1.1 joerg for (NamedDecl *D : Guides) { 10117 1.1 joerg auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl()); 10118 1.1 joerg if (FD && FD->getMinRequiredArguments() == 0) { 10119 1.1 joerg TryListConstructors = false; 10120 1.1 joerg break; 10121 1.1 joerg } 10122 1.1 joerg } 10123 1.1 joerg } else if (ListInit->getNumInits() == 1) { 10124 1.1 joerg // C++ [over.match.class.deduct]: 10125 1.1 joerg // As an exception, the first phase in [over.match.list] (considering 10126 1.1 joerg // initializer-list constructors) is omitted if the initializer list 10127 1.1 joerg // consists of a single expression of type cv U, where U is a 10128 1.1 joerg // specialization of C or a class derived from a specialization of C. 10129 1.1 joerg Expr *E = ListInit->getInit(0); 10130 1.1 joerg auto *RD = E->getType()->getAsCXXRecordDecl(); 10131 1.1 joerg if (!isa<InitListExpr>(E) && RD && 10132 1.1 joerg isCompleteType(Kind.getLocation(), E->getType()) && 10133 1.1 joerg isOrIsDerivedFromSpecializationOf(RD, Template)) 10134 1.1 joerg TryListConstructors = false; 10135 1.1 joerg } 10136 1.1 joerg 10137 1.1 joerg if (TryListConstructors) 10138 1.1 joerg Result = tryToResolveOverload(/*OnlyListConstructor*/true); 10139 1.1 joerg // Then unwrap the initializer list and try again considering all 10140 1.1 joerg // constructors. 10141 1.1 joerg Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits()); 10142 1.1 joerg } 10143 1.1 joerg 10144 1.1 joerg // If list-initialization fails, or if we're doing any other kind of 10145 1.1 joerg // initialization, we (eventually) consider constructors. 10146 1.1 joerg if (Result == OR_No_Viable_Function) 10147 1.1 joerg Result = tryToResolveOverload(/*OnlyListConstructor*/false); 10148 1.1 joerg 10149 1.1 joerg switch (Result) { 10150 1.1 joerg case OR_Ambiguous: 10151 1.1 joerg // FIXME: For list-initialization candidates, it'd usually be better to 10152 1.1 joerg // list why they were not viable when given the initializer list itself as 10153 1.1 joerg // an argument. 10154 1.1 joerg Candidates.NoteCandidates( 10155 1.1 joerg PartialDiagnosticAt( 10156 1.1 joerg Kind.getLocation(), 10157 1.1 joerg PDiag(diag::err_deduced_class_template_ctor_ambiguous) 10158 1.1 joerg << TemplateName), 10159 1.1 joerg *this, OCD_AmbiguousCandidates, Inits); 10160 1.1 joerg return QualType(); 10161 1.1 joerg 10162 1.1 joerg case OR_No_Viable_Function: { 10163 1.1 joerg CXXRecordDecl *Primary = 10164 1.1 joerg cast<ClassTemplateDecl>(Template)->getTemplatedDecl(); 10165 1.1 joerg bool Complete = 10166 1.1 joerg isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary)); 10167 1.1 joerg Candidates.NoteCandidates( 10168 1.1 joerg PartialDiagnosticAt( 10169 1.1 joerg Kind.getLocation(), 10170 1.1 joerg PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable 10171 1.1 joerg : diag::err_deduced_class_template_incomplete) 10172 1.1 joerg << TemplateName << !Guides.empty()), 10173 1.1 joerg *this, OCD_AllCandidates, Inits); 10174 1.1 joerg return QualType(); 10175 1.1 joerg } 10176 1.1 joerg 10177 1.1 joerg case OR_Deleted: { 10178 1.1 joerg Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted) 10179 1.1 joerg << TemplateName; 10180 1.1 joerg NoteDeletedFunction(Best->Function); 10181 1.1 joerg return QualType(); 10182 1.1 joerg } 10183 1.1 joerg 10184 1.1 joerg case OR_Success: 10185 1.1 joerg // C++ [over.match.list]p1: 10186 1.1 joerg // In copy-list-initialization, if an explicit constructor is chosen, the 10187 1.1 joerg // initialization is ill-formed. 10188 1.1 joerg if (Kind.isCopyInit() && ListInit && 10189 1.1 joerg cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) { 10190 1.1 joerg bool IsDeductionGuide = !Best->Function->isImplicit(); 10191 1.1 joerg Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit) 10192 1.1 joerg << TemplateName << IsDeductionGuide; 10193 1.1 joerg Diag(Best->Function->getLocation(), 10194 1.1 joerg diag::note_explicit_ctor_deduction_guide_here) 10195 1.1 joerg << IsDeductionGuide; 10196 1.1 joerg return QualType(); 10197 1.1 joerg } 10198 1.1 joerg 10199 1.1 joerg // Make sure we didn't select an unusable deduction guide, and mark it 10200 1.1 joerg // as referenced. 10201 1.1 joerg DiagnoseUseOfDecl(Best->Function, Kind.getLocation()); 10202 1.1 joerg MarkFunctionReferenced(Kind.getLocation(), Best->Function); 10203 1.1 joerg break; 10204 1.1 joerg } 10205 1.1 joerg 10206 1.1 joerg // C++ [dcl.type.class.deduct]p1: 10207 1.1 joerg // The placeholder is replaced by the return type of the function selected 10208 1.1 joerg // by overload resolution for class template deduction. 10209 1.1 joerg QualType DeducedType = 10210 1.1 joerg SubstAutoType(TSInfo->getType(), Best->Function->getReturnType()); 10211 1.1 joerg Diag(TSInfo->getTypeLoc().getBeginLoc(), 10212 1.1 joerg diag::warn_cxx14_compat_class_template_argument_deduction) 10213 1.1 joerg << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType; 10214 1.1 joerg 10215 1.1 joerg // Warn if CTAD was used on a type that does not have any user-defined 10216 1.1 joerg // deduction guides. 10217 1.1 joerg if (!HasAnyDeductionGuide) { 10218 1.1 joerg Diag(TSInfo->getTypeLoc().getBeginLoc(), 10219 1.1 joerg diag::warn_ctad_maybe_unsupported) 10220 1.1 joerg << TemplateName; 10221 1.1 joerg Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported); 10222 1.1 joerg } 10223 1.1 joerg 10224 1.1 joerg return DeducedType; 10225 1.1 joerg } 10226