| File: | build/source/clang/lib/Sema/SemaInit.cpp |
| Warning: | line 2918, column 7 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
| 1 | //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===// | |||
| 2 | // | |||
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
| 4 | // See https://llvm.org/LICENSE.txt for license information. | |||
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
| 6 | // | |||
| 7 | //===----------------------------------------------------------------------===// | |||
| 8 | // | |||
| 9 | // This file implements semantic analysis for initializers. | |||
| 10 | // | |||
| 11 | //===----------------------------------------------------------------------===// | |||
| 12 | ||||
| 13 | #include "clang/AST/ASTContext.h" | |||
| 14 | #include "clang/AST/DeclObjC.h" | |||
| 15 | #include "clang/AST/ExprCXX.h" | |||
| 16 | #include "clang/AST/ExprObjC.h" | |||
| 17 | #include "clang/AST/ExprOpenMP.h" | |||
| 18 | #include "clang/AST/TypeLoc.h" | |||
| 19 | #include "clang/Basic/CharInfo.h" | |||
| 20 | #include "clang/Basic/SourceManager.h" | |||
| 21 | #include "clang/Basic/TargetInfo.h" | |||
| 22 | #include "clang/Sema/Designator.h" | |||
| 23 | #include "clang/Sema/Initialization.h" | |||
| 24 | #include "clang/Sema/Lookup.h" | |||
| 25 | #include "clang/Sema/SemaInternal.h" | |||
| 26 | #include "llvm/ADT/APInt.h" | |||
| 27 | #include "llvm/ADT/PointerIntPair.h" | |||
| 28 | #include "llvm/ADT/SmallString.h" | |||
| 29 | #include "llvm/Support/ErrorHandling.h" | |||
| 30 | #include "llvm/Support/raw_ostream.h" | |||
| 31 | ||||
| 32 | using namespace clang; | |||
| 33 | ||||
| 34 | //===----------------------------------------------------------------------===// | |||
| 35 | // Sema Initialization Checking | |||
| 36 | //===----------------------------------------------------------------------===// | |||
| 37 | ||||
| 38 | /// Check whether T is compatible with a wide character type (wchar_t, | |||
| 39 | /// char16_t or char32_t). | |||
| 40 | static bool IsWideCharCompatible(QualType T, ASTContext &Context) { | |||
| 41 | if (Context.typesAreCompatible(Context.getWideCharType(), T)) | |||
| 42 | return true; | |||
| 43 | if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) { | |||
| 44 | return Context.typesAreCompatible(Context.Char16Ty, T) || | |||
| 45 | Context.typesAreCompatible(Context.Char32Ty, T); | |||
| 46 | } | |||
| 47 | return false; | |||
| 48 | } | |||
| 49 | ||||
| 50 | enum StringInitFailureKind { | |||
| 51 | SIF_None, | |||
| 52 | SIF_NarrowStringIntoWideChar, | |||
| 53 | SIF_WideStringIntoChar, | |||
| 54 | SIF_IncompatWideStringIntoWideChar, | |||
| 55 | SIF_UTF8StringIntoPlainChar, | |||
| 56 | SIF_PlainStringIntoUTF8Char, | |||
| 57 | SIF_Other | |||
| 58 | }; | |||
| 59 | ||||
| 60 | /// Check whether the array of type AT can be initialized by the Init | |||
| 61 | /// expression by means of string initialization. Returns SIF_None if so, | |||
| 62 | /// otherwise returns a StringInitFailureKind that describes why the | |||
| 63 | /// initialization would not work. | |||
| 64 | static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT, | |||
| 65 | ASTContext &Context) { | |||
| 66 | if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT)) | |||
| 67 | return SIF_Other; | |||
| 68 | ||||
| 69 | // See if this is a string literal or @encode. | |||
| 70 | Init = Init->IgnoreParens(); | |||
| 71 | ||||
| 72 | // Handle @encode, which is a narrow string. | |||
| 73 | if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType()) | |||
| 74 | return SIF_None; | |||
| 75 | ||||
| 76 | // Otherwise we can only handle string literals. | |||
| 77 | StringLiteral *SL = dyn_cast<StringLiteral>(Init); | |||
| 78 | if (!SL) | |||
| 79 | return SIF_Other; | |||
| 80 | ||||
| 81 | const QualType ElemTy = | |||
| 82 | Context.getCanonicalType(AT->getElementType()).getUnqualifiedType(); | |||
| 83 | ||||
| 84 | auto IsCharOrUnsignedChar = [](const QualType &T) { | |||
| 85 | const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr()); | |||
| 86 | return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar; | |||
| 87 | }; | |||
| 88 | ||||
| 89 | switch (SL->getKind()) { | |||
| 90 | case StringLiteral::UTF8: | |||
| 91 | // char8_t array can be initialized with a UTF-8 string. | |||
| 92 | // - C++20 [dcl.init.string] (DR) | |||
| 93 | // Additionally, an array of char or unsigned char may be initialized | |||
| 94 | // by a UTF-8 string literal. | |||
| 95 | if (ElemTy->isChar8Type() || | |||
| 96 | (Context.getLangOpts().Char8 && | |||
| 97 | IsCharOrUnsignedChar(ElemTy.getCanonicalType()))) | |||
| 98 | return SIF_None; | |||
| 99 | [[fallthrough]]; | |||
| 100 | case StringLiteral::Ordinary: | |||
| 101 | // char array can be initialized with a narrow string. | |||
| 102 | // Only allow char x[] = "foo"; not char x[] = L"foo"; | |||
| 103 | if (ElemTy->isCharType()) | |||
| 104 | return (SL->getKind() == StringLiteral::UTF8 && | |||
| 105 | Context.getLangOpts().Char8) | |||
| 106 | ? SIF_UTF8StringIntoPlainChar | |||
| 107 | : SIF_None; | |||
| 108 | if (ElemTy->isChar8Type()) | |||
| 109 | return SIF_PlainStringIntoUTF8Char; | |||
| 110 | if (IsWideCharCompatible(ElemTy, Context)) | |||
| 111 | return SIF_NarrowStringIntoWideChar; | |||
| 112 | return SIF_Other; | |||
| 113 | // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15: | |||
| 114 | // "An array with element type compatible with a qualified or unqualified | |||
| 115 | // version of wchar_t, char16_t, or char32_t may be initialized by a wide | |||
| 116 | // string literal with the corresponding encoding prefix (L, u, or U, | |||
| 117 | // respectively), optionally enclosed in braces. | |||
| 118 | case StringLiteral::UTF16: | |||
| 119 | if (Context.typesAreCompatible(Context.Char16Ty, ElemTy)) | |||
| 120 | return SIF_None; | |||
| 121 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) | |||
| 122 | return SIF_WideStringIntoChar; | |||
| 123 | if (IsWideCharCompatible(ElemTy, Context)) | |||
| 124 | return SIF_IncompatWideStringIntoWideChar; | |||
| 125 | return SIF_Other; | |||
| 126 | case StringLiteral::UTF32: | |||
| 127 | if (Context.typesAreCompatible(Context.Char32Ty, ElemTy)) | |||
| 128 | return SIF_None; | |||
| 129 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) | |||
| 130 | return SIF_WideStringIntoChar; | |||
| 131 | if (IsWideCharCompatible(ElemTy, Context)) | |||
| 132 | return SIF_IncompatWideStringIntoWideChar; | |||
| 133 | return SIF_Other; | |||
| 134 | case StringLiteral::Wide: | |||
| 135 | if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy)) | |||
| 136 | return SIF_None; | |||
| 137 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) | |||
| 138 | return SIF_WideStringIntoChar; | |||
| 139 | if (IsWideCharCompatible(ElemTy, Context)) | |||
| 140 | return SIF_IncompatWideStringIntoWideChar; | |||
| 141 | return SIF_Other; | |||
| 142 | } | |||
| 143 | ||||
| 144 | llvm_unreachable("missed a StringLiteral kind?")::llvm::llvm_unreachable_internal("missed a StringLiteral kind?" , "clang/lib/Sema/SemaInit.cpp", 144); | |||
| 145 | } | |||
| 146 | ||||
| 147 | static StringInitFailureKind IsStringInit(Expr *init, QualType declType, | |||
| 148 | ASTContext &Context) { | |||
| 149 | const ArrayType *arrayType = Context.getAsArrayType(declType); | |||
| 150 | if (!arrayType) | |||
| 151 | return SIF_Other; | |||
| 152 | return IsStringInit(init, arrayType, Context); | |||
| 153 | } | |||
| 154 | ||||
| 155 | bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) { | |||
| 156 | return ::IsStringInit(Init, AT, Context) == SIF_None; | |||
| 157 | } | |||
| 158 | ||||
| 159 | /// Update the type of a string literal, including any surrounding parentheses, | |||
| 160 | /// to match the type of the object which it is initializing. | |||
| 161 | static void updateStringLiteralType(Expr *E, QualType Ty) { | |||
| 162 | while (true) { | |||
| 163 | E->setType(Ty); | |||
| 164 | E->setValueKind(VK_PRValue); | |||
| 165 | if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) { | |||
| 166 | break; | |||
| 167 | } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { | |||
| 168 | E = PE->getSubExpr(); | |||
| 169 | } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { | |||
| 170 | assert(UO->getOpcode() == UO_Extension)(static_cast <bool> (UO->getOpcode() == UO_Extension ) ? void (0) : __assert_fail ("UO->getOpcode() == UO_Extension" , "clang/lib/Sema/SemaInit.cpp", 170, __extension__ __PRETTY_FUNCTION__ )); | |||
| 171 | E = UO->getSubExpr(); | |||
| 172 | } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) { | |||
| 173 | E = GSE->getResultExpr(); | |||
| 174 | } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) { | |||
| 175 | E = CE->getChosenSubExpr(); | |||
| 176 | } else { | |||
| 177 | llvm_unreachable("unexpected expr in string literal init")::llvm::llvm_unreachable_internal("unexpected expr in string literal init" , "clang/lib/Sema/SemaInit.cpp", 177); | |||
| 178 | } | |||
| 179 | } | |||
| 180 | } | |||
| 181 | ||||
| 182 | /// Fix a compound literal initializing an array so it's correctly marked | |||
| 183 | /// as an rvalue. | |||
| 184 | static void updateGNUCompoundLiteralRValue(Expr *E) { | |||
| 185 | while (true) { | |||
| 186 | E->setValueKind(VK_PRValue); | |||
| 187 | if (isa<CompoundLiteralExpr>(E)) { | |||
| 188 | break; | |||
| 189 | } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { | |||
| 190 | E = PE->getSubExpr(); | |||
| 191 | } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { | |||
| 192 | assert(UO->getOpcode() == UO_Extension)(static_cast <bool> (UO->getOpcode() == UO_Extension ) ? void (0) : __assert_fail ("UO->getOpcode() == UO_Extension" , "clang/lib/Sema/SemaInit.cpp", 192, __extension__ __PRETTY_FUNCTION__ )); | |||
| 193 | E = UO->getSubExpr(); | |||
| 194 | } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) { | |||
| 195 | E = GSE->getResultExpr(); | |||
| 196 | } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) { | |||
| 197 | E = CE->getChosenSubExpr(); | |||
| 198 | } else { | |||
| 199 | llvm_unreachable("unexpected expr in array compound literal init")::llvm::llvm_unreachable_internal("unexpected expr in array compound literal init" , "clang/lib/Sema/SemaInit.cpp", 199); | |||
| 200 | } | |||
| 201 | } | |||
| 202 | } | |||
| 203 | ||||
| 204 | static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, | |||
| 205 | Sema &S) { | |||
| 206 | // Get the length of the string as parsed. | |||
| 207 | auto *ConstantArrayTy = | |||
| 208 | cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe()); | |||
| 209 | uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue(); | |||
| 210 | ||||
| 211 | if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { | |||
| 212 | // C99 6.7.8p14. We have an array of character type with unknown size | |||
| 213 | // being initialized to a string literal. | |||
| 214 | llvm::APInt ConstVal(32, StrLength); | |||
| 215 | // Return a new array type (C99 6.7.8p22). | |||
| 216 | DeclT = S.Context.getConstantArrayType(IAT->getElementType(), | |||
| 217 | ConstVal, nullptr, | |||
| 218 | ArrayType::Normal, 0); | |||
| 219 | updateStringLiteralType(Str, DeclT); | |||
| 220 | return; | |||
| 221 | } | |||
| 222 | ||||
| 223 | const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); | |||
| 224 | ||||
| 225 | // We have an array of character type with known size. However, | |||
| 226 | // the size may be smaller or larger than the string we are initializing. | |||
| 227 | // FIXME: Avoid truncation for 64-bit length strings. | |||
| 228 | if (S.getLangOpts().CPlusPlus) { | |||
| 229 | if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) { | |||
| 230 | // For Pascal strings it's OK to strip off the terminating null character, | |||
| 231 | // so the example below is valid: | |||
| 232 | // | |||
| 233 | // unsigned char a[2] = "\pa"; | |||
| 234 | if (SL->isPascal()) | |||
| 235 | StrLength--; | |||
| 236 | } | |||
| 237 | ||||
| 238 | // [dcl.init.string]p2 | |||
| 239 | if (StrLength > CAT->getSize().getZExtValue()) | |||
| 240 | S.Diag(Str->getBeginLoc(), | |||
| 241 | diag::err_initializer_string_for_char_array_too_long) | |||
| 242 | << CAT->getSize().getZExtValue() << StrLength | |||
| 243 | << Str->getSourceRange(); | |||
| 244 | } else { | |||
| 245 | // C99 6.7.8p14. | |||
| 246 | if (StrLength-1 > CAT->getSize().getZExtValue()) | |||
| 247 | S.Diag(Str->getBeginLoc(), | |||
| 248 | diag::ext_initializer_string_for_char_array_too_long) | |||
| 249 | << Str->getSourceRange(); | |||
| 250 | } | |||
| 251 | ||||
| 252 | // Set the type to the actual size that we are initializing. If we have | |||
| 253 | // something like: | |||
| 254 | // char x[1] = "foo"; | |||
| 255 | // then this will set the string literal's type to char[1]. | |||
| 256 | updateStringLiteralType(Str, DeclT); | |||
| 257 | } | |||
| 258 | ||||
| 259 | //===----------------------------------------------------------------------===// | |||
| 260 | // Semantic checking for initializer lists. | |||
| 261 | //===----------------------------------------------------------------------===// | |||
| 262 | ||||
| 263 | namespace { | |||
| 264 | ||||
| 265 | /// Semantic checking for initializer lists. | |||
| 266 | /// | |||
| 267 | /// The InitListChecker class contains a set of routines that each | |||
| 268 | /// handle the initialization of a certain kind of entity, e.g., | |||
| 269 | /// arrays, vectors, struct/union types, scalars, etc. The | |||
| 270 | /// InitListChecker itself performs a recursive walk of the subobject | |||
| 271 | /// structure of the type to be initialized, while stepping through | |||
| 272 | /// the initializer list one element at a time. The IList and Index | |||
| 273 | /// parameters to each of the Check* routines contain the active | |||
| 274 | /// (syntactic) initializer list and the index into that initializer | |||
| 275 | /// list that represents the current initializer. Each routine is | |||
| 276 | /// responsible for moving that Index forward as it consumes elements. | |||
| 277 | /// | |||
| 278 | /// Each Check* routine also has a StructuredList/StructuredIndex | |||
| 279 | /// arguments, which contains the current "structured" (semantic) | |||
| 280 | /// initializer list and the index into that initializer list where we | |||
| 281 | /// are copying initializers as we map them over to the semantic | |||
| 282 | /// list. Once we have completed our recursive walk of the subobject | |||
| 283 | /// structure, we will have constructed a full semantic initializer | |||
| 284 | /// list. | |||
| 285 | /// | |||
| 286 | /// C99 designators cause changes in the initializer list traversal, | |||
| 287 | /// because they make the initialization "jump" into a specific | |||
| 288 | /// subobject and then continue the initialization from that | |||
| 289 | /// point. CheckDesignatedInitializer() recursively steps into the | |||
| 290 | /// designated subobject and manages backing out the recursion to | |||
| 291 | /// initialize the subobjects after the one designated. | |||
| 292 | /// | |||
| 293 | /// If an initializer list contains any designators, we build a placeholder | |||
| 294 | /// structured list even in 'verify only' mode, so that we can track which | |||
| 295 | /// elements need 'empty' initializtion. | |||
| 296 | class InitListChecker { | |||
| 297 | Sema &SemaRef; | |||
| 298 | bool hadError = false; | |||
| 299 | bool VerifyOnly; // No diagnostics. | |||
| 300 | bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode. | |||
| 301 | bool InOverloadResolution; | |||
| 302 | InitListExpr *FullyStructuredList = nullptr; | |||
| 303 | NoInitExpr *DummyExpr = nullptr; | |||
| 304 | ||||
| 305 | NoInitExpr *getDummyInit() { | |||
| 306 | if (!DummyExpr) | |||
| 307 | DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy); | |||
| 308 | return DummyExpr; | |||
| 309 | } | |||
| 310 | ||||
| 311 | void CheckImplicitInitList(const InitializedEntity &Entity, | |||
| 312 | InitListExpr *ParentIList, QualType T, | |||
| 313 | unsigned &Index, InitListExpr *StructuredList, | |||
| 314 | unsigned &StructuredIndex); | |||
| 315 | void CheckExplicitInitList(const InitializedEntity &Entity, | |||
| 316 | InitListExpr *IList, QualType &T, | |||
| 317 | InitListExpr *StructuredList, | |||
| 318 | bool TopLevelObject = false); | |||
| 319 | void CheckListElementTypes(const InitializedEntity &Entity, | |||
| 320 | InitListExpr *IList, QualType &DeclType, | |||
| 321 | bool SubobjectIsDesignatorContext, | |||
| 322 | unsigned &Index, | |||
| 323 | InitListExpr *StructuredList, | |||
| 324 | unsigned &StructuredIndex, | |||
| 325 | bool TopLevelObject = false); | |||
| 326 | void CheckSubElementType(const InitializedEntity &Entity, | |||
| 327 | InitListExpr *IList, QualType ElemType, | |||
| 328 | unsigned &Index, | |||
| 329 | InitListExpr *StructuredList, | |||
| 330 | unsigned &StructuredIndex, | |||
| 331 | bool DirectlyDesignated = false); | |||
| 332 | void CheckComplexType(const InitializedEntity &Entity, | |||
| 333 | InitListExpr *IList, QualType DeclType, | |||
| 334 | unsigned &Index, | |||
| 335 | InitListExpr *StructuredList, | |||
| 336 | unsigned &StructuredIndex); | |||
| 337 | void CheckScalarType(const InitializedEntity &Entity, | |||
| 338 | InitListExpr *IList, QualType DeclType, | |||
| 339 | unsigned &Index, | |||
| 340 | InitListExpr *StructuredList, | |||
| 341 | unsigned &StructuredIndex); | |||
| 342 | void CheckReferenceType(const InitializedEntity &Entity, | |||
| 343 | InitListExpr *IList, QualType DeclType, | |||
| 344 | unsigned &Index, | |||
| 345 | InitListExpr *StructuredList, | |||
| 346 | unsigned &StructuredIndex); | |||
| 347 | void CheckVectorType(const InitializedEntity &Entity, | |||
| 348 | InitListExpr *IList, QualType DeclType, unsigned &Index, | |||
| 349 | InitListExpr *StructuredList, | |||
| 350 | unsigned &StructuredIndex); | |||
| 351 | void CheckStructUnionTypes(const InitializedEntity &Entity, | |||
| 352 | InitListExpr *IList, QualType DeclType, | |||
| 353 | CXXRecordDecl::base_class_range Bases, | |||
| 354 | RecordDecl::field_iterator Field, | |||
| 355 | bool SubobjectIsDesignatorContext, unsigned &Index, | |||
| 356 | InitListExpr *StructuredList, | |||
| 357 | unsigned &StructuredIndex, | |||
| 358 | bool TopLevelObject = false); | |||
| 359 | void CheckArrayType(const InitializedEntity &Entity, | |||
| 360 | InitListExpr *IList, QualType &DeclType, | |||
| 361 | llvm::APSInt elementIndex, | |||
| 362 | bool SubobjectIsDesignatorContext, unsigned &Index, | |||
| 363 | InitListExpr *StructuredList, | |||
| 364 | unsigned &StructuredIndex); | |||
| 365 | bool CheckDesignatedInitializer(const InitializedEntity &Entity, | |||
| 366 | InitListExpr *IList, DesignatedInitExpr *DIE, | |||
| 367 | unsigned DesigIdx, | |||
| 368 | QualType &CurrentObjectType, | |||
| 369 | RecordDecl::field_iterator *NextField, | |||
| 370 | llvm::APSInt *NextElementIndex, | |||
| 371 | unsigned &Index, | |||
| 372 | InitListExpr *StructuredList, | |||
| 373 | unsigned &StructuredIndex, | |||
| 374 | bool FinishSubobjectInit, | |||
| 375 | bool TopLevelObject); | |||
| 376 | InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, | |||
| 377 | QualType CurrentObjectType, | |||
| 378 | InitListExpr *StructuredList, | |||
| 379 | unsigned StructuredIndex, | |||
| 380 | SourceRange InitRange, | |||
| 381 | bool IsFullyOverwritten = false); | |||
| 382 | void UpdateStructuredListElement(InitListExpr *StructuredList, | |||
| 383 | unsigned &StructuredIndex, | |||
| 384 | Expr *expr); | |||
| 385 | InitListExpr *createInitListExpr(QualType CurrentObjectType, | |||
| 386 | SourceRange InitRange, | |||
| 387 | unsigned ExpectedNumInits); | |||
| 388 | int numArrayElements(QualType DeclType); | |||
| 389 | int numStructUnionElements(QualType DeclType); | |||
| 390 | ||||
| 391 | ExprResult PerformEmptyInit(SourceLocation Loc, | |||
| 392 | const InitializedEntity &Entity); | |||
| 393 | ||||
| 394 | /// Diagnose that OldInit (or part thereof) has been overridden by NewInit. | |||
| 395 | void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange, | |||
| 396 | bool FullyOverwritten = true) { | |||
| 397 | // Overriding an initializer via a designator is valid with C99 designated | |||
| 398 | // initializers, but ill-formed with C++20 designated initializers. | |||
| 399 | unsigned DiagID = SemaRef.getLangOpts().CPlusPlus | |||
| 400 | ? diag::ext_initializer_overrides | |||
| 401 | : diag::warn_initializer_overrides; | |||
| 402 | ||||
| 403 | if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) { | |||
| 404 | // In overload resolution, we have to strictly enforce the rules, and so | |||
| 405 | // don't allow any overriding of prior initializers. This matters for a | |||
| 406 | // case such as: | |||
| 407 | // | |||
| 408 | // union U { int a, b; }; | |||
| 409 | // struct S { int a, b; }; | |||
| 410 | // void f(U), f(S); | |||
| 411 | // | |||
| 412 | // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For | |||
| 413 | // consistency, we disallow all overriding of prior initializers in | |||
| 414 | // overload resolution, not only overriding of union members. | |||
| 415 | hadError = true; | |||
| 416 | } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) { | |||
| 417 | // If we'll be keeping around the old initializer but overwriting part of | |||
| 418 | // the object it initialized, and that object is not trivially | |||
| 419 | // destructible, this can leak. Don't allow that, not even as an | |||
| 420 | // extension. | |||
| 421 | // | |||
| 422 | // FIXME: It might be reasonable to allow this in cases where the part of | |||
| 423 | // the initializer that we're overriding has trivial destruction. | |||
| 424 | DiagID = diag::err_initializer_overrides_destructed; | |||
| 425 | } else if (!OldInit->getSourceRange().isValid()) { | |||
| 426 | // We need to check on source range validity because the previous | |||
| 427 | // initializer does not have to be an explicit initializer. e.g., | |||
| 428 | // | |||
| 429 | // struct P { int a, b; }; | |||
| 430 | // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 }; | |||
| 431 | // | |||
| 432 | // There is an overwrite taking place because the first braced initializer | |||
| 433 | // list "{ .a = 2 }" already provides value for .p.b (which is zero). | |||
| 434 | // | |||
| 435 | // Such overwrites are harmless, so we don't diagnose them. (Note that in | |||
| 436 | // C++, this cannot be reached unless we've already seen and diagnosed a | |||
| 437 | // different conformance issue, such as a mixture of designated and | |||
| 438 | // non-designated initializers or a multi-level designator.) | |||
| 439 | return; | |||
| 440 | } | |||
| 441 | ||||
| 442 | if (!VerifyOnly) { | |||
| 443 | SemaRef.Diag(NewInitRange.getBegin(), DiagID) | |||
| 444 | << NewInitRange << FullyOverwritten << OldInit->getType(); | |||
| 445 | SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer) | |||
| 446 | << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten) | |||
| 447 | << OldInit->getSourceRange(); | |||
| 448 | } | |||
| 449 | } | |||
| 450 | ||||
| 451 | // Explanation on the "FillWithNoInit" mode: | |||
| 452 | // | |||
| 453 | // Assume we have the following definitions (Case#1): | |||
| 454 | // struct P { char x[6][6]; } xp = { .x[1] = "bar" }; | |||
| 455 | // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' }; | |||
| 456 | // | |||
| 457 | // l.lp.x[1][0..1] should not be filled with implicit initializers because the | |||
| 458 | // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf". | |||
| 459 | // | |||
| 460 | // But if we have (Case#2): | |||
| 461 | // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } }; | |||
| 462 | // | |||
| 463 | // l.lp.x[1][0..1] are implicitly initialized and do not use values from the | |||
| 464 | // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0". | |||
| 465 | // | |||
| 466 | // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes" | |||
| 467 | // in the InitListExpr, the "holes" in Case#1 are filled not with empty | |||
| 468 | // initializers but with special "NoInitExpr" place holders, which tells the | |||
| 469 | // CodeGen not to generate any initializers for these parts. | |||
| 470 | void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base, | |||
| 471 | const InitializedEntity &ParentEntity, | |||
| 472 | InitListExpr *ILE, bool &RequiresSecondPass, | |||
| 473 | bool FillWithNoInit); | |||
| 474 | void FillInEmptyInitForField(unsigned Init, FieldDecl *Field, | |||
| 475 | const InitializedEntity &ParentEntity, | |||
| 476 | InitListExpr *ILE, bool &RequiresSecondPass, | |||
| 477 | bool FillWithNoInit = false); | |||
| 478 | void FillInEmptyInitializations(const InitializedEntity &Entity, | |||
| 479 | InitListExpr *ILE, bool &RequiresSecondPass, | |||
| 480 | InitListExpr *OuterILE, unsigned OuterIndex, | |||
| 481 | bool FillWithNoInit = false); | |||
| 482 | bool CheckFlexibleArrayInit(const InitializedEntity &Entity, | |||
| 483 | Expr *InitExpr, FieldDecl *Field, | |||
| 484 | bool TopLevelObject); | |||
| 485 | void CheckEmptyInitializable(const InitializedEntity &Entity, | |||
| 486 | SourceLocation Loc); | |||
| 487 | ||||
| 488 | public: | |||
| 489 | InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL, | |||
| 490 | QualType &T, bool VerifyOnly, bool TreatUnavailableAsInvalid, | |||
| 491 | bool InOverloadResolution = false); | |||
| 492 | bool HadError() { return hadError; } | |||
| 493 | ||||
| 494 | // Retrieves the fully-structured initializer list used for | |||
| 495 | // semantic analysis and code generation. | |||
| 496 | InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } | |||
| 497 | }; | |||
| 498 | ||||
| 499 | } // end anonymous namespace | |||
| 500 | ||||
| 501 | ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc, | |||
| 502 | const InitializedEntity &Entity) { | |||
| 503 | InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, | |||
| 504 | true); | |||
| 505 | MultiExprArg SubInit; | |||
| 506 | Expr *InitExpr; | |||
| 507 | InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc); | |||
| 508 | ||||
| 509 | // C++ [dcl.init.aggr]p7: | |||
| 510 | // If there are fewer initializer-clauses in the list than there are | |||
| 511 | // members in the aggregate, then each member not explicitly initialized | |||
| 512 | // ... | |||
| 513 | bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 && | |||
| 514 | Entity.getType()->getBaseElementTypeUnsafe()->isRecordType(); | |||
| 515 | if (EmptyInitList) { | |||
| 516 | // C++1y / DR1070: | |||
| 517 | // shall be initialized [...] from an empty initializer list. | |||
| 518 | // | |||
| 519 | // We apply the resolution of this DR to C++11 but not C++98, since C++98 | |||
| 520 | // does not have useful semantics for initialization from an init list. | |||
| 521 | // We treat this as copy-initialization, because aggregate initialization | |||
| 522 | // always performs copy-initialization on its elements. | |||
| 523 | // | |||
| 524 | // Only do this if we're initializing a class type, to avoid filling in | |||
| 525 | // the initializer list where possible. | |||
| 526 | InitExpr = VerifyOnly | |||
| 527 | ? &DummyInitList | |||
| 528 | : new (SemaRef.Context) | |||
| 529 | InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc); | |||
| 530 | InitExpr->setType(SemaRef.Context.VoidTy); | |||
| 531 | SubInit = InitExpr; | |||
| 532 | Kind = InitializationKind::CreateCopy(Loc, Loc); | |||
| 533 | } else { | |||
| 534 | // C++03: | |||
| 535 | // shall be value-initialized. | |||
| 536 | } | |||
| 537 | ||||
| 538 | InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit); | |||
| 539 | // libstdc++4.6 marks the vector default constructor as explicit in | |||
| 540 | // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case. | |||
| 541 | // stlport does so too. Look for std::__debug for libstdc++, and for | |||
| 542 | // std:: for stlport. This is effectively a compiler-side implementation of | |||
| 543 | // LWG2193. | |||
| 544 | if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() == | |||
| 545 | InitializationSequence::FK_ExplicitConstructor) { | |||
| 546 | OverloadCandidateSet::iterator Best; | |||
| 547 | OverloadingResult O = | |||
| 548 | InitSeq.getFailedCandidateSet() | |||
| 549 | .BestViableFunction(SemaRef, Kind.getLocation(), Best); | |||
| 550 | (void)O; | |||
| 551 | assert(O == OR_Success && "Inconsistent overload resolution")(static_cast <bool> (O == OR_Success && "Inconsistent overload resolution" ) ? void (0) : __assert_fail ("O == OR_Success && \"Inconsistent overload resolution\"" , "clang/lib/Sema/SemaInit.cpp", 551, __extension__ __PRETTY_FUNCTION__ )); | |||
| 552 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); | |||
| 553 | CXXRecordDecl *R = CtorDecl->getParent(); | |||
| 554 | ||||
| 555 | if (CtorDecl->getMinRequiredArguments() == 0 && | |||
| 556 | CtorDecl->isExplicit() && R->getDeclName() && | |||
| 557 | SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) { | |||
| 558 | bool IsInStd = false; | |||
| 559 | for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext()); | |||
| 560 | ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) { | |||
| 561 | if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND)) | |||
| 562 | IsInStd = true; | |||
| 563 | } | |||
| 564 | ||||
| 565 | if (IsInStd && llvm::StringSwitch<bool>(R->getName()) | |||
| 566 | .Cases("basic_string", "deque", "forward_list", true) | |||
| 567 | .Cases("list", "map", "multimap", "multiset", true) | |||
| 568 | .Cases("priority_queue", "queue", "set", "stack", true) | |||
| 569 | .Cases("unordered_map", "unordered_set", "vector", true) | |||
| 570 | .Default(false)) { | |||
| 571 | InitSeq.InitializeFrom( | |||
| 572 | SemaRef, Entity, | |||
| 573 | InitializationKind::CreateValue(Loc, Loc, Loc, true), | |||
| 574 | MultiExprArg(), /*TopLevelOfInitList=*/false, | |||
| 575 | TreatUnavailableAsInvalid); | |||
| 576 | // Emit a warning for this. System header warnings aren't shown | |||
| 577 | // by default, but people working on system headers should see it. | |||
| 578 | if (!VerifyOnly) { | |||
| 579 | SemaRef.Diag(CtorDecl->getLocation(), | |||
| 580 | diag::warn_invalid_initializer_from_system_header); | |||
| 581 | if (Entity.getKind() == InitializedEntity::EK_Member) | |||
| 582 | SemaRef.Diag(Entity.getDecl()->getLocation(), | |||
| 583 | diag::note_used_in_initialization_here); | |||
| 584 | else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) | |||
| 585 | SemaRef.Diag(Loc, diag::note_used_in_initialization_here); | |||
| 586 | } | |||
| 587 | } | |||
| 588 | } | |||
| 589 | } | |||
| 590 | if (!InitSeq) { | |||
| 591 | if (!VerifyOnly) { | |||
| 592 | InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit); | |||
| 593 | if (Entity.getKind() == InitializedEntity::EK_Member) | |||
| 594 | SemaRef.Diag(Entity.getDecl()->getLocation(), | |||
| 595 | diag::note_in_omitted_aggregate_initializer) | |||
| 596 | << /*field*/1 << Entity.getDecl(); | |||
| 597 | else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) { | |||
| 598 | bool IsTrailingArrayNewMember = | |||
| 599 | Entity.getParent() && | |||
| 600 | Entity.getParent()->isVariableLengthArrayNew(); | |||
| 601 | SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer) | |||
| 602 | << (IsTrailingArrayNewMember ? 2 : /*array element*/0) | |||
| 603 | << Entity.getElementIndex(); | |||
| 604 | } | |||
| 605 | } | |||
| 606 | hadError = true; | |||
| 607 | return ExprError(); | |||
| 608 | } | |||
| 609 | ||||
| 610 | return VerifyOnly ? ExprResult() | |||
| 611 | : InitSeq.Perform(SemaRef, Entity, Kind, SubInit); | |||
| 612 | } | |||
| 613 | ||||
| 614 | void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity, | |||
| 615 | SourceLocation Loc) { | |||
| 616 | // If we're building a fully-structured list, we'll check this at the end | |||
| 617 | // once we know which elements are actually initialized. Otherwise, we know | |||
| 618 | // that there are no designators so we can just check now. | |||
| 619 | if (FullyStructuredList) | |||
| 620 | return; | |||
| 621 | PerformEmptyInit(Loc, Entity); | |||
| 622 | } | |||
| 623 | ||||
| 624 | void InitListChecker::FillInEmptyInitForBase( | |||
| 625 | unsigned Init, const CXXBaseSpecifier &Base, | |||
| 626 | const InitializedEntity &ParentEntity, InitListExpr *ILE, | |||
| 627 | bool &RequiresSecondPass, bool FillWithNoInit) { | |||
| 628 | InitializedEntity BaseEntity = InitializedEntity::InitializeBase( | |||
| 629 | SemaRef.Context, &Base, false, &ParentEntity); | |||
| 630 | ||||
| 631 | if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) { | |||
| 632 | ExprResult BaseInit = FillWithNoInit | |||
| 633 | ? new (SemaRef.Context) NoInitExpr(Base.getType()) | |||
| 634 | : PerformEmptyInit(ILE->getEndLoc(), BaseEntity); | |||
| 635 | if (BaseInit.isInvalid()) { | |||
| 636 | hadError = true; | |||
| 637 | return; | |||
| 638 | } | |||
| 639 | ||||
| 640 | if (!VerifyOnly) { | |||
| 641 | assert(Init < ILE->getNumInits() && "should have been expanded")(static_cast <bool> (Init < ILE->getNumInits() && "should have been expanded") ? void (0) : __assert_fail ("Init < ILE->getNumInits() && \"should have been expanded\"" , "clang/lib/Sema/SemaInit.cpp", 641, __extension__ __PRETTY_FUNCTION__ )); | |||
| 642 | ILE->setInit(Init, BaseInit.getAs<Expr>()); | |||
| 643 | } | |||
| 644 | } else if (InitListExpr *InnerILE = | |||
| 645 | dyn_cast<InitListExpr>(ILE->getInit(Init))) { | |||
| 646 | FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass, | |||
| 647 | ILE, Init, FillWithNoInit); | |||
| 648 | } else if (DesignatedInitUpdateExpr *InnerDIUE = | |||
| 649 | dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) { | |||
| 650 | FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(), | |||
| 651 | RequiresSecondPass, ILE, Init, | |||
| 652 | /*FillWithNoInit =*/true); | |||
| 653 | } | |||
| 654 | } | |||
| 655 | ||||
| 656 | void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field, | |||
| 657 | const InitializedEntity &ParentEntity, | |||
| 658 | InitListExpr *ILE, | |||
| 659 | bool &RequiresSecondPass, | |||
| 660 | bool FillWithNoInit) { | |||
| 661 | SourceLocation Loc = ILE->getEndLoc(); | |||
| 662 | unsigned NumInits = ILE->getNumInits(); | |||
| 663 | InitializedEntity MemberEntity | |||
| 664 | = InitializedEntity::InitializeMember(Field, &ParentEntity); | |||
| 665 | ||||
| 666 | if (Init >= NumInits || !ILE->getInit(Init)) { | |||
| 667 | if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) | |||
| 668 | if (!RType->getDecl()->isUnion()) | |||
| 669 | assert((Init < NumInits || VerifyOnly) &&(static_cast <bool> ((Init < NumInits || VerifyOnly) && "This ILE should have been expanded") ? void (0) : __assert_fail ("(Init < NumInits || VerifyOnly) && \"This ILE should have been expanded\"" , "clang/lib/Sema/SemaInit.cpp", 670, __extension__ __PRETTY_FUNCTION__ )) | |||
| 670 | "This ILE should have been expanded")(static_cast <bool> ((Init < NumInits || VerifyOnly) && "This ILE should have been expanded") ? void (0) : __assert_fail ("(Init < NumInits || VerifyOnly) && \"This ILE should have been expanded\"" , "clang/lib/Sema/SemaInit.cpp", 670, __extension__ __PRETTY_FUNCTION__ )); | |||
| 671 | ||||
| 672 | if (FillWithNoInit) { | |||
| 673 | assert(!VerifyOnly && "should not fill with no-init in verify-only mode")(static_cast <bool> (!VerifyOnly && "should not fill with no-init in verify-only mode" ) ? void (0) : __assert_fail ("!VerifyOnly && \"should not fill with no-init in verify-only mode\"" , "clang/lib/Sema/SemaInit.cpp", 673, __extension__ __PRETTY_FUNCTION__ )); | |||
| 674 | Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType()); | |||
| 675 | if (Init < NumInits) | |||
| 676 | ILE->setInit(Init, Filler); | |||
| 677 | else | |||
| 678 | ILE->updateInit(SemaRef.Context, Init, Filler); | |||
| 679 | return; | |||
| 680 | } | |||
| 681 | // C++1y [dcl.init.aggr]p7: | |||
| 682 | // If there are fewer initializer-clauses in the list than there are | |||
| 683 | // members in the aggregate, then each member not explicitly initialized | |||
| 684 | // shall be initialized from its brace-or-equal-initializer [...] | |||
| 685 | if (Field->hasInClassInitializer()) { | |||
| 686 | if (VerifyOnly) | |||
| 687 | return; | |||
| 688 | ||||
| 689 | ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field); | |||
| 690 | if (DIE.isInvalid()) { | |||
| 691 | hadError = true; | |||
| 692 | return; | |||
| 693 | } | |||
| 694 | SemaRef.checkInitializerLifetime(MemberEntity, DIE.get()); | |||
| 695 | if (Init < NumInits) | |||
| 696 | ILE->setInit(Init, DIE.get()); | |||
| 697 | else { | |||
| 698 | ILE->updateInit(SemaRef.Context, Init, DIE.get()); | |||
| 699 | RequiresSecondPass = true; | |||
| 700 | } | |||
| 701 | return; | |||
| 702 | } | |||
| 703 | ||||
| 704 | if (Field->getType()->isReferenceType()) { | |||
| 705 | if (!VerifyOnly) { | |||
| 706 | // C++ [dcl.init.aggr]p9: | |||
| 707 | // If an incomplete or empty initializer-list leaves a | |||
| 708 | // member of reference type uninitialized, the program is | |||
| 709 | // ill-formed. | |||
| 710 | SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) | |||
| 711 | << Field->getType() | |||
| 712 | << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm()) | |||
| 713 | ->getSourceRange(); | |||
| 714 | SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member); | |||
| 715 | } | |||
| 716 | hadError = true; | |||
| 717 | return; | |||
| 718 | } | |||
| 719 | ||||
| 720 | ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity); | |||
| 721 | if (MemberInit.isInvalid()) { | |||
| 722 | hadError = true; | |||
| 723 | return; | |||
| 724 | } | |||
| 725 | ||||
| 726 | if (hadError || VerifyOnly) { | |||
| 727 | // Do nothing | |||
| 728 | } else if (Init < NumInits) { | |||
| 729 | ILE->setInit(Init, MemberInit.getAs<Expr>()); | |||
| 730 | } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) { | |||
| 731 | // Empty initialization requires a constructor call, so | |||
| 732 | // extend the initializer list to include the constructor | |||
| 733 | // call and make a note that we'll need to take another pass | |||
| 734 | // through the initializer list. | |||
| 735 | ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>()); | |||
| 736 | RequiresSecondPass = true; | |||
| 737 | } | |||
| 738 | } else if (InitListExpr *InnerILE | |||
| 739 | = dyn_cast<InitListExpr>(ILE->getInit(Init))) { | |||
| 740 | FillInEmptyInitializations(MemberEntity, InnerILE, | |||
| 741 | RequiresSecondPass, ILE, Init, FillWithNoInit); | |||
| 742 | } else if (DesignatedInitUpdateExpr *InnerDIUE = | |||
| 743 | dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) { | |||
| 744 | FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(), | |||
| 745 | RequiresSecondPass, ILE, Init, | |||
| 746 | /*FillWithNoInit =*/true); | |||
| 747 | } | |||
| 748 | } | |||
| 749 | ||||
| 750 | /// Recursively replaces NULL values within the given initializer list | |||
| 751 | /// with expressions that perform value-initialization of the | |||
| 752 | /// appropriate type, and finish off the InitListExpr formation. | |||
| 753 | void | |||
| 754 | InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity, | |||
| 755 | InitListExpr *ILE, | |||
| 756 | bool &RequiresSecondPass, | |||
| 757 | InitListExpr *OuterILE, | |||
| 758 | unsigned OuterIndex, | |||
| 759 | bool FillWithNoInit) { | |||
| 760 | assert((ILE->getType() != SemaRef.Context.VoidTy) &&(static_cast <bool> ((ILE->getType() != SemaRef.Context .VoidTy) && "Should not have void type") ? void (0) : __assert_fail ("(ILE->getType() != SemaRef.Context.VoidTy) && \"Should not have void type\"" , "clang/lib/Sema/SemaInit.cpp", 761, __extension__ __PRETTY_FUNCTION__ )) | |||
| 761 | "Should not have void type")(static_cast <bool> ((ILE->getType() != SemaRef.Context .VoidTy) && "Should not have void type") ? void (0) : __assert_fail ("(ILE->getType() != SemaRef.Context.VoidTy) && \"Should not have void type\"" , "clang/lib/Sema/SemaInit.cpp", 761, __extension__ __PRETTY_FUNCTION__ )); | |||
| 762 | ||||
| 763 | // We don't need to do any checks when just filling NoInitExprs; that can't | |||
| 764 | // fail. | |||
| 765 | if (FillWithNoInit && VerifyOnly) | |||
| 766 | return; | |||
| 767 | ||||
| 768 | // If this is a nested initializer list, we might have changed its contents | |||
| 769 | // (and therefore some of its properties, such as instantiation-dependence) | |||
| 770 | // while filling it in. Inform the outer initializer list so that its state | |||
| 771 | // can be updated to match. | |||
| 772 | // FIXME: We should fully build the inner initializers before constructing | |||
| 773 | // the outer InitListExpr instead of mutating AST nodes after they have | |||
| 774 | // been used as subexpressions of other nodes. | |||
| 775 | struct UpdateOuterILEWithUpdatedInit { | |||
| 776 | InitListExpr *Outer; | |||
| 777 | unsigned OuterIndex; | |||
| 778 | ~UpdateOuterILEWithUpdatedInit() { | |||
| 779 | if (Outer) | |||
| 780 | Outer->setInit(OuterIndex, Outer->getInit(OuterIndex)); | |||
| 781 | } | |||
| 782 | } UpdateOuterRAII = {OuterILE, OuterIndex}; | |||
| 783 | ||||
| 784 | // A transparent ILE is not performing aggregate initialization and should | |||
| 785 | // not be filled in. | |||
| 786 | if (ILE->isTransparent()) | |||
| 787 | return; | |||
| 788 | ||||
| 789 | if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { | |||
| 790 | const RecordDecl *RDecl = RType->getDecl(); | |||
| 791 | if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) | |||
| 792 | FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), | |||
| 793 | Entity, ILE, RequiresSecondPass, FillWithNoInit); | |||
| 794 | else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) && | |||
| 795 | cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) { | |||
| 796 | for (auto *Field : RDecl->fields()) { | |||
| 797 | if (Field->hasInClassInitializer()) { | |||
| 798 | FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass, | |||
| 799 | FillWithNoInit); | |||
| 800 | break; | |||
| 801 | } | |||
| 802 | } | |||
| 803 | } else { | |||
| 804 | // The fields beyond ILE->getNumInits() are default initialized, so in | |||
| 805 | // order to leave them uninitialized, the ILE is expanded and the extra | |||
| 806 | // fields are then filled with NoInitExpr. | |||
| 807 | unsigned NumElems = numStructUnionElements(ILE->getType()); | |||
| 808 | if (RDecl->hasFlexibleArrayMember()) | |||
| 809 | ++NumElems; | |||
| 810 | if (!VerifyOnly && ILE->getNumInits() < NumElems) | |||
| 811 | ILE->resizeInits(SemaRef.Context, NumElems); | |||
| 812 | ||||
| 813 | unsigned Init = 0; | |||
| 814 | ||||
| 815 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) { | |||
| 816 | for (auto &Base : CXXRD->bases()) { | |||
| 817 | if (hadError) | |||
| 818 | return; | |||
| 819 | ||||
| 820 | FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass, | |||
| 821 | FillWithNoInit); | |||
| 822 | ++Init; | |||
| 823 | } | |||
| 824 | } | |||
| 825 | ||||
| 826 | for (auto *Field : RDecl->fields()) { | |||
| 827 | if (Field->isUnnamedBitfield()) | |||
| 828 | continue; | |||
| 829 | ||||
| 830 | if (hadError) | |||
| 831 | return; | |||
| 832 | ||||
| 833 | FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass, | |||
| 834 | FillWithNoInit); | |||
| 835 | if (hadError) | |||
| 836 | return; | |||
| 837 | ||||
| 838 | ++Init; | |||
| 839 | ||||
| 840 | // Only look at the first initialization of a union. | |||
| 841 | if (RDecl->isUnion()) | |||
| 842 | break; | |||
| 843 | } | |||
| 844 | } | |||
| 845 | ||||
| 846 | return; | |||
| 847 | } | |||
| 848 | ||||
| 849 | QualType ElementType; | |||
| 850 | ||||
| 851 | InitializedEntity ElementEntity = Entity; | |||
| 852 | unsigned NumInits = ILE->getNumInits(); | |||
| 853 | unsigned NumElements = NumInits; | |||
| 854 | if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { | |||
| 855 | ElementType = AType->getElementType(); | |||
| 856 | if (const auto *CAType = dyn_cast<ConstantArrayType>(AType)) | |||
| 857 | NumElements = CAType->getSize().getZExtValue(); | |||
| 858 | // For an array new with an unknown bound, ask for one additional element | |||
| 859 | // in order to populate the array filler. | |||
| 860 | if (Entity.isVariableLengthArrayNew()) | |||
| 861 | ++NumElements; | |||
| 862 | ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, | |||
| 863 | 0, Entity); | |||
| 864 | } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { | |||
| 865 | ElementType = VType->getElementType(); | |||
| 866 | NumElements = VType->getNumElements(); | |||
| 867 | ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, | |||
| 868 | 0, Entity); | |||
| 869 | } else | |||
| 870 | ElementType = ILE->getType(); | |||
| 871 | ||||
| 872 | bool SkipEmptyInitChecks = false; | |||
| 873 | for (unsigned Init = 0; Init != NumElements; ++Init) { | |||
| 874 | if (hadError) | |||
| 875 | return; | |||
| 876 | ||||
| 877 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement || | |||
| 878 | ElementEntity.getKind() == InitializedEntity::EK_VectorElement) | |||
| 879 | ElementEntity.setElementIndex(Init); | |||
| 880 | ||||
| 881 | if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks)) | |||
| 882 | return; | |||
| 883 | ||||
| 884 | Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr); | |||
| 885 | if (!InitExpr && Init < NumInits && ILE->hasArrayFiller()) | |||
| 886 | ILE->setInit(Init, ILE->getArrayFiller()); | |||
| 887 | else if (!InitExpr && !ILE->hasArrayFiller()) { | |||
| 888 | // In VerifyOnly mode, there's no point performing empty initialization | |||
| 889 | // more than once. | |||
| 890 | if (SkipEmptyInitChecks) | |||
| 891 | continue; | |||
| 892 | ||||
| 893 | Expr *Filler = nullptr; | |||
| 894 | ||||
| 895 | if (FillWithNoInit) | |||
| 896 | Filler = new (SemaRef.Context) NoInitExpr(ElementType); | |||
| 897 | else { | |||
| 898 | ExprResult ElementInit = | |||
| 899 | PerformEmptyInit(ILE->getEndLoc(), ElementEntity); | |||
| 900 | if (ElementInit.isInvalid()) { | |||
| 901 | hadError = true; | |||
| 902 | return; | |||
| 903 | } | |||
| 904 | ||||
| 905 | Filler = ElementInit.getAs<Expr>(); | |||
| 906 | } | |||
| 907 | ||||
| 908 | if (hadError) { | |||
| 909 | // Do nothing | |||
| 910 | } else if (VerifyOnly) { | |||
| 911 | SkipEmptyInitChecks = true; | |||
| 912 | } else if (Init < NumInits) { | |||
| 913 | // For arrays, just set the expression used for value-initialization | |||
| 914 | // of the "holes" in the array. | |||
| 915 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) | |||
| 916 | ILE->setArrayFiller(Filler); | |||
| 917 | else | |||
| 918 | ILE->setInit(Init, Filler); | |||
| 919 | } else { | |||
| 920 | // For arrays, just set the expression used for value-initialization | |||
| 921 | // of the rest of elements and exit. | |||
| 922 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) { | |||
| 923 | ILE->setArrayFiller(Filler); | |||
| 924 | return; | |||
| 925 | } | |||
| 926 | ||||
| 927 | if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) { | |||
| 928 | // Empty initialization requires a constructor call, so | |||
| 929 | // extend the initializer list to include the constructor | |||
| 930 | // call and make a note that we'll need to take another pass | |||
| 931 | // through the initializer list. | |||
| 932 | ILE->updateInit(SemaRef.Context, Init, Filler); | |||
| 933 | RequiresSecondPass = true; | |||
| 934 | } | |||
| 935 | } | |||
| 936 | } else if (InitListExpr *InnerILE | |||
| 937 | = dyn_cast_or_null<InitListExpr>(InitExpr)) { | |||
| 938 | FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass, | |||
| 939 | ILE, Init, FillWithNoInit); | |||
| 940 | } else if (DesignatedInitUpdateExpr *InnerDIUE = | |||
| 941 | dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) { | |||
| 942 | FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(), | |||
| 943 | RequiresSecondPass, ILE, Init, | |||
| 944 | /*FillWithNoInit =*/true); | |||
| 945 | } | |||
| 946 | } | |||
| 947 | } | |||
| 948 | ||||
| 949 | static bool hasAnyDesignatedInits(const InitListExpr *IL) { | |||
| 950 | for (const Stmt *Init : *IL) | |||
| 951 | if (Init && isa<DesignatedInitExpr>(Init)) | |||
| 952 | return true; | |||
| 953 | return false; | |||
| 954 | } | |||
| 955 | ||||
| 956 | InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity, | |||
| 957 | InitListExpr *IL, QualType &T, bool VerifyOnly, | |||
| 958 | bool TreatUnavailableAsInvalid, | |||
| 959 | bool InOverloadResolution) | |||
| 960 | : SemaRef(S), VerifyOnly(VerifyOnly), | |||
| 961 | TreatUnavailableAsInvalid(TreatUnavailableAsInvalid), | |||
| 962 | InOverloadResolution(InOverloadResolution) { | |||
| 963 | if (!VerifyOnly || hasAnyDesignatedInits(IL)) { | |||
| 964 | FullyStructuredList = | |||
| 965 | createInitListExpr(T, IL->getSourceRange(), IL->getNumInits()); | |||
| 966 | ||||
| 967 | // FIXME: Check that IL isn't already the semantic form of some other | |||
| 968 | // InitListExpr. If it is, we'd create a broken AST. | |||
| 969 | if (!VerifyOnly) | |||
| 970 | FullyStructuredList->setSyntacticForm(IL); | |||
| 971 | } | |||
| 972 | ||||
| 973 | CheckExplicitInitList(Entity, IL, T, FullyStructuredList, | |||
| 974 | /*TopLevelObject=*/true); | |||
| 975 | ||||
| 976 | if (!hadError && FullyStructuredList) { | |||
| 977 | bool RequiresSecondPass = false; | |||
| 978 | FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass, | |||
| 979 | /*OuterILE=*/nullptr, /*OuterIndex=*/0); | |||
| 980 | if (RequiresSecondPass && !hadError) | |||
| 981 | FillInEmptyInitializations(Entity, FullyStructuredList, | |||
| 982 | RequiresSecondPass, nullptr, 0); | |||
| 983 | } | |||
| 984 | if (hadError && FullyStructuredList) | |||
| 985 | FullyStructuredList->markError(); | |||
| 986 | } | |||
| 987 | ||||
| 988 | int InitListChecker::numArrayElements(QualType DeclType) { | |||
| 989 | // FIXME: use a proper constant | |||
| 990 | int maxElements = 0x7FFFFFFF; | |||
| 991 | if (const ConstantArrayType *CAT = | |||
| 992 | SemaRef.Context.getAsConstantArrayType(DeclType)) { | |||
| 993 | maxElements = static_cast<int>(CAT->getSize().getZExtValue()); | |||
| 994 | } | |||
| 995 | return maxElements; | |||
| 996 | } | |||
| 997 | ||||
| 998 | int InitListChecker::numStructUnionElements(QualType DeclType) { | |||
| 999 | RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl(); | |||
| 1000 | int InitializableMembers = 0; | |||
| 1001 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl)) | |||
| 1002 | InitializableMembers += CXXRD->getNumBases(); | |||
| 1003 | for (const auto *Field : structDecl->fields()) | |||
| 1004 | if (!Field->isUnnamedBitfield()) | |||
| 1005 | ++InitializableMembers; | |||
| 1006 | ||||
| 1007 | if (structDecl->isUnion()) | |||
| 1008 | return std::min(InitializableMembers, 1); | |||
| 1009 | return InitializableMembers - structDecl->hasFlexibleArrayMember(); | |||
| 1010 | } | |||
| 1011 | ||||
| 1012 | /// Determine whether Entity is an entity for which it is idiomatic to elide | |||
| 1013 | /// the braces in aggregate initialization. | |||
| 1014 | static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) { | |||
| 1015 | // Recursive initialization of the one and only field within an aggregate | |||
| 1016 | // class is considered idiomatic. This case arises in particular for | |||
| 1017 | // initialization of std::array, where the C++ standard suggests the idiom of | |||
| 1018 | // | |||
| 1019 | // std::array<T, N> arr = {1, 2, 3}; | |||
| 1020 | // | |||
| 1021 | // (where std::array is an aggregate struct containing a single array field. | |||
| 1022 | ||||
| 1023 | if (!Entity.getParent()) | |||
| 1024 | return false; | |||
| 1025 | ||||
| 1026 | // Allows elide brace initialization for aggregates with empty base. | |||
| 1027 | if (Entity.getKind() == InitializedEntity::EK_Base) { | |||
| 1028 | auto *ParentRD = | |||
| 1029 | Entity.getParent()->getType()->castAs<RecordType>()->getDecl(); | |||
| 1030 | CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD); | |||
| 1031 | return CXXRD->getNumBases() == 1 && CXXRD->field_empty(); | |||
| 1032 | } | |||
| 1033 | ||||
| 1034 | // Allow brace elision if the only subobject is a field. | |||
| 1035 | if (Entity.getKind() == InitializedEntity::EK_Member) { | |||
| 1036 | auto *ParentRD = | |||
| 1037 | Entity.getParent()->getType()->castAs<RecordType>()->getDecl(); | |||
| 1038 | if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) { | |||
| 1039 | if (CXXRD->getNumBases()) { | |||
| 1040 | return false; | |||
| 1041 | } | |||
| 1042 | } | |||
| 1043 | auto FieldIt = ParentRD->field_begin(); | |||
| 1044 | assert(FieldIt != ParentRD->field_end() &&(static_cast <bool> (FieldIt != ParentRD->field_end( ) && "no fields but have initializer for member?") ? void (0) : __assert_fail ("FieldIt != ParentRD->field_end() && \"no fields but have initializer for member?\"" , "clang/lib/Sema/SemaInit.cpp", 1045, __extension__ __PRETTY_FUNCTION__ )) | |||
| 1045 | "no fields but have initializer for member?")(static_cast <bool> (FieldIt != ParentRD->field_end( ) && "no fields but have initializer for member?") ? void (0) : __assert_fail ("FieldIt != ParentRD->field_end() && \"no fields but have initializer for member?\"" , "clang/lib/Sema/SemaInit.cpp", 1045, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1046 | return ++FieldIt == ParentRD->field_end(); | |||
| 1047 | } | |||
| 1048 | ||||
| 1049 | return false; | |||
| 1050 | } | |||
| 1051 | ||||
| 1052 | /// Check whether the range of the initializer \p ParentIList from element | |||
| 1053 | /// \p Index onwards can be used to initialize an object of type \p T. Update | |||
| 1054 | /// \p Index to indicate how many elements of the list were consumed. | |||
| 1055 | /// | |||
| 1056 | /// This also fills in \p StructuredList, from element \p StructuredIndex | |||
| 1057 | /// onwards, with the fully-braced, desugared form of the initialization. | |||
| 1058 | void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity, | |||
| 1059 | InitListExpr *ParentIList, | |||
| 1060 | QualType T, unsigned &Index, | |||
| 1061 | InitListExpr *StructuredList, | |||
| 1062 | unsigned &StructuredIndex) { | |||
| 1063 | int maxElements = 0; | |||
| 1064 | ||||
| 1065 | if (T->isArrayType()) | |||
| 1066 | maxElements = numArrayElements(T); | |||
| 1067 | else if (T->isRecordType()) | |||
| 1068 | maxElements = numStructUnionElements(T); | |||
| 1069 | else if (T->isVectorType()) | |||
| 1070 | maxElements = T->castAs<VectorType>()->getNumElements(); | |||
| 1071 | else | |||
| 1072 | llvm_unreachable("CheckImplicitInitList(): Illegal type")::llvm::llvm_unreachable_internal("CheckImplicitInitList(): Illegal type" , "clang/lib/Sema/SemaInit.cpp", 1072); | |||
| 1073 | ||||
| 1074 | if (maxElements == 0) { | |||
| 1075 | if (!VerifyOnly) | |||
| 1076 | SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(), | |||
| 1077 | diag::err_implicit_empty_initializer); | |||
| 1078 | ++Index; | |||
| 1079 | hadError = true; | |||
| 1080 | return; | |||
| 1081 | } | |||
| 1082 | ||||
| 1083 | // Build a structured initializer list corresponding to this subobject. | |||
| 1084 | InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit( | |||
| 1085 | ParentIList, Index, T, StructuredList, StructuredIndex, | |||
| 1086 | SourceRange(ParentIList->getInit(Index)->getBeginLoc(), | |||
| 1087 | ParentIList->getSourceRange().getEnd())); | |||
| 1088 | unsigned StructuredSubobjectInitIndex = 0; | |||
| 1089 | ||||
| 1090 | // Check the element types and build the structural subobject. | |||
| 1091 | unsigned StartIndex = Index; | |||
| 1092 | CheckListElementTypes(Entity, ParentIList, T, | |||
| 1093 | /*SubobjectIsDesignatorContext=*/false, Index, | |||
| 1094 | StructuredSubobjectInitList, | |||
| 1095 | StructuredSubobjectInitIndex); | |||
| 1096 | ||||
| 1097 | if (StructuredSubobjectInitList) { | |||
| 1098 | StructuredSubobjectInitList->setType(T); | |||
| 1099 | ||||
| 1100 | unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); | |||
| 1101 | // Update the structured sub-object initializer so that it's ending | |||
| 1102 | // range corresponds with the end of the last initializer it used. | |||
| 1103 | if (EndIndex < ParentIList->getNumInits() && | |||
| 1104 | ParentIList->getInit(EndIndex)) { | |||
| 1105 | SourceLocation EndLoc | |||
| 1106 | = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); | |||
| 1107 | StructuredSubobjectInitList->setRBraceLoc(EndLoc); | |||
| 1108 | } | |||
| 1109 | ||||
| 1110 | // Complain about missing braces. | |||
| 1111 | if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) && | |||
| 1112 | !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) && | |||
| 1113 | !isIdiomaticBraceElisionEntity(Entity)) { | |||
| 1114 | SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(), | |||
| 1115 | diag::warn_missing_braces) | |||
| 1116 | << StructuredSubobjectInitList->getSourceRange() | |||
| 1117 | << FixItHint::CreateInsertion( | |||
| 1118 | StructuredSubobjectInitList->getBeginLoc(), "{") | |||
| 1119 | << FixItHint::CreateInsertion( | |||
| 1120 | SemaRef.getLocForEndOfToken( | |||
| 1121 | StructuredSubobjectInitList->getEndLoc()), | |||
| 1122 | "}"); | |||
| 1123 | } | |||
| 1124 | ||||
| 1125 | // Warn if this type won't be an aggregate in future versions of C++. | |||
| 1126 | auto *CXXRD = T->getAsCXXRecordDecl(); | |||
| 1127 | if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) { | |||
| 1128 | SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(), | |||
| 1129 | diag::warn_cxx20_compat_aggregate_init_with_ctors) | |||
| 1130 | << StructuredSubobjectInitList->getSourceRange() << T; | |||
| 1131 | } | |||
| 1132 | } | |||
| 1133 | } | |||
| 1134 | ||||
| 1135 | /// Warn that \p Entity was of scalar type and was initialized by a | |||
| 1136 | /// single-element braced initializer list. | |||
| 1137 | static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity, | |||
| 1138 | SourceRange Braces) { | |||
| 1139 | // Don't warn during template instantiation. If the initialization was | |||
| 1140 | // non-dependent, we warned during the initial parse; otherwise, the | |||
| 1141 | // type might not be scalar in some uses of the template. | |||
| 1142 | if (S.inTemplateInstantiation()) | |||
| 1143 | return; | |||
| 1144 | ||||
| 1145 | unsigned DiagID = 0; | |||
| 1146 | ||||
| 1147 | switch (Entity.getKind()) { | |||
| 1148 | case InitializedEntity::EK_VectorElement: | |||
| 1149 | case InitializedEntity::EK_ComplexElement: | |||
| 1150 | case InitializedEntity::EK_ArrayElement: | |||
| 1151 | case InitializedEntity::EK_Parameter: | |||
| 1152 | case InitializedEntity::EK_Parameter_CF_Audited: | |||
| 1153 | case InitializedEntity::EK_TemplateParameter: | |||
| 1154 | case InitializedEntity::EK_Result: | |||
| 1155 | // Extra braces here are suspicious. | |||
| 1156 | DiagID = diag::warn_braces_around_init; | |||
| 1157 | break; | |||
| 1158 | ||||
| 1159 | case InitializedEntity::EK_Member: | |||
| 1160 | // Warn on aggregate initialization but not on ctor init list or | |||
| 1161 | // default member initializer. | |||
| 1162 | if (Entity.getParent()) | |||
| 1163 | DiagID = diag::warn_braces_around_init; | |||
| 1164 | break; | |||
| 1165 | ||||
| 1166 | case InitializedEntity::EK_Variable: | |||
| 1167 | case InitializedEntity::EK_LambdaCapture: | |||
| 1168 | // No warning, might be direct-list-initialization. | |||
| 1169 | // FIXME: Should we warn for copy-list-initialization in these cases? | |||
| 1170 | break; | |||
| 1171 | ||||
| 1172 | case InitializedEntity::EK_New: | |||
| 1173 | case InitializedEntity::EK_Temporary: | |||
| 1174 | case InitializedEntity::EK_CompoundLiteralInit: | |||
| 1175 | // No warning, braces are part of the syntax of the underlying construct. | |||
| 1176 | break; | |||
| 1177 | ||||
| 1178 | case InitializedEntity::EK_RelatedResult: | |||
| 1179 | // No warning, we already warned when initializing the result. | |||
| 1180 | break; | |||
| 1181 | ||||
| 1182 | case InitializedEntity::EK_Exception: | |||
| 1183 | case InitializedEntity::EK_Base: | |||
| 1184 | case InitializedEntity::EK_Delegating: | |||
| 1185 | case InitializedEntity::EK_BlockElement: | |||
| 1186 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | |||
| 1187 | case InitializedEntity::EK_Binding: | |||
| 1188 | case InitializedEntity::EK_StmtExprResult: | |||
| 1189 | llvm_unreachable("unexpected braced scalar init")::llvm::llvm_unreachable_internal("unexpected braced scalar init" , "clang/lib/Sema/SemaInit.cpp", 1189); | |||
| 1190 | } | |||
| 1191 | ||||
| 1192 | if (DiagID) { | |||
| 1193 | S.Diag(Braces.getBegin(), DiagID) | |||
| 1194 | << Entity.getType()->isSizelessBuiltinType() << Braces | |||
| 1195 | << FixItHint::CreateRemoval(Braces.getBegin()) | |||
| 1196 | << FixItHint::CreateRemoval(Braces.getEnd()); | |||
| 1197 | } | |||
| 1198 | } | |||
| 1199 | ||||
| 1200 | /// Check whether the initializer \p IList (that was written with explicit | |||
| 1201 | /// braces) can be used to initialize an object of type \p T. | |||
| 1202 | /// | |||
| 1203 | /// This also fills in \p StructuredList with the fully-braced, desugared | |||
| 1204 | /// form of the initialization. | |||
| 1205 | void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity, | |||
| 1206 | InitListExpr *IList, QualType &T, | |||
| 1207 | InitListExpr *StructuredList, | |||
| 1208 | bool TopLevelObject) { | |||
| 1209 | unsigned Index = 0, StructuredIndex = 0; | |||
| 1210 | CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true, | |||
| 1211 | Index, StructuredList, StructuredIndex, TopLevelObject); | |||
| 1212 | if (StructuredList) { | |||
| 1213 | QualType ExprTy = T; | |||
| 1214 | if (!ExprTy->isArrayType()) | |||
| 1215 | ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context); | |||
| 1216 | if (!VerifyOnly) | |||
| 1217 | IList->setType(ExprTy); | |||
| 1218 | StructuredList->setType(ExprTy); | |||
| 1219 | } | |||
| 1220 | if (hadError) | |||
| 1221 | return; | |||
| 1222 | ||||
| 1223 | // Don't complain for incomplete types, since we'll get an error elsewhere. | |||
| 1224 | if (Index < IList->getNumInits() && !T->isIncompleteType()) { | |||
| 1225 | // We have leftover initializers | |||
| 1226 | bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus || | |||
| 1227 | (SemaRef.getLangOpts().OpenCL && T->isVectorType()); | |||
| 1228 | hadError = ExtraInitsIsError; | |||
| 1229 | if (VerifyOnly) { | |||
| 1230 | return; | |||
| 1231 | } else if (StructuredIndex == 1 && | |||
| 1232 | IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) == | |||
| 1233 | SIF_None) { | |||
| 1234 | unsigned DK = | |||
| 1235 | ExtraInitsIsError | |||
| 1236 | ? diag::err_excess_initializers_in_char_array_initializer | |||
| 1237 | : diag::ext_excess_initializers_in_char_array_initializer; | |||
| 1238 | SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) | |||
| 1239 | << IList->getInit(Index)->getSourceRange(); | |||
| 1240 | } else if (T->isSizelessBuiltinType()) { | |||
| 1241 | unsigned DK = ExtraInitsIsError | |||
| 1242 | ? diag::err_excess_initializers_for_sizeless_type | |||
| 1243 | : diag::ext_excess_initializers_for_sizeless_type; | |||
| 1244 | SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) | |||
| 1245 | << T << IList->getInit(Index)->getSourceRange(); | |||
| 1246 | } else { | |||
| 1247 | int initKind = T->isArrayType() ? 0 : | |||
| 1248 | T->isVectorType() ? 1 : | |||
| 1249 | T->isScalarType() ? 2 : | |||
| 1250 | T->isUnionType() ? 3 : | |||
| 1251 | 4; | |||
| 1252 | ||||
| 1253 | unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers | |||
| 1254 | : diag::ext_excess_initializers; | |||
| 1255 | SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) | |||
| 1256 | << initKind << IList->getInit(Index)->getSourceRange(); | |||
| 1257 | } | |||
| 1258 | } | |||
| 1259 | ||||
| 1260 | if (!VerifyOnly) { | |||
| 1261 | if (T->isScalarType() && IList->getNumInits() == 1 && | |||
| 1262 | !isa<InitListExpr>(IList->getInit(0))) | |||
| 1263 | warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange()); | |||
| 1264 | ||||
| 1265 | // Warn if this is a class type that won't be an aggregate in future | |||
| 1266 | // versions of C++. | |||
| 1267 | auto *CXXRD = T->getAsCXXRecordDecl(); | |||
| 1268 | if (CXXRD && CXXRD->hasUserDeclaredConstructor()) { | |||
| 1269 | // Don't warn if there's an equivalent default constructor that would be | |||
| 1270 | // used instead. | |||
| 1271 | bool HasEquivCtor = false; | |||
| 1272 | if (IList->getNumInits() == 0) { | |||
| 1273 | auto *CD = SemaRef.LookupDefaultConstructor(CXXRD); | |||
| 1274 | HasEquivCtor = CD && !CD->isDeleted(); | |||
| 1275 | } | |||
| 1276 | ||||
| 1277 | if (!HasEquivCtor) { | |||
| 1278 | SemaRef.Diag(IList->getBeginLoc(), | |||
| 1279 | diag::warn_cxx20_compat_aggregate_init_with_ctors) | |||
| 1280 | << IList->getSourceRange() << T; | |||
| 1281 | } | |||
| 1282 | } | |||
| 1283 | } | |||
| 1284 | } | |||
| 1285 | ||||
| 1286 | void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity, | |||
| 1287 | InitListExpr *IList, | |||
| 1288 | QualType &DeclType, | |||
| 1289 | bool SubobjectIsDesignatorContext, | |||
| 1290 | unsigned &Index, | |||
| 1291 | InitListExpr *StructuredList, | |||
| 1292 | unsigned &StructuredIndex, | |||
| 1293 | bool TopLevelObject) { | |||
| 1294 | if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) { | |||
| 1295 | // Explicitly braced initializer for complex type can be real+imaginary | |||
| 1296 | // parts. | |||
| 1297 | CheckComplexType(Entity, IList, DeclType, Index, | |||
| 1298 | StructuredList, StructuredIndex); | |||
| 1299 | } else if (DeclType->isScalarType()) { | |||
| 1300 | CheckScalarType(Entity, IList, DeclType, Index, | |||
| 1301 | StructuredList, StructuredIndex); | |||
| 1302 | } else if (DeclType->isVectorType()) { | |||
| 1303 | CheckVectorType(Entity, IList, DeclType, Index, | |||
| 1304 | StructuredList, StructuredIndex); | |||
| 1305 | } else if (DeclType->isRecordType()) { | |||
| 1306 | assert(DeclType->isAggregateType() &&(static_cast <bool> (DeclType->isAggregateType() && "non-aggregate records should be handed in CheckSubElementType" ) ? void (0) : __assert_fail ("DeclType->isAggregateType() && \"non-aggregate records should be handed in CheckSubElementType\"" , "clang/lib/Sema/SemaInit.cpp", 1307, __extension__ __PRETTY_FUNCTION__ )) | |||
| 1307 | "non-aggregate records should be handed in CheckSubElementType")(static_cast <bool> (DeclType->isAggregateType() && "non-aggregate records should be handed in CheckSubElementType" ) ? void (0) : __assert_fail ("DeclType->isAggregateType() && \"non-aggregate records should be handed in CheckSubElementType\"" , "clang/lib/Sema/SemaInit.cpp", 1307, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1308 | RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); | |||
| 1309 | auto Bases = | |||
| 1310 | CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), | |||
| 1311 | CXXRecordDecl::base_class_iterator()); | |||
| 1312 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) | |||
| 1313 | Bases = CXXRD->bases(); | |||
| 1314 | CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(), | |||
| 1315 | SubobjectIsDesignatorContext, Index, StructuredList, | |||
| 1316 | StructuredIndex, TopLevelObject); | |||
| 1317 | } else if (DeclType->isArrayType()) { | |||
| 1318 | llvm::APSInt Zero( | |||
| 1319 | SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), | |||
| 1320 | false); | |||
| 1321 | CheckArrayType(Entity, IList, DeclType, Zero, | |||
| 1322 | SubobjectIsDesignatorContext, Index, | |||
| 1323 | StructuredList, StructuredIndex); | |||
| 1324 | } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { | |||
| 1325 | // This type is invalid, issue a diagnostic. | |||
| 1326 | ++Index; | |||
| 1327 | if (!VerifyOnly) | |||
| 1328 | SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type) | |||
| 1329 | << DeclType; | |||
| 1330 | hadError = true; | |||
| 1331 | } else if (DeclType->isReferenceType()) { | |||
| 1332 | CheckReferenceType(Entity, IList, DeclType, Index, | |||
| 1333 | StructuredList, StructuredIndex); | |||
| 1334 | } else if (DeclType->isObjCObjectType()) { | |||
| 1335 | if (!VerifyOnly) | |||
| 1336 | SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType; | |||
| 1337 | hadError = true; | |||
| 1338 | } else if (DeclType->isOCLIntelSubgroupAVCType() || | |||
| 1339 | DeclType->isSizelessBuiltinType()) { | |||
| 1340 | // Checks for scalar type are sufficient for these types too. | |||
| 1341 | CheckScalarType(Entity, IList, DeclType, Index, StructuredList, | |||
| 1342 | StructuredIndex); | |||
| 1343 | } else { | |||
| 1344 | if (!VerifyOnly) | |||
| 1345 | SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type) | |||
| 1346 | << DeclType; | |||
| 1347 | hadError = true; | |||
| 1348 | } | |||
| 1349 | } | |||
| 1350 | ||||
| 1351 | void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, | |||
| 1352 | InitListExpr *IList, | |||
| 1353 | QualType ElemType, | |||
| 1354 | unsigned &Index, | |||
| 1355 | InitListExpr *StructuredList, | |||
| 1356 | unsigned &StructuredIndex, | |||
| 1357 | bool DirectlyDesignated) { | |||
| 1358 | Expr *expr = IList->getInit(Index); | |||
| 1359 | ||||
| 1360 | if (ElemType->isReferenceType()) | |||
| 1361 | return CheckReferenceType(Entity, IList, ElemType, Index, | |||
| 1362 | StructuredList, StructuredIndex); | |||
| 1363 | ||||
| 1364 | if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { | |||
| 1365 | if (SubInitList->getNumInits() == 1 && | |||
| 1366 | IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) == | |||
| 1367 | SIF_None) { | |||
| 1368 | // FIXME: It would be more faithful and no less correct to include an | |||
| 1369 | // InitListExpr in the semantic form of the initializer list in this case. | |||
| 1370 | expr = SubInitList->getInit(0); | |||
| 1371 | } | |||
| 1372 | // Nested aggregate initialization and C++ initialization are handled later. | |||
| 1373 | } else if (isa<ImplicitValueInitExpr>(expr)) { | |||
| 1374 | // This happens during template instantiation when we see an InitListExpr | |||
| 1375 | // that we've already checked once. | |||
| 1376 | assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&(static_cast <bool> (SemaRef.Context.hasSameType(expr-> getType(), ElemType) && "found implicit initialization for the wrong type" ) ? void (0) : __assert_fail ("SemaRef.Context.hasSameType(expr->getType(), ElemType) && \"found implicit initialization for the wrong type\"" , "clang/lib/Sema/SemaInit.cpp", 1377, __extension__ __PRETTY_FUNCTION__ )) | |||
| 1377 | "found implicit initialization for the wrong type")(static_cast <bool> (SemaRef.Context.hasSameType(expr-> getType(), ElemType) && "found implicit initialization for the wrong type" ) ? void (0) : __assert_fail ("SemaRef.Context.hasSameType(expr->getType(), ElemType) && \"found implicit initialization for the wrong type\"" , "clang/lib/Sema/SemaInit.cpp", 1377, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1378 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); | |||
| 1379 | ++Index; | |||
| 1380 | return; | |||
| 1381 | } | |||
| 1382 | ||||
| 1383 | if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) { | |||
| 1384 | // C++ [dcl.init.aggr]p2: | |||
| 1385 | // Each member is copy-initialized from the corresponding | |||
| 1386 | // initializer-clause. | |||
| 1387 | ||||
| 1388 | // FIXME: Better EqualLoc? | |||
| 1389 | InitializationKind Kind = | |||
| 1390 | InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation()); | |||
| 1391 | ||||
| 1392 | // Vector elements can be initialized from other vectors in which case | |||
| 1393 | // we need initialization entity with a type of a vector (and not a vector | |||
| 1394 | // element!) initializing multiple vector elements. | |||
| 1395 | auto TmpEntity = | |||
| 1396 | (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType()) | |||
| 1397 | ? InitializedEntity::InitializeTemporary(ElemType) | |||
| 1398 | : Entity; | |||
| 1399 | ||||
| 1400 | InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr, | |||
| 1401 | /*TopLevelOfInitList*/ true); | |||
| 1402 | ||||
| 1403 | // C++14 [dcl.init.aggr]p13: | |||
| 1404 | // If the assignment-expression can initialize a member, the member is | |||
| 1405 | // initialized. Otherwise [...] brace elision is assumed | |||
| 1406 | // | |||
| 1407 | // Brace elision is never performed if the element is not an | |||
| 1408 | // assignment-expression. | |||
| 1409 | if (Seq || isa<InitListExpr>(expr)) { | |||
| 1410 | if (!VerifyOnly) { | |||
| 1411 | ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr); | |||
| 1412 | if (Result.isInvalid()) | |||
| 1413 | hadError = true; | |||
| 1414 | ||||
| 1415 | UpdateStructuredListElement(StructuredList, StructuredIndex, | |||
| 1416 | Result.getAs<Expr>()); | |||
| 1417 | } else if (!Seq) { | |||
| 1418 | hadError = true; | |||
| 1419 | } else if (StructuredList) { | |||
| 1420 | UpdateStructuredListElement(StructuredList, StructuredIndex, | |||
| 1421 | getDummyInit()); | |||
| 1422 | } | |||
| 1423 | ++Index; | |||
| 1424 | return; | |||
| 1425 | } | |||
| 1426 | ||||
| 1427 | // Fall through for subaggregate initialization | |||
| 1428 | } else if (ElemType->isScalarType() || ElemType->isAtomicType()) { | |||
| 1429 | // FIXME: Need to handle atomic aggregate types with implicit init lists. | |||
| 1430 | return CheckScalarType(Entity, IList, ElemType, Index, | |||
| 1431 | StructuredList, StructuredIndex); | |||
| 1432 | } else if (const ArrayType *arrayType = | |||
| 1433 | SemaRef.Context.getAsArrayType(ElemType)) { | |||
| 1434 | // arrayType can be incomplete if we're initializing a flexible | |||
| 1435 | // array member. There's nothing we can do with the completed | |||
| 1436 | // type here, though. | |||
| 1437 | ||||
| 1438 | if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) { | |||
| 1439 | // FIXME: Should we do this checking in verify-only mode? | |||
| 1440 | if (!VerifyOnly) | |||
| 1441 | CheckStringInit(expr, ElemType, arrayType, SemaRef); | |||
| 1442 | if (StructuredList) | |||
| 1443 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); | |||
| 1444 | ++Index; | |||
| 1445 | return; | |||
| 1446 | } | |||
| 1447 | ||||
| 1448 | // Fall through for subaggregate initialization. | |||
| 1449 | ||||
| 1450 | } else { | |||
| 1451 | assert((ElemType->isRecordType() || ElemType->isVectorType() ||(static_cast <bool> ((ElemType->isRecordType() || ElemType ->isVectorType() || ElemType->isOpenCLSpecificType()) && "Unexpected type") ? void (0) : __assert_fail ("(ElemType->isRecordType() || ElemType->isVectorType() || ElemType->isOpenCLSpecificType()) && \"Unexpected type\"" , "clang/lib/Sema/SemaInit.cpp", 1452, __extension__ __PRETTY_FUNCTION__ )) | |||
| 1452 | ElemType->isOpenCLSpecificType()) && "Unexpected type")(static_cast <bool> ((ElemType->isRecordType() || ElemType ->isVectorType() || ElemType->isOpenCLSpecificType()) && "Unexpected type") ? void (0) : __assert_fail ("(ElemType->isRecordType() || ElemType->isVectorType() || ElemType->isOpenCLSpecificType()) && \"Unexpected type\"" , "clang/lib/Sema/SemaInit.cpp", 1452, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1453 | ||||
| 1454 | // C99 6.7.8p13: | |||
| 1455 | // | |||
| 1456 | // The initializer for a structure or union object that has | |||
| 1457 | // automatic storage duration shall be either an initializer | |||
| 1458 | // list as described below, or a single expression that has | |||
| 1459 | // compatible structure or union type. In the latter case, the | |||
| 1460 | // initial value of the object, including unnamed members, is | |||
| 1461 | // that of the expression. | |||
| 1462 | ExprResult ExprRes = expr; | |||
| 1463 | if (SemaRef.CheckSingleAssignmentConstraints( | |||
| 1464 | ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) { | |||
| 1465 | if (ExprRes.isInvalid()) | |||
| 1466 | hadError = true; | |||
| 1467 | else { | |||
| 1468 | ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get()); | |||
| 1469 | if (ExprRes.isInvalid()) | |||
| 1470 | hadError = true; | |||
| 1471 | } | |||
| 1472 | UpdateStructuredListElement(StructuredList, StructuredIndex, | |||
| 1473 | ExprRes.getAs<Expr>()); | |||
| 1474 | ++Index; | |||
| 1475 | return; | |||
| 1476 | } | |||
| 1477 | ExprRes.get(); | |||
| 1478 | // Fall through for subaggregate initialization | |||
| 1479 | } | |||
| 1480 | ||||
| 1481 | // C++ [dcl.init.aggr]p12: | |||
| 1482 | // | |||
| 1483 | // [...] Otherwise, if the member is itself a non-empty | |||
| 1484 | // subaggregate, brace elision is assumed and the initializer is | |||
| 1485 | // considered for the initialization of the first member of | |||
| 1486 | // the subaggregate. | |||
| 1487 | // OpenCL vector initializer is handled elsewhere. | |||
| 1488 | if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) || | |||
| 1489 | ElemType->isAggregateType()) { | |||
| 1490 | CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList, | |||
| 1491 | StructuredIndex); | |||
| 1492 | ++StructuredIndex; | |||
| 1493 | ||||
| 1494 | // In C++20, brace elision is not permitted for a designated initializer. | |||
| 1495 | if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) { | |||
| 1496 | if (InOverloadResolution) | |||
| 1497 | hadError = true; | |||
| 1498 | if (!VerifyOnly) { | |||
| 1499 | SemaRef.Diag(expr->getBeginLoc(), | |||
| 1500 | diag::ext_designated_init_brace_elision) | |||
| 1501 | << expr->getSourceRange() | |||
| 1502 | << FixItHint::CreateInsertion(expr->getBeginLoc(), "{") | |||
| 1503 | << FixItHint::CreateInsertion( | |||
| 1504 | SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}"); | |||
| 1505 | } | |||
| 1506 | } | |||
| 1507 | } else { | |||
| 1508 | if (!VerifyOnly) { | |||
| 1509 | // We cannot initialize this element, so let PerformCopyInitialization | |||
| 1510 | // produce the appropriate diagnostic. We already checked that this | |||
| 1511 | // initialization will fail. | |||
| 1512 | ExprResult Copy = | |||
| 1513 | SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr, | |||
| 1514 | /*TopLevelOfInitList=*/true); | |||
| 1515 | (void)Copy; | |||
| 1516 | assert(Copy.isInvalid() &&(static_cast <bool> (Copy.isInvalid() && "expected non-aggregate initialization to fail" ) ? void (0) : __assert_fail ("Copy.isInvalid() && \"expected non-aggregate initialization to fail\"" , "clang/lib/Sema/SemaInit.cpp", 1517, __extension__ __PRETTY_FUNCTION__ )) | |||
| 1517 | "expected non-aggregate initialization to fail")(static_cast <bool> (Copy.isInvalid() && "expected non-aggregate initialization to fail" ) ? void (0) : __assert_fail ("Copy.isInvalid() && \"expected non-aggregate initialization to fail\"" , "clang/lib/Sema/SemaInit.cpp", 1517, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1518 | } | |||
| 1519 | hadError = true; | |||
| 1520 | ++Index; | |||
| 1521 | ++StructuredIndex; | |||
| 1522 | } | |||
| 1523 | } | |||
| 1524 | ||||
| 1525 | void InitListChecker::CheckComplexType(const InitializedEntity &Entity, | |||
| 1526 | InitListExpr *IList, QualType DeclType, | |||
| 1527 | unsigned &Index, | |||
| 1528 | InitListExpr *StructuredList, | |||
| 1529 | unsigned &StructuredIndex) { | |||
| 1530 | assert(Index == 0 && "Index in explicit init list must be zero")(static_cast <bool> (Index == 0 && "Index in explicit init list must be zero" ) ? void (0) : __assert_fail ("Index == 0 && \"Index in explicit init list must be zero\"" , "clang/lib/Sema/SemaInit.cpp", 1530, __extension__ __PRETTY_FUNCTION__ )); | |||
| 1531 | ||||
| 1532 | // As an extension, clang supports complex initializers, which initialize | |||
| 1533 | // a complex number component-wise. When an explicit initializer list for | |||
| 1534 | // a complex number contains two initializers, this extension kicks in: | |||
| 1535 | // it expects the initializer list to contain two elements convertible to | |||
| 1536 | // the element type of the complex type. The first element initializes | |||
| 1537 | // the real part, and the second element intitializes the imaginary part. | |||
| 1538 | ||||
| 1539 | if (IList->getNumInits() < 2) | |||
| 1540 | return CheckScalarType(Entity, IList, DeclType, Index, StructuredList, | |||
| 1541 | StructuredIndex); | |||
| 1542 | ||||
| 1543 | // This is an extension in C. (The builtin _Complex type does not exist | |||
| 1544 | // in the C++ standard.) | |||
| 1545 | if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly) | |||
| 1546 | SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init) | |||
| 1547 | << IList->getSourceRange(); | |||
| 1548 | ||||
| 1549 | // Initialize the complex number. | |||
| 1550 | QualType elementType = DeclType->castAs<ComplexType>()->getElementType(); | |||
| 1551 | InitializedEntity ElementEntity = | |||
| 1552 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); | |||
| 1553 | ||||
| 1554 | for (unsigned i = 0; i < 2; ++i) { | |||
| 1555 | ElementEntity.setElementIndex(Index); | |||
| 1556 | CheckSubElementType(ElementEntity, IList, elementType, Index, | |||
| 1557 | StructuredList, StructuredIndex); | |||
| 1558 | } | |||
| 1559 | } | |||
| 1560 | ||||
| 1561 | void InitListChecker::CheckScalarType(const InitializedEntity &Entity, | |||
| 1562 | InitListExpr *IList, QualType DeclType, | |||
| 1563 | unsigned &Index, | |||
| 1564 | InitListExpr *StructuredList, | |||
| 1565 | unsigned &StructuredIndex) { | |||
| 1566 | if (Index >= IList->getNumInits()) { | |||
| 1567 | if (!VerifyOnly) { | |||
| 1568 | if (SemaRef.getLangOpts().CPlusPlus) { | |||
| 1569 | if (DeclType->isSizelessBuiltinType()) | |||
| 1570 | SemaRef.Diag(IList->getBeginLoc(), | |||
| 1571 | SemaRef.getLangOpts().CPlusPlus11 | |||
| 1572 | ? diag::warn_cxx98_compat_empty_sizeless_initializer | |||
| 1573 | : diag::err_empty_sizeless_initializer) | |||
| 1574 | << DeclType << IList->getSourceRange(); | |||
| 1575 | else | |||
| 1576 | SemaRef.Diag(IList->getBeginLoc(), | |||
| 1577 | SemaRef.getLangOpts().CPlusPlus11 | |||
| 1578 | ? diag::warn_cxx98_compat_empty_scalar_initializer | |||
| 1579 | : diag::err_empty_scalar_initializer) | |||
| 1580 | << IList->getSourceRange(); | |||
| 1581 | } | |||
| 1582 | } | |||
| 1583 | hadError = | |||
| 1584 | SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11; | |||
| 1585 | ++Index; | |||
| 1586 | ++StructuredIndex; | |||
| 1587 | return; | |||
| 1588 | } | |||
| 1589 | ||||
| 1590 | Expr *expr = IList->getInit(Index); | |||
| 1591 | if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) { | |||
| 1592 | // FIXME: This is invalid, and accepting it causes overload resolution | |||
| 1593 | // to pick the wrong overload in some corner cases. | |||
| 1594 | if (!VerifyOnly) | |||
| 1595 | SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init) | |||
| 1596 | << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange(); | |||
| 1597 | ||||
| 1598 | CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList, | |||
| 1599 | StructuredIndex); | |||
| 1600 | return; | |||
| 1601 | } else if (isa<DesignatedInitExpr>(expr)) { | |||
| 1602 | if (!VerifyOnly) | |||
| 1603 | SemaRef.Diag(expr->getBeginLoc(), | |||
| 1604 | diag::err_designator_for_scalar_or_sizeless_init) | |||
| 1605 | << DeclType->isSizelessBuiltinType() << DeclType | |||
| 1606 | << expr->getSourceRange(); | |||
| 1607 | hadError = true; | |||
| 1608 | ++Index; | |||
| 1609 | ++StructuredIndex; | |||
| 1610 | return; | |||
| 1611 | } | |||
| 1612 | ||||
| 1613 | ExprResult Result; | |||
| 1614 | if (VerifyOnly) { | |||
| 1615 | if (SemaRef.CanPerformCopyInitialization(Entity, expr)) | |||
| 1616 | Result = getDummyInit(); | |||
| 1617 | else | |||
| 1618 | Result = ExprError(); | |||
| 1619 | } else { | |||
| 1620 | Result = | |||
| 1621 | SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr, | |||
| 1622 | /*TopLevelOfInitList=*/true); | |||
| 1623 | } | |||
| 1624 | ||||
| 1625 | Expr *ResultExpr = nullptr; | |||
| 1626 | ||||
| 1627 | if (Result.isInvalid()) | |||
| 1628 | hadError = true; // types weren't compatible. | |||
| 1629 | else { | |||
| 1630 | ResultExpr = Result.getAs<Expr>(); | |||
| 1631 | ||||
| 1632 | if (ResultExpr != expr && !VerifyOnly) { | |||
| 1633 | // The type was promoted, update initializer list. | |||
| 1634 | // FIXME: Why are we updating the syntactic init list? | |||
| 1635 | IList->setInit(Index, ResultExpr); | |||
| 1636 | } | |||
| 1637 | } | |||
| 1638 | UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); | |||
| 1639 | ++Index; | |||
| 1640 | } | |||
| 1641 | ||||
| 1642 | void InitListChecker::CheckReferenceType(const InitializedEntity &Entity, | |||
| 1643 | InitListExpr *IList, QualType DeclType, | |||
| 1644 | unsigned &Index, | |||
| 1645 | InitListExpr *StructuredList, | |||
| 1646 | unsigned &StructuredIndex) { | |||
| 1647 | if (Index >= IList->getNumInits()) { | |||
| 1648 | // FIXME: It would be wonderful if we could point at the actual member. In | |||
| 1649 | // general, it would be useful to pass location information down the stack, | |||
| 1650 | // so that we know the location (or decl) of the "current object" being | |||
| 1651 | // initialized. | |||
| 1652 | if (!VerifyOnly) | |||
| 1653 | SemaRef.Diag(IList->getBeginLoc(), | |||
| 1654 | diag::err_init_reference_member_uninitialized) | |||
| 1655 | << DeclType << IList->getSourceRange(); | |||
| 1656 | hadError = true; | |||
| 1657 | ++Index; | |||
| 1658 | ++StructuredIndex; | |||
| 1659 | return; | |||
| 1660 | } | |||
| 1661 | ||||
| 1662 | Expr *expr = IList->getInit(Index); | |||
| 1663 | if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) { | |||
| 1664 | if (!VerifyOnly) | |||
| 1665 | SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list) | |||
| 1666 | << DeclType << IList->getSourceRange(); | |||
| 1667 | hadError = true; | |||
| 1668 | ++Index; | |||
| 1669 | ++StructuredIndex; | |||
| 1670 | return; | |||
| 1671 | } | |||
| 1672 | ||||
| 1673 | ExprResult Result; | |||
| 1674 | if (VerifyOnly) { | |||
| 1675 | if (SemaRef.CanPerformCopyInitialization(Entity,expr)) | |||
| 1676 | Result = getDummyInit(); | |||
| 1677 | else | |||
| 1678 | Result = ExprError(); | |||
| 1679 | } else { | |||
| 1680 | Result = | |||
| 1681 | SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr, | |||
| 1682 | /*TopLevelOfInitList=*/true); | |||
| 1683 | } | |||
| 1684 | ||||
| 1685 | if (Result.isInvalid()) | |||
| 1686 | hadError = true; | |||
| 1687 | ||||
| 1688 | expr = Result.getAs<Expr>(); | |||
| 1689 | // FIXME: Why are we updating the syntactic init list? | |||
| 1690 | if (!VerifyOnly && expr) | |||
| 1691 | IList->setInit(Index, expr); | |||
| 1692 | ||||
| 1693 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); | |||
| 1694 | ++Index; | |||
| 1695 | } | |||
| 1696 | ||||
| 1697 | void InitListChecker::CheckVectorType(const InitializedEntity &Entity, | |||
| 1698 | InitListExpr *IList, QualType DeclType, | |||
| 1699 | unsigned &Index, | |||
| 1700 | InitListExpr *StructuredList, | |||
| 1701 | unsigned &StructuredIndex) { | |||
| 1702 | const VectorType *VT = DeclType->castAs<VectorType>(); | |||
| 1703 | unsigned maxElements = VT->getNumElements(); | |||
| 1704 | unsigned numEltsInit = 0; | |||
| 1705 | QualType elementType = VT->getElementType(); | |||
| 1706 | ||||
| 1707 | if (Index >= IList->getNumInits()) { | |||
| 1708 | // Make sure the element type can be value-initialized. | |||
| 1709 | CheckEmptyInitializable( | |||
| 1710 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity), | |||
| 1711 | IList->getEndLoc()); | |||
| 1712 | return; | |||
| 1713 | } | |||
| 1714 | ||||
| 1715 | if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) { | |||
| 1716 | // If the initializing element is a vector, try to copy-initialize | |||
| 1717 | // instead of breaking it apart (which is doomed to failure anyway). | |||
| 1718 | Expr *Init = IList->getInit(Index); | |||
| 1719 | if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) { | |||
| 1720 | ExprResult Result; | |||
| 1721 | if (VerifyOnly) { | |||
| 1722 | if (SemaRef.CanPerformCopyInitialization(Entity, Init)) | |||
| 1723 | Result = getDummyInit(); | |||
| 1724 | else | |||
| 1725 | Result = ExprError(); | |||
| 1726 | } else { | |||
| 1727 | Result = | |||
| 1728 | SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init, | |||
| 1729 | /*TopLevelOfInitList=*/true); | |||
| 1730 | } | |||
| 1731 | ||||
| 1732 | Expr *ResultExpr = nullptr; | |||
| 1733 | if (Result.isInvalid()) | |||
| 1734 | hadError = true; // types weren't compatible. | |||
| 1735 | else { | |||
| 1736 | ResultExpr = Result.getAs<Expr>(); | |||
| 1737 | ||||
| 1738 | if (ResultExpr != Init && !VerifyOnly) { | |||
| 1739 | // The type was promoted, update initializer list. | |||
| 1740 | // FIXME: Why are we updating the syntactic init list? | |||
| 1741 | IList->setInit(Index, ResultExpr); | |||
| 1742 | } | |||
| 1743 | } | |||
| 1744 | UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); | |||
| 1745 | ++Index; | |||
| 1746 | return; | |||
| 1747 | } | |||
| 1748 | ||||
| 1749 | InitializedEntity ElementEntity = | |||
| 1750 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); | |||
| 1751 | ||||
| 1752 | for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { | |||
| 1753 | // Don't attempt to go past the end of the init list | |||
| 1754 | if (Index >= IList->getNumInits()) { | |||
| 1755 | CheckEmptyInitializable(ElementEntity, IList->getEndLoc()); | |||
| 1756 | break; | |||
| 1757 | } | |||
| 1758 | ||||
| 1759 | ElementEntity.setElementIndex(Index); | |||
| 1760 | CheckSubElementType(ElementEntity, IList, elementType, Index, | |||
| 1761 | StructuredList, StructuredIndex); | |||
| 1762 | } | |||
| 1763 | ||||
| 1764 | if (VerifyOnly) | |||
| 1765 | return; | |||
| 1766 | ||||
| 1767 | bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian(); | |||
| 1768 | const VectorType *T = Entity.getType()->castAs<VectorType>(); | |||
| 1769 | if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector || | |||
| 1770 | T->getVectorKind() == VectorType::NeonPolyVector)) { | |||
| 1771 | // The ability to use vector initializer lists is a GNU vector extension | |||
| 1772 | // and is unrelated to the NEON intrinsics in arm_neon.h. On little | |||
| 1773 | // endian machines it works fine, however on big endian machines it | |||
| 1774 | // exhibits surprising behaviour: | |||
| 1775 | // | |||
| 1776 | // uint32x2_t x = {42, 64}; | |||
| 1777 | // return vget_lane_u32(x, 0); // Will return 64. | |||
| 1778 | // | |||
| 1779 | // Because of this, explicitly call out that it is non-portable. | |||
| 1780 | // | |||
| 1781 | SemaRef.Diag(IList->getBeginLoc(), | |||
| 1782 | diag::warn_neon_vector_initializer_non_portable); | |||
| 1783 | ||||
| 1784 | const char *typeCode; | |||
| 1785 | unsigned typeSize = SemaRef.Context.getTypeSize(elementType); | |||
| 1786 | ||||
| 1787 | if (elementType->isFloatingType()) | |||
| 1788 | typeCode = "f"; | |||
| 1789 | else if (elementType->isSignedIntegerType()) | |||
| 1790 | typeCode = "s"; | |||
| 1791 | else if (elementType->isUnsignedIntegerType()) | |||
| 1792 | typeCode = "u"; | |||
| 1793 | else | |||
| 1794 | llvm_unreachable("Invalid element type!")::llvm::llvm_unreachable_internal("Invalid element type!", "clang/lib/Sema/SemaInit.cpp" , 1794); | |||
| 1795 | ||||
| 1796 | SemaRef.Diag(IList->getBeginLoc(), | |||
| 1797 | SemaRef.Context.getTypeSize(VT) > 64 | |||
| 1798 | ? diag::note_neon_vector_initializer_non_portable_q | |||
| 1799 | : diag::note_neon_vector_initializer_non_portable) | |||
| 1800 | << typeCode << typeSize; | |||
| 1801 | } | |||
| 1802 | ||||
| 1803 | return; | |||
| 1804 | } | |||
| 1805 | ||||
| 1806 | InitializedEntity ElementEntity = | |||
| 1807 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); | |||
| 1808 | ||||
| 1809 | // OpenCL and HLSL initializers allow vectors to be constructed from vectors. | |||
| 1810 | for (unsigned i = 0; i < maxElements; ++i) { | |||
| 1811 | // Don't attempt to go past the end of the init list | |||
| 1812 | if (Index >= IList->getNumInits()) | |||
| 1813 | break; | |||
| 1814 | ||||
| 1815 | ElementEntity.setElementIndex(Index); | |||
| 1816 | ||||
| 1817 | QualType IType = IList->getInit(Index)->getType(); | |||
| 1818 | if (!IType->isVectorType()) { | |||
| 1819 | CheckSubElementType(ElementEntity, IList, elementType, Index, | |||
| 1820 | StructuredList, StructuredIndex); | |||
| 1821 | ++numEltsInit; | |||
| 1822 | } else { | |||
| 1823 | QualType VecType; | |||
| 1824 | const VectorType *IVT = IType->castAs<VectorType>(); | |||
| 1825 | unsigned numIElts = IVT->getNumElements(); | |||
| 1826 | ||||
| 1827 | if (IType->isExtVectorType()) | |||
| 1828 | VecType = SemaRef.Context.getExtVectorType(elementType, numIElts); | |||
| 1829 | else | |||
| 1830 | VecType = SemaRef.Context.getVectorType(elementType, numIElts, | |||
| 1831 | IVT->getVectorKind()); | |||
| 1832 | CheckSubElementType(ElementEntity, IList, VecType, Index, | |||
| 1833 | StructuredList, StructuredIndex); | |||
| 1834 | numEltsInit += numIElts; | |||
| 1835 | } | |||
| 1836 | } | |||
| 1837 | ||||
| 1838 | // OpenCL and HLSL require all elements to be initialized. | |||
| 1839 | if (numEltsInit != maxElements) { | |||
| 1840 | if (!VerifyOnly) | |||
| 1841 | SemaRef.Diag(IList->getBeginLoc(), | |||
| 1842 | diag::err_vector_incorrect_num_initializers) | |||
| 1843 | << (numEltsInit < maxElements) << maxElements << numEltsInit; | |||
| 1844 | hadError = true; | |||
| 1845 | } | |||
| 1846 | } | |||
| 1847 | ||||
| 1848 | /// Check if the type of a class element has an accessible destructor, and marks | |||
| 1849 | /// it referenced. Returns true if we shouldn't form a reference to the | |||
| 1850 | /// destructor. | |||
| 1851 | /// | |||
| 1852 | /// Aggregate initialization requires a class element's destructor be | |||
| 1853 | /// accessible per 11.6.1 [dcl.init.aggr]: | |||
| 1854 | /// | |||
| 1855 | /// The destructor for each element of class type is potentially invoked | |||
| 1856 | /// (15.4 [class.dtor]) from the context where the aggregate initialization | |||
| 1857 | /// occurs. | |||
| 1858 | static bool checkDestructorReference(QualType ElementType, SourceLocation Loc, | |||
| 1859 | Sema &SemaRef) { | |||
| 1860 | auto *CXXRD = ElementType->getAsCXXRecordDecl(); | |||
| 1861 | if (!CXXRD) | |||
| 1862 | return false; | |||
| 1863 | ||||
| 1864 | CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD); | |||
| 1865 | SemaRef.CheckDestructorAccess(Loc, Destructor, | |||
| 1866 | SemaRef.PDiag(diag::err_access_dtor_temp) | |||
| 1867 | << ElementType); | |||
| 1868 | SemaRef.MarkFunctionReferenced(Loc, Destructor); | |||
| 1869 | return SemaRef.DiagnoseUseOfDecl(Destructor, Loc); | |||
| 1870 | } | |||
| 1871 | ||||
| 1872 | void InitListChecker::CheckArrayType(const InitializedEntity &Entity, | |||
| 1873 | InitListExpr *IList, QualType &DeclType, | |||
| 1874 | llvm::APSInt elementIndex, | |||
| 1875 | bool SubobjectIsDesignatorContext, | |||
| 1876 | unsigned &Index, | |||
| 1877 | InitListExpr *StructuredList, | |||
| 1878 | unsigned &StructuredIndex) { | |||
| 1879 | const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType); | |||
| 1880 | ||||
| 1881 | if (!VerifyOnly) { | |||
| 1882 | if (checkDestructorReference(arrayType->getElementType(), | |||
| 1883 | IList->getEndLoc(), SemaRef)) { | |||
| 1884 | hadError = true; | |||
| 1885 | return; | |||
| 1886 | } | |||
| 1887 | } | |||
| 1888 | ||||
| 1889 | // Check for the special-case of initializing an array with a string. | |||
| 1890 | if (Index < IList->getNumInits()) { | |||
| 1891 | if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) == | |||
| 1892 | SIF_None) { | |||
| 1893 | // We place the string literal directly into the resulting | |||
| 1894 | // initializer list. This is the only place where the structure | |||
| 1895 | // of the structured initializer list doesn't match exactly, | |||
| 1896 | // because doing so would involve allocating one character | |||
| 1897 | // constant for each string. | |||
| 1898 | // FIXME: Should we do these checks in verify-only mode too? | |||
| 1899 | if (!VerifyOnly) | |||
| 1900 | CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef); | |||
| 1901 | if (StructuredList) { | |||
| 1902 | UpdateStructuredListElement(StructuredList, StructuredIndex, | |||
| 1903 | IList->getInit(Index)); | |||
| 1904 | StructuredList->resizeInits(SemaRef.Context, StructuredIndex); | |||
| 1905 | } | |||
| 1906 | ++Index; | |||
| 1907 | return; | |||
| 1908 | } | |||
| 1909 | } | |||
| 1910 | if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) { | |||
| 1911 | // Check for VLAs; in standard C it would be possible to check this | |||
| 1912 | // earlier, but I don't know where clang accepts VLAs (gcc accepts | |||
| 1913 | // them in all sorts of strange places). | |||
| 1914 | bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus; | |||
| 1915 | if (!VerifyOnly) { | |||
| 1916 | // C2x 6.7.9p4: An entity of variable length array type shall not be | |||
| 1917 | // initialized except by an empty initializer. | |||
| 1918 | // | |||
| 1919 | // The C extension warnings are issued from ParseBraceInitializer() and | |||
| 1920 | // do not need to be issued here. However, we continue to issue an error | |||
| 1921 | // in the case there are initializers or we are compiling C++. We allow | |||
| 1922 | // use of VLAs in C++, but it's not clear we want to allow {} to zero | |||
| 1923 | // init a VLA in C++ in all cases (such as with non-trivial constructors). | |||
| 1924 | // FIXME: should we allow this construct in C++ when it makes sense to do | |||
| 1925 | // so? | |||
| 1926 | if (HasErr) | |||
| 1927 | SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(), | |||
| 1928 | diag::err_variable_object_no_init) | |||
| 1929 | << VAT->getSizeExpr()->getSourceRange(); | |||
| 1930 | } | |||
| 1931 | hadError = HasErr; | |||
| 1932 | ++Index; | |||
| 1933 | ++StructuredIndex; | |||
| 1934 | return; | |||
| 1935 | } | |||
| 1936 | ||||
| 1937 | // We might know the maximum number of elements in advance. | |||
| 1938 | llvm::APSInt maxElements(elementIndex.getBitWidth(), | |||
| 1939 | elementIndex.isUnsigned()); | |||
| 1940 | bool maxElementsKnown = false; | |||
| 1941 | if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) { | |||
| 1942 | maxElements = CAT->getSize(); | |||
| 1943 | elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth()); | |||
| 1944 | elementIndex.setIsUnsigned(maxElements.isUnsigned()); | |||
| 1945 | maxElementsKnown = true; | |||
| 1946 | } | |||
| 1947 | ||||
| 1948 | QualType elementType = arrayType->getElementType(); | |||
| 1949 | while (Index < IList->getNumInits()) { | |||
| 1950 | Expr *Init = IList->getInit(Index); | |||
| 1951 | if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { | |||
| 1952 | // If we're not the subobject that matches up with the '{' for | |||
| 1953 | // the designator, we shouldn't be handling the | |||
| 1954 | // designator. Return immediately. | |||
| 1955 | if (!SubobjectIsDesignatorContext) | |||
| 1956 | return; | |||
| 1957 | ||||
| 1958 | // Handle this designated initializer. elementIndex will be | |||
| 1959 | // updated to be the next array element we'll initialize. | |||
| 1960 | if (CheckDesignatedInitializer(Entity, IList, DIE, 0, | |||
| 1961 | DeclType, nullptr, &elementIndex, Index, | |||
| 1962 | StructuredList, StructuredIndex, true, | |||
| 1963 | false)) { | |||
| 1964 | hadError = true; | |||
| 1965 | continue; | |||
| 1966 | } | |||
| 1967 | ||||
| 1968 | if (elementIndex.getBitWidth() > maxElements.getBitWidth()) | |||
| 1969 | maxElements = maxElements.extend(elementIndex.getBitWidth()); | |||
| 1970 | else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) | |||
| 1971 | elementIndex = elementIndex.extend(maxElements.getBitWidth()); | |||
| 1972 | elementIndex.setIsUnsigned(maxElements.isUnsigned()); | |||
| 1973 | ||||
| 1974 | // If the array is of incomplete type, keep track of the number of | |||
| 1975 | // elements in the initializer. | |||
| 1976 | if (!maxElementsKnown && elementIndex > maxElements) | |||
| 1977 | maxElements = elementIndex; | |||
| 1978 | ||||
| 1979 | continue; | |||
| 1980 | } | |||
| 1981 | ||||
| 1982 | // If we know the maximum number of elements, and we've already | |||
| 1983 | // hit it, stop consuming elements in the initializer list. | |||
| 1984 | if (maxElementsKnown && elementIndex == maxElements) | |||
| 1985 | break; | |||
| 1986 | ||||
| 1987 | InitializedEntity ElementEntity = | |||
| 1988 | InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex, | |||
| 1989 | Entity); | |||
| 1990 | // Check this element. | |||
| 1991 | CheckSubElementType(ElementEntity, IList, elementType, Index, | |||
| 1992 | StructuredList, StructuredIndex); | |||
| 1993 | ++elementIndex; | |||
| 1994 | ||||
| 1995 | // If the array is of incomplete type, keep track of the number of | |||
| 1996 | // elements in the initializer. | |||
| 1997 | if (!maxElementsKnown && elementIndex > maxElements) | |||
| 1998 | maxElements = elementIndex; | |||
| 1999 | } | |||
| 2000 | if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) { | |||
| 2001 | // If this is an incomplete array type, the actual type needs to | |||
| 2002 | // be calculated here. | |||
| 2003 | llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); | |||
| 2004 | if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) { | |||
| 2005 | // Sizing an array implicitly to zero is not allowed by ISO C, | |||
| 2006 | // but is supported by GNU. | |||
| 2007 | SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size); | |||
| 2008 | } | |||
| 2009 | ||||
| 2010 | DeclType = SemaRef.Context.getConstantArrayType( | |||
| 2011 | elementType, maxElements, nullptr, ArrayType::Normal, 0); | |||
| 2012 | } | |||
| 2013 | if (!hadError) { | |||
| 2014 | // If there are any members of the array that get value-initialized, check | |||
| 2015 | // that is possible. That happens if we know the bound and don't have | |||
| 2016 | // enough elements, or if we're performing an array new with an unknown | |||
| 2017 | // bound. | |||
| 2018 | if ((maxElementsKnown && elementIndex < maxElements) || | |||
| 2019 | Entity.isVariableLengthArrayNew()) | |||
| 2020 | CheckEmptyInitializable( | |||
| 2021 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity), | |||
| 2022 | IList->getEndLoc()); | |||
| 2023 | } | |||
| 2024 | } | |||
| 2025 | ||||
| 2026 | bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity, | |||
| 2027 | Expr *InitExpr, | |||
| 2028 | FieldDecl *Field, | |||
| 2029 | bool TopLevelObject) { | |||
| 2030 | // Handle GNU flexible array initializers. | |||
| 2031 | unsigned FlexArrayDiag; | |||
| 2032 | if (isa<InitListExpr>(InitExpr) && | |||
| 2033 | cast<InitListExpr>(InitExpr)->getNumInits() == 0) { | |||
| 2034 | // Empty flexible array init always allowed as an extension | |||
| 2035 | FlexArrayDiag = diag::ext_flexible_array_init; | |||
| 2036 | } else if (!TopLevelObject) { | |||
| 2037 | // Disallow flexible array init on non-top-level object | |||
| 2038 | FlexArrayDiag = diag::err_flexible_array_init; | |||
| 2039 | } else if (Entity.getKind() != InitializedEntity::EK_Variable) { | |||
| 2040 | // Disallow flexible array init on anything which is not a variable. | |||
| 2041 | FlexArrayDiag = diag::err_flexible_array_init; | |||
| 2042 | } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) { | |||
| 2043 | // Disallow flexible array init on local variables. | |||
| 2044 | FlexArrayDiag = diag::err_flexible_array_init; | |||
| 2045 | } else { | |||
| 2046 | // Allow other cases. | |||
| 2047 | FlexArrayDiag = diag::ext_flexible_array_init; | |||
| 2048 | } | |||
| 2049 | ||||
| 2050 | if (!VerifyOnly) { | |||
| 2051 | SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag) | |||
| 2052 | << InitExpr->getBeginLoc(); | |||
| 2053 | SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) | |||
| 2054 | << Field; | |||
| 2055 | } | |||
| 2056 | ||||
| 2057 | return FlexArrayDiag != diag::ext_flexible_array_init; | |||
| 2058 | } | |||
| 2059 | ||||
| 2060 | void InitListChecker::CheckStructUnionTypes( | |||
| 2061 | const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, | |||
| 2062 | CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field, | |||
| 2063 | bool SubobjectIsDesignatorContext, unsigned &Index, | |||
| 2064 | InitListExpr *StructuredList, unsigned &StructuredIndex, | |||
| 2065 | bool TopLevelObject) { | |||
| 2066 | RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl(); | |||
| 2067 | ||||
| 2068 | // If the record is invalid, some of it's members are invalid. To avoid | |||
| 2069 | // confusion, we forgo checking the initializer for the entire record. | |||
| 2070 | if (structDecl->isInvalidDecl()) { | |||
| 2071 | // Assume it was supposed to consume a single initializer. | |||
| 2072 | ++Index; | |||
| 2073 | hadError = true; | |||
| 2074 | return; | |||
| 2075 | } | |||
| 2076 | ||||
| 2077 | if (DeclType->isUnionType() && IList->getNumInits() == 0) { | |||
| 2078 | RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); | |||
| 2079 | ||||
| 2080 | if (!VerifyOnly) | |||
| 2081 | for (FieldDecl *FD : RD->fields()) { | |||
| 2082 | QualType ET = SemaRef.Context.getBaseElementType(FD->getType()); | |||
| 2083 | if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) { | |||
| 2084 | hadError = true; | |||
| 2085 | return; | |||
| 2086 | } | |||
| 2087 | } | |||
| 2088 | ||||
| 2089 | // If there's a default initializer, use it. | |||
| 2090 | if (isa<CXXRecordDecl>(RD) && | |||
| 2091 | cast<CXXRecordDecl>(RD)->hasInClassInitializer()) { | |||
| 2092 | if (!StructuredList) | |||
| 2093 | return; | |||
| 2094 | for (RecordDecl::field_iterator FieldEnd = RD->field_end(); | |||
| 2095 | Field != FieldEnd; ++Field) { | |||
| 2096 | if (Field->hasInClassInitializer()) { | |||
| 2097 | StructuredList->setInitializedFieldInUnion(*Field); | |||
| 2098 | // FIXME: Actually build a CXXDefaultInitExpr? | |||
| 2099 | return; | |||
| 2100 | } | |||
| 2101 | } | |||
| 2102 | } | |||
| 2103 | ||||
| 2104 | // Value-initialize the first member of the union that isn't an unnamed | |||
| 2105 | // bitfield. | |||
| 2106 | for (RecordDecl::field_iterator FieldEnd = RD->field_end(); | |||
| 2107 | Field != FieldEnd; ++Field) { | |||
| 2108 | if (!Field->isUnnamedBitfield()) { | |||
| 2109 | CheckEmptyInitializable( | |||
| 2110 | InitializedEntity::InitializeMember(*Field, &Entity), | |||
| 2111 | IList->getEndLoc()); | |||
| 2112 | if (StructuredList) | |||
| 2113 | StructuredList->setInitializedFieldInUnion(*Field); | |||
| 2114 | break; | |||
| 2115 | } | |||
| 2116 | } | |||
| 2117 | return; | |||
| 2118 | } | |||
| 2119 | ||||
| 2120 | bool InitializedSomething = false; | |||
| 2121 | ||||
| 2122 | // If we have any base classes, they are initialized prior to the fields. | |||
| 2123 | for (auto &Base : Bases) { | |||
| 2124 | Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr; | |||
| 2125 | ||||
| 2126 | // Designated inits always initialize fields, so if we see one, all | |||
| 2127 | // remaining base classes have no explicit initializer. | |||
| 2128 | if (Init && isa<DesignatedInitExpr>(Init)) | |||
| 2129 | Init = nullptr; | |||
| 2130 | ||||
| 2131 | SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc(); | |||
| 2132 | InitializedEntity BaseEntity = InitializedEntity::InitializeBase( | |||
| 2133 | SemaRef.Context, &Base, false, &Entity); | |||
| 2134 | if (Init) { | |||
| 2135 | CheckSubElementType(BaseEntity, IList, Base.getType(), Index, | |||
| 2136 | StructuredList, StructuredIndex); | |||
| 2137 | InitializedSomething = true; | |||
| 2138 | } else { | |||
| 2139 | CheckEmptyInitializable(BaseEntity, InitLoc); | |||
| 2140 | } | |||
| 2141 | ||||
| 2142 | if (!VerifyOnly) | |||
| 2143 | if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) { | |||
| 2144 | hadError = true; | |||
| 2145 | return; | |||
| 2146 | } | |||
| 2147 | } | |||
| 2148 | ||||
| 2149 | // If structDecl is a forward declaration, this loop won't do | |||
| 2150 | // anything except look at designated initializers; That's okay, | |||
| 2151 | // because an error should get printed out elsewhere. It might be | |||
| 2152 | // worthwhile to skip over the rest of the initializer, though. | |||
| 2153 | RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); | |||
| 2154 | RecordDecl::field_iterator FieldEnd = RD->field_end(); | |||
| 2155 | size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) { | |||
| 2156 | return isa<FieldDecl>(D) || isa<RecordDecl>(D); | |||
| 2157 | }); | |||
| 2158 | bool CheckForMissingFields = | |||
| 2159 | !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()); | |||
| 2160 | bool HasDesignatedInit = false; | |||
| 2161 | ||||
| 2162 | while (Index < IList->getNumInits()) { | |||
| 2163 | Expr *Init = IList->getInit(Index); | |||
| 2164 | SourceLocation InitLoc = Init->getBeginLoc(); | |||
| 2165 | ||||
| 2166 | if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { | |||
| 2167 | // If we're not the subobject that matches up with the '{' for | |||
| 2168 | // the designator, we shouldn't be handling the | |||
| 2169 | // designator. Return immediately. | |||
| 2170 | if (!SubobjectIsDesignatorContext) | |||
| 2171 | return; | |||
| 2172 | ||||
| 2173 | HasDesignatedInit = true; | |||
| 2174 | ||||
| 2175 | // Handle this designated initializer. Field will be updated to | |||
| 2176 | // the next field that we'll be initializing. | |||
| 2177 | if (CheckDesignatedInitializer(Entity, IList, DIE, 0, | |||
| 2178 | DeclType, &Field, nullptr, Index, | |||
| 2179 | StructuredList, StructuredIndex, | |||
| 2180 | true, TopLevelObject)) | |||
| 2181 | hadError = true; | |||
| 2182 | else if (!VerifyOnly) { | |||
| 2183 | // Find the field named by the designated initializer. | |||
| 2184 | RecordDecl::field_iterator F = RD->field_begin(); | |||
| 2185 | while (std::next(F) != Field) | |||
| 2186 | ++F; | |||
| 2187 | QualType ET = SemaRef.Context.getBaseElementType(F->getType()); | |||
| 2188 | if (checkDestructorReference(ET, InitLoc, SemaRef)) { | |||
| 2189 | hadError = true; | |||
| 2190 | return; | |||
| 2191 | } | |||
| 2192 | } | |||
| 2193 | ||||
| 2194 | InitializedSomething = true; | |||
| 2195 | ||||
| 2196 | // Disable check for missing fields when designators are used. | |||
| 2197 | // This matches gcc behaviour. | |||
| 2198 | CheckForMissingFields = false; | |||
| 2199 | continue; | |||
| 2200 | } | |||
| 2201 | ||||
| 2202 | // Check if this is an initializer of forms: | |||
| 2203 | // | |||
| 2204 | // struct foo f = {}; | |||
| 2205 | // struct foo g = {0}; | |||
| 2206 | // | |||
| 2207 | // These are okay for randomized structures. [C99 6.7.8p19] | |||
| 2208 | // | |||
| 2209 | // Also, if there is only one element in the structure, we allow something | |||
| 2210 | // like this, because it's really not randomized in the tranditional sense. | |||
| 2211 | // | |||
| 2212 | // struct foo h = {bar}; | |||
| 2213 | auto IsZeroInitializer = [&](const Expr *I) { | |||
| 2214 | if (IList->getNumInits() == 1) { | |||
| 2215 | if (NumRecordDecls == 1) | |||
| 2216 | return true; | |||
| 2217 | if (const auto *IL = dyn_cast<IntegerLiteral>(I)) | |||
| 2218 | return IL->getValue().isZero(); | |||
| 2219 | } | |||
| 2220 | return false; | |||
| 2221 | }; | |||
| 2222 | ||||
| 2223 | // Don't allow non-designated initializers on randomized structures. | |||
| 2224 | if (RD->isRandomized() && !IsZeroInitializer(Init)) { | |||
| 2225 | if (!VerifyOnly) | |||
| 2226 | SemaRef.Diag(InitLoc, diag::err_non_designated_init_used); | |||
| 2227 | hadError = true; | |||
| 2228 | break; | |||
| 2229 | } | |||
| 2230 | ||||
| 2231 | if (Field == FieldEnd) { | |||
| 2232 | // We've run out of fields. We're done. | |||
| 2233 | break; | |||
| 2234 | } | |||
| 2235 | ||||
| 2236 | // We've already initialized a member of a union. We're done. | |||
| 2237 | if (InitializedSomething && DeclType->isUnionType()) | |||
| 2238 | break; | |||
| 2239 | ||||
| 2240 | // If we've hit the flexible array member at the end, we're done. | |||
| 2241 | if (Field->getType()->isIncompleteArrayType()) | |||
| 2242 | break; | |||
| 2243 | ||||
| 2244 | if (Field->isUnnamedBitfield()) { | |||
| 2245 | // Don't initialize unnamed bitfields, e.g. "int : 20;" | |||
| 2246 | ++Field; | |||
| 2247 | continue; | |||
| 2248 | } | |||
| 2249 | ||||
| 2250 | // Make sure we can use this declaration. | |||
| 2251 | bool InvalidUse; | |||
| 2252 | if (VerifyOnly) | |||
| 2253 | InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); | |||
| 2254 | else | |||
| 2255 | InvalidUse = SemaRef.DiagnoseUseOfDecl( | |||
| 2256 | *Field, IList->getInit(Index)->getBeginLoc()); | |||
| 2257 | if (InvalidUse) { | |||
| 2258 | ++Index; | |||
| 2259 | ++Field; | |||
| 2260 | hadError = true; | |||
| 2261 | continue; | |||
| 2262 | } | |||
| 2263 | ||||
| 2264 | if (!VerifyOnly) { | |||
| 2265 | QualType ET = SemaRef.Context.getBaseElementType(Field->getType()); | |||
| 2266 | if (checkDestructorReference(ET, InitLoc, SemaRef)) { | |||
| 2267 | hadError = true; | |||
| 2268 | return; | |||
| 2269 | } | |||
| 2270 | } | |||
| 2271 | ||||
| 2272 | InitializedEntity MemberEntity = | |||
| 2273 | InitializedEntity::InitializeMember(*Field, &Entity); | |||
| 2274 | CheckSubElementType(MemberEntity, IList, Field->getType(), Index, | |||
| 2275 | StructuredList, StructuredIndex); | |||
| 2276 | InitializedSomething = true; | |||
| 2277 | ||||
| 2278 | if (DeclType->isUnionType() && StructuredList) { | |||
| 2279 | // Initialize the first field within the union. | |||
| 2280 | StructuredList->setInitializedFieldInUnion(*Field); | |||
| 2281 | } | |||
| 2282 | ||||
| 2283 | ++Field; | |||
| 2284 | } | |||
| 2285 | ||||
| 2286 | // Emit warnings for missing struct field initializers. | |||
| 2287 | if (!VerifyOnly && InitializedSomething && CheckForMissingFields && | |||
| 2288 | Field != FieldEnd && !Field->getType()->isIncompleteArrayType() && | |||
| 2289 | !DeclType->isUnionType()) { | |||
| 2290 | // It is possible we have one or more unnamed bitfields remaining. | |||
| 2291 | // Find first (if any) named field and emit warning. | |||
| 2292 | for (RecordDecl::field_iterator it = Field, end = RD->field_end(); | |||
| 2293 | it != end; ++it) { | |||
| 2294 | if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) { | |||
| 2295 | SemaRef.Diag(IList->getSourceRange().getEnd(), | |||
| 2296 | diag::warn_missing_field_initializers) << *it; | |||
| 2297 | break; | |||
| 2298 | } | |||
| 2299 | } | |||
| 2300 | } | |||
| 2301 | ||||
| 2302 | // Check that any remaining fields can be value-initialized if we're not | |||
| 2303 | // building a structured list. (If we are, we'll check this later.) | |||
| 2304 | if (!StructuredList && Field != FieldEnd && !DeclType->isUnionType() && | |||
| 2305 | !Field->getType()->isIncompleteArrayType()) { | |||
| 2306 | for (; Field != FieldEnd && !hadError; ++Field) { | |||
| 2307 | if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer()) | |||
| 2308 | CheckEmptyInitializable( | |||
| 2309 | InitializedEntity::InitializeMember(*Field, &Entity), | |||
| 2310 | IList->getEndLoc()); | |||
| 2311 | } | |||
| 2312 | } | |||
| 2313 | ||||
| 2314 | // Check that the types of the remaining fields have accessible destructors. | |||
| 2315 | if (!VerifyOnly) { | |||
| 2316 | // If the initializer expression has a designated initializer, check the | |||
| 2317 | // elements for which a designated initializer is not provided too. | |||
| 2318 | RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin() | |||
| 2319 | : Field; | |||
| 2320 | for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) { | |||
| 2321 | QualType ET = SemaRef.Context.getBaseElementType(I->getType()); | |||
| 2322 | if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) { | |||
| 2323 | hadError = true; | |||
| 2324 | return; | |||
| 2325 | } | |||
| 2326 | } | |||
| 2327 | } | |||
| 2328 | ||||
| 2329 | if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || | |||
| 2330 | Index >= IList->getNumInits()) | |||
| 2331 | return; | |||
| 2332 | ||||
| 2333 | if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field, | |||
| 2334 | TopLevelObject)) { | |||
| 2335 | hadError = true; | |||
| 2336 | ++Index; | |||
| 2337 | return; | |||
| 2338 | } | |||
| 2339 | ||||
| 2340 | InitializedEntity MemberEntity = | |||
| 2341 | InitializedEntity::InitializeMember(*Field, &Entity); | |||
| 2342 | ||||
| 2343 | if (isa<InitListExpr>(IList->getInit(Index))) | |||
| 2344 | CheckSubElementType(MemberEntity, IList, Field->getType(), Index, | |||
| 2345 | StructuredList, StructuredIndex); | |||
| 2346 | else | |||
| 2347 | CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index, | |||
| 2348 | StructuredList, StructuredIndex); | |||
| 2349 | } | |||
| 2350 | ||||
| 2351 | /// Expand a field designator that refers to a member of an | |||
| 2352 | /// anonymous struct or union into a series of field designators that | |||
| 2353 | /// refers to the field within the appropriate subobject. | |||
| 2354 | /// | |||
| 2355 | static void ExpandAnonymousFieldDesignator(Sema &SemaRef, | |||
| 2356 | DesignatedInitExpr *DIE, | |||
| 2357 | unsigned DesigIdx, | |||
| 2358 | IndirectFieldDecl *IndirectField) { | |||
| 2359 | typedef DesignatedInitExpr::Designator Designator; | |||
| 2360 | ||||
| 2361 | // Build the replacement designators. | |||
| 2362 | SmallVector<Designator, 4> Replacements; | |||
| 2363 | for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(), | |||
| 2364 | PE = IndirectField->chain_end(); PI != PE; ++PI) { | |||
| 2365 | if (PI + 1 == PE) | |||
| 2366 | Replacements.push_back(Designator::CreateFieldDesignator( | |||
| 2367 | (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(), | |||
| 2368 | DIE->getDesignator(DesigIdx)->getFieldLoc())); | |||
| 2369 | else | |||
| 2370 | Replacements.push_back(Designator::CreateFieldDesignator( | |||
| 2371 | (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation())); | |||
| 2372 | assert(isa<FieldDecl>(*PI))(static_cast <bool> (isa<FieldDecl>(*PI)) ? void ( 0) : __assert_fail ("isa<FieldDecl>(*PI)", "clang/lib/Sema/SemaInit.cpp" , 2372, __extension__ __PRETTY_FUNCTION__)); | |||
| 2373 | Replacements.back().setField(cast<FieldDecl>(*PI)); | |||
| 2374 | } | |||
| 2375 | ||||
| 2376 | // Expand the current designator into the set of replacement | |||
| 2377 | // designators, so we have a full subobject path down to where the | |||
| 2378 | // member of the anonymous struct/union is actually stored. | |||
| 2379 | DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0], | |||
| 2380 | &Replacements[0] + Replacements.size()); | |||
| 2381 | } | |||
| 2382 | ||||
| 2383 | static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef, | |||
| 2384 | DesignatedInitExpr *DIE) { | |||
| 2385 | unsigned NumIndexExprs = DIE->getNumSubExprs() - 1; | |||
| 2386 | SmallVector<Expr*, 4> IndexExprs(NumIndexExprs); | |||
| 2387 | for (unsigned I = 0; I < NumIndexExprs; ++I) | |||
| 2388 | IndexExprs[I] = DIE->getSubExpr(I + 1); | |||
| 2389 | return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(), | |||
| 2390 | IndexExprs, | |||
| 2391 | DIE->getEqualOrColonLoc(), | |||
| 2392 | DIE->usesGNUSyntax(), DIE->getInit()); | |||
| 2393 | } | |||
| 2394 | ||||
| 2395 | namespace { | |||
| 2396 | ||||
| 2397 | // Callback to only accept typo corrections that are for field members of | |||
| 2398 | // the given struct or union. | |||
| 2399 | class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback { | |||
| 2400 | public: | |||
| 2401 | explicit FieldInitializerValidatorCCC(RecordDecl *RD) | |||
| 2402 | : Record(RD) {} | |||
| 2403 | ||||
| 2404 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
| 2405 | FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>(); | |||
| 2406 | return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record); | |||
| 2407 | } | |||
| 2408 | ||||
| 2409 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | |||
| 2410 | return std::make_unique<FieldInitializerValidatorCCC>(*this); | |||
| 2411 | } | |||
| 2412 | ||||
| 2413 | private: | |||
| 2414 | RecordDecl *Record; | |||
| 2415 | }; | |||
| 2416 | ||||
| 2417 | } // end anonymous namespace | |||
| 2418 | ||||
| 2419 | /// Check the well-formedness of a C99 designated initializer. | |||
| 2420 | /// | |||
| 2421 | /// Determines whether the designated initializer @p DIE, which | |||
| 2422 | /// resides at the given @p Index within the initializer list @p | |||
| 2423 | /// IList, is well-formed for a current object of type @p DeclType | |||
| 2424 | /// (C99 6.7.8). The actual subobject that this designator refers to | |||
| 2425 | /// within the current subobject is returned in either | |||
| 2426 | /// @p NextField or @p NextElementIndex (whichever is appropriate). | |||
| 2427 | /// | |||
| 2428 | /// @param IList The initializer list in which this designated | |||
| 2429 | /// initializer occurs. | |||
| 2430 | /// | |||
| 2431 | /// @param DIE The designated initializer expression. | |||
| 2432 | /// | |||
| 2433 | /// @param DesigIdx The index of the current designator. | |||
| 2434 | /// | |||
| 2435 | /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17), | |||
| 2436 | /// into which the designation in @p DIE should refer. | |||
| 2437 | /// | |||
| 2438 | /// @param NextField If non-NULL and the first designator in @p DIE is | |||
| 2439 | /// a field, this will be set to the field declaration corresponding | |||
| 2440 | /// to the field named by the designator. On input, this is expected to be | |||
| 2441 | /// the next field that would be initialized in the absence of designation, | |||
| 2442 | /// if the complete object being initialized is a struct. | |||
| 2443 | /// | |||
| 2444 | /// @param NextElementIndex If non-NULL and the first designator in @p | |||
| 2445 | /// DIE is an array designator or GNU array-range designator, this | |||
| 2446 | /// will be set to the last index initialized by this designator. | |||
| 2447 | /// | |||
| 2448 | /// @param Index Index into @p IList where the designated initializer | |||
| 2449 | /// @p DIE occurs. | |||
| 2450 | /// | |||
| 2451 | /// @param StructuredList The initializer list expression that | |||
| 2452 | /// describes all of the subobject initializers in the order they'll | |||
| 2453 | /// actually be initialized. | |||
| 2454 | /// | |||
| 2455 | /// @returns true if there was an error, false otherwise. | |||
| 2456 | bool | |||
| 2457 | InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, | |||
| 2458 | InitListExpr *IList, | |||
| 2459 | DesignatedInitExpr *DIE, | |||
| 2460 | unsigned DesigIdx, | |||
| 2461 | QualType &CurrentObjectType, | |||
| 2462 | RecordDecl::field_iterator *NextField, | |||
| 2463 | llvm::APSInt *NextElementIndex, | |||
| 2464 | unsigned &Index, | |||
| 2465 | InitListExpr *StructuredList, | |||
| 2466 | unsigned &StructuredIndex, | |||
| 2467 | bool FinishSubobjectInit, | |||
| 2468 | bool TopLevelObject) { | |||
| 2469 | if (DesigIdx == DIE->size()) { | |||
| ||||
| 2470 | // C++20 designated initialization can result in direct-list-initialization | |||
| 2471 | // of the designated subobject. This is the only way that we can end up | |||
| 2472 | // performing direct initialization as part of aggregate initialization, so | |||
| 2473 | // it needs special handling. | |||
| 2474 | if (DIE->isDirectInit()) { | |||
| 2475 | Expr *Init = DIE->getInit(); | |||
| 2476 | assert(isa<InitListExpr>(Init) &&(static_cast <bool> (isa<InitListExpr>(Init) && "designator result in direct non-list initialization?") ? void (0) : __assert_fail ("isa<InitListExpr>(Init) && \"designator result in direct non-list initialization?\"" , "clang/lib/Sema/SemaInit.cpp", 2477, __extension__ __PRETTY_FUNCTION__ )) | |||
| 2477 | "designator result in direct non-list initialization?")(static_cast <bool> (isa<InitListExpr>(Init) && "designator result in direct non-list initialization?") ? void (0) : __assert_fail ("isa<InitListExpr>(Init) && \"designator result in direct non-list initialization?\"" , "clang/lib/Sema/SemaInit.cpp", 2477, __extension__ __PRETTY_FUNCTION__ )); | |||
| 2478 | InitializationKind Kind = InitializationKind::CreateDirectList( | |||
| 2479 | DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc()); | |||
| 2480 | InitializationSequence Seq(SemaRef, Entity, Kind, Init, | |||
| 2481 | /*TopLevelOfInitList*/ true); | |||
| 2482 | if (StructuredList) { | |||
| 2483 | ExprResult Result = VerifyOnly | |||
| 2484 | ? getDummyInit() | |||
| 2485 | : Seq.Perform(SemaRef, Entity, Kind, Init); | |||
| 2486 | UpdateStructuredListElement(StructuredList, StructuredIndex, | |||
| 2487 | Result.get()); | |||
| 2488 | } | |||
| 2489 | ++Index; | |||
| 2490 | return !Seq; | |||
| 2491 | } | |||
| 2492 | ||||
| 2493 | // Check the actual initialization for the designated object type. | |||
| 2494 | bool prevHadError = hadError; | |||
| 2495 | ||||
| 2496 | // Temporarily remove the designator expression from the | |||
| 2497 | // initializer list that the child calls see, so that we don't try | |||
| 2498 | // to re-process the designator. | |||
| 2499 | unsigned OldIndex = Index; | |||
| 2500 | IList->setInit(OldIndex, DIE->getInit()); | |||
| 2501 | ||||
| 2502 | CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList, | |||
| 2503 | StructuredIndex, /*DirectlyDesignated=*/true); | |||
| 2504 | ||||
| 2505 | // Restore the designated initializer expression in the syntactic | |||
| 2506 | // form of the initializer list. | |||
| 2507 | if (IList->getInit(OldIndex) != DIE->getInit()) | |||
| 2508 | DIE->setInit(IList->getInit(OldIndex)); | |||
| 2509 | IList->setInit(OldIndex, DIE); | |||
| 2510 | ||||
| 2511 | return hadError && !prevHadError; | |||
| 2512 | } | |||
| 2513 | ||||
| 2514 | DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); | |||
| 2515 | bool IsFirstDesignator = (DesigIdx == 0); | |||
| 2516 | if (IsFirstDesignator
| |||
| 2517 | // Determine the structural initializer list that corresponds to the | |||
| 2518 | // current subobject. | |||
| 2519 | if (IsFirstDesignator) | |||
| 2520 | StructuredList = FullyStructuredList; | |||
| 2521 | else { | |||
| 2522 | Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ? | |||
| 2523 | StructuredList->getInit(StructuredIndex) : nullptr; | |||
| 2524 | if (!ExistingInit && StructuredList->hasArrayFiller()) | |||
| 2525 | ExistingInit = StructuredList->getArrayFiller(); | |||
| 2526 | ||||
| 2527 | if (!ExistingInit) | |||
| 2528 | StructuredList = getStructuredSubobjectInit( | |||
| 2529 | IList, Index, CurrentObjectType, StructuredList, StructuredIndex, | |||
| 2530 | SourceRange(D->getBeginLoc(), DIE->getEndLoc())); | |||
| 2531 | else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit)) | |||
| 2532 | StructuredList = Result; | |||
| 2533 | else { | |||
| 2534 | // We are creating an initializer list that initializes the | |||
| 2535 | // subobjects of the current object, but there was already an | |||
| 2536 | // initialization that completely initialized the current | |||
| 2537 | // subobject, e.g., by a compound literal: | |||
| 2538 | // | |||
| 2539 | // struct X { int a, b; }; | |||
| 2540 | // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; | |||
| 2541 | // | |||
| 2542 | // Here, xs[0].a == 1 and xs[0].b == 3, since the second, | |||
| 2543 | // designated initializer re-initializes only its current object | |||
| 2544 | // subobject [0].b. | |||
| 2545 | diagnoseInitOverride(ExistingInit, | |||
| 2546 | SourceRange(D->getBeginLoc(), DIE->getEndLoc()), | |||
| 2547 | /*FullyOverwritten=*/false); | |||
| 2548 | ||||
| 2549 | if (!VerifyOnly) { | |||
| 2550 | if (DesignatedInitUpdateExpr *E = | |||
| 2551 | dyn_cast<DesignatedInitUpdateExpr>(ExistingInit)) | |||
| 2552 | StructuredList = E->getUpdater(); | |||
| 2553 | else { | |||
| 2554 | DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context) | |||
| 2555 | DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(), | |||
| 2556 | ExistingInit, DIE->getEndLoc()); | |||
| 2557 | StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE); | |||
| 2558 | StructuredList = DIUE->getUpdater(); | |||
| 2559 | } | |||
| 2560 | } else { | |||
| 2561 | // We don't need to track the structured representation of a | |||
| 2562 | // designated init update of an already-fully-initialized object in | |||
| 2563 | // verify-only mode. The only reason we would need the structure is | |||
| 2564 | // to determine where the uninitialized "holes" are, and in this | |||
| 2565 | // case, we know there aren't any and we can't introduce any. | |||
| 2566 | StructuredList = nullptr; | |||
| 2567 | } | |||
| 2568 | } | |||
| 2569 | } | |||
| 2570 | } | |||
| 2571 | ||||
| 2572 | if (D->isFieldDesignator()) { | |||
| 2573 | // C99 6.7.8p7: | |||
| 2574 | // | |||
| 2575 | // If a designator has the form | |||
| 2576 | // | |||
| 2577 | // . identifier | |||
| 2578 | // | |||
| 2579 | // then the current object (defined below) shall have | |||
| 2580 | // structure or union type and the identifier shall be the | |||
| 2581 | // name of a member of that type. | |||
| 2582 | const RecordType *RT = CurrentObjectType->getAs<RecordType>(); | |||
| 2583 | if (!RT) { | |||
| 2584 | SourceLocation Loc = D->getDotLoc(); | |||
| 2585 | if (Loc.isInvalid()) | |||
| 2586 | Loc = D->getFieldLoc(); | |||
| 2587 | if (!VerifyOnly) | |||
| 2588 | SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) | |||
| 2589 | << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType; | |||
| 2590 | ++Index; | |||
| 2591 | return true; | |||
| 2592 | } | |||
| 2593 | ||||
| 2594 | FieldDecl *KnownField = D->getField(); | |||
| 2595 | if (!KnownField) { | |||
| 2596 | const IdentifierInfo *FieldName = D->getFieldName(); | |||
| 2597 | DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); | |||
| 2598 | for (NamedDecl *ND : Lookup) { | |||
| 2599 | if (auto *FD = dyn_cast<FieldDecl>(ND)) { | |||
| 2600 | KnownField = FD; | |||
| 2601 | break; | |||
| 2602 | } | |||
| 2603 | if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) { | |||
| 2604 | // In verify mode, don't modify the original. | |||
| 2605 | if (VerifyOnly) | |||
| 2606 | DIE = CloneDesignatedInitExpr(SemaRef, DIE); | |||
| 2607 | ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD); | |||
| 2608 | D = DIE->getDesignator(DesigIdx); | |||
| 2609 | KnownField = cast<FieldDecl>(*IFD->chain_begin()); | |||
| 2610 | break; | |||
| 2611 | } | |||
| 2612 | } | |||
| 2613 | if (!KnownField) { | |||
| 2614 | if (VerifyOnly) { | |||
| 2615 | ++Index; | |||
| 2616 | return true; // No typo correction when just trying this out. | |||
| 2617 | } | |||
| 2618 | ||||
| 2619 | // Name lookup found something, but it wasn't a field. | |||
| 2620 | if (!Lookup.empty()) { | |||
| 2621 | SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) | |||
| 2622 | << FieldName; | |||
| 2623 | SemaRef.Diag(Lookup.front()->getLocation(), | |||
| 2624 | diag::note_field_designator_found); | |||
| 2625 | ++Index; | |||
| 2626 | return true; | |||
| 2627 | } | |||
| 2628 | ||||
| 2629 | // Name lookup didn't find anything. | |||
| 2630 | // Determine whether this was a typo for another field name. | |||
| 2631 | FieldInitializerValidatorCCC CCC(RT->getDecl()); | |||
| 2632 | if (TypoCorrection Corrected = SemaRef.CorrectTypo( | |||
| 2633 | DeclarationNameInfo(FieldName, D->getFieldLoc()), | |||
| 2634 | Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC, | |||
| 2635 | Sema::CTK_ErrorRecovery, RT->getDecl())) { | |||
| 2636 | SemaRef.diagnoseTypo( | |||
| 2637 | Corrected, | |||
| 2638 | SemaRef.PDiag(diag::err_field_designator_unknown_suggest) | |||
| 2639 | << FieldName << CurrentObjectType); | |||
| 2640 | KnownField = Corrected.getCorrectionDeclAs<FieldDecl>(); | |||
| 2641 | hadError = true; | |||
| 2642 | } else { | |||
| 2643 | // Typo correction didn't find anything. | |||
| 2644 | SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) | |||
| 2645 | << FieldName << CurrentObjectType; | |||
| 2646 | ++Index; | |||
| 2647 | return true; | |||
| 2648 | } | |||
| 2649 | } | |||
| 2650 | } | |||
| 2651 | ||||
| 2652 | unsigned NumBases = 0; | |||
| 2653 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) | |||
| 2654 | NumBases = CXXRD->getNumBases(); | |||
| 2655 | ||||
| 2656 | unsigned FieldIndex = NumBases; | |||
| 2657 | ||||
| 2658 | for (auto *FI : RT->getDecl()->fields()) { | |||
| 2659 | if (FI->isUnnamedBitfield()) | |||
| 2660 | continue; | |||
| 2661 | if (declaresSameEntity(KnownField, FI)) { | |||
| 2662 | KnownField = FI; | |||
| 2663 | break; | |||
| 2664 | } | |||
| 2665 | ++FieldIndex; | |||
| 2666 | } | |||
| 2667 | ||||
| 2668 | RecordDecl::field_iterator Field = | |||
| 2669 | RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField)); | |||
| 2670 | ||||
| 2671 | // All of the fields of a union are located at the same place in | |||
| 2672 | // the initializer list. | |||
| 2673 | if (RT->getDecl()->isUnion()) { | |||
| 2674 | FieldIndex = 0; | |||
| 2675 | if (StructuredList) { | |||
| 2676 | FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion(); | |||
| 2677 | if (CurrentField && !declaresSameEntity(CurrentField, *Field)) { | |||
| 2678 | assert(StructuredList->getNumInits() == 1(static_cast <bool> (StructuredList->getNumInits() == 1 && "A union should never have more than one initializer!" ) ? void (0) : __assert_fail ("StructuredList->getNumInits() == 1 && \"A union should never have more than one initializer!\"" , "clang/lib/Sema/SemaInit.cpp", 2679, __extension__ __PRETTY_FUNCTION__ )) | |||
| 2679 | && "A union should never have more than one initializer!")(static_cast <bool> (StructuredList->getNumInits() == 1 && "A union should never have more than one initializer!" ) ? void (0) : __assert_fail ("StructuredList->getNumInits() == 1 && \"A union should never have more than one initializer!\"" , "clang/lib/Sema/SemaInit.cpp", 2679, __extension__ __PRETTY_FUNCTION__ )); | |||
| 2680 | ||||
| 2681 | Expr *ExistingInit = StructuredList->getInit(0); | |||
| 2682 | if (ExistingInit) { | |||
| 2683 | // We're about to throw away an initializer, emit warning. | |||
| 2684 | diagnoseInitOverride( | |||
| 2685 | ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc())); | |||
| 2686 | } | |||
| 2687 | ||||
| 2688 | // remove existing initializer | |||
| 2689 | StructuredList->resizeInits(SemaRef.Context, 0); | |||
| 2690 | StructuredList->setInitializedFieldInUnion(nullptr); | |||
| 2691 | } | |||
| 2692 | ||||
| 2693 | StructuredList->setInitializedFieldInUnion(*Field); | |||
| 2694 | } | |||
| 2695 | } | |||
| 2696 | ||||
| 2697 | // Make sure we can use this declaration. | |||
| 2698 | bool InvalidUse; | |||
| 2699 | if (VerifyOnly) | |||
| 2700 | InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); | |||
| 2701 | else | |||
| 2702 | InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc()); | |||
| 2703 | if (InvalidUse) { | |||
| 2704 | ++Index; | |||
| 2705 | return true; | |||
| 2706 | } | |||
| 2707 | ||||
| 2708 | // C++20 [dcl.init.list]p3: | |||
| 2709 | // The ordered identifiers in the designators of the designated- | |||
| 2710 | // initializer-list shall form a subsequence of the ordered identifiers | |||
| 2711 | // in the direct non-static data members of T. | |||
| 2712 | // | |||
| 2713 | // Note that this is not a condition on forming the aggregate | |||
| 2714 | // initialization, only on actually performing initialization, | |||
| 2715 | // so it is not checked in VerifyOnly mode. | |||
| 2716 | // | |||
| 2717 | // FIXME: This is the only reordering diagnostic we produce, and it only | |||
| 2718 | // catches cases where we have a top-level field designator that jumps | |||
| 2719 | // backwards. This is the only such case that is reachable in an | |||
| 2720 | // otherwise-valid C++20 program, so is the only case that's required for | |||
| 2721 | // conformance, but for consistency, we should diagnose all the other | |||
| 2722 | // cases where a designator takes us backwards too. | |||
| 2723 | if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus && | |||
| 2724 | NextField && | |||
| 2725 | (*NextField == RT->getDecl()->field_end() || | |||
| 2726 | (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) { | |||
| 2727 | // Find the field that we just initialized. | |||
| 2728 | FieldDecl *PrevField = nullptr; | |||
| 2729 | for (auto FI = RT->getDecl()->field_begin(); | |||
| 2730 | FI != RT->getDecl()->field_end(); ++FI) { | |||
| 2731 | if (FI->isUnnamedBitfield()) | |||
| 2732 | continue; | |||
| 2733 | if (*NextField != RT->getDecl()->field_end() && | |||
| 2734 | declaresSameEntity(*FI, **NextField)) | |||
| 2735 | break; | |||
| 2736 | PrevField = *FI; | |||
| 2737 | } | |||
| 2738 | ||||
| 2739 | if (PrevField && | |||
| 2740 | PrevField->getFieldIndex() > KnownField->getFieldIndex()) { | |||
| 2741 | SemaRef.Diag(DIE->getBeginLoc(), diag::ext_designated_init_reordered) | |||
| 2742 | << KnownField << PrevField << DIE->getSourceRange(); | |||
| 2743 | ||||
| 2744 | unsigned OldIndex = NumBases + PrevField->getFieldIndex(); | |||
| 2745 | if (StructuredList && OldIndex <= StructuredList->getNumInits()) { | |||
| 2746 | if (Expr *PrevInit = StructuredList->getInit(OldIndex)) { | |||
| 2747 | SemaRef.Diag(PrevInit->getBeginLoc(), | |||
| 2748 | diag::note_previous_field_init) | |||
| 2749 | << PrevField << PrevInit->getSourceRange(); | |||
| 2750 | } | |||
| 2751 | } | |||
| 2752 | } | |||
| 2753 | } | |||
| 2754 | ||||
| 2755 | ||||
| 2756 | // Update the designator with the field declaration. | |||
| 2757 | if (!VerifyOnly) | |||
| 2758 | D->setField(*Field); | |||
| 2759 | ||||
| 2760 | // Make sure that our non-designated initializer list has space | |||
| 2761 | // for a subobject corresponding to this field. | |||
| 2762 | if (StructuredList && FieldIndex >= StructuredList->getNumInits()) | |||
| 2763 | StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); | |||
| 2764 | ||||
| 2765 | // This designator names a flexible array member. | |||
| 2766 | if (Field->getType()->isIncompleteArrayType()) { | |||
| 2767 | bool Invalid = false; | |||
| 2768 | if ((DesigIdx + 1) != DIE->size()) { | |||
| 2769 | // We can't designate an object within the flexible array | |||
| 2770 | // member (because GCC doesn't allow it). | |||
| 2771 | if (!VerifyOnly) { | |||
| 2772 | DesignatedInitExpr::Designator *NextD | |||
| 2773 | = DIE->getDesignator(DesigIdx + 1); | |||
| 2774 | SemaRef.Diag(NextD->getBeginLoc(), | |||
| 2775 | diag::err_designator_into_flexible_array_member) | |||
| 2776 | << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc()); | |||
| 2777 | SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) | |||
| 2778 | << *Field; | |||
| 2779 | } | |||
| 2780 | Invalid = true; | |||
| 2781 | } | |||
| 2782 | ||||
| 2783 | if (!hadError && !isa<InitListExpr>(DIE->getInit()) && | |||
| 2784 | !isa<StringLiteral>(DIE->getInit())) { | |||
| 2785 | // The initializer is not an initializer list. | |||
| 2786 | if (!VerifyOnly) { | |||
| 2787 | SemaRef.Diag(DIE->getInit()->getBeginLoc(), | |||
| 2788 | diag::err_flexible_array_init_needs_braces) | |||
| 2789 | << DIE->getInit()->getSourceRange(); | |||
| 2790 | SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) | |||
| 2791 | << *Field; | |||
| 2792 | } | |||
| 2793 | Invalid = true; | |||
| 2794 | } | |||
| 2795 | ||||
| 2796 | // Check GNU flexible array initializer. | |||
| 2797 | if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field, | |||
| 2798 | TopLevelObject)) | |||
| 2799 | Invalid = true; | |||
| 2800 | ||||
| 2801 | if (Invalid) { | |||
| 2802 | ++Index; | |||
| 2803 | return true; | |||
| 2804 | } | |||
| 2805 | ||||
| 2806 | // Initialize the array. | |||
| 2807 | bool prevHadError = hadError; | |||
| 2808 | unsigned newStructuredIndex = FieldIndex; | |||
| 2809 | unsigned OldIndex = Index; | |||
| 2810 | IList->setInit(Index, DIE->getInit()); | |||
| 2811 | ||||
| 2812 | InitializedEntity MemberEntity = | |||
| 2813 | InitializedEntity::InitializeMember(*Field, &Entity); | |||
| 2814 | CheckSubElementType(MemberEntity, IList, Field->getType(), Index, | |||
| 2815 | StructuredList, newStructuredIndex); | |||
| 2816 | ||||
| 2817 | IList->setInit(OldIndex, DIE); | |||
| 2818 | if (hadError && !prevHadError) { | |||
| 2819 | ++Field; | |||
| 2820 | ++FieldIndex; | |||
| 2821 | if (NextField) | |||
| 2822 | *NextField = Field; | |||
| 2823 | StructuredIndex = FieldIndex; | |||
| 2824 | return true; | |||
| 2825 | } | |||
| 2826 | } else { | |||
| 2827 | // Recurse to check later designated subobjects. | |||
| 2828 | QualType FieldType = Field->getType(); | |||
| 2829 | unsigned newStructuredIndex = FieldIndex; | |||
| 2830 | ||||
| 2831 | InitializedEntity MemberEntity = | |||
| 2832 | InitializedEntity::InitializeMember(*Field, &Entity); | |||
| 2833 | if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1, | |||
| 2834 | FieldType, nullptr, nullptr, Index, | |||
| 2835 | StructuredList, newStructuredIndex, | |||
| 2836 | FinishSubobjectInit, false)) | |||
| 2837 | return true; | |||
| 2838 | } | |||
| 2839 | ||||
| 2840 | // Find the position of the next field to be initialized in this | |||
| 2841 | // subobject. | |||
| 2842 | ++Field; | |||
| 2843 | ++FieldIndex; | |||
| 2844 | ||||
| 2845 | // If this the first designator, our caller will continue checking | |||
| 2846 | // the rest of this struct/class/union subobject. | |||
| 2847 | if (IsFirstDesignator) { | |||
| 2848 | if (NextField) | |||
| 2849 | *NextField = Field; | |||
| 2850 | StructuredIndex = FieldIndex; | |||
| 2851 | return false; | |||
| 2852 | } | |||
| 2853 | ||||
| 2854 | if (!FinishSubobjectInit) | |||
| 2855 | return false; | |||
| 2856 | ||||
| 2857 | // We've already initialized something in the union; we're done. | |||
| 2858 | if (RT->getDecl()->isUnion()) | |||
| 2859 | return hadError; | |||
| 2860 | ||||
| 2861 | // Check the remaining fields within this class/struct/union subobject. | |||
| 2862 | bool prevHadError = hadError; | |||
| 2863 | ||||
| 2864 | auto NoBases = | |||
| 2865 | CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), | |||
| 2866 | CXXRecordDecl::base_class_iterator()); | |||
| 2867 | CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field, | |||
| 2868 | false, Index, StructuredList, FieldIndex); | |||
| 2869 | return hadError && !prevHadError; | |||
| 2870 | } | |||
| 2871 | ||||
| 2872 | // C99 6.7.8p6: | |||
| 2873 | // | |||
| 2874 | // If a designator has the form | |||
| 2875 | // | |||
| 2876 | // [ constant-expression ] | |||
| 2877 | // | |||
| 2878 | // then the current object (defined below) shall have array | |||
| 2879 | // type and the expression shall be an integer constant | |||
| 2880 | // expression. If the array is of unknown size, any | |||
| 2881 | // nonnegative value is valid. | |||
| 2882 | // | |||
| 2883 | // Additionally, cope with the GNU extension that permits | |||
| 2884 | // designators of the form | |||
| 2885 | // | |||
| 2886 | // [ constant-expression ... constant-expression ] | |||
| 2887 | const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); | |||
| 2888 | if (!AT) { | |||
| 2889 | if (!VerifyOnly) | |||
| 2890 | SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) | |||
| 2891 | << CurrentObjectType; | |||
| 2892 | ++Index; | |||
| 2893 | return true; | |||
| 2894 | } | |||
| 2895 | ||||
| 2896 | Expr *IndexExpr = nullptr; | |||
| 2897 | llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; | |||
| 2898 | if (D->isArrayDesignator()) { | |||
| 2899 | IndexExpr = DIE->getArrayIndex(*D); | |||
| 2900 | DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context); | |||
| 2901 | DesignatedEndIndex = DesignatedStartIndex; | |||
| 2902 | } else { | |||
| 2903 | assert(D->isArrayRangeDesignator() && "Need array-range designator")(static_cast <bool> (D->isArrayRangeDesignator() && "Need array-range designator") ? void (0) : __assert_fail ("D->isArrayRangeDesignator() && \"Need array-range designator\"" , "clang/lib/Sema/SemaInit.cpp", 2903, __extension__ __PRETTY_FUNCTION__ )); | |||
| 2904 | ||||
| 2905 | DesignatedStartIndex = | |||
| 2906 | DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context); | |||
| 2907 | DesignatedEndIndex = | |||
| 2908 | DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context); | |||
| 2909 | IndexExpr = DIE->getArrayRangeEnd(*D); | |||
| 2910 | ||||
| 2911 | // Codegen can't handle evaluating array range designators that have side | |||
| 2912 | // effects, because we replicate the AST value for each initialized element. | |||
| 2913 | // As such, set the sawArrayRangeDesignator() bit if we initialize multiple | |||
| 2914 | // elements with something that has a side effect, so codegen can emit an | |||
| 2915 | // "error unsupported" error instead of miscompiling the app. | |||
| 2916 | if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&& | |||
| 2917 | DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly) | |||
| 2918 | FullyStructuredList->sawArrayRangeDesignator(); | |||
| ||||
| 2919 | } | |||
| 2920 | ||||
| 2921 | if (isa<ConstantArrayType>(AT)) { | |||
| 2922 | llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); | |||
| 2923 | DesignatedStartIndex | |||
| 2924 | = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); | |||
| 2925 | DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); | |||
| 2926 | DesignatedEndIndex | |||
| 2927 | = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); | |||
| 2928 | DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); | |||
| 2929 | if (DesignatedEndIndex >= MaxElements) { | |||
| 2930 | if (!VerifyOnly) | |||
| 2931 | SemaRef.Diag(IndexExpr->getBeginLoc(), | |||
| 2932 | diag::err_array_designator_too_large) | |||
| 2933 | << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10) | |||
| 2934 | << IndexExpr->getSourceRange(); | |||
| 2935 | ++Index; | |||
| 2936 | return true; | |||
| 2937 | } | |||
| 2938 | } else { | |||
| 2939 | unsigned DesignatedIndexBitWidth = | |||
| 2940 | ConstantArrayType::getMaxSizeBits(SemaRef.Context); | |||
| 2941 | DesignatedStartIndex = | |||
| 2942 | DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth); | |||
| 2943 | DesignatedEndIndex = | |||
| 2944 | DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth); | |||
| 2945 | DesignatedStartIndex.setIsUnsigned(true); | |||
| 2946 | DesignatedEndIndex.setIsUnsigned(true); | |||
| 2947 | } | |||
| 2948 | ||||
| 2949 | bool IsStringLiteralInitUpdate = | |||
| 2950 | StructuredList && StructuredList->isStringLiteralInit(); | |||
| 2951 | if (IsStringLiteralInitUpdate && VerifyOnly) { | |||
| 2952 | // We're just verifying an update to a string literal init. We don't need | |||
| 2953 | // to split the string up into individual characters to do that. | |||
| 2954 | StructuredList = nullptr; | |||
| 2955 | } else if (IsStringLiteralInitUpdate) { | |||
| 2956 | // We're modifying a string literal init; we have to decompose the string | |||
| 2957 | // so we can modify the individual characters. | |||
| 2958 | ASTContext &Context = SemaRef.Context; | |||
| 2959 | Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts(); | |||
| 2960 | ||||
| 2961 | // Compute the character type | |||
| 2962 | QualType CharTy = AT->getElementType(); | |||
| 2963 | ||||
| 2964 | // Compute the type of the integer literals. | |||
| 2965 | QualType PromotedCharTy = CharTy; | |||
| 2966 | if (Context.isPromotableIntegerType(CharTy)) | |||
| 2967 | PromotedCharTy = Context.getPromotedIntegerType(CharTy); | |||
| 2968 | unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy); | |||
| 2969 | ||||
| 2970 | if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) { | |||
| 2971 | // Get the length of the string. | |||
| 2972 | uint64_t StrLen = SL->getLength(); | |||
| 2973 | if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) | |||
| 2974 | StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); | |||
| 2975 | StructuredList->resizeInits(Context, StrLen); | |||
| 2976 | ||||
| 2977 | // Build a literal for each character in the string, and put them into | |||
| 2978 | // the init list. | |||
| 2979 | for (unsigned i = 0, e = StrLen; i != e; ++i) { | |||
| 2980 | llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i)); | |||
| 2981 | Expr *Init = new (Context) IntegerLiteral( | |||
| 2982 | Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); | |||
| 2983 | if (CharTy != PromotedCharTy) | |||
| 2984 | Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, | |||
| 2985 | Init, nullptr, VK_PRValue, | |||
| 2986 | FPOptionsOverride()); | |||
| 2987 | StructuredList->updateInit(Context, i, Init); | |||
| 2988 | } | |||
| 2989 | } else { | |||
| 2990 | ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr); | |||
| 2991 | std::string Str; | |||
| 2992 | Context.getObjCEncodingForType(E->getEncodedType(), Str); | |||
| 2993 | ||||
| 2994 | // Get the length of the string. | |||
| 2995 | uint64_t StrLen = Str.size(); | |||
| 2996 | if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) | |||
| 2997 | StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); | |||
| 2998 | StructuredList->resizeInits(Context, StrLen); | |||
| 2999 | ||||
| 3000 | // Build a literal for each character in the string, and put them into | |||
| 3001 | // the init list. | |||
| 3002 | for (unsigned i = 0, e = StrLen; i != e; ++i) { | |||
| 3003 | llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]); | |||
| 3004 | Expr *Init = new (Context) IntegerLiteral( | |||
| 3005 | Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); | |||
| 3006 | if (CharTy != PromotedCharTy) | |||
| 3007 | Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, | |||
| 3008 | Init, nullptr, VK_PRValue, | |||
| 3009 | FPOptionsOverride()); | |||
| 3010 | StructuredList->updateInit(Context, i, Init); | |||
| 3011 | } | |||
| 3012 | } | |||
| 3013 | } | |||
| 3014 | ||||
| 3015 | // Make sure that our non-designated initializer list has space | |||
| 3016 | // for a subobject corresponding to this array element. | |||
| 3017 | if (StructuredList && | |||
| 3018 | DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) | |||
| 3019 | StructuredList->resizeInits(SemaRef.Context, | |||
| 3020 | DesignatedEndIndex.getZExtValue() + 1); | |||
| 3021 | ||||
| 3022 | // Repeatedly perform subobject initializations in the range | |||
| 3023 | // [DesignatedStartIndex, DesignatedEndIndex]. | |||
| 3024 | ||||
| 3025 | // Move to the next designator | |||
| 3026 | unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); | |||
| 3027 | unsigned OldIndex = Index; | |||
| 3028 | ||||
| 3029 | InitializedEntity ElementEntity = | |||
| 3030 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); | |||
| 3031 | ||||
| 3032 | while (DesignatedStartIndex <= DesignatedEndIndex) { | |||
| 3033 | // Recurse to check later designated subobjects. | |||
| 3034 | QualType ElementType = AT->getElementType(); | |||
| 3035 | Index = OldIndex; | |||
| 3036 | ||||
| 3037 | ElementEntity.setElementIndex(ElementIndex); | |||
| 3038 | if (CheckDesignatedInitializer( | |||
| 3039 | ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr, | |||
| 3040 | nullptr, Index, StructuredList, ElementIndex, | |||
| 3041 | FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex), | |||
| 3042 | false)) | |||
| 3043 | return true; | |||
| 3044 | ||||
| 3045 | // Move to the next index in the array that we'll be initializing. | |||
| 3046 | ++DesignatedStartIndex; | |||
| 3047 | ElementIndex = DesignatedStartIndex.getZExtValue(); | |||
| 3048 | } | |||
| 3049 | ||||
| 3050 | // If this the first designator, our caller will continue checking | |||
| 3051 | // the rest of this array subobject. | |||
| 3052 | if (IsFirstDesignator) { | |||
| 3053 | if (NextElementIndex) | |||
| 3054 | *NextElementIndex = DesignatedStartIndex; | |||
| 3055 | StructuredIndex = ElementIndex; | |||
| 3056 | return false; | |||
| 3057 | } | |||
| 3058 | ||||
| 3059 | if (!FinishSubobjectInit) | |||
| 3060 | return false; | |||
| 3061 | ||||
| 3062 | // Check the remaining elements within this array subobject. | |||
| 3063 | bool prevHadError = hadError; | |||
| 3064 | CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex, | |||
| 3065 | /*SubobjectIsDesignatorContext=*/false, Index, | |||
| 3066 | StructuredList, ElementIndex); | |||
| 3067 | return hadError && !prevHadError; | |||
| 3068 | } | |||
| 3069 | ||||
| 3070 | // Get the structured initializer list for a subobject of type | |||
| 3071 | // @p CurrentObjectType. | |||
| 3072 | InitListExpr * | |||
| 3073 | InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, | |||
| 3074 | QualType CurrentObjectType, | |||
| 3075 | InitListExpr *StructuredList, | |||
| 3076 | unsigned StructuredIndex, | |||
| 3077 | SourceRange InitRange, | |||
| 3078 | bool IsFullyOverwritten) { | |||
| 3079 | if (!StructuredList) | |||
| 3080 | return nullptr; | |||
| 3081 | ||||
| 3082 | Expr *ExistingInit = nullptr; | |||
| 3083 | if (StructuredIndex < StructuredList->getNumInits()) | |||
| 3084 | ExistingInit = StructuredList->getInit(StructuredIndex); | |||
| 3085 | ||||
| 3086 | if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) | |||
| 3087 | // There might have already been initializers for subobjects of the current | |||
| 3088 | // object, but a subsequent initializer list will overwrite the entirety | |||
| 3089 | // of the current object. (See DR 253 and C99 6.7.8p21). e.g., | |||
| 3090 | // | |||
| 3091 | // struct P { char x[6]; }; | |||
| 3092 | // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } }; | |||
| 3093 | // | |||
| 3094 | // The first designated initializer is ignored, and l.x is just "f". | |||
| 3095 | if (!IsFullyOverwritten) | |||
| 3096 | return Result; | |||
| 3097 | ||||
| 3098 | if (ExistingInit) { | |||
| 3099 | // We are creating an initializer list that initializes the | |||
| 3100 | // subobjects of the current object, but there was already an | |||
| 3101 | // initialization that completely initialized the current | |||
| 3102 | // subobject: | |||
| 3103 | // | |||
| 3104 | // struct X { int a, b; }; | |||
| 3105 | // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 }; | |||
| 3106 | // | |||
| 3107 | // Here, xs[0].a == 1 and xs[0].b == 3, since the second, | |||
| 3108 | // designated initializer overwrites the [0].b initializer | |||
| 3109 | // from the prior initialization. | |||
| 3110 | // | |||
| 3111 | // When the existing initializer is an expression rather than an | |||
| 3112 | // initializer list, we cannot decompose and update it in this way. | |||
| 3113 | // For example: | |||
| 3114 | // | |||
| 3115 | // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; | |||
| 3116 | // | |||
| 3117 | // This case is handled by CheckDesignatedInitializer. | |||
| 3118 | diagnoseInitOverride(ExistingInit, InitRange); | |||
| 3119 | } | |||
| 3120 | ||||
| 3121 | unsigned ExpectedNumInits = 0; | |||
| 3122 | if (Index < IList->getNumInits()) { | |||
| 3123 | if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index))) | |||
| 3124 | ExpectedNumInits = Init->getNumInits(); | |||
| 3125 | else | |||
| 3126 | ExpectedNumInits = IList->getNumInits() - Index; | |||
| 3127 | } | |||
| 3128 | ||||
| 3129 | InitListExpr *Result = | |||
| 3130 | createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits); | |||
| 3131 | ||||
| 3132 | // Link this new initializer list into the structured initializer | |||
| 3133 | // lists. | |||
| 3134 | StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result); | |||
| 3135 | return Result; | |||
| 3136 | } | |||
| 3137 | ||||
| 3138 | InitListExpr * | |||
| 3139 | InitListChecker::createInitListExpr(QualType CurrentObjectType, | |||
| 3140 | SourceRange InitRange, | |||
| 3141 | unsigned ExpectedNumInits) { | |||
| 3142 | InitListExpr *Result = new (SemaRef.Context) InitListExpr( | |||
| 3143 | SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd()); | |||
| 3144 | ||||
| 3145 | QualType ResultType = CurrentObjectType; | |||
| 3146 | if (!ResultType->isArrayType()) | |||
| 3147 | ResultType = ResultType.getNonLValueExprType(SemaRef.Context); | |||
| 3148 | Result->setType(ResultType); | |||
| 3149 | ||||
| 3150 | // Pre-allocate storage for the structured initializer list. | |||
| 3151 | unsigned NumElements = 0; | |||
| 3152 | ||||
| 3153 | if (const ArrayType *AType | |||
| 3154 | = SemaRef.Context.getAsArrayType(CurrentObjectType)) { | |||
| 3155 | if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { | |||
| 3156 | NumElements = CAType->getSize().getZExtValue(); | |||
| 3157 | // Simple heuristic so that we don't allocate a very large | |||
| 3158 | // initializer with many empty entries at the end. | |||
| 3159 | if (NumElements > ExpectedNumInits) | |||
| 3160 | NumElements = 0; | |||
| 3161 | } | |||
| 3162 | } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) { | |||
| 3163 | NumElements = VType->getNumElements(); | |||
| 3164 | } else if (CurrentObjectType->isRecordType()) { | |||
| 3165 | NumElements = numStructUnionElements(CurrentObjectType); | |||
| 3166 | } | |||
| 3167 | ||||
| 3168 | Result->reserveInits(SemaRef.Context, NumElements); | |||
| 3169 | ||||
| 3170 | return Result; | |||
| 3171 | } | |||
| 3172 | ||||
| 3173 | /// Update the initializer at index @p StructuredIndex within the | |||
| 3174 | /// structured initializer list to the value @p expr. | |||
| 3175 | void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, | |||
| 3176 | unsigned &StructuredIndex, | |||
| 3177 | Expr *expr) { | |||
| 3178 | // No structured initializer list to update | |||
| 3179 | if (!StructuredList) | |||
| 3180 | return; | |||
| 3181 | ||||
| 3182 | if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context, | |||
| 3183 | StructuredIndex, expr)) { | |||
| 3184 | // This initializer overwrites a previous initializer. | |||
| 3185 | // No need to diagnose when `expr` is nullptr because a more relevant | |||
| 3186 | // diagnostic has already been issued and this diagnostic is potentially | |||
| 3187 | // noise. | |||
| 3188 | if (expr) | |||
| 3189 | diagnoseInitOverride(PrevInit, expr->getSourceRange()); | |||
| 3190 | } | |||
| 3191 | ||||
| 3192 | ++StructuredIndex; | |||
| 3193 | } | |||
| 3194 | ||||
| 3195 | /// Determine whether we can perform aggregate initialization for the purposes | |||
| 3196 | /// of overload resolution. | |||
| 3197 | bool Sema::CanPerformAggregateInitializationForOverloadResolution( | |||
| 3198 | const InitializedEntity &Entity, InitListExpr *From) { | |||
| 3199 | QualType Type = Entity.getType(); | |||
| 3200 | InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true, | |||
| 3201 | /*TreatUnavailableAsInvalid=*/false, | |||
| 3202 | /*InOverloadResolution=*/true); | |||
| 3203 | return !Check.HadError(); | |||
| 3204 | } | |||
| 3205 | ||||
| 3206 | /// Check that the given Index expression is a valid array designator | |||
| 3207 | /// value. This is essentially just a wrapper around | |||
| 3208 | /// VerifyIntegerConstantExpression that also checks for negative values | |||
| 3209 | /// and produces a reasonable diagnostic if there is a | |||
| 3210 | /// failure. Returns the index expression, possibly with an implicit cast | |||
| 3211 | /// added, on success. If everything went okay, Value will receive the | |||
| 3212 | /// value of the constant expression. | |||
| 3213 | static ExprResult | |||
| 3214 | CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { | |||
| 3215 | SourceLocation Loc = Index->getBeginLoc(); | |||
| 3216 | ||||
| 3217 | // Make sure this is an integer constant expression. | |||
| 3218 | ExprResult Result = | |||
| 3219 | S.VerifyIntegerConstantExpression(Index, &Value, Sema::AllowFold); | |||
| 3220 | if (Result.isInvalid()) | |||
| 3221 | return Result; | |||
| 3222 | ||||
| 3223 | if (Value.isSigned() && Value.isNegative()) | |||
| 3224 | return S.Diag(Loc, diag::err_array_designator_negative) | |||
| 3225 | << toString(Value, 10) << Index->getSourceRange(); | |||
| 3226 | ||||
| 3227 | Value.setIsUnsigned(true); | |||
| 3228 | return Result; | |||
| 3229 | } | |||
| 3230 | ||||
| 3231 | ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, | |||
| 3232 | SourceLocation EqualOrColonLoc, | |||
| 3233 | bool GNUSyntax, | |||
| 3234 | ExprResult Init) { | |||
| 3235 | typedef DesignatedInitExpr::Designator ASTDesignator; | |||
| 3236 | ||||
| 3237 | bool Invalid = false; | |||
| 3238 | SmallVector<ASTDesignator, 32> Designators; | |||
| 3239 | SmallVector<Expr *, 32> InitExpressions; | |||
| 3240 | ||||
| 3241 | // Build designators and check array designator expressions. | |||
| 3242 | for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { | |||
| 3243 | const Designator &D = Desig.getDesignator(Idx); | |||
| 3244 | ||||
| 3245 | if (D.isFieldDesignator()) { | |||
| 3246 | Designators.push_back(ASTDesignator::CreateFieldDesignator( | |||
| 3247 | D.getField(), D.getDotLoc(), D.getFieldLoc())); | |||
| 3248 | } else if (D.isArrayDesignator()) { | |||
| 3249 | Expr *Index = static_cast<Expr *>(D.getArrayIndex()); | |||
| 3250 | llvm::APSInt IndexValue; | |||
| 3251 | if (!Index->isTypeDependent() && !Index->isValueDependent()) | |||
| 3252 | Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get(); | |||
| 3253 | if (!Index) | |||
| 3254 | Invalid = true; | |||
| 3255 | else { | |||
| 3256 | Designators.push_back(ASTDesignator::CreateArrayDesignator( | |||
| 3257 | InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc())); | |||
| 3258 | InitExpressions.push_back(Index); | |||
| 3259 | } | |||
| 3260 | } else if (D.isArrayRangeDesignator()) { | |||
| 3261 | Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); | |||
| 3262 | Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); | |||
| 3263 | llvm::APSInt StartValue; | |||
| 3264 | llvm::APSInt EndValue; | |||
| 3265 | bool StartDependent = StartIndex->isTypeDependent() || | |||
| 3266 | StartIndex->isValueDependent(); | |||
| 3267 | bool EndDependent = EndIndex->isTypeDependent() || | |||
| 3268 | EndIndex->isValueDependent(); | |||
| 3269 | if (!StartDependent) | |||
| 3270 | StartIndex = | |||
| 3271 | CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get(); | |||
| 3272 | if (!EndDependent) | |||
| 3273 | EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get(); | |||
| 3274 | ||||
| 3275 | if (!StartIndex || !EndIndex) | |||
| 3276 | Invalid = true; | |||
| 3277 | else { | |||
| 3278 | // Make sure we're comparing values with the same bit width. | |||
| 3279 | if (StartDependent || EndDependent) { | |||
| 3280 | // Nothing to compute. | |||
| 3281 | } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) | |||
| 3282 | EndValue = EndValue.extend(StartValue.getBitWidth()); | |||
| 3283 | else if (StartValue.getBitWidth() < EndValue.getBitWidth()) | |||
| 3284 | StartValue = StartValue.extend(EndValue.getBitWidth()); | |||
| 3285 | ||||
| 3286 | if (!StartDependent && !EndDependent && EndValue < StartValue) { | |||
| 3287 | Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) | |||
| 3288 | << toString(StartValue, 10) << toString(EndValue, 10) | |||
| 3289 | << StartIndex->getSourceRange() << EndIndex->getSourceRange(); | |||
| 3290 | Invalid = true; | |||
| 3291 | } else { | |||
| 3292 | Designators.push_back(ASTDesignator::CreateArrayRangeDesignator( | |||
| 3293 | InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(), | |||
| 3294 | D.getRBracketLoc())); | |||
| 3295 | InitExpressions.push_back(StartIndex); | |||
| 3296 | InitExpressions.push_back(EndIndex); | |||
| 3297 | } | |||
| 3298 | } | |||
| 3299 | } | |||
| 3300 | } | |||
| 3301 | ||||
| 3302 | if (Invalid || Init.isInvalid()) | |||
| 3303 | return ExprError(); | |||
| 3304 | ||||
| 3305 | return DesignatedInitExpr::Create(Context, Designators, InitExpressions, | |||
| 3306 | EqualOrColonLoc, GNUSyntax, | |||
| 3307 | Init.getAs<Expr>()); | |||
| 3308 | } | |||
| 3309 | ||||
| 3310 | //===----------------------------------------------------------------------===// | |||
| 3311 | // Initialization entity | |||
| 3312 | //===----------------------------------------------------------------------===// | |||
| 3313 | ||||
| 3314 | InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, | |||
| 3315 | const InitializedEntity &Parent) | |||
| 3316 | : Parent(&Parent), Index(Index) | |||
| 3317 | { | |||
| 3318 | if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) { | |||
| 3319 | Kind = EK_ArrayElement; | |||
| 3320 | Type = AT->getElementType(); | |||
| 3321 | } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) { | |||
| 3322 | Kind = EK_VectorElement; | |||
| 3323 | Type = VT->getElementType(); | |||
| 3324 | } else { | |||
| 3325 | const ComplexType *CT = Parent.getType()->getAs<ComplexType>(); | |||
| 3326 | assert(CT && "Unexpected type")(static_cast <bool> (CT && "Unexpected type") ? void (0) : __assert_fail ("CT && \"Unexpected type\"" , "clang/lib/Sema/SemaInit.cpp", 3326, __extension__ __PRETTY_FUNCTION__ )); | |||
| 3327 | Kind = EK_ComplexElement; | |||
| 3328 | Type = CT->getElementType(); | |||
| 3329 | } | |||
| 3330 | } | |||
| 3331 | ||||
| 3332 | InitializedEntity | |||
| 3333 | InitializedEntity::InitializeBase(ASTContext &Context, | |||
| 3334 | const CXXBaseSpecifier *Base, | |||
| 3335 | bool IsInheritedVirtualBase, | |||
| 3336 | const InitializedEntity *Parent) { | |||
| 3337 | InitializedEntity Result; | |||
| 3338 | Result.Kind = EK_Base; | |||
| 3339 | Result.Parent = Parent; | |||
| 3340 | Result.Base = {Base, IsInheritedVirtualBase}; | |||
| 3341 | Result.Type = Base->getType(); | |||
| 3342 | return Result; | |||
| 3343 | } | |||
| 3344 | ||||
| 3345 | DeclarationName InitializedEntity::getName() const { | |||
| 3346 | switch (getKind()) { | |||
| 3347 | case EK_Parameter: | |||
| 3348 | case EK_Parameter_CF_Audited: { | |||
| 3349 | ParmVarDecl *D = Parameter.getPointer(); | |||
| 3350 | return (D ? D->getDeclName() : DeclarationName()); | |||
| 3351 | } | |||
| 3352 | ||||
| 3353 | case EK_Variable: | |||
| 3354 | case EK_Member: | |||
| 3355 | case EK_Binding: | |||
| 3356 | case EK_TemplateParameter: | |||
| 3357 | return Variable.VariableOrMember->getDeclName(); | |||
| 3358 | ||||
| 3359 | case EK_LambdaCapture: | |||
| 3360 | return DeclarationName(Capture.VarID); | |||
| 3361 | ||||
| 3362 | case EK_Result: | |||
| 3363 | case EK_StmtExprResult: | |||
| 3364 | case EK_Exception: | |||
| 3365 | case EK_New: | |||
| 3366 | case EK_Temporary: | |||
| 3367 | case EK_Base: | |||
| 3368 | case EK_Delegating: | |||
| 3369 | case EK_ArrayElement: | |||
| 3370 | case EK_VectorElement: | |||
| 3371 | case EK_ComplexElement: | |||
| 3372 | case EK_BlockElement: | |||
| 3373 | case EK_LambdaToBlockConversionBlockElement: | |||
| 3374 | case EK_CompoundLiteralInit: | |||
| 3375 | case EK_RelatedResult: | |||
| 3376 | return DeclarationName(); | |||
| 3377 | } | |||
| 3378 | ||||
| 3379 | llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp" , 3379); | |||
| 3380 | } | |||
| 3381 | ||||
| 3382 | ValueDecl *InitializedEntity::getDecl() const { | |||
| 3383 | switch (getKind()) { | |||
| 3384 | case EK_Variable: | |||
| 3385 | case EK_Member: | |||
| 3386 | case EK_Binding: | |||
| 3387 | case EK_TemplateParameter: | |||
| 3388 | return Variable.VariableOrMember; | |||
| 3389 | ||||
| 3390 | case EK_Parameter: | |||
| 3391 | case EK_Parameter_CF_Audited: | |||
| 3392 | return Parameter.getPointer(); | |||
| 3393 | ||||
| 3394 | case EK_Result: | |||
| 3395 | case EK_StmtExprResult: | |||
| 3396 | case EK_Exception: | |||
| 3397 | case EK_New: | |||
| 3398 | case EK_Temporary: | |||
| 3399 | case EK_Base: | |||
| 3400 | case EK_Delegating: | |||
| 3401 | case EK_ArrayElement: | |||
| 3402 | case EK_VectorElement: | |||
| 3403 | case EK_ComplexElement: | |||
| 3404 | case EK_BlockElement: | |||
| 3405 | case EK_LambdaToBlockConversionBlockElement: | |||
| 3406 | case EK_LambdaCapture: | |||
| 3407 | case EK_CompoundLiteralInit: | |||
| 3408 | case EK_RelatedResult: | |||
| 3409 | return nullptr; | |||
| 3410 | } | |||
| 3411 | ||||
| 3412 | llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp" , 3412); | |||
| 3413 | } | |||
| 3414 | ||||
| 3415 | bool InitializedEntity::allowsNRVO() const { | |||
| 3416 | switch (getKind()) { | |||
| 3417 | case EK_Result: | |||
| 3418 | case EK_Exception: | |||
| 3419 | return LocAndNRVO.NRVO; | |||
| 3420 | ||||
| 3421 | case EK_StmtExprResult: | |||
| 3422 | case EK_Variable: | |||
| 3423 | case EK_Parameter: | |||
| 3424 | case EK_Parameter_CF_Audited: | |||
| 3425 | case EK_TemplateParameter: | |||
| 3426 | case EK_Member: | |||
| 3427 | case EK_Binding: | |||
| 3428 | case EK_New: | |||
| 3429 | case EK_Temporary: | |||
| 3430 | case EK_CompoundLiteralInit: | |||
| 3431 | case EK_Base: | |||
| 3432 | case EK_Delegating: | |||
| 3433 | case EK_ArrayElement: | |||
| 3434 | case EK_VectorElement: | |||
| 3435 | case EK_ComplexElement: | |||
| 3436 | case EK_BlockElement: | |||
| 3437 | case EK_LambdaToBlockConversionBlockElement: | |||
| 3438 | case EK_LambdaCapture: | |||
| 3439 | case EK_RelatedResult: | |||
| 3440 | break; | |||
| 3441 | } | |||
| 3442 | ||||
| 3443 | return false; | |||
| 3444 | } | |||
| 3445 | ||||
| 3446 | unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const { | |||
| 3447 | assert(getParent() != this)(static_cast <bool> (getParent() != this) ? void (0) : __assert_fail ("getParent() != this", "clang/lib/Sema/SemaInit.cpp", 3447, __extension__ __PRETTY_FUNCTION__)); | |||
| 3448 | unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0; | |||
| 3449 | for (unsigned I = 0; I != Depth; ++I) | |||
| 3450 | OS << "`-"; | |||
| 3451 | ||||
| 3452 | switch (getKind()) { | |||
| 3453 | case EK_Variable: OS << "Variable"; break; | |||
| 3454 | case EK_Parameter: OS << "Parameter"; break; | |||
| 3455 | case EK_Parameter_CF_Audited: OS << "CF audited function Parameter"; | |||
| 3456 | break; | |||
| 3457 | case EK_TemplateParameter: OS << "TemplateParameter"; break; | |||
| 3458 | case EK_Result: OS << "Result"; break; | |||
| 3459 | case EK_StmtExprResult: OS << "StmtExprResult"; break; | |||
| 3460 | case EK_Exception: OS << "Exception"; break; | |||
| 3461 | case EK_Member: OS << "Member"; break; | |||
| 3462 | case EK_Binding: OS << "Binding"; break; | |||
| 3463 | case EK_New: OS << "New"; break; | |||
| 3464 | case EK_Temporary: OS << "Temporary"; break; | |||
| 3465 | case EK_CompoundLiteralInit: OS << "CompoundLiteral";break; | |||
| 3466 | case EK_RelatedResult: OS << "RelatedResult"; break; | |||
| 3467 | case EK_Base: OS << "Base"; break; | |||
| 3468 | case EK_Delegating: OS << "Delegating"; break; | |||
| 3469 | case EK_ArrayElement: OS << "ArrayElement " << Index; break; | |||
| 3470 | case EK_VectorElement: OS << "VectorElement " << Index; break; | |||
| 3471 | case EK_ComplexElement: OS << "ComplexElement " << Index; break; | |||
| 3472 | case EK_BlockElement: OS << "Block"; break; | |||
| 3473 | case EK_LambdaToBlockConversionBlockElement: | |||
| 3474 | OS << "Block (lambda)"; | |||
| 3475 | break; | |||
| 3476 | case EK_LambdaCapture: | |||
| 3477 | OS << "LambdaCapture "; | |||
| 3478 | OS << DeclarationName(Capture.VarID); | |||
| 3479 | break; | |||
| 3480 | } | |||
| 3481 | ||||
| 3482 | if (auto *D = getDecl()) { | |||
| 3483 | OS << " "; | |||
| 3484 | D->printQualifiedName(OS); | |||
| 3485 | } | |||
| 3486 | ||||
| 3487 | OS << " '" << getType() << "'\n"; | |||
| 3488 | ||||
| 3489 | return Depth + 1; | |||
| 3490 | } | |||
| 3491 | ||||
| 3492 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void InitializedEntity::dump() const { | |||
| 3493 | dumpImpl(llvm::errs()); | |||
| 3494 | } | |||
| 3495 | ||||
| 3496 | //===----------------------------------------------------------------------===// | |||
| 3497 | // Initialization sequence | |||
| 3498 | //===----------------------------------------------------------------------===// | |||
| 3499 | ||||
| 3500 | void InitializationSequence::Step::Destroy() { | |||
| 3501 | switch (Kind) { | |||
| 3502 | case SK_ResolveAddressOfOverloadedFunction: | |||
| 3503 | case SK_CastDerivedToBasePRValue: | |||
| 3504 | case SK_CastDerivedToBaseXValue: | |||
| 3505 | case SK_CastDerivedToBaseLValue: | |||
| 3506 | case SK_BindReference: | |||
| 3507 | case SK_BindReferenceToTemporary: | |||
| 3508 | case SK_FinalCopy: | |||
| 3509 | case SK_ExtraneousCopyToTemporary: | |||
| 3510 | case SK_UserConversion: | |||
| 3511 | case SK_QualificationConversionPRValue: | |||
| 3512 | case SK_QualificationConversionXValue: | |||
| 3513 | case SK_QualificationConversionLValue: | |||
| 3514 | case SK_FunctionReferenceConversion: | |||
| 3515 | case SK_AtomicConversion: | |||
| 3516 | case SK_ListInitialization: | |||
| 3517 | case SK_UnwrapInitList: | |||
| 3518 | case SK_RewrapInitList: | |||
| 3519 | case SK_ConstructorInitialization: | |||
| 3520 | case SK_ConstructorInitializationFromList: | |||
| 3521 | case SK_ZeroInitialization: | |||
| 3522 | case SK_CAssignment: | |||
| 3523 | case SK_StringInit: | |||
| 3524 | case SK_ObjCObjectConversion: | |||
| 3525 | case SK_ArrayLoopIndex: | |||
| 3526 | case SK_ArrayLoopInit: | |||
| 3527 | case SK_ArrayInit: | |||
| 3528 | case SK_GNUArrayInit: | |||
| 3529 | case SK_ParenthesizedArrayInit: | |||
| 3530 | case SK_PassByIndirectCopyRestore: | |||
| 3531 | case SK_PassByIndirectRestore: | |||
| 3532 | case SK_ProduceObjCObject: | |||
| 3533 | case SK_StdInitializerList: | |||
| 3534 | case SK_StdInitializerListConstructorCall: | |||
| 3535 | case SK_OCLSamplerInit: | |||
| 3536 | case SK_OCLZeroOpaqueType: | |||
| 3537 | case SK_ParenthesizedListInit: | |||
| 3538 | break; | |||
| 3539 | ||||
| 3540 | case SK_ConversionSequence: | |||
| 3541 | case SK_ConversionSequenceNoNarrowing: | |||
| 3542 | delete ICS; | |||
| 3543 | } | |||
| 3544 | } | |||
| 3545 | ||||
| 3546 | bool InitializationSequence::isDirectReferenceBinding() const { | |||
| 3547 | // There can be some lvalue adjustments after the SK_BindReference step. | |||
| 3548 | for (const Step &S : llvm::reverse(Steps)) { | |||
| 3549 | if (S.Kind == SK_BindReference) | |||
| 3550 | return true; | |||
| 3551 | if (S.Kind == SK_BindReferenceToTemporary) | |||
| 3552 | return false; | |||
| 3553 | } | |||
| 3554 | return false; | |||
| 3555 | } | |||
| 3556 | ||||
| 3557 | bool InitializationSequence::isAmbiguous() const { | |||
| 3558 | if (!Failed()) | |||
| 3559 | return false; | |||
| 3560 | ||||
| 3561 | switch (getFailureKind()) { | |||
| 3562 | case FK_TooManyInitsForReference: | |||
| 3563 | case FK_ParenthesizedListInitForReference: | |||
| 3564 | case FK_ArrayNeedsInitList: | |||
| 3565 | case FK_ArrayNeedsInitListOrStringLiteral: | |||
| 3566 | case FK_ArrayNeedsInitListOrWideStringLiteral: | |||
| 3567 | case FK_NarrowStringIntoWideCharArray: | |||
| 3568 | case FK_WideStringIntoCharArray: | |||
| 3569 | case FK_IncompatWideStringIntoWideChar: | |||
| 3570 | case FK_PlainStringIntoUTF8Char: | |||
| 3571 | case FK_UTF8StringIntoPlainChar: | |||
| 3572 | case FK_AddressOfOverloadFailed: // FIXME: Could do better | |||
| 3573 | case FK_NonConstLValueReferenceBindingToTemporary: | |||
| 3574 | case FK_NonConstLValueReferenceBindingToBitfield: | |||
| 3575 | case FK_NonConstLValueReferenceBindingToVectorElement: | |||
| 3576 | case FK_NonConstLValueReferenceBindingToMatrixElement: | |||
| 3577 | case FK_NonConstLValueReferenceBindingToUnrelated: | |||
| 3578 | case FK_RValueReferenceBindingToLValue: | |||
| 3579 | case FK_ReferenceAddrspaceMismatchTemporary: | |||
| 3580 | case FK_ReferenceInitDropsQualifiers: | |||
| 3581 | case FK_ReferenceInitFailed: | |||
| 3582 | case FK_ConversionFailed: | |||
| 3583 | case FK_ConversionFromPropertyFailed: | |||
| 3584 | case FK_TooManyInitsForScalar: | |||
| 3585 | case FK_ParenthesizedListInitForScalar: | |||
| 3586 | case FK_ReferenceBindingToInitList: | |||
| 3587 | case FK_InitListBadDestinationType: | |||
| 3588 | case FK_DefaultInitOfConst: | |||
| 3589 | case FK_Incomplete: | |||
| 3590 | case FK_ArrayTypeMismatch: | |||
| 3591 | case FK_NonConstantArrayInit: | |||
| 3592 | case FK_ListInitializationFailed: | |||
| 3593 | case FK_VariableLengthArrayHasInitializer: | |||
| 3594 | case FK_PlaceholderType: | |||
| 3595 | case FK_ExplicitConstructor: | |||
| 3596 | case FK_AddressOfUnaddressableFunction: | |||
| 3597 | case FK_ParenthesizedListInitFailed: | |||
| 3598 | return false; | |||
| 3599 | ||||
| 3600 | case FK_ReferenceInitOverloadFailed: | |||
| 3601 | case FK_UserConversionOverloadFailed: | |||
| 3602 | case FK_ConstructorOverloadFailed: | |||
| 3603 | case FK_ListConstructorOverloadFailed: | |||
| 3604 | return FailedOverloadResult == OR_Ambiguous; | |||
| 3605 | } | |||
| 3606 | ||||
| 3607 | llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp" , 3607); | |||
| 3608 | } | |||
| 3609 | ||||
| 3610 | bool InitializationSequence::isConstructorInitialization() const { | |||
| 3611 | return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; | |||
| 3612 | } | |||
| 3613 | ||||
| 3614 | void | |||
| 3615 | InitializationSequence | |||
| 3616 | ::AddAddressOverloadResolutionStep(FunctionDecl *Function, | |||
| 3617 | DeclAccessPair Found, | |||
| 3618 | bool HadMultipleCandidates) { | |||
| 3619 | Step S; | |||
| 3620 | S.Kind = SK_ResolveAddressOfOverloadedFunction; | |||
| 3621 | S.Type = Function->getType(); | |||
| 3622 | S.Function.HadMultipleCandidates = HadMultipleCandidates; | |||
| 3623 | S.Function.Function = Function; | |||
| 3624 | S.Function.FoundDecl = Found; | |||
| 3625 | Steps.push_back(S); | |||
| 3626 | } | |||
| 3627 | ||||
| 3628 | void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, | |||
| 3629 | ExprValueKind VK) { | |||
| 3630 | Step S; | |||
| 3631 | switch (VK) { | |||
| 3632 | case VK_PRValue: | |||
| 3633 | S.Kind = SK_CastDerivedToBasePRValue; | |||
| 3634 | break; | |||
| 3635 | case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; | |||
| 3636 | case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; | |||
| 3637 | } | |||
| 3638 | S.Type = BaseType; | |||
| 3639 | Steps.push_back(S); | |||
| 3640 | } | |||
| 3641 | ||||
| 3642 | void InitializationSequence::AddReferenceBindingStep(QualType T, | |||
| 3643 | bool BindingTemporary) { | |||
| 3644 | Step S; | |||
| 3645 | S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; | |||
| 3646 | S.Type = T; | |||
| 3647 | Steps.push_back(S); | |||
| 3648 | } | |||
| 3649 | ||||
| 3650 | void InitializationSequence::AddFinalCopy(QualType T) { | |||
| 3651 | Step S; | |||
| 3652 | S.Kind = SK_FinalCopy; | |||
| 3653 | S.Type = T; | |||
| 3654 | Steps.push_back(S); | |||
| 3655 | } | |||
| 3656 | ||||
| 3657 | void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) { | |||
| 3658 | Step S; | |||
| 3659 | S.Kind = SK_ExtraneousCopyToTemporary; | |||
| 3660 | S.Type = T; | |||
| 3661 | Steps.push_back(S); | |||
| 3662 | } | |||
| 3663 | ||||
| 3664 | void | |||
| 3665 | InitializationSequence::AddUserConversionStep(FunctionDecl *Function, | |||
| 3666 | DeclAccessPair FoundDecl, | |||
| 3667 | QualType T, | |||
| 3668 | bool HadMultipleCandidates) { | |||
| 3669 | Step S; | |||
| 3670 | S.Kind = SK_UserConversion; | |||
| 3671 | S.Type = T; | |||
| 3672 | S.Function.HadMultipleCandidates = HadMultipleCandidates; | |||
| 3673 | S.Function.Function = Function; | |||
| 3674 | S.Function.FoundDecl = FoundDecl; | |||
| 3675 | Steps.push_back(S); | |||
| 3676 | } | |||
| 3677 | ||||
| 3678 | void InitializationSequence::AddQualificationConversionStep(QualType Ty, | |||
| 3679 | ExprValueKind VK) { | |||
| 3680 | Step S; | |||
| 3681 | S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning | |||
| 3682 | switch (VK) { | |||
| 3683 | case VK_PRValue: | |||
| 3684 | S.Kind = SK_QualificationConversionPRValue; | |||
| 3685 | break; | |||
| 3686 | case VK_XValue: | |||
| 3687 | S.Kind = SK_QualificationConversionXValue; | |||
| 3688 | break; | |||
| 3689 | case VK_LValue: | |||
| 3690 | S.Kind = SK_QualificationConversionLValue; | |||
| 3691 | break; | |||
| 3692 | } | |||
| 3693 | S.Type = Ty; | |||
| 3694 | Steps.push_back(S); | |||
| 3695 | } | |||
| 3696 | ||||
| 3697 | void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) { | |||
| 3698 | Step S; | |||
| 3699 | S.Kind = SK_FunctionReferenceConversion; | |||
| 3700 | S.Type = Ty; | |||
| 3701 | Steps.push_back(S); | |||
| 3702 | } | |||
| 3703 | ||||
| 3704 | void InitializationSequence::AddAtomicConversionStep(QualType Ty) { | |||
| 3705 | Step S; | |||
| 3706 | S.Kind = SK_AtomicConversion; | |||
| 3707 | S.Type = Ty; | |||
| 3708 | Steps.push_back(S); | |||
| 3709 | } | |||
| 3710 | ||||
| 3711 | void InitializationSequence::AddConversionSequenceStep( | |||
| 3712 | const ImplicitConversionSequence &ICS, QualType T, | |||
| 3713 | bool TopLevelOfInitList) { | |||
| 3714 | Step S; | |||
| 3715 | S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing | |||
| 3716 | : SK_ConversionSequence; | |||
| 3717 | S.Type = T; | |||
| 3718 | S.ICS = new ImplicitConversionSequence(ICS); | |||
| 3719 | Steps.push_back(S); | |||
| 3720 | } | |||
| 3721 | ||||
| 3722 | void InitializationSequence::AddListInitializationStep(QualType T) { | |||
| 3723 | Step S; | |||
| 3724 | S.Kind = SK_ListInitialization; | |||
| 3725 | S.Type = T; | |||
| 3726 | Steps.push_back(S); | |||
| 3727 | } | |||
| 3728 | ||||
| 3729 | void InitializationSequence::AddConstructorInitializationStep( | |||
| 3730 | DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, | |||
| 3731 | bool HadMultipleCandidates, bool FromInitList, bool AsInitList) { | |||
| 3732 | Step S; | |||
| 3733 | S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall | |||
| 3734 | : SK_ConstructorInitializationFromList | |||
| 3735 | : SK_ConstructorInitialization; | |||
| 3736 | S.Type = T; | |||
| 3737 | S.Function.HadMultipleCandidates = HadMultipleCandidates; | |||
| 3738 | S.Function.Function = Constructor; | |||
| 3739 | S.Function.FoundDecl = FoundDecl; | |||
| 3740 | Steps.push_back(S); | |||
| 3741 | } | |||
| 3742 | ||||
| 3743 | void InitializationSequence::AddZeroInitializationStep(QualType T) { | |||
| 3744 | Step S; | |||
| 3745 | S.Kind = SK_ZeroInitialization; | |||
| 3746 | S.Type = T; | |||
| 3747 | Steps.push_back(S); | |||
| 3748 | } | |||
| 3749 | ||||
| 3750 | void InitializationSequence::AddCAssignmentStep(QualType T) { | |||
| 3751 | Step S; | |||
| 3752 | S.Kind = SK_CAssignment; | |||
| 3753 | S.Type = T; | |||
| 3754 | Steps.push_back(S); | |||
| 3755 | } | |||
| 3756 | ||||
| 3757 | void InitializationSequence::AddStringInitStep(QualType T) { | |||
| 3758 | Step S; | |||
| 3759 | S.Kind = SK_StringInit; | |||
| 3760 | S.Type = T; | |||
| 3761 | Steps.push_back(S); | |||
| 3762 | } | |||
| 3763 | ||||
| 3764 | void InitializationSequence::AddObjCObjectConversionStep(QualType T) { | |||
| 3765 | Step S; | |||
| 3766 | S.Kind = SK_ObjCObjectConversion; | |||
| 3767 | S.Type = T; | |||
| 3768 | Steps.push_back(S); | |||
| 3769 | } | |||
| 3770 | ||||
| 3771 | void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) { | |||
| 3772 | Step S; | |||
| 3773 | S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit; | |||
| 3774 | S.Type = T; | |||
| 3775 | Steps.push_back(S); | |||
| 3776 | } | |||
| 3777 | ||||
| 3778 | void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) { | |||
| 3779 | Step S; | |||
| 3780 | S.Kind = SK_ArrayLoopIndex; | |||
| 3781 | S.Type = EltT; | |||
| 3782 | Steps.insert(Steps.begin(), S); | |||
| 3783 | ||||
| 3784 | S.Kind = SK_ArrayLoopInit; | |||
| 3785 | S.Type = T; | |||
| 3786 | Steps.push_back(S); | |||
| 3787 | } | |||
| 3788 | ||||
| 3789 | void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) { | |||
| 3790 | Step S; | |||
| 3791 | S.Kind = SK_ParenthesizedArrayInit; | |||
| 3792 | S.Type = T; | |||
| 3793 | Steps.push_back(S); | |||
| 3794 | } | |||
| 3795 | ||||
| 3796 | void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, | |||
| 3797 | bool shouldCopy) { | |||
| 3798 | Step s; | |||
| 3799 | s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore | |||
| 3800 | : SK_PassByIndirectRestore); | |||
| 3801 | s.Type = type; | |||
| 3802 | Steps.push_back(s); | |||
| 3803 | } | |||
| 3804 | ||||
| 3805 | void InitializationSequence::AddProduceObjCObjectStep(QualType T) { | |||
| 3806 | Step S; | |||
| 3807 | S.Kind = SK_ProduceObjCObject; | |||
| 3808 | S.Type = T; | |||
| 3809 | Steps.push_back(S); | |||
| 3810 | } | |||
| 3811 | ||||
| 3812 | void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) { | |||
| 3813 | Step S; | |||
| 3814 | S.Kind = SK_StdInitializerList; | |||
| 3815 | S.Type = T; | |||
| 3816 | Steps.push_back(S); | |||
| 3817 | } | |||
| 3818 | ||||
| 3819 | void InitializationSequence::AddOCLSamplerInitStep(QualType T) { | |||
| 3820 | Step S; | |||
| 3821 | S.Kind = SK_OCLSamplerInit; | |||
| 3822 | S.Type = T; | |||
| 3823 | Steps.push_back(S); | |||
| 3824 | } | |||
| 3825 | ||||
| 3826 | void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) { | |||
| 3827 | Step S; | |||
| 3828 | S.Kind = SK_OCLZeroOpaqueType; | |||
| 3829 | S.Type = T; | |||
| 3830 | Steps.push_back(S); | |||
| 3831 | } | |||
| 3832 | ||||
| 3833 | void InitializationSequence::AddParenthesizedListInitStep(QualType T) { | |||
| 3834 | Step S; | |||
| 3835 | S.Kind = SK_ParenthesizedListInit; | |||
| 3836 | S.Type = T; | |||
| 3837 | Steps.push_back(S); | |||
| 3838 | } | |||
| 3839 | ||||
| 3840 | void InitializationSequence::RewrapReferenceInitList(QualType T, | |||
| 3841 | InitListExpr *Syntactic) { | |||
| 3842 | assert(Syntactic->getNumInits() == 1 &&(static_cast <bool> (Syntactic->getNumInits() == 1 && "Can only rewrap trivial init lists.") ? void (0) : __assert_fail ("Syntactic->getNumInits() == 1 && \"Can only rewrap trivial init lists.\"" , "clang/lib/Sema/SemaInit.cpp", 3843, __extension__ __PRETTY_FUNCTION__ )) | |||
| 3843 | "Can only rewrap trivial init lists.")(static_cast <bool> (Syntactic->getNumInits() == 1 && "Can only rewrap trivial init lists.") ? void (0) : __assert_fail ("Syntactic->getNumInits() == 1 && \"Can only rewrap trivial init lists.\"" , "clang/lib/Sema/SemaInit.cpp", 3843, __extension__ __PRETTY_FUNCTION__ )); | |||
| 3844 | Step S; | |||
| 3845 | S.Kind = SK_UnwrapInitList; | |||
| 3846 | S.Type = Syntactic->getInit(0)->getType(); | |||
| 3847 | Steps.insert(Steps.begin(), S); | |||
| 3848 | ||||
| 3849 | S.Kind = SK_RewrapInitList; | |||
| 3850 | S.Type = T; | |||
| 3851 | S.WrappingSyntacticList = Syntactic; | |||
| 3852 | Steps.push_back(S); | |||
| 3853 | } | |||
| 3854 | ||||
| 3855 | void InitializationSequence::SetOverloadFailure(FailureKind Failure, | |||
| 3856 | OverloadingResult Result) { | |||
| 3857 | setSequenceKind(FailedSequence); | |||
| 3858 | this->Failure = Failure; | |||
| 3859 | this->FailedOverloadResult = Result; | |||
| 3860 | } | |||
| 3861 | ||||
| 3862 | //===----------------------------------------------------------------------===// | |||
| 3863 | // Attempt initialization | |||
| 3864 | //===----------------------------------------------------------------------===// | |||
| 3865 | ||||
| 3866 | /// Tries to add a zero initializer. Returns true if that worked. | |||
| 3867 | static bool | |||
| 3868 | maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, | |||
| 3869 | const InitializedEntity &Entity) { | |||
| 3870 | if (Entity.getKind() != InitializedEntity::EK_Variable) | |||
| 3871 | return false; | |||
| 3872 | ||||
| 3873 | VarDecl *VD = cast<VarDecl>(Entity.getDecl()); | |||
| 3874 | if (VD->getInit() || VD->getEndLoc().isMacroID()) | |||
| 3875 | return false; | |||
| 3876 | ||||
| 3877 | QualType VariableTy = VD->getType().getCanonicalType(); | |||
| 3878 | SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc()); | |||
| 3879 | std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc); | |||
| 3880 | if (!Init.empty()) { | |||
| 3881 | Sequence.AddZeroInitializationStep(Entity.getType()); | |||
| 3882 | Sequence.SetZeroInitializationFixit(Init, Loc); | |||
| 3883 | return true; | |||
| 3884 | } | |||
| 3885 | return false; | |||
| 3886 | } | |||
| 3887 | ||||
| 3888 | static void MaybeProduceObjCObject(Sema &S, | |||
| 3889 | InitializationSequence &Sequence, | |||
| 3890 | const InitializedEntity &Entity) { | |||
| 3891 | if (!S.getLangOpts().ObjCAutoRefCount) return; | |||
| 3892 | ||||
| 3893 | /// When initializing a parameter, produce the value if it's marked | |||
| 3894 | /// __attribute__((ns_consumed)). | |||
| 3895 | if (Entity.isParameterKind()) { | |||
| 3896 | if (!Entity.isParameterConsumed()) | |||
| 3897 | return; | |||
| 3898 | ||||
| 3899 | assert(Entity.getType()->isObjCRetainableType() &&(static_cast <bool> (Entity.getType()->isObjCRetainableType () && "consuming an object of unretainable type?") ? void (0) : __assert_fail ("Entity.getType()->isObjCRetainableType() && \"consuming an object of unretainable type?\"" , "clang/lib/Sema/SemaInit.cpp", 3900, __extension__ __PRETTY_FUNCTION__ )) | |||
| 3900 | "consuming an object of unretainable type?")(static_cast <bool> (Entity.getType()->isObjCRetainableType () && "consuming an object of unretainable type?") ? void (0) : __assert_fail ("Entity.getType()->isObjCRetainableType() && \"consuming an object of unretainable type?\"" , "clang/lib/Sema/SemaInit.cpp", 3900, __extension__ __PRETTY_FUNCTION__ )); | |||
| 3901 | Sequence.AddProduceObjCObjectStep(Entity.getType()); | |||
| 3902 | ||||
| 3903 | /// When initializing a return value, if the return type is a | |||
| 3904 | /// retainable type, then returns need to immediately retain the | |||
| 3905 | /// object. If an autorelease is required, it will be done at the | |||
| 3906 | /// last instant. | |||
| 3907 | } else if (Entity.getKind() == InitializedEntity::EK_Result || | |||
| 3908 | Entity.getKind() == InitializedEntity::EK_StmtExprResult) { | |||
| 3909 | if (!Entity.getType()->isObjCRetainableType()) | |||
| 3910 | return; | |||
| 3911 | ||||
| 3912 | Sequence.AddProduceObjCObjectStep(Entity.getType()); | |||
| 3913 | } | |||
| 3914 | } | |||
| 3915 | ||||
| 3916 | static void TryListInitialization(Sema &S, | |||
| 3917 | const InitializedEntity &Entity, | |||
| 3918 | const InitializationKind &Kind, | |||
| 3919 | InitListExpr *InitList, | |||
| 3920 | InitializationSequence &Sequence, | |||
| 3921 | bool TreatUnavailableAsInvalid); | |||
| 3922 | ||||
| 3923 | /// When initializing from init list via constructor, handle | |||
| 3924 | /// initialization of an object of type std::initializer_list<T>. | |||
| 3925 | /// | |||
| 3926 | /// \return true if we have handled initialization of an object of type | |||
| 3927 | /// std::initializer_list<T>, false otherwise. | |||
| 3928 | static bool TryInitializerListConstruction(Sema &S, | |||
| 3929 | InitListExpr *List, | |||
| 3930 | QualType DestType, | |||
| 3931 | InitializationSequence &Sequence, | |||
| 3932 | bool TreatUnavailableAsInvalid) { | |||
| 3933 | QualType E; | |||
| 3934 | if (!S.isStdInitializerList(DestType, &E)) | |||
| 3935 | return false; | |||
| 3936 | ||||
| 3937 | if (!S.isCompleteType(List->getExprLoc(), E)) { | |||
| 3938 | Sequence.setIncompleteTypeFailure(E); | |||
| 3939 | return true; | |||
| 3940 | } | |||
| 3941 | ||||
| 3942 | // Try initializing a temporary array from the init list. | |||
| 3943 | QualType ArrayType = S.Context.getConstantArrayType( | |||
| 3944 | E.withConst(), | |||
| 3945 | llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), | |||
| 3946 | List->getNumInits()), | |||
| 3947 | nullptr, clang::ArrayType::Normal, 0); | |||
| 3948 | InitializedEntity HiddenArray = | |||
| 3949 | InitializedEntity::InitializeTemporary(ArrayType); | |||
| 3950 | InitializationKind Kind = InitializationKind::CreateDirectList( | |||
| 3951 | List->getExprLoc(), List->getBeginLoc(), List->getEndLoc()); | |||
| 3952 | TryListInitialization(S, HiddenArray, Kind, List, Sequence, | |||
| 3953 | TreatUnavailableAsInvalid); | |||
| 3954 | if (Sequence) | |||
| 3955 | Sequence.AddStdInitializerListConstructionStep(DestType); | |||
| 3956 | return true; | |||
| 3957 | } | |||
| 3958 | ||||
| 3959 | /// Determine if the constructor has the signature of a copy or move | |||
| 3960 | /// constructor for the type T of the class in which it was found. That is, | |||
| 3961 | /// determine if its first parameter is of type T or reference to (possibly | |||
| 3962 | /// cv-qualified) T. | |||
| 3963 | static bool hasCopyOrMoveCtorParam(ASTContext &Ctx, | |||
| 3964 | const ConstructorInfo &Info) { | |||
| 3965 | if (Info.Constructor->getNumParams() == 0) | |||
| 3966 | return false; | |||
| 3967 | ||||
| 3968 | QualType ParmT = | |||
| 3969 | Info.Constructor->getParamDecl(0)->getType().getNonReferenceType(); | |||
| 3970 | QualType ClassT = | |||
| 3971 | Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext())); | |||
| 3972 | ||||
| 3973 | return Ctx.hasSameUnqualifiedType(ParmT, ClassT); | |||
| 3974 | } | |||
| 3975 | ||||
| 3976 | static OverloadingResult | |||
| 3977 | ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, | |||
| 3978 | MultiExprArg Args, | |||
| 3979 | OverloadCandidateSet &CandidateSet, | |||
| 3980 | QualType DestType, | |||
| 3981 | DeclContext::lookup_result Ctors, | |||
| 3982 | OverloadCandidateSet::iterator &Best, | |||
| 3983 | bool CopyInitializing, bool AllowExplicit, | |||
| 3984 | bool OnlyListConstructors, bool IsListInit, | |||
| 3985 | bool SecondStepOfCopyInit = false) { | |||
| 3986 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor); | |||
| 3987 | CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); | |||
| 3988 | ||||
| 3989 | for (NamedDecl *D : Ctors) { | |||
| 3990 | auto Info = getConstructorInfo(D); | |||
| 3991 | if (!Info.Constructor || Info.Constructor->isInvalidDecl()) | |||
| 3992 | continue; | |||
| 3993 | ||||
| 3994 | if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor)) | |||
| 3995 | continue; | |||
| 3996 | ||||
| 3997 | // C++11 [over.best.ics]p4: | |||
| 3998 | // ... and the constructor or user-defined conversion function is a | |||
| 3999 | // candidate by | |||
| 4000 | // - 13.3.1.3, when the argument is the temporary in the second step | |||
| 4001 | // of a class copy-initialization, or | |||
| 4002 | // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here] | |||
| 4003 | // - the second phase of 13.3.1.7 when the initializer list has exactly | |||
| 4004 | // one element that is itself an initializer list, and the target is | |||
| 4005 | // the first parameter of a constructor of class X, and the conversion | |||
| 4006 | // is to X or reference to (possibly cv-qualified X), | |||
| 4007 | // user-defined conversion sequences are not considered. | |||
| 4008 | bool SuppressUserConversions = | |||
| 4009 | SecondStepOfCopyInit || | |||
| 4010 | (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) && | |||
| 4011 | hasCopyOrMoveCtorParam(S.Context, Info)); | |||
| 4012 | ||||
| 4013 | if (Info.ConstructorTmpl) | |||
| 4014 | S.AddTemplateOverloadCandidate( | |||
| 4015 | Info.ConstructorTmpl, Info.FoundDecl, | |||
| 4016 | /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions, | |||
| 4017 | /*PartialOverloading=*/false, AllowExplicit); | |||
| 4018 | else { | |||
| 4019 | // C++ [over.match.copy]p1: | |||
| 4020 | // - When initializing a temporary to be bound to the first parameter | |||
| 4021 | // of a constructor [for type T] that takes a reference to possibly | |||
| 4022 | // cv-qualified T as its first argument, called with a single | |||
| 4023 | // argument in the context of direct-initialization, explicit | |||
| 4024 | // conversion functions are also considered. | |||
| 4025 | // FIXME: What if a constructor template instantiates to such a signature? | |||
| 4026 | bool AllowExplicitConv = AllowExplicit && !CopyInitializing && | |||
| 4027 | Args.size() == 1 && | |||
| 4028 | hasCopyOrMoveCtorParam(S.Context, Info); | |||
| 4029 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args, | |||
| 4030 | CandidateSet, SuppressUserConversions, | |||
| 4031 | /*PartialOverloading=*/false, AllowExplicit, | |||
| 4032 | AllowExplicitConv); | |||
| 4033 | } | |||
| 4034 | } | |||
| 4035 | ||||
| 4036 | // FIXME: Work around a bug in C++17 guaranteed copy elision. | |||
| 4037 | // | |||
| 4038 | // When initializing an object of class type T by constructor | |||
| 4039 | // ([over.match.ctor]) or by list-initialization ([over.match.list]) | |||
| 4040 | // from a single expression of class type U, conversion functions of | |||
| 4041 | // U that convert to the non-reference type cv T are candidates. | |||
| 4042 | // Explicit conversion functions are only candidates during | |||
| 4043 | // direct-initialization. | |||
| 4044 | // | |||
| 4045 | // Note: SecondStepOfCopyInit is only ever true in this case when | |||
| 4046 | // evaluating whether to produce a C++98 compatibility warning. | |||
| 4047 | if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 && | |||
| 4048 | !SecondStepOfCopyInit) { | |||
| 4049 | Expr *Initializer = Args[0]; | |||
| 4050 | auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl(); | |||
| 4051 | if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) { | |||
| 4052 | const auto &Conversions = SourceRD->getVisibleConversionFunctions(); | |||
| 4053 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | |||
| 4054 | NamedDecl *D = *I; | |||
| 4055 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); | |||
| 4056 | D = D->getUnderlyingDecl(); | |||
| 4057 | ||||
| 4058 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); | |||
| 4059 | CXXConversionDecl *Conv; | |||
| 4060 | if (ConvTemplate) | |||
| 4061 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | |||
| 4062 | else | |||
| 4063 | Conv = cast<CXXConversionDecl>(D); | |||
| 4064 | ||||
| 4065 | if (ConvTemplate) | |||
| 4066 | S.AddTemplateConversionCandidate( | |||
| 4067 | ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, | |||
| 4068 | CandidateSet, AllowExplicit, AllowExplicit, | |||
| 4069 | /*AllowResultConversion*/ false); | |||
| 4070 | else | |||
| 4071 | S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, | |||
| 4072 | DestType, CandidateSet, AllowExplicit, | |||
| 4073 | AllowExplicit, | |||
| 4074 | /*AllowResultConversion*/ false); | |||
| 4075 | } | |||
| 4076 | } | |||
| 4077 | } | |||
| 4078 | ||||
| 4079 | // Perform overload resolution and return the result. | |||
| 4080 | return CandidateSet.BestViableFunction(S, DeclLoc, Best); | |||
| 4081 | } | |||
| 4082 | ||||
| 4083 | /// Attempt initialization by constructor (C++ [dcl.init]), which | |||
| 4084 | /// enumerates the constructors of the initialized entity and performs overload | |||
| 4085 | /// resolution to select the best. | |||
| 4086 | /// \param DestType The destination class type. | |||
| 4087 | /// \param DestArrayType The destination type, which is either DestType or | |||
| 4088 | /// a (possibly multidimensional) array of DestType. | |||
| 4089 | /// \param IsListInit Is this list-initialization? | |||
| 4090 | /// \param IsInitListCopy Is this non-list-initialization resulting from a | |||
| 4091 | /// list-initialization from {x} where x is the same | |||
| 4092 | /// type as the entity? | |||
| 4093 | static void TryConstructorInitialization(Sema &S, | |||
| 4094 | const InitializedEntity &Entity, | |||
| 4095 | const InitializationKind &Kind, | |||
| 4096 | MultiExprArg Args, QualType DestType, | |||
| 4097 | QualType DestArrayType, | |||
| 4098 | InitializationSequence &Sequence, | |||
| 4099 | bool IsListInit = false, | |||
| 4100 | bool IsInitListCopy = false) { | |||
| 4101 | assert(((!IsListInit && !IsInitListCopy) ||(static_cast <bool> (((!IsListInit && !IsInitListCopy ) || (Args.size() == 1 && isa<InitListExpr>(Args [0]))) && "IsListInit/IsInitListCopy must come with a single initializer list " "argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\"" , "clang/lib/Sema/SemaInit.cpp", 4104, __extension__ __PRETTY_FUNCTION__ )) | |||
| 4102 | (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&(static_cast <bool> (((!IsListInit && !IsInitListCopy ) || (Args.size() == 1 && isa<InitListExpr>(Args [0]))) && "IsListInit/IsInitListCopy must come with a single initializer list " "argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\"" , "clang/lib/Sema/SemaInit.cpp", 4104, __extension__ __PRETTY_FUNCTION__ )) | |||
| 4103 | "IsListInit/IsInitListCopy must come with a single initializer list "(static_cast <bool> (((!IsListInit && !IsInitListCopy ) || (Args.size() == 1 && isa<InitListExpr>(Args [0]))) && "IsListInit/IsInitListCopy must come with a single initializer list " "argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\"" , "clang/lib/Sema/SemaInit.cpp", 4104, __extension__ __PRETTY_FUNCTION__ )) | |||
| 4104 | "argument.")(static_cast <bool> (((!IsListInit && !IsInitListCopy ) || (Args.size() == 1 && isa<InitListExpr>(Args [0]))) && "IsListInit/IsInitListCopy must come with a single initializer list " "argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\"" , "clang/lib/Sema/SemaInit.cpp", 4104, __extension__ __PRETTY_FUNCTION__ )); | |||
| 4105 | InitListExpr *ILE = | |||
| 4106 | (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr; | |||
| 4107 | MultiExprArg UnwrappedArgs = | |||
| 4108 | ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args; | |||
| 4109 | ||||
| 4110 | // The type we're constructing needs to be complete. | |||
| 4111 | if (!S.isCompleteType(Kind.getLocation(), DestType)) { | |||
| 4112 | Sequence.setIncompleteTypeFailure(DestType); | |||
| 4113 | return; | |||
| 4114 | } | |||
| 4115 | ||||
| 4116 | // C++17 [dcl.init]p17: | |||
| 4117 | // - If the initializer expression is a prvalue and the cv-unqualified | |||
| 4118 | // version of the source type is the same class as the class of the | |||
| 4119 | // destination, the initializer expression is used to initialize the | |||
| 4120 | // destination object. | |||
| 4121 | // Per DR (no number yet), this does not apply when initializing a base | |||
| 4122 | // class or delegating to another constructor from a mem-initializer. | |||
| 4123 | // ObjC++: Lambda captured by the block in the lambda to block conversion | |||
| 4124 | // should avoid copy elision. | |||
| 4125 | if (S.getLangOpts().CPlusPlus17 && | |||
| 4126 | Entity.getKind() != InitializedEntity::EK_Base && | |||
| 4127 | Entity.getKind() != InitializedEntity::EK_Delegating && | |||
| 4128 | Entity.getKind() != | |||
| 4129 | InitializedEntity::EK_LambdaToBlockConversionBlockElement && | |||
| 4130 | UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() && | |||
| 4131 | S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) { | |||
| 4132 | // Convert qualifications if necessary. | |||
| 4133 | Sequence.AddQualificationConversionStep(DestType, VK_PRValue); | |||
| 4134 | if (ILE) | |||
| 4135 | Sequence.RewrapReferenceInitList(DestType, ILE); | |||
| 4136 | return; | |||
| 4137 | } | |||
| 4138 | ||||
| 4139 | const RecordType *DestRecordType = DestType->getAs<RecordType>(); | |||
| 4140 | assert(DestRecordType && "Constructor initialization requires record type")(static_cast <bool> (DestRecordType && "Constructor initialization requires record type" ) ? void (0) : __assert_fail ("DestRecordType && \"Constructor initialization requires record type\"" , "clang/lib/Sema/SemaInit.cpp", 4140, __extension__ __PRETTY_FUNCTION__ )); | |||
| 4141 | CXXRecordDecl *DestRecordDecl | |||
| 4142 | = cast<CXXRecordDecl>(DestRecordType->getDecl()); | |||
| 4143 | ||||
| 4144 | // Build the candidate set directly in the initialization sequence | |||
| 4145 | // structure, so that it will persist if we fail. | |||
| 4146 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); | |||
| 4147 | ||||
| 4148 | // Determine whether we are allowed to call explicit constructors or | |||
| 4149 | // explicit conversion operators. | |||
| 4150 | bool AllowExplicit = Kind.AllowExplicit() || IsListInit; | |||
| 4151 | bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy; | |||
| 4152 | ||||
| 4153 | // - Otherwise, if T is a class type, constructors are considered. The | |||
| 4154 | // applicable constructors are enumerated, and the best one is chosen | |||
| 4155 | // through overload resolution. | |||
| 4156 | DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl); | |||
| 4157 | ||||
| 4158 | OverloadingResult Result = OR_No_Viable_Function; | |||
| 4159 | OverloadCandidateSet::iterator Best; | |||
| 4160 | bool AsInitializerList = false; | |||
| 4161 | ||||
| 4162 | // C++11 [over.match.list]p1, per DR1467: | |||
| 4163 | // When objects of non-aggregate type T are list-initialized, such that | |||
| 4164 | // 8.5.4 [dcl.init.list] specifies that overload resolution is performed | |||
| 4165 | // according to the rules in this section, overload resolution selects | |||
| 4166 | // the constructor in two phases: | |||
| 4167 | // | |||
| 4168 | // - Initially, the candidate functions are the initializer-list | |||
| 4169 | // constructors of the class T and the argument list consists of the | |||
| 4170 | // initializer list as a single argument. | |||
| 4171 | if (IsListInit) { | |||
| 4172 | AsInitializerList = true; | |||
| 4173 | ||||
| 4174 | // If the initializer list has no elements and T has a default constructor, | |||
| 4175 | // the first phase is omitted. | |||
| 4176 | if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl))) | |||
| 4177 | Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, | |||
| 4178 | CandidateSet, DestType, Ctors, Best, | |||
| 4179 | CopyInitialization, AllowExplicit, | |||
| 4180 | /*OnlyListConstructors=*/true, | |||
| 4181 | IsListInit); | |||
| 4182 | } | |||
| 4183 | ||||
| 4184 | // C++11 [over.match.list]p1: | |||
| 4185 | // - If no viable initializer-list constructor is found, overload resolution | |||
| 4186 | // is performed again, where the candidate functions are all the | |||
| 4187 | // constructors of the class T and the argument list consists of the | |||
| 4188 | // elements of the initializer list. | |||
| 4189 | if (Result == OR_No_Viable_Function) { | |||
| 4190 | AsInitializerList = false; | |||
| 4191 | Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs, | |||
| 4192 | CandidateSet, DestType, Ctors, Best, | |||
| 4193 | CopyInitialization, AllowExplicit, | |||
| 4194 | /*OnlyListConstructors=*/false, | |||
| 4195 | IsListInit); | |||
| 4196 | } | |||
| 4197 | if (Result) { | |||
| 4198 | Sequence.SetOverloadFailure( | |||
| 4199 | IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed | |||
| 4200 | : InitializationSequence::FK_ConstructorOverloadFailed, | |||
| 4201 | Result); | |||
| 4202 | ||||
| 4203 | if (Result != OR_Deleted) | |||
| 4204 | return; | |||
| 4205 | } | |||
| 4206 | ||||
| 4207 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
| 4208 | ||||
| 4209 | // In C++17, ResolveConstructorOverload can select a conversion function | |||
| 4210 | // instead of a constructor. | |||
| 4211 | if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) { | |||
| 4212 | // Add the user-defined conversion step that calls the conversion function. | |||
| 4213 | QualType ConvType = CD->getConversionType(); | |||
| 4214 | assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&(static_cast <bool> (S.Context.hasSameUnqualifiedType(ConvType , DestType) && "should not have selected this conversion function" ) ? void (0) : __assert_fail ("S.Context.hasSameUnqualifiedType(ConvType, DestType) && \"should not have selected this conversion function\"" , "clang/lib/Sema/SemaInit.cpp", 4215, __extension__ __PRETTY_FUNCTION__ )) | |||
| 4215 | "should not have selected this conversion function")(static_cast <bool> (S.Context.hasSameUnqualifiedType(ConvType , DestType) && "should not have selected this conversion function" ) ? void (0) : __assert_fail ("S.Context.hasSameUnqualifiedType(ConvType, DestType) && \"should not have selected this conversion function\"" , "clang/lib/Sema/SemaInit.cpp", 4215, __extension__ __PRETTY_FUNCTION__ )); | |||
| 4216 | Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType, | |||
| 4217 | HadMultipleCandidates); | |||
| 4218 | if (!S.Context.hasSameType(ConvType, DestType)) | |||
| 4219 | Sequence.AddQualificationConversionStep(DestType, VK_PRValue); | |||
| 4220 | if (IsListInit) | |||
| 4221 | Sequence.RewrapReferenceInitList(Entity.getType(), ILE); | |||
| 4222 | return; | |||
| 4223 | } | |||
| 4224 | ||||
| 4225 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); | |||
| 4226 | if (Result != OR_Deleted) { | |||
| 4227 | // C++11 [dcl.init]p6: | |||
| 4228 | // If a program calls for the default initialization of an object | |||
| 4229 | // of a const-qualified type T, T shall be a class type with a | |||
| 4230 | // user-provided default constructor. | |||
| 4231 | // C++ core issue 253 proposal: | |||
| 4232 | // If the implicit default constructor initializes all subobjects, no | |||
| 4233 | // initializer should be required. | |||
| 4234 | // The 253 proposal is for example needed to process libstdc++ headers | |||
| 4235 | // in 5.x. | |||
| 4236 | if (Kind.getKind() == InitializationKind::IK_Default && | |||
| 4237 | Entity.getType().isConstQualified()) { | |||
| 4238 | if (!CtorDecl->getParent()->allowConstDefaultInit()) { | |||
| 4239 | if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) | |||
| 4240 | Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); | |||
| 4241 | return; | |||
| 4242 | } | |||
| 4243 | } | |||
| 4244 | ||||
| 4245 | // C++11 [over.match.list]p1: | |||
| 4246 | // In copy-list-initialization, if an explicit constructor is chosen, the | |||
| 4247 | // initializer is ill-formed. | |||
| 4248 | if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) { | |||
| 4249 | Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor); | |||
| 4250 | return; | |||
| 4251 | } | |||
| 4252 | } | |||
| 4253 | ||||
| 4254 | // [class.copy.elision]p3: | |||
| 4255 | // In some copy-initialization contexts, a two-stage overload resolution | |||
| 4256 | // is performed. | |||
| 4257 | // If the first overload resolution selects a deleted function, we also | |||
| 4258 | // need the initialization sequence to decide whether to perform the second | |||
| 4259 | // overload resolution. | |||
| 4260 | // For deleted functions in other contexts, there is no need to get the | |||
| 4261 | // initialization sequence. | |||
| 4262 | if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy) | |||
| 4263 | return; | |||
| 4264 | ||||
| 4265 | // Add the constructor initialization step. Any cv-qualification conversion is | |||
| 4266 | // subsumed by the initialization. | |||
| 4267 | Sequence.AddConstructorInitializationStep( | |||
| 4268 | Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates, | |||
| 4269 | IsListInit | IsInitListCopy, AsInitializerList); | |||
| 4270 | } | |||
| 4271 | ||||
| 4272 | static bool | |||
| 4273 | ResolveOverloadedFunctionForReferenceBinding(Sema &S, | |||
| 4274 | Expr *Initializer, | |||
| 4275 | QualType &SourceType, | |||
| 4276 | QualType &UnqualifiedSourceType, | |||
| 4277 | QualType UnqualifiedTargetType, | |||
| 4278 | InitializationSequence &Sequence) { | |||
| 4279 | if (S.Context.getCanonicalType(UnqualifiedSourceType) == | |||
| 4280 | S.Context.OverloadTy) { | |||
| 4281 | DeclAccessPair Found; | |||
| 4282 | bool HadMultipleCandidates = false; | |||
| 4283 | if (FunctionDecl *Fn | |||
| 4284 | = S.ResolveAddressOfOverloadedFunction(Initializer, | |||
| 4285 | UnqualifiedTargetType, | |||
| 4286 | false, Found, | |||
| 4287 | &HadMultipleCandidates)) { | |||
| 4288 | Sequence.AddAddressOverloadResolutionStep(Fn, Found, | |||
| 4289 | HadMultipleCandidates); | |||
| 4290 | SourceType = Fn->getType(); | |||
| 4291 | UnqualifiedSourceType = SourceType.getUnqualifiedType(); | |||
| 4292 | } else if (!UnqualifiedTargetType->isRecordType()) { | |||
| 4293 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); | |||
| 4294 | return true; | |||
| 4295 | } | |||
| 4296 | } | |||
| 4297 | return false; | |||
| 4298 | } | |||
| 4299 | ||||
| 4300 | static void TryReferenceInitializationCore(Sema &S, | |||
| 4301 | const InitializedEntity &Entity, | |||
| 4302 | const InitializationKind &Kind, | |||
| 4303 | Expr *Initializer, | |||
| 4304 | QualType cv1T1, QualType T1, | |||
| 4305 | Qualifiers T1Quals, | |||
| 4306 | QualType cv2T2, QualType T2, | |||
| 4307 | Qualifiers T2Quals, | |||
| 4308 | InitializationSequence &Sequence); | |||
| 4309 | ||||
| 4310 | static void TryValueInitialization(Sema &S, | |||
| 4311 | const InitializedEntity &Entity, | |||
| 4312 | const InitializationKind &Kind, | |||
| 4313 | InitializationSequence &Sequence, | |||
| 4314 | InitListExpr *InitList = nullptr); | |||
| 4315 | ||||
| 4316 | /// Attempt list initialization of a reference. | |||
| 4317 | static void TryReferenceListInitialization(Sema &S, | |||
| 4318 | const InitializedEntity &Entity, | |||
| 4319 | const InitializationKind &Kind, | |||
| 4320 | InitListExpr *InitList, | |||
| 4321 | InitializationSequence &Sequence, | |||
| 4322 | bool TreatUnavailableAsInvalid) { | |||
| 4323 | // First, catch C++03 where this isn't possible. | |||
| 4324 | if (!S.getLangOpts().CPlusPlus11) { | |||
| 4325 | Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); | |||
| 4326 | return; | |||
| 4327 | } | |||
| 4328 | // Can't reference initialize a compound literal. | |||
| 4329 | if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) { | |||
| 4330 | Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); | |||
| 4331 | return; | |||
| 4332 | } | |||
| 4333 | ||||
| 4334 | QualType DestType = Entity.getType(); | |||
| 4335 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); | |||
| 4336 | Qualifiers T1Quals; | |||
| 4337 | QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); | |||
| 4338 | ||||
| 4339 | // Reference initialization via an initializer list works thus: | |||
| 4340 | // If the initializer list consists of a single element that is | |||
| 4341 | // reference-related to the referenced type, bind directly to that element | |||
| 4342 | // (possibly creating temporaries). | |||
| 4343 | // Otherwise, initialize a temporary with the initializer list and | |||
| 4344 | // bind to that. | |||
| 4345 | if (InitList->getNumInits() == 1) { | |||
| 4346 | Expr *Initializer = InitList->getInit(0); | |||
| 4347 | QualType cv2T2 = S.getCompletedType(Initializer); | |||
| 4348 | Qualifiers T2Quals; | |||
| 4349 | QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); | |||
| 4350 | ||||
| 4351 | // If this fails, creating a temporary wouldn't work either. | |||
| 4352 | if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, | |||
| 4353 | T1, Sequence)) | |||
| 4354 | return; | |||
| 4355 | ||||
| 4356 | SourceLocation DeclLoc = Initializer->getBeginLoc(); | |||
| 4357 | Sema::ReferenceCompareResult RefRelationship | |||
| 4358 | = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2); | |||
| 4359 | if (RefRelationship >= Sema::Ref_Related) { | |||
| 4360 | // Try to bind the reference here. | |||
| 4361 | TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, | |||
| 4362 | T1Quals, cv2T2, T2, T2Quals, Sequence); | |||
| 4363 | if (Sequence) | |||
| 4364 | Sequence.RewrapReferenceInitList(cv1T1, InitList); | |||
| 4365 | return; | |||
| 4366 | } | |||
| 4367 | ||||
| 4368 | // Update the initializer if we've resolved an overloaded function. | |||
| 4369 | if (Sequence.step_begin() != Sequence.step_end()) | |||
| 4370 | Sequence.RewrapReferenceInitList(cv1T1, InitList); | |||
| 4371 | } | |||
| 4372 | // Perform address space compatibility check. | |||
| 4373 | QualType cv1T1IgnoreAS = cv1T1; | |||
| 4374 | if (T1Quals.hasAddressSpace()) { | |||
| 4375 | Qualifiers T2Quals; | |||
| 4376 | (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals); | |||
| 4377 | if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) { | |||
| 4378 | Sequence.SetFailed( | |||
| 4379 | InitializationSequence::FK_ReferenceInitDropsQualifiers); | |||
| 4380 | return; | |||
| 4381 | } | |||
| 4382 | // Ignore address space of reference type at this point and perform address | |||
| 4383 | // space conversion after the reference binding step. | |||
| 4384 | cv1T1IgnoreAS = | |||
| 4385 | S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace()); | |||
| 4386 | } | |||
| 4387 | // Not reference-related. Create a temporary and bind to that. | |||
| 4388 | InitializedEntity TempEntity = | |||
| 4389 | InitializedEntity::InitializeTemporary(cv1T1IgnoreAS); | |||
| 4390 | ||||
| 4391 | TryListInitialization(S, TempEntity, Kind, InitList, Sequence, | |||
| 4392 | TreatUnavailableAsInvalid); | |||
| 4393 | if (Sequence) { | |||
| 4394 | if (DestType->isRValueReferenceType() || | |||
| 4395 | (T1Quals.hasConst() && !T1Quals.hasVolatile())) { | |||
| 4396 | Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, | |||
| 4397 | /*BindingTemporary=*/true); | |||
| 4398 | if (T1Quals.hasAddressSpace()) | |||
| 4399 | Sequence.AddQualificationConversionStep( | |||
| 4400 | cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue); | |||
| 4401 | } else | |||
| 4402 | Sequence.SetFailed( | |||
| 4403 | InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); | |||
| 4404 | } | |||
| 4405 | } | |||
| 4406 | ||||
| 4407 | /// Attempt list initialization (C++0x [dcl.init.list]) | |||
| 4408 | static void TryListInitialization(Sema &S, | |||
| 4409 | const InitializedEntity &Entity, | |||
| 4410 | const InitializationKind &Kind, | |||
| 4411 | InitListExpr *InitList, | |||
| 4412 | InitializationSequence &Sequence, | |||
| 4413 | bool TreatUnavailableAsInvalid) { | |||
| 4414 | QualType DestType = Entity.getType(); | |||
| 4415 | ||||
| 4416 | // C++ doesn't allow scalar initialization with more than one argument. | |||
| 4417 | // But C99 complex numbers are scalars and it makes sense there. | |||
| 4418 | if (S.getLangOpts().CPlusPlus && DestType->isScalarType() && | |||
| 4419 | !DestType->isAnyComplexType() && InitList->getNumInits() > 1) { | |||
| 4420 | Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); | |||
| 4421 | return; | |||
| 4422 | } | |||
| 4423 | if (DestType->isReferenceType()) { | |||
| 4424 | TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence, | |||
| 4425 | TreatUnavailableAsInvalid); | |||
| 4426 | return; | |||
| 4427 | } | |||
| 4428 | ||||
| 4429 | if (DestType->isRecordType() && | |||
| 4430 | !S.isCompleteType(InitList->getBeginLoc(), DestType)) { | |||
| 4431 | Sequence.setIncompleteTypeFailure(DestType); | |||
| 4432 | return; | |||
| 4433 | } | |||
| 4434 | ||||
| 4435 | // C++11 [dcl.init.list]p3, per DR1467: | |||
| 4436 | // - If T is a class type and the initializer list has a single element of | |||
| 4437 | // type cv U, where U is T or a class derived from T, the object is | |||
| 4438 | // initialized from that element (by copy-initialization for | |||
| 4439 | // copy-list-initialization, or by direct-initialization for | |||
| 4440 | // direct-list-initialization). | |||
| 4441 | // - Otherwise, if T is a character array and the initializer list has a | |||
| 4442 | // single element that is an appropriately-typed string literal | |||
| 4443 | // (8.5.2 [dcl.init.string]), initialization is performed as described | |||
| 4444 | // in that section. | |||
| 4445 | // - Otherwise, if T is an aggregate, [...] (continue below). | |||
| 4446 | if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) { | |||
| 4447 | if (DestType->isRecordType()) { | |||
| 4448 | QualType InitType = InitList->getInit(0)->getType(); | |||
| 4449 | if (S.Context.hasSameUnqualifiedType(InitType, DestType) || | |||
| 4450 | S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) { | |||
| 4451 | Expr *InitListAsExpr = InitList; | |||
| 4452 | TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, | |||
| 4453 | DestType, Sequence, | |||
| 4454 | /*InitListSyntax*/false, | |||
| 4455 | /*IsInitListCopy*/true); | |||
| 4456 | return; | |||
| 4457 | } | |||
| 4458 | } | |||
| 4459 | if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) { | |||
| 4460 | Expr *SubInit[1] = {InitList->getInit(0)}; | |||
| 4461 | if (!isa<VariableArrayType>(DestAT) && | |||
| 4462 | IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) { | |||
| 4463 | InitializationKind SubKind = | |||
| 4464 | Kind.getKind() == InitializationKind::IK_DirectList | |||
| 4465 | ? InitializationKind::CreateDirect(Kind.getLocation(), | |||
| 4466 | InitList->getLBraceLoc(), | |||
| 4467 | InitList->getRBraceLoc()) | |||
| 4468 | : Kind; | |||
| 4469 | Sequence.InitializeFrom(S, Entity, SubKind, SubInit, | |||
| 4470 | /*TopLevelOfInitList*/ true, | |||
| 4471 | TreatUnavailableAsInvalid); | |||
| 4472 | ||||
| 4473 | // TryStringLiteralInitialization() (in InitializeFrom()) will fail if | |||
| 4474 | // the element is not an appropriately-typed string literal, in which | |||
| 4475 | // case we should proceed as in C++11 (below). | |||
| 4476 | if (Sequence) { | |||
| 4477 | Sequence.RewrapReferenceInitList(Entity.getType(), InitList); | |||
| 4478 | return; | |||
| 4479 | } | |||
| 4480 | } | |||
| 4481 | } | |||
| 4482 | } | |||
| 4483 | ||||
| 4484 | // C++11 [dcl.init.list]p3: | |||
| 4485 | // - If T is an aggregate, aggregate initialization is performed. | |||
| 4486 | if ((DestType->isRecordType() && !DestType->isAggregateType()) || | |||
| 4487 | (S.getLangOpts().CPlusPlus11 && | |||
| 4488 | S.isStdInitializerList(DestType, nullptr))) { | |||
| 4489 | if (S.getLangOpts().CPlusPlus11) { | |||
| 4490 | // - Otherwise, if the initializer list has no elements and T is a | |||
| 4491 | // class type with a default constructor, the object is | |||
| 4492 | // value-initialized. | |||
| 4493 | if (InitList->getNumInits() == 0) { | |||
| 4494 | CXXRecordDecl *RD = DestType->getAsCXXRecordDecl(); | |||
| 4495 | if (S.LookupDefaultConstructor(RD)) { | |||
| 4496 | TryValueInitialization(S, Entity, Kind, Sequence, InitList); | |||
| 4497 | return; | |||
| 4498 | } | |||
| 4499 | } | |||
| 4500 | ||||
| 4501 | // - Otherwise, if T is a specialization of std::initializer_list<E>, | |||
| 4502 | // an initializer_list object constructed [...] | |||
| 4503 | if (TryInitializerListConstruction(S, InitList, DestType, Sequence, | |||
| 4504 | TreatUnavailableAsInvalid)) | |||
| 4505 | return; | |||
| 4506 | ||||
| 4507 | // - Otherwise, if T is a class type, constructors are considered. | |||
| 4508 | Expr *InitListAsExpr = InitList; | |||
| 4509 | TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, | |||
| 4510 | DestType, Sequence, /*InitListSyntax*/true); | |||
| 4511 | } else | |||
| 4512 | Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); | |||
| 4513 | return; | |||
| 4514 | } | |||
| 4515 | ||||
| 4516 | if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() && | |||
| 4517 | InitList->getNumInits() == 1) { | |||
| 4518 | Expr *E = InitList->getInit(0); | |||
| 4519 | ||||
| 4520 | // - Otherwise, if T is an enumeration with a fixed underlying type, | |||
| 4521 | // the initializer-list has a single element v, and the initialization | |||
| 4522 | // is direct-list-initialization, the object is initialized with the | |||
| 4523 | // value T(v); if a narrowing conversion is required to convert v to | |||
| 4524 | // the underlying type of T, the program is ill-formed. | |||
| 4525 | auto *ET = DestType->getAs<EnumType>(); | |||
| 4526 | if (S.getLangOpts().CPlusPlus17 && | |||
| 4527 | Kind.getKind() == InitializationKind::IK_DirectList && | |||
| 4528 | ET && ET->getDecl()->isFixed() && | |||
| 4529 | !S.Context.hasSameUnqualifiedType(E->getType(), DestType) && | |||
| 4530 | (E->getType()->isIntegralOrUnscopedEnumerationType() || | |||
| 4531 | E->getType()->isFloatingType())) { | |||
| 4532 | // There are two ways that T(v) can work when T is an enumeration type. | |||
| 4533 | // If there is either an implicit conversion sequence from v to T or | |||
| 4534 | // a conversion function that can convert from v to T, then we use that. | |||
| 4535 | // Otherwise, if v is of integral, unscoped enumeration, or floating-point | |||
| 4536 | // type, it is converted to the enumeration type via its underlying type. | |||
| 4537 | // There is no overlap possible between these two cases (except when the | |||
| 4538 | // source value is already of the destination type), and the first | |||
| 4539 | // case is handled by the general case for single-element lists below. | |||
| 4540 | ImplicitConversionSequence ICS; | |||
| 4541 | ICS.setStandard(); | |||
| 4542 | ICS.Standard.setAsIdentityConversion(); | |||
| 4543 | if (!E->isPRValue()) | |||
| 4544 | ICS.Standard.First = ICK_Lvalue_To_Rvalue; | |||
| 4545 | // If E is of a floating-point type, then the conversion is ill-formed | |||
| 4546 | // due to narrowing, but go through the motions in order to produce the | |||
| 4547 | // right diagnostic. | |||
| 4548 | ICS.Standard.Second = E->getType()->isFloatingType() | |||
| 4549 | ? ICK_Floating_Integral | |||
| 4550 | : ICK_Integral_Conversion; | |||
| 4551 | ICS.Standard.setFromType(E->getType()); | |||
| 4552 | ICS.Standard.setToType(0, E->getType()); | |||
| 4553 | ICS.Standard.setToType(1, DestType); | |||
| 4554 | ICS.Standard.setToType(2, DestType); | |||
| 4555 | Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2), | |||
| 4556 | /*TopLevelOfInitList*/true); | |||
| 4557 | Sequence.RewrapReferenceInitList(Entity.getType(), InitList); | |||
| 4558 | return; | |||
| 4559 | } | |||
| 4560 | ||||
| 4561 | // - Otherwise, if the initializer list has a single element of type E | |||
| 4562 | // [...references are handled above...], the object or reference is | |||
| 4563 | // initialized from that element (by copy-initialization for | |||
| 4564 | // copy-list-initialization, or by direct-initialization for | |||
| 4565 | // direct-list-initialization); if a narrowing conversion is required | |||
| 4566 | // to convert the element to T, the program is ill-formed. | |||
| 4567 | // | |||
| 4568 | // Per core-24034, this is direct-initialization if we were performing | |||
| 4569 | // direct-list-initialization and copy-initialization otherwise. | |||
| 4570 | // We can't use InitListChecker for this, because it always performs | |||
| 4571 | // copy-initialization. This only matters if we might use an 'explicit' | |||
| 4572 | // conversion operator, or for the special case conversion of nullptr_t to | |||
| 4573 | // bool, so we only need to handle those cases. | |||
| 4574 | // | |||
| 4575 | // FIXME: Why not do this in all cases? | |||
| 4576 | Expr *Init = InitList->getInit(0); | |||
| 4577 | if (Init->getType()->isRecordType() || | |||
| 4578 | (Init->getType()->isNullPtrType() && DestType->isBooleanType())) { | |||
| 4579 | InitializationKind SubKind = | |||
| 4580 | Kind.getKind() == InitializationKind::IK_DirectList | |||
| 4581 | ? InitializationKind::CreateDirect(Kind.getLocation(), | |||
| 4582 | InitList->getLBraceLoc(), | |||
| 4583 | InitList->getRBraceLoc()) | |||
| 4584 | : Kind; | |||
| 4585 | Expr *SubInit[1] = { Init }; | |||
| 4586 | Sequence.InitializeFrom(S, Entity, SubKind, SubInit, | |||
| 4587 | /*TopLevelOfInitList*/true, | |||
| 4588 | TreatUnavailableAsInvalid); | |||
| 4589 | if (Sequence) | |||
| 4590 | Sequence.RewrapReferenceInitList(Entity.getType(), InitList); | |||
| 4591 | return; | |||
| 4592 | } | |||
| 4593 | } | |||
| 4594 | ||||
| 4595 | InitListChecker CheckInitList(S, Entity, InitList, | |||
| 4596 | DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid); | |||
| 4597 | if (CheckInitList.HadError()) { | |||
| 4598 | Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed); | |||
| 4599 | return; | |||
| 4600 | } | |||
| 4601 | ||||
| 4602 | // Add the list initialization step with the built init list. | |||
| 4603 | Sequence.AddListInitializationStep(DestType); | |||
| 4604 | } | |||
| 4605 | ||||
| 4606 | /// Try a reference initialization that involves calling a conversion | |||
| 4607 | /// function. | |||
| 4608 | static OverloadingResult TryRefInitWithConversionFunction( | |||
| 4609 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, | |||
| 4610 | Expr *Initializer, bool AllowRValues, bool IsLValueRef, | |||
| 4611 | InitializationSequence &Sequence) { | |||
| 4612 | QualType DestType = Entity.getType(); | |||
| 4613 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); | |||
| 4614 | QualType T1 = cv1T1.getUnqualifiedType(); | |||
| 4615 | QualType cv2T2 = Initializer->getType(); | |||
| 4616 | QualType T2 = cv2T2.getUnqualifiedType(); | |||
| 4617 | ||||
| 4618 | assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&(static_cast <bool> (!S.CompareReferenceRelationship(Initializer ->getBeginLoc(), T1, T2) && "Must have incompatible references when binding via conversion" ) ? void (0) : __assert_fail ("!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && \"Must have incompatible references when binding via conversion\"" , "clang/lib/Sema/SemaInit.cpp", 4619, __extension__ __PRETTY_FUNCTION__ )) | |||
| 4619 | "Must have incompatible references when binding via conversion")(static_cast <bool> (!S.CompareReferenceRelationship(Initializer ->getBeginLoc(), T1, T2) && "Must have incompatible references when binding via conversion" ) ? void (0) : __assert_fail ("!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && \"Must have incompatible references when binding via conversion\"" , "clang/lib/Sema/SemaInit.cpp", 4619, __extension__ __PRETTY_FUNCTION__ )); | |||
| 4620 | ||||
| 4621 | // Build the candidate set directly in the initialization sequence | |||
| 4622 | // structure, so that it will persist if we fail. | |||
| 4623 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); | |||
| 4624 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); | |||
| 4625 | ||||
| 4626 | // Determine whether we are allowed to call explicit conversion operators. | |||
| 4627 | // Note that none of [over.match.copy], [over.match.conv], nor | |||
| 4628 | // [over.match.ref] permit an explicit constructor to be chosen when | |||
| 4629 | // initializing a reference, not even for direct-initialization. | |||
| 4630 | bool AllowExplicitCtors = false; | |||
| 4631 | bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding(); | |||
| 4632 | ||||
| 4633 | const RecordType *T1RecordType = nullptr; | |||
| 4634 | if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) && | |||
| 4635 | S.isCompleteType(Kind.getLocation(), T1)) { | |||
| 4636 | // The type we're converting to is a class type. Enumerate its constructors | |||
| 4637 | // to see if there is a suitable conversion. | |||
| 4638 | CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); | |||
| 4639 | ||||
| 4640 | for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) { | |||
| 4641 | auto Info = getConstructorInfo(D); | |||
| 4642 | if (!Info.Constructor) | |||
| 4643 | continue; | |||
| 4644 | ||||
| 4645 | if (!Info.Constructor->isInvalidDecl() && | |||
| 4646 | Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { | |||
| 4647 | if (Info.ConstructorTmpl) | |||
| 4648 | S.AddTemplateOverloadCandidate( | |||
| 4649 | Info.ConstructorTmpl, Info.FoundDecl, | |||
| 4650 | /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, | |||
| 4651 | /*SuppressUserConversions=*/true, | |||
| 4652 | /*PartialOverloading*/ false, AllowExplicitCtors); | |||
| 4653 | else | |||
| 4654 | S.AddOverloadCandidate( | |||
| 4655 | Info.Constructor, Info.FoundDecl, Initializer, CandidateSet, | |||
| 4656 | /*SuppressUserConversions=*/true, | |||
| 4657 | /*PartialOverloading*/ false, AllowExplicitCtors); | |||
| 4658 | } | |||
| 4659 | } | |||
| 4660 | } | |||
| 4661 | if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) | |||
| 4662 | return OR_No_Viable_Function; | |||
| 4663 | ||||
| 4664 | const RecordType *T2RecordType = nullptr; | |||
| 4665 | if ((T2RecordType = T2->getAs<RecordType>()) && | |||
| 4666 | S.isCompleteType(Kind.getLocation(), T2)) { | |||
| 4667 | // The type we're converting from is a class type, enumerate its conversion | |||
| 4668 | // functions. | |||
| 4669 | CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); | |||
| 4670 | ||||
| 4671 | const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); | |||
| 4672 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | |||
| 4673 | NamedDecl *D = *I; | |||
| 4674 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); | |||
| 4675 | if (isa<UsingShadowDecl>(D)) | |||
| 4676 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
| 4677 | ||||
| 4678 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); | |||
| 4679 | CXXConversionDecl *Conv; | |||
| 4680 | if (ConvTemplate) | |||
| 4681 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | |||
| 4682 | else | |||
| 4683 | Conv = cast<CXXConversionDecl>(D); | |||
| 4684 | ||||
| 4685 | // If the conversion function doesn't return a reference type, | |||
| 4686 | // it can't be considered for this conversion unless we're allowed to | |||
| 4687 | // consider rvalues. | |||
| 4688 | // FIXME: Do we need to make sure that we only consider conversion | |||
| 4689 | // candidates with reference-compatible results? That might be needed to | |||
| 4690 | // break recursion. | |||
| 4691 | if ((AllowRValues || | |||
| 4692 | Conv->getConversionType()->isLValueReferenceType())) { | |||
| 4693 | if (ConvTemplate) | |||
| 4694 | S.AddTemplateConversionCandidate( | |||
| 4695 | ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, | |||
| 4696 | CandidateSet, | |||
| 4697 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs); | |||
| 4698 | else | |||
| 4699 | S.AddConversionCandidate( | |||
| 4700 | Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet, | |||
| 4701 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs); | |||
| 4702 | } | |||
| 4703 | } | |||
| 4704 | } | |||
| 4705 | if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) | |||
| 4706 | return OR_No_Viable_Function; | |||
| 4707 | ||||
| 4708 | SourceLocation DeclLoc = Initializer->getBeginLoc(); | |||
| 4709 | ||||
| 4710 | // Perform overload resolution. If it fails, return the failed result. | |||
| 4711 | OverloadCandidateSet::iterator Best; | |||
| 4712 | if (OverloadingResult Result | |||
| 4713 | = CandidateSet.BestViableFunction(S, DeclLoc, Best)) | |||
| 4714 | return Result; | |||
| 4715 | ||||
| 4716 | FunctionDecl *Function = Best->Function; | |||
| 4717 | // This is the overload that will be used for this initialization step if we | |||
| 4718 | // use this initialization. Mark it as referenced. | |||
| 4719 | Function->setReferenced(); | |||
| 4720 | ||||
| 4721 | // Compute the returned type and value kind of the conversion. | |||
| 4722 | QualType cv3T3; | |||
| 4723 | if (isa<CXXConversionDecl>(Function)) | |||
| 4724 | cv3T3 = Function->getReturnType(); | |||
| 4725 | else | |||
| 4726 | cv3T3 = T1; | |||
| 4727 | ||||
| 4728 | ExprValueKind VK = VK_PRValue; | |||
| 4729 | if (cv3T3->isLValueReferenceType()) | |||
| 4730 | VK = VK_LValue; | |||
| 4731 | else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>()) | |||
| 4732 | VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; | |||
| 4733 | cv3T3 = cv3T3.getNonLValueExprType(S.Context); | |||
| 4734 | ||||
| 4735 | // Add the user-defined conversion step. | |||
| 4736 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
| 4737 | Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3, | |||
| 4738 | HadMultipleCandidates); | |||
| 4739 | ||||
| 4740 | // Determine whether we'll need to perform derived-to-base adjustments or | |||
| 4741 | // other conversions. | |||
| 4742 | Sema::ReferenceConversions RefConv; | |||
| 4743 | Sema::ReferenceCompareResult NewRefRelationship = | |||
| 4744 | S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv); | |||
| 4745 | ||||
| 4746 | // Add the final conversion sequence, if necessary. | |||
| 4747 | if (NewRefRelationship == Sema::Ref_Incompatible) { | |||
| 4748 | assert(!isa<CXXConstructorDecl>(Function) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Function ) && "should not have conversion after constructor") ? void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Function) && \"should not have conversion after constructor\"" , "clang/lib/Sema/SemaInit.cpp", 4749, __extension__ __PRETTY_FUNCTION__ )) | |||
| 4749 | "should not have conversion after constructor")(static_cast <bool> (!isa<CXXConstructorDecl>(Function ) && "should not have conversion after constructor") ? void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Function) && \"should not have conversion after constructor\"" , "clang/lib/Sema/SemaInit.cpp", 4749, __extension__ __PRETTY_FUNCTION__ )); | |||
| 4750 | ||||
| 4751 | ImplicitConversionSequence ICS; | |||
| 4752 | ICS.setStandard(); | |||
| 4753 | ICS.Standard = Best->FinalConversion; | |||
| 4754 | Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2)); | |||
| 4755 | ||||
| 4756 | // Every implicit conversion results in a prvalue, except for a glvalue | |||
| 4757 | // derived-to-base conversion, which we handle below. | |||
| 4758 | cv3T3 = ICS.Standard.getToType(2); | |||
| 4759 | VK = VK_PRValue; | |||
| 4760 | } | |||
| 4761 | ||||
| 4762 | // If the converted initializer is a prvalue, its type T4 is adjusted to | |||
| 4763 | // type "cv1 T4" and the temporary materialization conversion is applied. | |||
| 4764 | // | |||
| 4765 | // We adjust the cv-qualifications to match the reference regardless of | |||
| 4766 | // whether we have a prvalue so that the AST records the change. In this | |||
| 4767 | // case, T4 is "cv3 T3". | |||
| 4768 | QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers()); | |||
| 4769 | if (cv1T4.getQualifiers() != cv3T3.getQualifiers()) | |||
| 4770 | Sequence.AddQualificationConversionStep(cv1T4, VK); | |||
| 4771 | Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue); | |||
| 4772 | VK = IsLValueRef ? VK_LValue : VK_XValue; | |||
| 4773 | ||||
| 4774 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) | |||
| 4775 | Sequence.AddDerivedToBaseCastStep(cv1T1, VK); | |||
| 4776 | else if (RefConv & Sema::ReferenceConversions::ObjC) | |||
| 4777 | Sequence.AddObjCObjectConversionStep(cv1T1); | |||
| 4778 | else if (RefConv & Sema::ReferenceConversions::Function) | |||
| 4779 | Sequence.AddFunctionReferenceConversionStep(cv1T1); | |||
| 4780 | else if (RefConv & Sema::ReferenceConversions::Qualification) { | |||
| 4781 | if (!S.Context.hasSameType(cv1T4, cv1T1)) | |||
| 4782 | Sequence.AddQualificationConversionStep(cv1T1, VK); | |||
| 4783 | } | |||
| 4784 | ||||
| 4785 | return OR_Success; | |||
| 4786 | } | |||
| 4787 | ||||
| 4788 | static void CheckCXX98CompatAccessibleCopy(Sema &S, | |||
| 4789 | const InitializedEntity &Entity, | |||
| 4790 | Expr *CurInitExpr); | |||
| 4791 | ||||
| 4792 | /// Attempt reference initialization (C++0x [dcl.init.ref]) | |||
| 4793 | static void TryReferenceInitialization(Sema &S, | |||
| 4794 | const InitializedEntity &Entity, | |||
| 4795 | const InitializationKind &Kind, | |||
| 4796 | Expr *Initializer, | |||
| 4797 | InitializationSequence &Sequence) { | |||
| 4798 | QualType DestType = Entity.getType(); | |||
| 4799 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); | |||
| 4800 | Qualifiers T1Quals; | |||
| 4801 | QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); | |||
| 4802 | QualType cv2T2 = S.getCompletedType(Initializer); | |||
| 4803 | Qualifiers T2Quals; | |||
| 4804 | QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); | |||
| 4805 | ||||
| 4806 | // If the initializer is the address of an overloaded function, try | |||
| 4807 | // to resolve the overloaded function. If all goes well, T2 is the | |||
| 4808 | // type of the resulting function. | |||
| 4809 | if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, | |||
| 4810 | T1, Sequence)) | |||
| 4811 | return; | |||
| 4812 | ||||
| 4813 | // Delegate everything else to a subfunction. | |||
| 4814 | TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, | |||
| 4815 | T1Quals, cv2T2, T2, T2Quals, Sequence); | |||
| 4816 | } | |||
| 4817 | ||||
| 4818 | /// Determine whether an expression is a non-referenceable glvalue (one to | |||
| 4819 | /// which a reference can never bind). Attempting to bind a reference to | |||
| 4820 | /// such a glvalue will always create a temporary. | |||
| 4821 | static bool isNonReferenceableGLValue(Expr *E) { | |||
| 4822 | return E->refersToBitField() || E->refersToVectorElement() || | |||
| 4823 | E->refersToMatrixElement(); | |||
| 4824 | } | |||
| 4825 | ||||
| 4826 | /// Reference initialization without resolving overloaded functions. | |||
| 4827 | /// | |||
| 4828 | /// We also can get here in C if we call a builtin which is declared as | |||
| 4829 | /// a function with a parameter of reference type (such as __builtin_va_end()). | |||
| 4830 | static void TryReferenceInitializationCore(Sema &S, | |||
| 4831 | const InitializedEntity &Entity, | |||
| 4832 | const InitializationKind &Kind, | |||
| 4833 | Expr *Initializer, | |||
| 4834 | QualType cv1T1, QualType T1, | |||
| 4835 | Qualifiers T1Quals, | |||
| 4836 | QualType cv2T2, QualType T2, | |||
| 4837 | Qualifiers T2Quals, | |||
| 4838 | InitializationSequence &Sequence) { | |||
| 4839 | QualType DestType = Entity.getType(); | |||
| 4840 | SourceLocation DeclLoc = Initializer->getBeginLoc(); | |||
| 4841 | ||||
| 4842 | // Compute some basic properties of the types and the initializer. | |||
| 4843 | bool isLValueRef = DestType->isLValueReferenceType(); | |||
| 4844 | bool isRValueRef = !isLValueRef; | |||
| 4845 | Expr::Classification InitCategory = Initializer->Classify(S.Context); | |||
| 4846 | ||||
| 4847 | Sema::ReferenceConversions RefConv; | |||
| 4848 | Sema::ReferenceCompareResult RefRelationship = | |||
| 4849 | S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv); | |||
| 4850 | ||||
| 4851 | // C++0x [dcl.init.ref]p5: | |||
| 4852 | // A reference to type "cv1 T1" is initialized by an expression of type | |||
| 4853 | // "cv2 T2" as follows: | |||
| 4854 | // | |||
| 4855 | // - If the reference is an lvalue reference and the initializer | |||
| 4856 | // expression | |||
| 4857 | // Note the analogous bullet points for rvalue refs to functions. Because | |||
| 4858 | // there are no function rvalues in C++, rvalue refs to functions are treated | |||
| 4859 | // like lvalue refs. | |||
| 4860 | OverloadingResult ConvOvlResult = OR_Success; | |||
| 4861 | bool T1Function = T1->isFunctionType(); | |||
| 4862 | if (isLValueRef || T1Function) { | |||
| 4863 | if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) && | |||
| 4864 | (RefRelationship == Sema::Ref_Compatible || | |||
| 4865 | (Kind.isCStyleOrFunctionalCast() && | |||
| 4866 | RefRelationship == Sema::Ref_Related))) { | |||
| 4867 | // - is an lvalue (but is not a bit-field), and "cv1 T1" is | |||
| 4868 | // reference-compatible with "cv2 T2," or | |||
| 4869 | if (RefConv & (Sema::ReferenceConversions::DerivedToBase | | |||
| 4870 | Sema::ReferenceConversions::ObjC)) { | |||
| 4871 | // If we're converting the pointee, add any qualifiers first; | |||
| 4872 | // these qualifiers must all be top-level, so just convert to "cv1 T2". | |||
| 4873 | if (RefConv & (Sema::ReferenceConversions::Qualification)) | |||
| 4874 | Sequence.AddQualificationConversionStep( | |||
| 4875 | S.Context.getQualifiedType(T2, T1Quals), | |||
| 4876 | Initializer->getValueKind()); | |||
| 4877 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) | |||
| 4878 | Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue); | |||
| 4879 | else | |||
| 4880 | Sequence.AddObjCObjectConversionStep(cv1T1); | |||
| 4881 | } else if (RefConv & Sema::ReferenceConversions::Qualification) { | |||
| 4882 | // Perform a (possibly multi-level) qualification conversion. | |||
| 4883 | Sequence.AddQualificationConversionStep(cv1T1, | |||
| 4884 | Initializer->getValueKind()); | |||
| 4885 | } else if (RefConv & Sema::ReferenceConversions::Function) { | |||
| 4886 | Sequence.AddFunctionReferenceConversionStep(cv1T1); | |||
| 4887 | } | |||
| 4888 | ||||
| 4889 | // We only create a temporary here when binding a reference to a | |||
| 4890 | // bit-field or vector element. Those cases are't supposed to be | |||
| 4891 | // handled by this bullet, but the outcome is the same either way. | |||
| 4892 | Sequence.AddReferenceBindingStep(cv1T1, false); | |||
| 4893 | return; | |||
| 4894 | } | |||
| 4895 | ||||
| 4896 | // - has a class type (i.e., T2 is a class type), where T1 is not | |||
| 4897 | // reference-related to T2, and can be implicitly converted to an | |||
| 4898 | // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible | |||
| 4899 | // with "cv3 T3" (this conversion is selected by enumerating the | |||
| 4900 | // applicable conversion functions (13.3.1.6) and choosing the best | |||
| 4901 | // one through overload resolution (13.3)), | |||
| 4902 | // If we have an rvalue ref to function type here, the rhs must be | |||
| 4903 | // an rvalue. DR1287 removed the "implicitly" here. | |||
| 4904 | if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && | |||
| 4905 | (isLValueRef || InitCategory.isRValue())) { | |||
| 4906 | if (S.getLangOpts().CPlusPlus) { | |||
| 4907 | // Try conversion functions only for C++. | |||
| 4908 | ConvOvlResult = TryRefInitWithConversionFunction( | |||
| 4909 | S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef, | |||
| 4910 | /*IsLValueRef*/ isLValueRef, Sequence); | |||
| 4911 | if (ConvOvlResult == OR_Success) | |||
| 4912 | return; | |||
| 4913 | if (ConvOvlResult != OR_No_Viable_Function) | |||
| 4914 | Sequence.SetOverloadFailure( | |||
| 4915 | InitializationSequence::FK_ReferenceInitOverloadFailed, | |||
| 4916 | ConvOvlResult); | |||
| 4917 | } else { | |||
| 4918 | ConvOvlResult = OR_No_Viable_Function; | |||
| 4919 | } | |||
| 4920 | } | |||
| 4921 | } | |||
| 4922 | ||||
| 4923 | // - Otherwise, the reference shall be an lvalue reference to a | |||
| 4924 | // non-volatile const type (i.e., cv1 shall be const), or the reference | |||
| 4925 | // shall be an rvalue reference. | |||
| 4926 | // For address spaces, we interpret this to mean that an addr space | |||
| 4927 | // of a reference "cv1 T1" is a superset of addr space of "cv2 T2". | |||
| 4928 | if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() && | |||
| 4929 | T1Quals.isAddressSpaceSupersetOf(T2Quals))) { | |||
| 4930 | if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) | |||
| 4931 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); | |||
| 4932 | else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) | |||
| 4933 | Sequence.SetOverloadFailure( | |||
| 4934 | InitializationSequence::FK_ReferenceInitOverloadFailed, | |||
| 4935 | ConvOvlResult); | |||
| 4936 | else if (!InitCategory.isLValue()) | |||
| 4937 | Sequence.SetFailed( | |||
| 4938 | T1Quals.isAddressSpaceSupersetOf(T2Quals) | |||
| 4939 | ? InitializationSequence:: | |||
| 4940 | FK_NonConstLValueReferenceBindingToTemporary | |||
| 4941 | : InitializationSequence::FK_ReferenceInitDropsQualifiers); | |||
| 4942 | else { | |||
| 4943 | InitializationSequence::FailureKind FK; | |||
| 4944 | switch (RefRelationship) { | |||
| 4945 | case Sema::Ref_Compatible: | |||
| 4946 | if (Initializer->refersToBitField()) | |||
| 4947 | FK = InitializationSequence:: | |||
| 4948 | FK_NonConstLValueReferenceBindingToBitfield; | |||
| 4949 | else if (Initializer->refersToVectorElement()) | |||
| 4950 | FK = InitializationSequence:: | |||
| 4951 | FK_NonConstLValueReferenceBindingToVectorElement; | |||
| 4952 | else if (Initializer->refersToMatrixElement()) | |||
| 4953 | FK = InitializationSequence:: | |||
| 4954 | FK_NonConstLValueReferenceBindingToMatrixElement; | |||
| 4955 | else | |||
| 4956 | llvm_unreachable("unexpected kind of compatible initializer")::llvm::llvm_unreachable_internal("unexpected kind of compatible initializer" , "clang/lib/Sema/SemaInit.cpp", 4956); | |||
| 4957 | break; | |||
| 4958 | case Sema::Ref_Related: | |||
| 4959 | FK = InitializationSequence::FK_ReferenceInitDropsQualifiers; | |||
| 4960 | break; | |||
| 4961 | case Sema::Ref_Incompatible: | |||
| 4962 | FK = InitializationSequence:: | |||
| 4963 | FK_NonConstLValueReferenceBindingToUnrelated; | |||
| 4964 | break; | |||
| 4965 | } | |||
| 4966 | Sequence.SetFailed(FK); | |||
| 4967 | } | |||
| 4968 | return; | |||
| 4969 | } | |||
| 4970 | ||||
| 4971 | // - If the initializer expression | |||
| 4972 | // - is an | |||
| 4973 | // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or | |||
| 4974 | // [1z] rvalue (but not a bit-field) or | |||
| 4975 | // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2" | |||
| 4976 | // | |||
| 4977 | // Note: functions are handled above and below rather than here... | |||
| 4978 | if (!T1Function && | |||
| 4979 | (RefRelationship == Sema::Ref_Compatible || | |||
| 4980 | (Kind.isCStyleOrFunctionalCast() && | |||
| 4981 | RefRelationship == Sema::Ref_Related)) && | |||
| 4982 | ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) || | |||
| 4983 | (InitCategory.isPRValue() && | |||
| 4984 | (S.getLangOpts().CPlusPlus17 || T2->isRecordType() || | |||
| 4985 | T2->isArrayType())))) { | |||
| 4986 | ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue; | |||
| 4987 | if (InitCategory.isPRValue() && T2->isRecordType()) { | |||
| 4988 | // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the | |||
| 4989 | // compiler the freedom to perform a copy here or bind to the | |||
| 4990 | // object, while C++0x requires that we bind directly to the | |||
| 4991 | // object. Hence, we always bind to the object without making an | |||
| 4992 | // extra copy. However, in C++03 requires that we check for the | |||
| 4993 | // presence of a suitable copy constructor: | |||
| 4994 | // | |||
| 4995 | // The constructor that would be used to make the copy shall | |||
| 4996 | // be callable whether or not the copy is actually done. | |||
| 4997 | if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt) | |||
| 4998 | Sequence.AddExtraneousCopyToTemporary(cv2T2); | |||
| 4999 | else if (S.getLangOpts().CPlusPlus11) | |||
| 5000 | CheckCXX98CompatAccessibleCopy(S, Entity, Initializer); | |||
| 5001 | } | |||
| 5002 | ||||
| 5003 | // C++1z [dcl.init.ref]/5.2.1.2: | |||
| 5004 | // If the converted initializer is a prvalue, its type T4 is adjusted | |||
| 5005 | // to type "cv1 T4" and the temporary materialization conversion is | |||
| 5006 | // applied. | |||
| 5007 | // Postpone address space conversions to after the temporary materialization | |||
| 5008 | // conversion to allow creating temporaries in the alloca address space. | |||
| 5009 | auto T1QualsIgnoreAS = T1Quals; | |||
| 5010 | auto T2QualsIgnoreAS = T2Quals; | |||
| 5011 | if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { | |||
| 5012 | T1QualsIgnoreAS.removeAddressSpace(); | |||
| 5013 | T2QualsIgnoreAS.removeAddressSpace(); | |||
| 5014 | } | |||
| 5015 | QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS); | |||
| 5016 | if (T1QualsIgnoreAS != T2QualsIgnoreAS) | |||
| 5017 | Sequence.AddQualificationConversionStep(cv1T4, ValueKind); | |||
| 5018 | Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue); | |||
| 5019 | ValueKind = isLValueRef ? VK_LValue : VK_XValue; | |||
| 5020 | // Add addr space conversion if required. | |||
| 5021 | if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { | |||
| 5022 | auto T4Quals = cv1T4.getQualifiers(); | |||
| 5023 | T4Quals.addAddressSpace(T1Quals.getAddressSpace()); | |||
| 5024 | QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals); | |||
| 5025 | Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind); | |||
| 5026 | cv1T4 = cv1T4WithAS; | |||
| 5027 | } | |||
| 5028 | ||||
| 5029 | // In any case, the reference is bound to the resulting glvalue (or to | |||
| 5030 | // an appropriate base class subobject). | |||
| 5031 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) | |||
| 5032 | Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind); | |||
| 5033 | else if (RefConv & Sema::ReferenceConversions::ObjC) | |||
| 5034 | Sequence.AddObjCObjectConversionStep(cv1T1); | |||
| 5035 | else if (RefConv & Sema::ReferenceConversions::Qualification) { | |||
| 5036 | if (!S.Context.hasSameType(cv1T4, cv1T1)) | |||
| 5037 | Sequence.AddQualificationConversionStep(cv1T1, ValueKind); | |||
| 5038 | } | |||
| 5039 | return; | |||
| 5040 | } | |||
| 5041 | ||||
| 5042 | // - has a class type (i.e., T2 is a class type), where T1 is not | |||
| 5043 | // reference-related to T2, and can be implicitly converted to an | |||
| 5044 | // xvalue, class prvalue, or function lvalue of type "cv3 T3", | |||
| 5045 | // where "cv1 T1" is reference-compatible with "cv3 T3", | |||
| 5046 | // | |||
| 5047 | // DR1287 removes the "implicitly" here. | |||
| 5048 | if (T2->isRecordType()) { | |||
| 5049 | if (RefRelationship == Sema::Ref_Incompatible) { | |||
| 5050 | ConvOvlResult = TryRefInitWithConversionFunction( | |||
| 5051 | S, Entity, Kind, Initializer, /*AllowRValues*/ true, | |||
| 5052 | /*IsLValueRef*/ isLValueRef, Sequence); | |||
| 5053 | if (ConvOvlResult) | |||
| 5054 | Sequence.SetOverloadFailure( | |||
| 5055 | InitializationSequence::FK_ReferenceInitOverloadFailed, | |||
| 5056 | ConvOvlResult); | |||
| 5057 | ||||
| 5058 | return; | |||
| 5059 | } | |||
| 5060 | ||||
| 5061 | if (RefRelationship == Sema::Ref_Compatible && | |||
| 5062 | isRValueRef && InitCategory.isLValue()) { | |||
| 5063 | Sequence.SetFailed( | |||
| 5064 | InitializationSequence::FK_RValueReferenceBindingToLValue); | |||
| 5065 | return; | |||
| 5066 | } | |||
| 5067 | ||||
| 5068 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); | |||
| 5069 | return; | |||
| 5070 | } | |||
| 5071 | ||||
| 5072 | // - Otherwise, a temporary of type "cv1 T1" is created and initialized | |||
| 5073 | // from the initializer expression using the rules for a non-reference | |||
| 5074 | // copy-initialization (8.5). The reference is then bound to the | |||
| 5075 | // temporary. [...] | |||
| 5076 | ||||
| 5077 | // Ignore address space of reference type at this point and perform address | |||
| 5078 | // space conversion after the reference binding step. | |||
| 5079 | QualType cv1T1IgnoreAS = | |||
| 5080 | T1Quals.hasAddressSpace() | |||
| 5081 | ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace()) | |||
| 5082 | : cv1T1; | |||
| 5083 | ||||
| 5084 | InitializedEntity TempEntity = | |||
| 5085 | InitializedEntity::InitializeTemporary(cv1T1IgnoreAS); | |||
| 5086 | ||||
| 5087 | // FIXME: Why do we use an implicit conversion here rather than trying | |||
| 5088 | // copy-initialization? | |||
| 5089 | ImplicitConversionSequence ICS | |||
| 5090 | = S.TryImplicitConversion(Initializer, TempEntity.getType(), | |||
| 5091 | /*SuppressUserConversions=*/false, | |||
| 5092 | Sema::AllowedExplicit::None, | |||
| 5093 | /*FIXME:InOverloadResolution=*/false, | |||
| 5094 | /*CStyle=*/Kind.isCStyleOrFunctionalCast(), | |||
| 5095 | /*AllowObjCWritebackConversion=*/false); | |||
| 5096 | ||||
| 5097 | if (ICS.isBad()) { | |||
| 5098 | // FIXME: Use the conversion function set stored in ICS to turn | |||
| 5099 | // this into an overloading ambiguity diagnostic. However, we need | |||
| 5100 | // to keep that set as an OverloadCandidateSet rather than as some | |||
| 5101 | // other kind of set. | |||
| 5102 | if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) | |||
| 5103 | Sequence.SetOverloadFailure( | |||
| 5104 | InitializationSequence::FK_ReferenceInitOverloadFailed, | |||
| 5105 | ConvOvlResult); | |||
| 5106 | else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) | |||
| 5107 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); | |||
| 5108 | else | |||
| 5109 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); | |||
| 5110 | return; | |||
| 5111 | } else { | |||
| 5112 | Sequence.AddConversionSequenceStep(ICS, TempEntity.getType()); | |||
| 5113 | } | |||
| 5114 | ||||
| 5115 | // [...] If T1 is reference-related to T2, cv1 must be the | |||
| 5116 | // same cv-qualification as, or greater cv-qualification | |||
| 5117 | // than, cv2; otherwise, the program is ill-formed. | |||
| 5118 | unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); | |||
| 5119 | unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); | |||
| 5120 | if (RefRelationship == Sema::Ref_Related && | |||
| 5121 | ((T1CVRQuals | T2CVRQuals) != T1CVRQuals || | |||
| 5122 | !T1Quals.isAddressSpaceSupersetOf(T2Quals))) { | |||
| 5123 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); | |||
| 5124 | return; | |||
| 5125 | } | |||
| 5126 | ||||
| 5127 | // [...] If T1 is reference-related to T2 and the reference is an rvalue | |||
| 5128 | // reference, the initializer expression shall not be an lvalue. | |||
| 5129 | if (RefRelationship >= Sema::Ref_Related && !isLValueRef && | |||
| 5130 | InitCategory.isLValue()) { | |||
| 5131 | Sequence.SetFailed( | |||
| 5132 | InitializationSequence::FK_RValueReferenceBindingToLValue); | |||
| 5133 | return; | |||
| 5134 | } | |||
| 5135 | ||||
| 5136 | Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true); | |||
| 5137 | ||||
| 5138 | if (T1Quals.hasAddressSpace()) { | |||
| 5139 | if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(), | |||
| 5140 | LangAS::Default)) { | |||
| 5141 | Sequence.SetFailed( | |||
| 5142 | InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary); | |||
| 5143 | return; | |||
| 5144 | } | |||
| 5145 | Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue | |||
| 5146 | : VK_XValue); | |||
| 5147 | } | |||
| 5148 | } | |||
| 5149 | ||||
| 5150 | /// Attempt character array initialization from a string literal | |||
| 5151 | /// (C++ [dcl.init.string], C99 6.7.8). | |||
| 5152 | static void TryStringLiteralInitialization(Sema &S, | |||
| 5153 | const InitializedEntity &Entity, | |||
| 5154 | const InitializationKind &Kind, | |||
| 5155 | Expr *Initializer, | |||
| 5156 | InitializationSequence &Sequence) { | |||
| 5157 | Sequence.AddStringInitStep(Entity.getType()); | |||
| 5158 | } | |||
| 5159 | ||||
| 5160 | /// Attempt value initialization (C++ [dcl.init]p7). | |||
| 5161 | static void TryValueInitialization(Sema &S, | |||
| 5162 | const InitializedEntity &Entity, | |||
| 5163 | const InitializationKind &Kind, | |||
| 5164 | InitializationSequence &Sequence, | |||
| 5165 | InitListExpr *InitList) { | |||
| 5166 | assert((!InitList || InitList->getNumInits() == 0) &&(static_cast <bool> ((!InitList || InitList->getNumInits () == 0) && "Shouldn't use value-init for non-empty init lists" ) ? void (0) : __assert_fail ("(!InitList || InitList->getNumInits() == 0) && \"Shouldn't use value-init for non-empty init lists\"" , "clang/lib/Sema/SemaInit.cpp", 5167, __extension__ __PRETTY_FUNCTION__ )) | |||
| 5167 | "Shouldn't use value-init for non-empty init lists")(static_cast <bool> ((!InitList || InitList->getNumInits () == 0) && "Shouldn't use value-init for non-empty init lists" ) ? void (0) : __assert_fail ("(!InitList || InitList->getNumInits() == 0) && \"Shouldn't use value-init for non-empty init lists\"" , "clang/lib/Sema/SemaInit.cpp", 5167, __extension__ __PRETTY_FUNCTION__ )); | |||
| 5168 | ||||
| 5169 | // C++98 [dcl.init]p5, C++11 [dcl.init]p7: | |||
| 5170 | // | |||
| 5171 | // To value-initialize an object of type T means: | |||
| 5172 | QualType T = Entity.getType(); | |||
| 5173 | ||||
| 5174 | // -- if T is an array type, then each element is value-initialized; | |||
| 5175 | T = S.Context.getBaseElementType(T); | |||
| 5176 | ||||
| 5177 | if (const RecordType *RT = T->getAs<RecordType>()) { | |||
| 5178 | if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { | |||
| 5179 | bool NeedZeroInitialization = true; | |||
| 5180 | // C++98: | |||
| 5181 | // -- if T is a class type (clause 9) with a user-declared constructor | |||
| 5182 | // (12.1), then the default constructor for T is called (and the | |||
| 5183 | // initialization is ill-formed if T has no accessible default | |||
| 5184 | // constructor); | |||
| 5185 | // C++11: | |||
| 5186 | // -- if T is a class type (clause 9) with either no default constructor | |||
| 5187 | // (12.1 [class.ctor]) or a default constructor that is user-provided | |||
| 5188 | // or deleted, then the object is default-initialized; | |||
| 5189 | // | |||
| 5190 | // Note that the C++11 rule is the same as the C++98 rule if there are no | |||
| 5191 | // defaulted or deleted constructors, so we just use it unconditionally. | |||
| 5192 | CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl); | |||
| 5193 | if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted()) | |||
| 5194 | NeedZeroInitialization = false; | |||
| 5195 | ||||
| 5196 | // -- if T is a (possibly cv-qualified) non-union class type without a | |||
| 5197 | // user-provided or deleted default constructor, then the object is | |||
| 5198 | // zero-initialized and, if T has a non-trivial default constructor, | |||
| 5199 | // default-initialized; | |||
| 5200 | // The 'non-union' here was removed by DR1502. The 'non-trivial default | |||
| 5201 | // constructor' part was removed by DR1507. | |||
| 5202 | if (NeedZeroInitialization) | |||
| 5203 | Sequence.AddZeroInitializationStep(Entity.getType()); | |||
| 5204 | ||||
| 5205 | // C++03: | |||
| 5206 | // -- if T is a non-union class type without a user-declared constructor, | |||
| 5207 | // then every non-static data member and base class component of T is | |||
| 5208 | // value-initialized; | |||
| 5209 | // [...] A program that calls for [...] value-initialization of an | |||
| 5210 | // entity of reference type is ill-formed. | |||
| 5211 | // | |||
| 5212 | // C++11 doesn't need this handling, because value-initialization does not | |||
| 5213 | // occur recursively there, and the implicit default constructor is | |||
| 5214 | // defined as deleted in the problematic cases. | |||
| 5215 | if (!S.getLangOpts().CPlusPlus11 && | |||
| 5216 | ClassDecl->hasUninitializedReferenceMember()) { | |||
| 5217 | Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference); | |||
| 5218 | return; | |||
| 5219 | } | |||
| 5220 | ||||
| 5221 | // If this is list-value-initialization, pass the empty init list on when | |||
| 5222 | // building the constructor call. This affects the semantics of a few | |||
| 5223 | // things (such as whether an explicit default constructor can be called). | |||
| 5224 | Expr *InitListAsExpr = InitList; | |||
| 5225 | MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0); | |||
| 5226 | bool InitListSyntax = InitList; | |||
| 5227 | ||||
| 5228 | // FIXME: Instead of creating a CXXConstructExpr of array type here, | |||
| 5229 | // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr. | |||
| 5230 | return TryConstructorInitialization( | |||
| 5231 | S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax); | |||
| 5232 | } | |||
| 5233 | } | |||
| 5234 | ||||
| 5235 | Sequence.AddZeroInitializationStep(Entity.getType()); | |||
| 5236 | } | |||
| 5237 | ||||
| 5238 | /// Attempt default initialization (C++ [dcl.init]p6). | |||
| 5239 | static void TryDefaultInitialization(Sema &S, | |||
| 5240 | const InitializedEntity &Entity, | |||
| 5241 | const InitializationKind &Kind, | |||
| 5242 | InitializationSequence &Sequence) { | |||
| 5243 | assert(Kind.getKind() == InitializationKind::IK_Default)(static_cast <bool> (Kind.getKind() == InitializationKind ::IK_Default) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Default" , "clang/lib/Sema/SemaInit.cpp", 5243, __extension__ __PRETTY_FUNCTION__ )); | |||
| 5244 | ||||
| 5245 | // C++ [dcl.init]p6: | |||
| 5246 | // To default-initialize an object of type T means: | |||
| 5247 | // - if T is an array type, each element is default-initialized; | |||
| 5248 | QualType DestType = S.Context.getBaseElementType(Entity.getType()); | |||
| 5249 | ||||
| 5250 | // - if T is a (possibly cv-qualified) class type (Clause 9), the default | |||
| 5251 | // constructor for T is called (and the initialization is ill-formed if | |||
| 5252 | // T has no accessible default constructor); | |||
| 5253 | if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) { | |||
| 5254 | TryConstructorInitialization(S, Entity, Kind, std::nullopt, DestType, | |||
| 5255 | Entity.getType(), Sequence); | |||
| 5256 | return; | |||
| 5257 | } | |||
| 5258 | ||||
| 5259 | // - otherwise, no initialization is performed. | |||
| 5260 | ||||
| 5261 | // If a program calls for the default initialization of an object of | |||
| 5262 | // a const-qualified type T, T shall be a class type with a user-provided | |||
| 5263 | // default constructor. | |||
| 5264 | if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) { | |||
| 5265 | if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) | |||
| 5266 | Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); | |||
| 5267 | return; | |||
| 5268 | } | |||
| 5269 | ||||
| 5270 | // If the destination type has a lifetime property, zero-initialize it. | |||
| 5271 | if (DestType.getQualifiers().hasObjCLifetime()) { | |||
| 5272 | Sequence.AddZeroInitializationStep(Entity.getType()); | |||
| 5273 | return; | |||
| 5274 | } | |||
| 5275 | } | |||
| 5276 | ||||
| 5277 | static void TryOrBuildParenListInitialization( | |||
| 5278 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, | |||
| 5279 | ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly, | |||
| 5280 | ExprResult *Result = nullptr) { | |||
| 5281 | unsigned ArgIndexToProcess = 0; | |||
| 5282 | SmallVector<Expr *, 4> InitExprs; | |||
| 5283 | QualType ResultType; | |||
| 5284 | Expr *ArrayFiller = nullptr; | |||
| 5285 | FieldDecl *InitializedFieldInUnion = nullptr; | |||
| 5286 | ||||
| 5287 | // Process entities (i.e. array members, base classes, or class fields) by | |||
| 5288 | // adding an initialization expression to InitExprs for each entity to | |||
| 5289 | // initialize. | |||
| 5290 | auto ProcessEntities = [&](auto Range) -> bool { | |||
| 5291 | bool IsUnionType = Entity.getType()->isUnionType(); | |||
| 5292 | for (InitializedEntity SubEntity : Range) { | |||
| 5293 | // Unions should only have one initializer expression. | |||
| 5294 | // If there are more initializers than it will be caught when we check | |||
| 5295 | // whether Index equals Args.size(). | |||
| 5296 | if (ArgIndexToProcess == 1 && IsUnionType) | |||
| 5297 | return true; | |||
| 5298 | ||||
| 5299 | bool IsMember = SubEntity.getKind() == InitializedEntity::EK_Member; | |||
| 5300 | ||||
| 5301 | // Unnamed bitfields should not be initialized at all, either with an arg | |||
| 5302 | // or by default. | |||
| 5303 | if (IsMember && cast<FieldDecl>(SubEntity.getDecl())->isUnnamedBitfield()) | |||
| 5304 | continue; | |||
| 5305 | ||||
| 5306 | if (ArgIndexToProcess < Args.size()) { | |||
| 5307 | // There are still expressions in Args that haven't been processed. | |||
| 5308 | // Let's match them to the current entity to initialize. | |||
| 5309 | Expr *E = Args[ArgIndexToProcess++]; | |||
| 5310 | ||||
| 5311 | // Incomplete array types indicate flexible array members. Do not allow | |||
| 5312 | // paren list initializations of structs with these members, as GCC | |||
| 5313 | // doesn't either. | |||
| 5314 | if (IsMember) { | |||
| 5315 | auto *FD = cast<FieldDecl>(SubEntity.getDecl()); | |||
| 5316 | if (FD->getType()->isIncompleteArrayType()) { | |||
| 5317 | if (!VerifyOnly) { | |||
| 5318 | S.Diag(E->getBeginLoc(), diag::err_flexible_array_init) | |||
| 5319 | << SourceRange(E->getBeginLoc(), E->getEndLoc()); | |||
| 5320 | S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD; | |||
| 5321 | } | |||
| 5322 | Sequence.SetFailed( | |||
| 5323 | InitializationSequence::FK_ParenthesizedListInitFailed); | |||
| 5324 | return false; | |||
| 5325 | } | |||
| 5326 | } | |||
| 5327 | ||||
| 5328 | InitializationKind SubKind = InitializationKind::CreateForInit( | |||
| 5329 | E->getExprLoc(), /*isDirectInit=*/false, E); | |||
| 5330 | InitializationSequence SubSeq(S, SubEntity, SubKind, E); | |||
| 5331 | ||||
| 5332 | if (SubSeq.Failed()) { | |||
| 5333 | if (!VerifyOnly) | |||
| 5334 | SubSeq.Diagnose(S, SubEntity, SubKind, E); | |||
| 5335 | else | |||
| 5336 | Sequence.SetFailed( | |||
| 5337 | InitializationSequence::FK_ParenthesizedListInitFailed); | |||
| 5338 | ||||
| 5339 | return false; | |||
| 5340 | } | |||
| 5341 | if (!VerifyOnly) { | |||
| 5342 | ExprResult ER = SubSeq.Perform(S, SubEntity, SubKind, E); | |||
| 5343 | InitExprs.push_back(ER.get()); | |||
| 5344 | if (IsMember && IsUnionType) | |||
| 5345 | InitializedFieldInUnion = cast<FieldDecl>(SubEntity.getDecl()); | |||
| 5346 | } | |||
| 5347 | } else { | |||
| 5348 | // We've processed all of the args, but there are still entities that | |||
| 5349 | // have to be initialized. | |||
| 5350 | if (IsMember) { | |||
| 5351 | // C++ [dcl.init]p17.6.2.2 | |||
| 5352 | // The remaining elements are initialized with their default member | |||
| 5353 | // initializers, if any | |||
| 5354 | auto *FD = cast<FieldDecl>(SubEntity.getDecl()); | |||
| 5355 | if (Expr *ICE = FD->getInClassInitializer(); ICE && !VerifyOnly) { | |||
| 5356 | ExprResult DIE = S.BuildCXXDefaultInitExpr(FD->getLocation(), FD); | |||
| 5357 | if (DIE.isInvalid()) | |||
| 5358 | return false; | |||
| 5359 | S.checkInitializerLifetime(SubEntity, DIE.get()); | |||
| 5360 | InitExprs.push_back(DIE.get()); | |||
| 5361 | continue; | |||
| 5362 | }; | |||
| 5363 | } | |||
| 5364 | // Remaining class elements without default member initializers and | |||
| 5365 | // array elements are value initialized: | |||
| 5366 | // | |||
| 5367 | // C++ [dcl.init]p17.6.2.2 | |||
| 5368 | // The remaining elements...otherwise are value initialzed | |||
| 5369 | // | |||
| 5370 | // C++ [dcl.init]p17.5 | |||
| 5371 | // if the destination type is an array, the object is initialized as | |||
| 5372 | // . follows. Let x1, . . . , xk be the elements of the expression-list | |||
| 5373 | // ...Let n denote the array size...the ith array element is...value- | |||
| 5374 | // initialized for each k < i <= n. | |||
| 5375 | InitializationKind SubKind = InitializationKind::CreateValue( | |||
| 5376 | Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true); | |||
| 5377 | InitializationSequence SubSeq(S, SubEntity, SubKind, std::nullopt); | |||
| 5378 | if (SubSeq.Failed()) { | |||
| 5379 | if (!VerifyOnly) | |||
| 5380 | SubSeq.Diagnose(S, SubEntity, SubKind, std::nullopt); | |||
| 5381 | return false; | |||
| 5382 | } | |||
| 5383 | if (!VerifyOnly) { | |||
| 5384 | ExprResult ER = SubSeq.Perform(S, SubEntity, SubKind, std::nullopt); | |||
| 5385 | if (SubEntity.getKind() == InitializedEntity::EK_ArrayElement) { | |||
| 5386 | ArrayFiller = ER.get(); | |||
| 5387 | return true; | |||
| 5388 | } | |||
| 5389 | InitExprs.push_back(ER.get()); | |||
| 5390 | } | |||
| 5391 | } | |||
| 5392 | } | |||
| 5393 | return true; | |||
| 5394 | }; | |||
| 5395 | ||||
| 5396 | if (const ArrayType *AT = | |||
| 5397 | S.getASTContext().getAsArrayType(Entity.getType())) { | |||
| 5398 | ||||
| 5399 | SmallVector<InitializedEntity, 4> ElementEntities; | |||
| 5400 | uint64_t ArrayLength; | |||
| 5401 | // C++ [dcl.init]p17.5 | |||
| 5402 | // if the destination type is an array, the object is initialized as | |||
| 5403 | // follows. Let x1, . . . , xk be the elements of the expression-list. If | |||
| 5404 | // the destination type is an array of unknown bound, it is define as | |||
| 5405 | // having k elements. | |||
| 5406 | if (const ConstantArrayType *CAT = | |||
| 5407 | S.getASTContext().getAsConstantArrayType(Entity.getType())) | |||
| 5408 | ArrayLength = CAT->getSize().getZExtValue(); | |||
| 5409 | else | |||
| 5410 | ArrayLength = Args.size(); | |||
| 5411 | ||||
| 5412 | if (ArrayLength >= Args.size()) { | |||
| 5413 | for (uint64_t I = 0; I < ArrayLength; ++I) | |||
| 5414 | ElementEntities.push_back( | |||
| 5415 | InitializedEntity::InitializeElement(S.getASTContext(), I, Entity)); | |||
| 5416 | ||||
| 5417 | if (!ProcessEntities(ElementEntities)) | |||
| 5418 | return; | |||
| 5419 | ||||
| 5420 | ResultType = S.Context.getConstantArrayType( | |||
| 5421 | AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength), | |||
| 5422 | nullptr, ArrayType::Normal, 0); | |||
| 5423 | } | |||
| 5424 | } else if (auto *RT = Entity.getType()->getAs<RecordType>()) { | |||
| 5425 | const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); | |||
| 5426 | ||||
| 5427 | auto BaseRange = map_range(RD->bases(), [&S](auto &base) { | |||
| 5428 | return InitializedEntity::InitializeBase(S.getASTContext(), &base, false); | |||
| 5429 | }); | |||
| 5430 | auto FieldRange = map_range(RD->fields(), [](auto *field) { | |||
| 5431 | return InitializedEntity::InitializeMember(field); | |||
| 5432 | }); | |||
| 5433 | ||||
| 5434 | if (!ProcessEntities(BaseRange)) | |||
| 5435 | return; | |||
| 5436 | ||||
| 5437 | if (!ProcessEntities(FieldRange)) | |||
| 5438 | return; | |||
| 5439 | ||||
| 5440 | ResultType = Entity.getType(); | |||
| 5441 | } | |||
| 5442 | ||||
| 5443 | // Not all of the args have been processed, so there must've been more args | |||
| 5444 | // than were required to initialize the element. | |||
| 5445 | if (ArgIndexToProcess < Args.size()) { | |||
| 5446 | Sequence.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed); | |||
| 5447 | if (!VerifyOnly) { | |||
| 5448 | QualType T = Entity.getType(); | |||
| 5449 | int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4; | |||
| 5450 | SourceRange ExcessInitSR(Args[ArgIndexToProcess]->getBeginLoc(), | |||
| 5451 | Args.back()->getEndLoc()); | |||
| 5452 | S.Diag(Kind.getLocation(), diag::err_excess_initializers) | |||
| 5453 | << InitKind << ExcessInitSR; | |||
| 5454 | } | |||
| 5455 | return; | |||
| 5456 | } | |||
| 5457 | ||||
| 5458 | if (VerifyOnly) { | |||
| 5459 | Sequence.setSequenceKind(InitializationSequence::NormalSequence); | |||
| 5460 | Sequence.AddParenthesizedListInitStep(Entity.getType()); | |||
| 5461 | } else if (Result) { | |||
| 5462 | SourceRange SR = Kind.getParenOrBraceRange(); | |||
| 5463 | auto *CPLIE = CXXParenListInitExpr::Create( | |||
| 5464 | S.getASTContext(), InitExprs, ResultType, Args.size(), | |||
| 5465 | Kind.getLocation(), SR.getBegin(), SR.getEnd()); | |||
| 5466 | if (ArrayFiller) | |||
| 5467 | CPLIE->setArrayFiller(ArrayFiller); | |||
| 5468 | if (InitializedFieldInUnion) | |||
| 5469 | CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion); | |||
| 5470 | *Result = CPLIE; | |||
| 5471 | S.Diag(Kind.getLocation(), | |||
| 5472 | diag::warn_cxx17_compat_aggregate_init_paren_list) | |||
| 5473 | << Kind.getLocation() << SR << ResultType; | |||
| 5474 | } | |||
| 5475 | ||||
| 5476 | return; | |||
| 5477 | } | |||
| 5478 | ||||
| 5479 | /// Attempt a user-defined conversion between two types (C++ [dcl.init]), | |||
| 5480 | /// which enumerates all conversion functions and performs overload resolution | |||
| 5481 | /// to select the best. | |||
| 5482 | static void TryUserDefinedConversion(Sema &S, | |||
| 5483 | QualType DestType, | |||
| 5484 | const InitializationKind &Kind, | |||
| 5485 | Expr *Initializer, | |||
| 5486 | InitializationSequence &Sequence, | |||
| 5487 | bool TopLevelOfInitList) { | |||
| 5488 | assert(!DestType->isReferenceType() && "References are handled elsewhere")(static_cast <bool> (!DestType->isReferenceType() && "References are handled elsewhere") ? void (0) : __assert_fail ("!DestType->isReferenceType() && \"References are handled elsewhere\"" , "clang/lib/Sema/SemaInit.cpp", 5488, __extension__ __PRETTY_FUNCTION__ )); | |||
| 5489 | QualType SourceType = Initializer->getType(); | |||
| 5490 | assert((DestType->isRecordType() || SourceType->isRecordType()) &&(static_cast <bool> ((DestType->isRecordType() || SourceType ->isRecordType()) && "Must have a class type to perform a user-defined conversion" ) ? void (0) : __assert_fail ("(DestType->isRecordType() || SourceType->isRecordType()) && \"Must have a class type to perform a user-defined conversion\"" , "clang/lib/Sema/SemaInit.cpp", 5491, __extension__ __PRETTY_FUNCTION__ )) | |||
| 5491 | "Must have a class type to perform a user-defined conversion")(static_cast <bool> ((DestType->isRecordType() || SourceType ->isRecordType()) && "Must have a class type to perform a user-defined conversion" ) ? void (0) : __assert_fail ("(DestType->isRecordType() || SourceType->isRecordType()) && \"Must have a class type to perform a user-defined conversion\"" , "clang/lib/Sema/SemaInit.cpp", 5491, __extension__ __PRETTY_FUNCTION__ )); | |||
| 5492 | ||||
| 5493 | // Build the candidate set directly in the initialization sequence | |||
| 5494 | // structure, so that it will persist if we fail. | |||
| 5495 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); | |||
| 5496 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); | |||
| 5497 | CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); | |||
| 5498 | ||||
| 5499 | // Determine whether we are allowed to call explicit constructors or | |||
| 5500 | // explicit conversion operators. | |||
| 5501 | bool AllowExplicit = Kind.AllowExplicit(); | |||
| 5502 | ||||
| 5503 | if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { | |||
| 5504 | // The type we're converting to is a class type. Enumerate its constructors | |||
| 5505 | // to see if there is a suitable conversion. | |||
| 5506 | CXXRecordDecl *DestRecordDecl | |||
| 5507 | = cast<CXXRecordDecl>(DestRecordType->getDecl()); | |||
| 5508 | ||||
| 5509 | // Try to complete the type we're converting to. | |||
| 5510 | if (S.isCompleteType(Kind.getLocation(), DestType)) { | |||
| 5511 | for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) { | |||
| 5512 | auto Info = getConstructorInfo(D); | |||
| 5513 | if (!Info.Constructor) | |||
| 5514 | continue; | |||
| 5515 | ||||
| 5516 | if (!Info.Constructor->isInvalidDecl() && | |||
| 5517 | Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { | |||
| 5518 | if (Info.ConstructorTmpl) | |||
| 5519 | S.AddTemplateOverloadCandidate( | |||
| 5520 | Info.ConstructorTmpl, Info.FoundDecl, | |||
| 5521 | /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, | |||
| 5522 | /*SuppressUserConversions=*/true, | |||
| 5523 | /*PartialOverloading*/ false, AllowExplicit); | |||
| 5524 | else | |||
| 5525 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, | |||
| 5526 | Initializer, CandidateSet, | |||
| 5527 | /*SuppressUserConversions=*/true, | |||
| 5528 | /*PartialOverloading*/ false, AllowExplicit); | |||
| 5529 | } | |||
| 5530 | } | |||
| 5531 | } | |||
| 5532 | } | |||
| 5533 | ||||
| 5534 | SourceLocation DeclLoc = Initializer->getBeginLoc(); | |||
| 5535 | ||||
| 5536 | if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { | |||
| 5537 | // The type we're converting from is a class type, enumerate its conversion | |||
| 5538 | // functions. | |||
| 5539 | ||||
| 5540 | // We can only enumerate the conversion functions for a complete type; if | |||
| 5541 | // the type isn't complete, simply skip this step. | |||
| 5542 | if (S.isCompleteType(DeclLoc, SourceType)) { | |||
| 5543 | CXXRecordDecl *SourceRecordDecl | |||
| 5544 | = cast<CXXRecordDecl>(SourceRecordType->getDecl()); | |||
| 5545 | ||||
| 5546 | const auto &Conversions = | |||
| 5547 | SourceRecordDecl->getVisibleConversionFunctions(); | |||
| 5548 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | |||
| 5549 | NamedDecl *D = *I; | |||
| 5550 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); | |||
| 5551 | if (isa<UsingShadowDecl>(D)) | |||
| 5552 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
| 5553 | ||||
| 5554 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); | |||
| 5555 | CXXConversionDecl *Conv; | |||
| 5556 | if (ConvTemplate) | |||
| 5557 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | |||
| 5558 | else | |||
| 5559 | Conv = cast<CXXConversionDecl>(D); | |||
| 5560 | ||||
| 5561 | if (ConvTemplate) | |||
| 5562 | S.AddTemplateConversionCandidate( | |||
| 5563 | ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, | |||
| 5564 | CandidateSet, AllowExplicit, AllowExplicit); | |||
| 5565 | else | |||
| 5566 | S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, | |||
| 5567 | DestType, CandidateSet, AllowExplicit, | |||
| 5568 | AllowExplicit); | |||
| 5569 | } | |||
| 5570 | } | |||
| 5571 | } | |||
| 5572 | ||||
| 5573 | // Perform overload resolution. If it fails, return the failed result. | |||
| 5574 | OverloadCandidateSet::iterator Best; | |||
| 5575 | if (OverloadingResult Result | |||
| 5576 | = CandidateSet.BestViableFunction(S, DeclLoc, Best)) { | |||
| 5577 | Sequence.SetOverloadFailure( | |||
| 5578 | InitializationSequence::FK_UserConversionOverloadFailed, Result); | |||
| 5579 | ||||
| 5580 | // [class.copy.elision]p3: | |||
| 5581 | // In some copy-initialization contexts, a two-stage overload resolution | |||
| 5582 | // is performed. | |||
| 5583 | // If the first overload resolution selects a deleted function, we also | |||
| 5584 | // need the initialization sequence to decide whether to perform the second | |||
| 5585 | // overload resolution. | |||
| 5586 | if (!(Result == OR_Deleted && | |||
| 5587 | Kind.getKind() == InitializationKind::IK_Copy)) | |||
| 5588 | return; | |||
| 5589 | } | |||
| 5590 | ||||
| 5591 | FunctionDecl *Function = Best->Function; | |||
| 5592 | Function->setReferenced(); | |||
| 5593 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
| 5594 | ||||
| 5595 | if (isa<CXXConstructorDecl>(Function)) { | |||
| 5596 | // Add the user-defined conversion step. Any cv-qualification conversion is | |||
| 5597 | // subsumed by the initialization. Per DR5, the created temporary is of the | |||
| 5598 | // cv-unqualified type of the destination. | |||
| 5599 | Sequence.AddUserConversionStep(Function, Best->FoundDecl, | |||
| 5600 | DestType.getUnqualifiedType(), | |||
| 5601 | HadMultipleCandidates); | |||
| 5602 | ||||
| 5603 | // C++14 and before: | |||
| 5604 | // - if the function is a constructor, the call initializes a temporary | |||
| 5605 | // of the cv-unqualified version of the destination type. The [...] | |||
| 5606 | // temporary [...] is then used to direct-initialize, according to the | |||
| 5607 | // rules above, the object that is the destination of the | |||
| 5608 | // copy-initialization. | |||
| 5609 | // Note that this just performs a simple object copy from the temporary. | |||
| 5610 | // | |||
| 5611 | // C++17: | |||
| 5612 | // - if the function is a constructor, the call is a prvalue of the | |||
| 5613 | // cv-unqualified version of the destination type whose return object | |||
| 5614 | // is initialized by the constructor. The call is used to | |||
| 5615 | // direct-initialize, according to the rules above, the object that | |||
| 5616 | // is the destination of the copy-initialization. | |||
| 5617 | // Therefore we need to do nothing further. | |||
| 5618 | // | |||
| 5619 | // FIXME: Mark this copy as extraneous. | |||
| 5620 | if (!S.getLangOpts().CPlusPlus17) | |||
| 5621 | Sequence.AddFinalCopy(DestType); | |||
| 5622 | else if (DestType.hasQualifiers()) | |||
| 5623 | Sequence.AddQualificationConversionStep(DestType, VK_PRValue); | |||
| 5624 | return; | |||
| 5625 | } | |||
| 5626 | ||||
| 5627 | // Add the user-defined conversion step that calls the conversion function. | |||
| 5628 | QualType ConvType = Function->getCallResultType(); | |||
| 5629 | Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType, | |||
| 5630 | HadMultipleCandidates); | |||
| 5631 | ||||
| 5632 | if (ConvType->getAs<RecordType>()) { | |||
| 5633 | // The call is used to direct-initialize [...] the object that is the | |||
| 5634 | // destination of the copy-initialization. | |||
| 5635 | // | |||
| 5636 | // In C++17, this does not call a constructor if we enter /17.6.1: | |||
| 5637 | // - If the initializer expression is a prvalue and the cv-unqualified | |||
| 5638 | // version of the source type is the same as the class of the | |||
| 5639 | // destination [... do not make an extra copy] | |||
| 5640 | // | |||
| 5641 | // FIXME: Mark this copy as extraneous. | |||
| 5642 | if (!S.getLangOpts().CPlusPlus17 || | |||
| 5643 | Function->getReturnType()->isReferenceType() || | |||
| 5644 | !S.Context.hasSameUnqualifiedType(ConvType, DestType)) | |||
| 5645 | Sequence.AddFinalCopy(DestType); | |||
| 5646 | else if (!S.Context.hasSameType(ConvType, DestType)) | |||
| 5647 | Sequence.AddQualificationConversionStep(DestType, VK_PRValue); | |||
| 5648 | return; | |||
| 5649 | } | |||
| 5650 | ||||
| 5651 | // If the conversion following the call to the conversion function | |||
| 5652 | // is interesting, add it as a separate step. | |||
| 5653 | if (Best->FinalConversion.First || Best->FinalConversion.Second || | |||
| 5654 | Best->FinalConversion.Third) { | |||
| 5655 | ImplicitConversionSequence ICS; | |||
| 5656 | ICS.setStandard(); | |||
| 5657 | ICS.Standard = Best->FinalConversion; | |||
| 5658 | Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); | |||
| 5659 | } | |||
| 5660 | } | |||
| 5661 | ||||
| 5662 | /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>, | |||
| 5663 | /// a function with a pointer return type contains a 'return false;' statement. | |||
| 5664 | /// In C++11, 'false' is not a null pointer, so this breaks the build of any | |||
| 5665 | /// code using that header. | |||
| 5666 | /// | |||
| 5667 | /// Work around this by treating 'return false;' as zero-initializing the result | |||
| 5668 | /// if it's used in a pointer-returning function in a system header. | |||
| 5669 | static bool isLibstdcxxPointerReturnFalseHack(Sema &S, | |||
| 5670 | const InitializedEntity &Entity, | |||
| 5671 | const Expr *Init) { | |||
| 5672 | return S.getLangOpts().CPlusPlus11 && | |||
| 5673 | Entity.getKind() == InitializedEntity::EK_Result && | |||
| 5674 | Entity.getType()->isPointerType() && | |||
| 5675 | isa<CXXBoolLiteralExpr>(Init) && | |||
| 5676 | !cast<CXXBoolLiteralExpr>(Init)->getValue() && | |||
| 5677 | S.getSourceManager().isInSystemHeader(Init->getExprLoc()); | |||
| 5678 | } | |||
| 5679 | ||||
| 5680 | /// The non-zero enum values here are indexes into diagnostic alternatives. | |||
| 5681 | enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; | |||
| 5682 | ||||
| 5683 | /// Determines whether this expression is an acceptable ICR source. | |||
| 5684 | static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, | |||
| 5685 | bool isAddressOf, bool &isWeakAccess) { | |||
| 5686 | // Skip parens. | |||
| 5687 | e = e->IgnoreParens(); | |||
| 5688 | ||||
| 5689 | // Skip address-of nodes. | |||
| 5690 | if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { | |||
| 5691 | if (op->getOpcode() == UO_AddrOf) | |||
| 5692 | return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true, | |||
| 5693 | isWeakAccess); | |||
| 5694 | ||||
| 5695 | // Skip certain casts. | |||
| 5696 | } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) { | |||
| 5697 | switch (ce->getCastKind()) { | |||
| 5698 | case CK_Dependent: | |||
| 5699 | case CK_BitCast: | |||
| 5700 | case CK_LValueBitCast: | |||
| 5701 | case CK_NoOp: | |||
| 5702 | return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess); | |||
| 5703 | ||||
| 5704 | case CK_ArrayToPointerDecay: | |||
| 5705 | return IIK_nonscalar; | |||
| 5706 | ||||
| 5707 | case CK_NullToPointer: | |||
| 5708 | return IIK_okay; | |||
| 5709 | ||||
| 5710 | default: | |||
| 5711 | break; | |||
| 5712 | } | |||
| 5713 | ||||
| 5714 | // If we have a declaration reference, it had better be a local variable. | |||
| 5715 | } else if (isa<DeclRefExpr>(e)) { | |||
| 5716 | // set isWeakAccess to true, to mean that there will be an implicit | |||
| 5717 | // load which requires a cleanup. | |||
| 5718 | if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak) | |||
| 5719 | isWeakAccess = true; | |||
| 5720 | ||||
| 5721 | if (!isAddressOf) return IIK_nonlocal; | |||
| 5722 | ||||
| 5723 | VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl()); | |||
| 5724 | if (!var) return IIK_nonlocal; | |||
| 5725 | ||||
| 5726 | return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); | |||
| 5727 | ||||
| 5728 | // If we have a conditional operator, check both sides. | |||
| 5729 | } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) { | |||
| 5730 | if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf, | |||
| 5731 | isWeakAccess)) | |||
| 5732 | return iik; | |||
| 5733 | ||||
| 5734 | return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess); | |||
| 5735 | ||||
| 5736 | // These are never scalar. | |||
| 5737 | } else if (isa<ArraySubscriptExpr>(e)) { | |||
| 5738 | return IIK_nonscalar; | |||
| 5739 | ||||
| 5740 | // Otherwise, it needs to be a null pointer constant. | |||
| 5741 | } else { | |||
| 5742 | return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull) | |||
| 5743 | ? IIK_okay : IIK_nonlocal); | |||
| 5744 | } | |||
| 5745 | ||||
| 5746 | return IIK_nonlocal; | |||
| 5747 | } | |||
| 5748 | ||||
| 5749 | /// Check whether the given expression is a valid operand for an | |||
| 5750 | /// indirect copy/restore. | |||
| 5751 | static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { | |||
| 5752 | assert(src->isPRValue())(static_cast <bool> (src->isPRValue()) ? void (0) : __assert_fail ("src->isPRValue()", "clang/lib/Sema/SemaInit.cpp", 5752, __extension__ __PRETTY_FUNCTION__)); | |||
| 5753 | bool isWeakAccess = false; | |||
| 5754 | InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess); | |||
| 5755 | // If isWeakAccess to true, there will be an implicit | |||
| 5756 | // load which requires a cleanup. | |||
| 5757 | if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess) | |||
| 5758 | S.Cleanup.setExprNeedsCleanups(true); | |||
| 5759 | ||||
| 5760 | if (iik == IIK_okay) return; | |||
| 5761 | ||||
| 5762 | S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback) | |||
| 5763 | << ((unsigned) iik - 1) // shift index into diagnostic explanations | |||
| 5764 | << src->getSourceRange(); | |||
| 5765 | } | |||
| 5766 | ||||
| 5767 | /// Determine whether we have compatible array types for the | |||
| 5768 | /// purposes of GNU by-copy array initialization. | |||
| 5769 | static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, | |||
| 5770 | const ArrayType *Source) { | |||
| 5771 | // If the source and destination array types are equivalent, we're | |||
| 5772 | // done. | |||
| 5773 | if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0))) | |||
| 5774 | return true; | |||
| 5775 | ||||
| 5776 | // Make sure that the element types are the same. | |||
| 5777 | if (!Context.hasSameType(Dest->getElementType(), Source->getElementType())) | |||
| 5778 | return false; | |||
| 5779 | ||||
| 5780 | // The only mismatch we allow is when the destination is an | |||
| 5781 | // incomplete array type and the source is a constant array type. | |||
| 5782 | return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); | |||
| 5783 | } | |||
| 5784 | ||||
| 5785 | static bool tryObjCWritebackConversion(Sema &S, | |||
| 5786 | InitializationSequence &Sequence, | |||
| 5787 | const InitializedEntity &Entity, | |||
| 5788 | Expr *Initializer) { | |||
| 5789 | bool ArrayDecay = false; | |||
| 5790 | QualType ArgType = Initializer->getType(); | |||
| 5791 | QualType ArgPointee; | |||
| 5792 | if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) { | |||
| 5793 | ArrayDecay = true; | |||
| 5794 | ArgPointee = ArgArrayType->getElementType(); | |||
| 5795 | ArgType = S.Context.getPointerType(ArgPointee); | |||
| 5796 | } | |||
| 5797 | ||||
| 5798 | // Handle write-back conversion. | |||
| 5799 | QualType ConvertedArgType; | |||
| 5800 | if (!S.isObjCWritebackConversion(ArgType, Entity.getType(), | |||
| 5801 | ConvertedArgType)) | |||
| 5802 | return false; | |||
| 5803 | ||||
| 5804 | // We should copy unless we're passing to an argument explicitly | |||
| 5805 | // marked 'out'. | |||
| 5806 | bool ShouldCopy = true; | |||
| 5807 | if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl())) | |||
| 5808 | ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); | |||
| 5809 | ||||
| 5810 | // Do we need an lvalue conversion? | |||
| 5811 | if (ArrayDecay || Initializer->isGLValue()) { | |||
| 5812 | ImplicitConversionSequence ICS; | |||
| 5813 | ICS.setStandard(); | |||
| 5814 | ICS.Standard.setAsIdentityConversion(); | |||
| 5815 | ||||
| 5816 | QualType ResultType; | |||
| 5817 | if (ArrayDecay) { | |||
| 5818 | ICS.Standard.First = ICK_Array_To_Pointer; | |||
| 5819 | ResultType = S.Context.getPointerType(ArgPointee); | |||
| 5820 | } else { | |||
| 5821 | ICS.Standard.First = ICK_Lvalue_To_Rvalue; | |||
| 5822 | ResultType = Initializer->getType().getNonLValueExprType(S.Context); | |||
| 5823 | } | |||
| 5824 | ||||
| 5825 | Sequence.AddConversionSequenceStep(ICS, ResultType); | |||
| 5826 | } | |||
| 5827 | ||||
| 5828 | Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); | |||
| 5829 | return true; | |||
| 5830 | } | |||
| 5831 | ||||
| 5832 | static bool TryOCLSamplerInitialization(Sema &S, | |||
| 5833 | InitializationSequence &Sequence, | |||
| 5834 | QualType DestType, | |||
| 5835 | Expr *Initializer) { | |||
| 5836 | if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() || | |||
| 5837 | (!Initializer->isIntegerConstantExpr(S.Context) && | |||
| 5838 | !Initializer->getType()->isSamplerT())) | |||
| 5839 | return false; | |||
| 5840 | ||||
| 5841 | Sequence.AddOCLSamplerInitStep(DestType); | |||
| 5842 | return true; | |||
| 5843 | } | |||
| 5844 | ||||
| 5845 | static bool IsZeroInitializer(Expr *Initializer, Sema &S) { | |||
| 5846 | return Initializer->isIntegerConstantExpr(S.getASTContext()) && | |||
| 5847 | (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0); | |||
| 5848 | } | |||
| 5849 | ||||
| 5850 | static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, | |||
| 5851 | InitializationSequence &Sequence, | |||
| 5852 | QualType DestType, | |||
| 5853 | Expr *Initializer) { | |||
| 5854 | if (!S.getLangOpts().OpenCL) | |||
| 5855 | return false; | |||
| 5856 | ||||
| 5857 | // | |||
| 5858 | // OpenCL 1.2 spec, s6.12.10 | |||
| 5859 | // | |||
| 5860 | // The event argument can also be used to associate the | |||
| 5861 | // async_work_group_copy with a previous async copy allowing | |||
| 5862 | // an event to be shared by multiple async copies; otherwise | |||
| 5863 | // event should be zero. | |||
| 5864 | // | |||
| 5865 | if (DestType->isEventT() || DestType->isQueueT()) { | |||
| 5866 | if (!IsZeroInitializer(Initializer, S)) | |||
| 5867 | return false; | |||
| 5868 | ||||
| 5869 | Sequence.AddOCLZeroOpaqueTypeStep(DestType); | |||
| 5870 | return true; | |||
| 5871 | } | |||
| 5872 | ||||
| 5873 | // We should allow zero initialization for all types defined in the | |||
| 5874 | // cl_intel_device_side_avc_motion_estimation extension, except | |||
| 5875 | // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t. | |||
| 5876 | if (S.getOpenCLOptions().isAvailableOption( | |||
| 5877 | "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) && | |||
| 5878 | DestType->isOCLIntelSubgroupAVCType()) { | |||
| 5879 | if (DestType->isOCLIntelSubgroupAVCMcePayloadType() || | |||
| 5880 | DestType->isOCLIntelSubgroupAVCMceResultType()) | |||
| 5881 | return false; | |||
| 5882 | if (!IsZeroInitializer(Initializer, S)) | |||
| 5883 | return false; | |||
| 5884 | ||||
| 5885 | Sequence.AddOCLZeroOpaqueTypeStep(DestType); | |||
| 5886 | return true; | |||
| 5887 | } | |||
| 5888 | ||||
| 5889 | return false; | |||
| 5890 | } | |||
| 5891 | ||||
| 5892 | InitializationSequence::InitializationSequence( | |||
| 5893 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, | |||
| 5894 | MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid) | |||
| 5895 | : FailedOverloadResult(OR_Success), | |||
| 5896 | FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) { | |||
| 5897 | InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList, | |||
| 5898 | TreatUnavailableAsInvalid); | |||
| 5899 | } | |||
| 5900 | ||||
| 5901 | /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the | |||
| 5902 | /// address of that function, this returns true. Otherwise, it returns false. | |||
| 5903 | static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) { | |||
| 5904 | auto *DRE = dyn_cast<DeclRefExpr>(E); | |||
| 5905 | if (!DRE || !isa<FunctionDecl>(DRE->getDecl())) | |||
| 5906 | return false; | |||
| 5907 | ||||
| 5908 | return !S.checkAddressOfFunctionIsAvailable( | |||
| 5909 | cast<FunctionDecl>(DRE->getDecl())); | |||
| 5910 | } | |||
| 5911 | ||||
| 5912 | /// Determine whether we can perform an elementwise array copy for this kind | |||
| 5913 | /// of entity. | |||
| 5914 | static bool canPerformArrayCopy(const InitializedEntity &Entity) { | |||
| 5915 | switch (Entity.getKind()) { | |||
| 5916 | case InitializedEntity::EK_LambdaCapture: | |||
| 5917 | // C++ [expr.prim.lambda]p24: | |||
| 5918 | // For array members, the array elements are direct-initialized in | |||
| 5919 | // increasing subscript order. | |||
| 5920 | return true; | |||
| 5921 | ||||
| 5922 | case InitializedEntity::EK_Variable: | |||
| 5923 | // C++ [dcl.decomp]p1: | |||
| 5924 | // [...] each element is copy-initialized or direct-initialized from the | |||
| 5925 | // corresponding element of the assignment-expression [...] | |||
| 5926 | return isa<DecompositionDecl>(Entity.getDecl()); | |||
| 5927 | ||||
| 5928 | case InitializedEntity::EK_Member: | |||
| 5929 | // C++ [class.copy.ctor]p14: | |||
| 5930 | // - if the member is an array, each element is direct-initialized with | |||
| 5931 | // the corresponding subobject of x | |||
| 5932 | return Entity.isImplicitMemberInitializer(); | |||
| 5933 | ||||
| 5934 | case InitializedEntity::EK_ArrayElement: | |||
| 5935 | // All the above cases are intended to apply recursively, even though none | |||
| 5936 | // of them actually say that. | |||
| 5937 | if (auto *E = Entity.getParent()) | |||
| 5938 | return canPerformArrayCopy(*E); | |||
| 5939 | break; | |||
| 5940 | ||||
| 5941 | default: | |||
| 5942 | break; | |||
| 5943 | } | |||
| 5944 | ||||
| 5945 | return false; | |||
| 5946 | } | |||
| 5947 | ||||
| 5948 | void InitializationSequence::InitializeFrom(Sema &S, | |||
| 5949 | const InitializedEntity &Entity, | |||
| 5950 | const InitializationKind &Kind, | |||
| 5951 | MultiExprArg Args, | |||
| 5952 | bool TopLevelOfInitList, | |||
| 5953 | bool TreatUnavailableAsInvalid) { | |||
| 5954 | ASTContext &Context = S.Context; | |||
| 5955 | ||||
| 5956 | // Eliminate non-overload placeholder types in the arguments. We | |||
| 5957 | // need to do this before checking whether types are dependent | |||
| 5958 | // because lowering a pseudo-object expression might well give us | |||
| 5959 | // something of dependent type. | |||
| 5960 | for (unsigned I = 0, E = Args.size(); I != E; ++I) | |||
| 5961 | if (Args[I]->getType()->isNonOverloadPlaceholderType()) { | |||
| 5962 | // FIXME: should we be doing this here? | |||
| 5963 | ExprResult result = S.CheckPlaceholderExpr(Args[I]); | |||
| 5964 | if (result.isInvalid()) { | |||
| 5965 | SetFailed(FK_PlaceholderType); | |||
| 5966 | return; | |||
| 5967 | } | |||
| 5968 | Args[I] = result.get(); | |||
| 5969 | } | |||
| 5970 | ||||
| 5971 | // C++0x [dcl.init]p16: | |||
| 5972 | // The semantics of initializers are as follows. The destination type is | |||
| 5973 | // the type of the object or reference being initialized and the source | |||
| 5974 | // type is the type of the initializer expression. The source type is not | |||
| 5975 | // defined when the initializer is a braced-init-list or when it is a | |||
| 5976 | // parenthesized list of expressions. | |||
| 5977 | QualType DestType = Entity.getType(); | |||
| 5978 | ||||
| 5979 | if (DestType->isDependentType() || | |||
| 5980 | Expr::hasAnyTypeDependentArguments(Args)) { | |||
| 5981 | SequenceKind = DependentSequence; | |||
| 5982 | return; | |||
| 5983 | } | |||
| 5984 | ||||
| 5985 | // Almost everything is a normal sequence. | |||
| 5986 | setSequenceKind(NormalSequence); | |||
| 5987 | ||||
| 5988 | QualType SourceType; | |||
| 5989 | Expr *Initializer = nullptr; | |||
| 5990 | if (Args.size() == 1) { | |||
| 5991 | Initializer = Args[0]; | |||
| 5992 | if (S.getLangOpts().ObjC) { | |||
| 5993 | if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(), | |||
| 5994 | DestType, Initializer->getType(), | |||
| 5995 | Initializer) || | |||
| 5996 | S.CheckConversionToObjCLiteral(DestType, Initializer)) | |||
| 5997 | Args[0] = Initializer; | |||
| 5998 | } | |||
| 5999 | if (!isa<InitListExpr>(Initializer)) | |||
| 6000 | SourceType = Initializer->getType(); | |||
| 6001 | } | |||
| 6002 | ||||
| 6003 | // - If the initializer is a (non-parenthesized) braced-init-list, the | |||
| 6004 | // object is list-initialized (8.5.4). | |||
| 6005 | if (Kind.getKind() != InitializationKind::IK_Direct) { | |||
| 6006 | if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { | |||
| 6007 | TryListInitialization(S, Entity, Kind, InitList, *this, | |||
| 6008 | TreatUnavailableAsInvalid); | |||
| 6009 | return; | |||
| 6010 | } | |||
| 6011 | } | |||
| 6012 | ||||
| 6013 | // - If the destination type is a reference type, see 8.5.3. | |||
| 6014 | if (DestType->isReferenceType()) { | |||
| 6015 | // C++0x [dcl.init.ref]p1: | |||
| 6016 | // A variable declared to be a T& or T&&, that is, "reference to type T" | |||
| 6017 | // (8.3.2), shall be initialized by an object, or function, of type T or | |||
| 6018 | // by an object that can be converted into a T. | |||
| 6019 | // (Therefore, multiple arguments are not permitted.) | |||
| 6020 | if (Args.size() != 1) | |||
| 6021 | SetFailed(FK_TooManyInitsForReference); | |||
| 6022 | // C++17 [dcl.init.ref]p5: | |||
| 6023 | // A reference [...] is initialized by an expression [...] as follows: | |||
| 6024 | // If the initializer is not an expression, presumably we should reject, | |||
| 6025 | // but the standard fails to actually say so. | |||
| 6026 | else if (isa<InitListExpr>(Args[0])) | |||
| 6027 | SetFailed(FK_ParenthesizedListInitForReference); | |||
| 6028 | else | |||
| 6029 | TryReferenceInitialization(S, Entity, Kind, Args[0], *this); | |||
| 6030 | return; | |||
| 6031 | } | |||
| 6032 | ||||
| 6033 | // - If the initializer is (), the object is value-initialized. | |||
| 6034 | if (Kind.getKind() == InitializationKind::IK_Value || | |||
| 6035 | (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) { | |||
| 6036 | TryValueInitialization(S, Entity, Kind, *this); | |||
| 6037 | return; | |||
| 6038 | } | |||
| 6039 | ||||
| 6040 | // Handle default initialization. | |||
| 6041 | if (Kind.getKind() == InitializationKind::IK_Default) { | |||
| 6042 | TryDefaultInitialization(S, Entity, Kind, *this); | |||
| 6043 | return; | |||
| 6044 | } | |||
| 6045 | ||||
| 6046 | // - If the destination type is an array of characters, an array of | |||
| 6047 | // char16_t, an array of char32_t, or an array of wchar_t, and the | |||
| 6048 | // initializer is a string literal, see 8.5.2. | |||
| 6049 | // - Otherwise, if the destination type is an array, the program is | |||
| 6050 | // ill-formed. | |||
| 6051 | if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) { | |||
| 6052 | if (Initializer && isa<VariableArrayType>(DestAT)) { | |||
| 6053 | SetFailed(FK_VariableLengthArrayHasInitializer); | |||
| 6054 | return; | |||
| 6055 | } | |||
| 6056 | ||||
| 6057 | if (Initializer) { | |||
| 6058 | switch (IsStringInit(Initializer, DestAT, Context)) { | |||
| 6059 | case SIF_None: | |||
| 6060 | TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); | |||
| 6061 | return; | |||
| 6062 | case SIF_NarrowStringIntoWideChar: | |||
| 6063 | SetFailed(FK_NarrowStringIntoWideCharArray); | |||
| 6064 | return; | |||
| 6065 | case SIF_WideStringIntoChar: | |||
| 6066 | SetFailed(FK_WideStringIntoCharArray); | |||
| 6067 | return; | |||
| 6068 | case SIF_IncompatWideStringIntoWideChar: | |||
| 6069 | SetFailed(FK_IncompatWideStringIntoWideChar); | |||
| 6070 | return; | |||
| 6071 | case SIF_PlainStringIntoUTF8Char: | |||
| 6072 | SetFailed(FK_PlainStringIntoUTF8Char); | |||
| 6073 | return; | |||
| 6074 | case SIF_UTF8StringIntoPlainChar: | |||
| 6075 | SetFailed(FK_UTF8StringIntoPlainChar); | |||
| 6076 | return; | |||
| 6077 | case SIF_Other: | |||
| 6078 | break; | |||
| 6079 | } | |||
| 6080 | } | |||
| 6081 | ||||
| 6082 | // Some kinds of initialization permit an array to be initialized from | |||
| 6083 | // another array of the same type, and perform elementwise initialization. | |||
| 6084 | if (Initializer && isa<ConstantArrayType>(DestAT) && | |||
| 6085 | S.Context.hasSameUnqualifiedType(Initializer->getType(), | |||
| 6086 | Entity.getType()) && | |||
| 6087 | canPerformArrayCopy(Entity)) { | |||
| 6088 | // If source is a prvalue, use it directly. | |||
| 6089 | if (Initializer->isPRValue()) { | |||
| 6090 | AddArrayInitStep(DestType, /*IsGNUExtension*/false); | |||
| 6091 | return; | |||
| 6092 | } | |||
| 6093 | ||||
| 6094 | // Emit element-at-a-time copy loop. | |||
| 6095 | InitializedEntity Element = | |||
| 6096 | InitializedEntity::InitializeElement(S.Context, 0, Entity); | |||
| 6097 | QualType InitEltT = | |||
| 6098 | Context.getAsArrayType(Initializer->getType())->getElementType(); | |||
| 6099 | OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT, | |||
| 6100 | Initializer->getValueKind(), | |||
| 6101 | Initializer->getObjectKind()); | |||
| 6102 | Expr *OVEAsExpr = &OVE; | |||
| 6103 | InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList, | |||
| 6104 | TreatUnavailableAsInvalid); | |||
| 6105 | if (!Failed()) | |||
| 6106 | AddArrayInitLoopStep(Entity.getType(), InitEltT); | |||
| 6107 | return; | |||
| 6108 | } | |||
| 6109 | ||||
| 6110 | // Note: as an GNU C extension, we allow initialization of an | |||
| 6111 | // array from a compound literal that creates an array of the same | |||
| 6112 | // type, so long as the initializer has no side effects. | |||
| 6113 | if (!S.getLangOpts().CPlusPlus && Initializer && | |||
| 6114 | isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) && | |||
| 6115 | Initializer->getType()->isArrayType()) { | |||
| 6116 | const ArrayType *SourceAT | |||
| 6117 | = Context.getAsArrayType(Initializer->getType()); | |||
| 6118 | if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT)) | |||
| 6119 | SetFailed(FK_ArrayTypeMismatch); | |||
| 6120 | else if (Initializer->HasSideEffects(S.Context)) | |||
| 6121 | SetFailed(FK_NonConstantArrayInit); | |||
| 6122 | else { | |||
| 6123 | AddArrayInitStep(DestType, /*IsGNUExtension*/true); | |||
| 6124 | } | |||
| 6125 | } | |||
| 6126 | // Note: as a GNU C++ extension, we allow list-initialization of a | |||
| 6127 | // class member of array type from a parenthesized initializer list. | |||
| 6128 | else if (S.getLangOpts().CPlusPlus && | |||
| 6129 | Entity.getKind() == InitializedEntity::EK_Member && | |||
| 6130 | Initializer && isa<InitListExpr>(Initializer)) { | |||
| 6131 | TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer), | |||
| 6132 | *this, TreatUnavailableAsInvalid); | |||
| 6133 | AddParenthesizedArrayInitStep(DestType); | |||
| 6134 | } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList && | |||
| 6135 | Kind.getKind() == InitializationKind::IK_Direct) | |||
| 6136 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this, | |||
| 6137 | /*VerifyOnly=*/true); | |||
| 6138 | else if (DestAT->getElementType()->isCharType()) | |||
| 6139 | SetFailed(FK_ArrayNeedsInitListOrStringLiteral); | |||
| 6140 | else if (IsWideCharCompatible(DestAT->getElementType(), Context)) | |||
| 6141 | SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral); | |||
| 6142 | else | |||
| 6143 | SetFailed(FK_ArrayNeedsInitList); | |||
| 6144 | ||||
| 6145 | return; | |||
| 6146 | } | |||
| 6147 | ||||
| 6148 | // Determine whether we should consider writeback conversions for | |||
| 6149 | // Objective-C ARC. | |||
| 6150 | bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount && | |||
| 6151 | Entity.isParameterKind(); | |||
| 6152 | ||||
| 6153 | if (TryOCLSamplerInitialization(S, *this, DestType, Initializer)) | |||
| 6154 | return; | |||
| 6155 | ||||
| 6156 | // We're at the end of the line for C: it's either a write-back conversion | |||
| 6157 | // or it's a C assignment. There's no need to check anything else. | |||
| 6158 | if (!S.getLangOpts().CPlusPlus) { | |||
| 6159 | // If allowed, check whether this is an Objective-C writeback conversion. | |||
| 6160 | if (allowObjCWritebackConversion && | |||
| 6161 | tryObjCWritebackConversion(S, *this, Entity, Initializer)) { | |||
| 6162 | return; | |||
| 6163 | } | |||
| 6164 | ||||
| 6165 | if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer)) | |||
| 6166 | return; | |||
| 6167 | ||||
| 6168 | // Handle initialization in C | |||
| 6169 | AddCAssignmentStep(DestType); | |||
| 6170 | MaybeProduceObjCObject(S, *this, Entity); | |||
| 6171 | return; | |||
| 6172 | } | |||
| 6173 | ||||
| 6174 | assert(S.getLangOpts().CPlusPlus)(static_cast <bool> (S.getLangOpts().CPlusPlus) ? void ( 0) : __assert_fail ("S.getLangOpts().CPlusPlus", "clang/lib/Sema/SemaInit.cpp" , 6174, __extension__ __PRETTY_FUNCTION__)); | |||
| 6175 | ||||
| 6176 | // - If the destination type is a (possibly cv-qualified) class type: | |||
| 6177 | if (DestType->isRecordType()) { | |||
| 6178 | // - If the initialization is direct-initialization, or if it is | |||
| 6179 | // copy-initialization where the cv-unqualified version of the | |||
| 6180 | // source type is the same class as, or a derived class of, the | |||
| 6181 | // class of the destination, constructors are considered. [...] | |||
| 6182 | if (Kind.getKind() == InitializationKind::IK_Direct || | |||
| 6183 | (Kind.getKind() == InitializationKind::IK_Copy && | |||
| 6184 | (Context.hasSameUnqualifiedType(SourceType, DestType) || | |||
| 6185 | S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType)))) { | |||
| 6186 | TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType, | |||
| 6187 | *this); | |||
| 6188 | ||||
| 6189 | // We fall back to the "no matching constructor" path if the | |||
| 6190 | // failed candidate set has functions other than the three default | |||
| 6191 | // constructors. For example, conversion function. | |||
| 6192 | if (const auto *RD = | |||
| 6193 | dyn_cast<CXXRecordDecl>(DestType->getAs<RecordType>()->getDecl()); | |||
| 6194 | // In general, we should call isCompleteType for RD to check its | |||
| 6195 | // completeness, we don't call it here as it was already called in the | |||
| 6196 | // above TryConstructorInitialization. | |||
| 6197 | S.getLangOpts().CPlusPlus20 && RD && RD->hasDefinition() && | |||
| 6198 | RD->isAggregate() && Failed() && | |||
| 6199 | getFailureKind() == FK_ConstructorOverloadFailed) { | |||
| 6200 | // Do not attempt paren list initialization if overload resolution | |||
| 6201 | // resolves to a deleted function . | |||
| 6202 | // | |||
| 6203 | // We may reach this condition if we have a union wrapping a class with | |||
| 6204 | // a non-trivial copy or move constructor and we call one of those two | |||
| 6205 | // constructors. The union is an aggregate, but the matched constructor | |||
| 6206 | // is implicitly deleted, so we need to prevent aggregate initialization | |||
| 6207 | // (otherwise, it'll attempt aggregate initialization by initializing | |||
| 6208 | // the first element with a reference to the union). | |||
| 6209 | OverloadCandidateSet::iterator Best; | |||
| 6210 | OverloadingResult OR = getFailedCandidateSet().BestViableFunction( | |||
| 6211 | S, Kind.getLocation(), Best); | |||
| 6212 | if (OR != OverloadingResult::OR_Deleted) { | |||
| 6213 | // C++20 [dcl.init] 17.6.2.2: | |||
| 6214 | // - Otherwise, if no constructor is viable, the destination type is | |||
| 6215 | // an | |||
| 6216 | // aggregate class, and the initializer is a parenthesized | |||
| 6217 | // expression-list. | |||
| 6218 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this, | |||
| 6219 | /*VerifyOnly=*/true); | |||
| 6220 | } | |||
| 6221 | } | |||
| 6222 | } else { | |||
| 6223 | // - Otherwise (i.e., for the remaining copy-initialization cases), | |||
| 6224 | // user-defined conversion sequences that can convert from the | |||
| 6225 | // source type to the destination type or (when a conversion | |||
| 6226 | // function is used) to a derived class thereof are enumerated as | |||
| 6227 | // described in 13.3.1.4, and the best one is chosen through | |||
| 6228 | // overload resolution (13.3). | |||
| 6229 | TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, | |||
| 6230 | TopLevelOfInitList); | |||
| 6231 | } | |||
| 6232 | return; | |||
| 6233 | } | |||
| 6234 | ||||
| 6235 | assert(Args.size() >= 1 && "Zero-argument case handled above")(static_cast <bool> (Args.size() >= 1 && "Zero-argument case handled above" ) ? void (0) : __assert_fail ("Args.size() >= 1 && \"Zero-argument case handled above\"" , "clang/lib/Sema/SemaInit.cpp", 6235, __extension__ __PRETTY_FUNCTION__ )); | |||
| 6236 | ||||
| 6237 | // For HLSL ext vector types we allow list initialization behavior for C++ | |||
| 6238 | // constructor syntax. This is accomplished by converting initialization | |||
| 6239 | // arguments an InitListExpr late. | |||
| 6240 | if (S.getLangOpts().HLSL && DestType->isExtVectorType() && | |||
| 6241 | (SourceType.isNull() || | |||
| 6242 | !Context.hasSameUnqualifiedType(SourceType, DestType))) { | |||
| 6243 | ||||
| 6244 | llvm::SmallVector<Expr *> InitArgs; | |||
| 6245 | for (auto *Arg : Args) { | |||
| 6246 | if (Arg->getType()->isExtVectorType()) { | |||
| 6247 | const auto *VTy = Arg->getType()->castAs<ExtVectorType>(); | |||
| 6248 | unsigned Elm = VTy->getNumElements(); | |||
| 6249 | for (unsigned Idx = 0; Idx < Elm; ++Idx) { | |||
| 6250 | InitArgs.emplace_back(new (Context) ArraySubscriptExpr( | |||
| 6251 | Arg, | |||
| 6252 | IntegerLiteral::Create( | |||
| 6253 | Context, llvm::APInt(Context.getIntWidth(Context.IntTy), Idx), | |||
| 6254 | Context.IntTy, SourceLocation()), | |||
| 6255 | VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(), | |||
| 6256 | SourceLocation())); | |||
| 6257 | } | |||
| 6258 | } else | |||
| 6259 | InitArgs.emplace_back(Arg); | |||
| 6260 | } | |||
| 6261 | InitListExpr *ILE = new (Context) InitListExpr( | |||
| 6262 | S.getASTContext(), SourceLocation(), InitArgs, SourceLocation()); | |||
| 6263 | Args[0] = ILE; | |||
| 6264 | AddListInitializationStep(DestType); | |||
| 6265 | return; | |||
| 6266 | } | |||
| 6267 | ||||
| 6268 | // The remaining cases all need a source type. | |||
| 6269 | if (Args.size() > 1) { | |||
| 6270 | SetFailed(FK_TooManyInitsForScalar); | |||
| 6271 | return; | |||
| 6272 | } else if (isa<InitListExpr>(Args[0])) { | |||
| 6273 | SetFailed(FK_ParenthesizedListInitForScalar); | |||
| 6274 | return; | |||
| 6275 | } | |||
| 6276 | ||||
| 6277 | // - Otherwise, if the source type is a (possibly cv-qualified) class | |||
| 6278 | // type, conversion functions are considered. | |||
| 6279 | if (!SourceType.isNull() && SourceType->isRecordType()) { | |||
| 6280 | // For a conversion to _Atomic(T) from either T or a class type derived | |||
| 6281 | // from T, initialize the T object then convert to _Atomic type. | |||
| 6282 | bool NeedAtomicConversion = false; | |||
| 6283 | if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) { | |||
| 6284 | if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) || | |||
| 6285 | S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, | |||
| 6286 | Atomic->getValueType())) { | |||
| 6287 | DestType = Atomic->getValueType(); | |||
| 6288 | NeedAtomicConversion = true; | |||
| 6289 | } | |||
| 6290 | } | |||
| 6291 | ||||
| 6292 | TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, | |||
| 6293 | TopLevelOfInitList); | |||
| 6294 | MaybeProduceObjCObject(S, *this, Entity); | |||
| 6295 | if (!Failed() && NeedAtomicConversion) | |||
| 6296 | AddAtomicConversionStep(Entity.getType()); | |||
| 6297 | return; | |||
| 6298 | } | |||
| 6299 | ||||
| 6300 | // - Otherwise, if the initialization is direct-initialization, the source | |||
| 6301 | // type is std::nullptr_t, and the destination type is bool, the initial | |||
| 6302 | // value of the object being initialized is false. | |||
| 6303 | if (!SourceType.isNull() && SourceType->isNullPtrType() && | |||
| 6304 | DestType->isBooleanType() && | |||
| 6305 | Kind.getKind() == InitializationKind::IK_Direct) { | |||
| 6306 | AddConversionSequenceStep( | |||
| 6307 | ImplicitConversionSequence::getNullptrToBool(SourceType, DestType, | |||
| 6308 | Initializer->isGLValue()), | |||
| 6309 | DestType); | |||
| 6310 | return; | |||
| 6311 | } | |||
| 6312 | ||||
| 6313 | // - Otherwise, the initial value of the object being initialized is the | |||
| 6314 | // (possibly converted) value of the initializer expression. Standard | |||
| 6315 | // conversions (Clause 4) will be used, if necessary, to convert the | |||
| 6316 | // initializer expression to the cv-unqualified version of the | |||
| 6317 | // destination type; no user-defined conversions are considered. | |||
| 6318 | ||||
| 6319 | ImplicitConversionSequence ICS | |||
| 6320 | = S.TryImplicitConversion(Initializer, DestType, | |||
| 6321 | /*SuppressUserConversions*/true, | |||
| 6322 | Sema::AllowedExplicit::None, | |||
| 6323 | /*InOverloadResolution*/ false, | |||
| 6324 | /*CStyle=*/Kind.isCStyleOrFunctionalCast(), | |||
| 6325 | allowObjCWritebackConversion); | |||
| 6326 | ||||
| 6327 | if (ICS.isStandard() && | |||
| 6328 | ICS.Standard.Second == ICK_Writeback_Conversion) { | |||
| 6329 | // Objective-C ARC writeback conversion. | |||
| 6330 | ||||
| 6331 | // We should copy unless we're passing to an argument explicitly | |||
| 6332 | // marked 'out'. | |||
| 6333 | bool ShouldCopy = true; | |||
| 6334 | if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl())) | |||
| 6335 | ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); | |||
| 6336 | ||||
| 6337 | // If there was an lvalue adjustment, add it as a separate conversion. | |||
| 6338 | if (ICS.Standard.First == ICK_Array_To_Pointer || | |||
| 6339 | ICS.Standard.First == ICK_Lvalue_To_Rvalue) { | |||
| 6340 | ImplicitConversionSequence LvalueICS; | |||
| 6341 | LvalueICS.setStandard(); | |||
| 6342 | LvalueICS.Standard.setAsIdentityConversion(); | |||
| 6343 | LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0)); | |||
| 6344 | LvalueICS.Standard.First = ICS.Standard.First; | |||
| 6345 | AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); | |||
| 6346 | } | |||
| 6347 | ||||
| 6348 | AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy); | |||
| 6349 | } else if (ICS.isBad()) { | |||
| 6350 | DeclAccessPair dap; | |||
| 6351 | if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) { | |||
| 6352 | AddZeroInitializationStep(Entity.getType()); | |||
| 6353 | } else if (Initializer->getType() == Context.OverloadTy && | |||
| 6354 | !S.ResolveAddressOfOverloadedFunction(Initializer, DestType, | |||
| 6355 | false, dap)) | |||
| 6356 | SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); | |||
| 6357 | else if (Initializer->getType()->isFunctionType() && | |||
| 6358 | isExprAnUnaddressableFunction(S, Initializer)) | |||
| 6359 | SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction); | |||
| 6360 | else | |||
| 6361 | SetFailed(InitializationSequence::FK_ConversionFailed); | |||
| 6362 | } else { | |||
| 6363 | AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); | |||
| 6364 | ||||
| 6365 | MaybeProduceObjCObject(S, *this, Entity); | |||
| 6366 | } | |||
| 6367 | } | |||
| 6368 | ||||
| 6369 | InitializationSequence::~InitializationSequence() { | |||
| 6370 | for (auto &S : Steps) | |||
| 6371 | S.Destroy(); | |||
| 6372 | } | |||
| 6373 | ||||
| 6374 | //===----------------------------------------------------------------------===// | |||
| 6375 | // Perform initialization | |||
| 6376 | //===----------------------------------------------------------------------===// | |||
| 6377 | static Sema::AssignmentAction | |||
| 6378 | getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) { | |||
| 6379 | switch(Entity.getKind()) { | |||
| 6380 | case InitializedEntity::EK_Variable: | |||
| 6381 | case InitializedEntity::EK_New: | |||
| 6382 | case InitializedEntity::EK_Exception: | |||
| 6383 | case InitializedEntity::EK_Base: | |||
| 6384 | case InitializedEntity::EK_Delegating: | |||
| 6385 | return Sema::AA_Initializing; | |||
| 6386 | ||||
| 6387 | case InitializedEntity::EK_Parameter: | |||
| 6388 | if (Entity.getDecl() && | |||
| 6389 | isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) | |||
| 6390 | return Sema::AA_Sending; | |||
| 6391 | ||||
| 6392 | return Sema::AA_Passing; | |||
| 6393 | ||||
| 6394 | case InitializedEntity::EK_Parameter_CF_Audited: | |||
| 6395 | if (Entity.getDecl() && | |||
| 6396 | isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) | |||
| 6397 | return Sema::AA_Sending; | |||
| 6398 | ||||
| 6399 | return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited; | |||
| 6400 | ||||
| 6401 | case InitializedEntity::EK_Result: | |||
| 6402 | case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right. | |||
| 6403 | return Sema::AA_Returning; | |||
| 6404 | ||||
| 6405 | case InitializedEntity::EK_Temporary: | |||
| 6406 | case InitializedEntity::EK_RelatedResult: | |||
| 6407 | // FIXME: Can we tell apart casting vs. converting? | |||
| 6408 | return Sema::AA_Casting; | |||
| 6409 | ||||
| 6410 | case InitializedEntity::EK_TemplateParameter: | |||
| 6411 | // This is really initialization, but refer to it as conversion for | |||
| 6412 | // consistency with CheckConvertedConstantExpression. | |||
| 6413 | return Sema::AA_Converting; | |||
| 6414 | ||||
| 6415 | case InitializedEntity::EK_Member: | |||
| 6416 | case InitializedEntity::EK_Binding: | |||
| 6417 | case InitializedEntity::EK_ArrayElement: | |||
| 6418 | case InitializedEntity::EK_VectorElement: | |||
| 6419 | case InitializedEntity::EK_ComplexElement: | |||
| 6420 | case InitializedEntity::EK_BlockElement: | |||
| 6421 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | |||
| 6422 | case InitializedEntity::EK_LambdaCapture: | |||
| 6423 | case InitializedEntity::EK_CompoundLiteralInit: | |||
| 6424 | return Sema::AA_Initializing; | |||
| 6425 | } | |||
| 6426 | ||||
| 6427 | llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp" , 6427); | |||
| 6428 | } | |||
| 6429 | ||||
| 6430 | /// Whether we should bind a created object as a temporary when | |||
| 6431 | /// initializing the given entity. | |||
| 6432 | static bool shouldBindAsTemporary(const InitializedEntity &Entity) { | |||
| 6433 | switch (Entity.getKind()) { | |||
| 6434 | case InitializedEntity::EK_ArrayElement: | |||
| 6435 | case InitializedEntity::EK_Member: | |||
| 6436 | case InitializedEntity::EK_Result: | |||
| 6437 | case InitializedEntity::EK_StmtExprResult: | |||
| 6438 | case InitializedEntity::EK_New: | |||
| 6439 | case InitializedEntity::EK_Variable: | |||
| 6440 | case InitializedEntity::EK_Base: | |||
| 6441 | case InitializedEntity::EK_Delegating: | |||
| 6442 | case InitializedEntity::EK_VectorElement: | |||
| 6443 | case InitializedEntity::EK_ComplexElement: | |||
| 6444 | case InitializedEntity::EK_Exception: | |||
| 6445 | case InitializedEntity::EK_BlockElement: | |||
| 6446 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | |||
| 6447 | case InitializedEntity::EK_LambdaCapture: | |||
| 6448 | case InitializedEntity::EK_CompoundLiteralInit: | |||
| 6449 | case InitializedEntity::EK_TemplateParameter: | |||
| 6450 | return false; | |||
| 6451 | ||||
| 6452 | case InitializedEntity::EK_Parameter: | |||
| 6453 | case InitializedEntity::EK_Parameter_CF_Audited: | |||
| 6454 | case InitializedEntity::EK_Temporary: | |||
| 6455 | case InitializedEntity::EK_RelatedResult: | |||
| 6456 | case InitializedEntity::EK_Binding: | |||
| 6457 | return true; | |||
| 6458 | } | |||
| 6459 | ||||
| 6460 | llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?" , "clang/lib/Sema/SemaInit.cpp", 6460); | |||
| 6461 | } | |||
| 6462 | ||||
| 6463 | /// Whether the given entity, when initialized with an object | |||
| 6464 | /// created for that initialization, requires destruction. | |||
| 6465 | static bool shouldDestroyEntity(const InitializedEntity &Entity) { | |||
| 6466 | switch (Entity.getKind()) { | |||
| 6467 | case InitializedEntity::EK_Result: | |||
| 6468 | case InitializedEntity::EK_StmtExprResult: | |||
| 6469 | case InitializedEntity::EK_New: | |||
| 6470 | case InitializedEntity::EK_Base: | |||
| 6471 | case InitializedEntity::EK_Delegating: | |||
| 6472 | case InitializedEntity::EK_VectorElement: | |||
| 6473 | case InitializedEntity::EK_ComplexElement: | |||
| 6474 | case InitializedEntity::EK_BlockElement: | |||
| 6475 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | |||
| 6476 | case InitializedEntity::EK_LambdaCapture: | |||
| 6477 | return false; | |||
| 6478 | ||||
| 6479 | case InitializedEntity::EK_Member: | |||
| 6480 | case InitializedEntity::EK_Binding: | |||
| 6481 | case InitializedEntity::EK_Variable: | |||
| 6482 | case InitializedEntity::EK_Parameter: | |||
| 6483 | case InitializedEntity::EK_Parameter_CF_Audited: | |||
| 6484 | case InitializedEntity::EK_TemplateParameter: | |||
| 6485 | case InitializedEntity::EK_Temporary: | |||
| 6486 | case InitializedEntity::EK_ArrayElement: | |||
| 6487 | case InitializedEntity::EK_Exception: | |||
| 6488 | case InitializedEntity::EK_CompoundLiteralInit: | |||
| 6489 | case InitializedEntity::EK_RelatedResult: | |||
| 6490 | return true; | |||
| 6491 | } | |||
| 6492 | ||||
| 6493 | llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?" , "clang/lib/Sema/SemaInit.cpp", 6493); | |||
| 6494 | } | |||
| 6495 | ||||
| 6496 | /// Get the location at which initialization diagnostics should appear. | |||
| 6497 | static SourceLocation getInitializationLoc(const InitializedEntity &Entity, | |||
| 6498 | Expr *Initializer) { | |||
| 6499 | switch (Entity.getKind()) { | |||
| 6500 | case InitializedEntity::EK_Result: | |||
| 6501 | case InitializedEntity::EK_StmtExprResult: | |||
| 6502 | return Entity.getReturnLoc(); | |||
| 6503 | ||||
| 6504 | case InitializedEntity::EK_Exception: | |||
| 6505 | return Entity.getThrowLoc(); | |||
| 6506 | ||||
| 6507 | case InitializedEntity::EK_Variable: | |||
| 6508 | case InitializedEntity::EK_Binding: | |||
| 6509 | return Entity.getDecl()->getLocation(); | |||
| 6510 | ||||
| 6511 | case InitializedEntity::EK_LambdaCapture: | |||
| 6512 | return Entity.getCaptureLoc(); | |||
| 6513 | ||||
| 6514 | case InitializedEntity::EK_ArrayElement: | |||
| 6515 | case InitializedEntity::EK_Member: | |||
| 6516 | case InitializedEntity::EK_Parameter: | |||
| 6517 | case InitializedEntity::EK_Parameter_CF_Audited: | |||
| 6518 | case InitializedEntity::EK_TemplateParameter: | |||
| 6519 | case InitializedEntity::EK_Temporary: | |||
| 6520 | case InitializedEntity::EK_New: | |||
| 6521 | case InitializedEntity::EK_Base: | |||
| 6522 | case InitializedEntity::EK_Delegating: | |||
| 6523 | case InitializedEntity::EK_VectorElement: | |||
| 6524 | case InitializedEntity::EK_ComplexElement: | |||
| 6525 | case InitializedEntity::EK_BlockElement: | |||
| 6526 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | |||
| 6527 | case InitializedEntity::EK_CompoundLiteralInit: | |||
| 6528 | case InitializedEntity::EK_RelatedResult: | |||
| 6529 | return Initializer->getBeginLoc(); | |||
| 6530 | } | |||
| 6531 | llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?" , "clang/lib/Sema/SemaInit.cpp", 6531); | |||
| 6532 | } | |||
| 6533 | ||||
| 6534 | /// Make a (potentially elidable) temporary copy of the object | |||
| 6535 | /// provided by the given initializer by calling the appropriate copy | |||
| 6536 | /// constructor. | |||
| 6537 | /// | |||
| 6538 | /// \param S The Sema object used for type-checking. | |||
| 6539 | /// | |||
| 6540 | /// \param T The type of the temporary object, which must either be | |||
| 6541 | /// the type of the initializer expression or a superclass thereof. | |||
| 6542 | /// | |||
| 6543 | /// \param Entity The entity being initialized. | |||
| 6544 | /// | |||
| 6545 | /// \param CurInit The initializer expression. | |||
| 6546 | /// | |||
| 6547 | /// \param IsExtraneousCopy Whether this is an "extraneous" copy that | |||
| 6548 | /// is permitted in C++03 (but not C++0x) when binding a reference to | |||
| 6549 | /// an rvalue. | |||
| 6550 | /// | |||
| 6551 | /// \returns An expression that copies the initializer expression into | |||
| 6552 | /// a temporary object, or an error expression if a copy could not be | |||
| 6553 | /// created. | |||
| 6554 | static ExprResult CopyObject(Sema &S, | |||
| 6555 | QualType T, | |||
| 6556 | const InitializedEntity &Entity, | |||
| 6557 | ExprResult CurInit, | |||
| 6558 | bool IsExtraneousCopy) { | |||
| 6559 | if (CurInit.isInvalid()) | |||
| 6560 | return CurInit; | |||
| 6561 | // Determine which class type we're copying to. | |||
| 6562 | Expr *CurInitExpr = (Expr *)CurInit.get(); | |||
| 6563 | CXXRecordDecl *Class = nullptr; | |||
| 6564 | if (const RecordType *Record = T->getAs<RecordType>()) | |||
| 6565 | Class = cast<CXXRecordDecl>(Record->getDecl()); | |||
| 6566 | if (!Class) | |||
| 6567 | return CurInit; | |||
| 6568 | ||||
| 6569 | SourceLocation Loc = getInitializationLoc(Entity, CurInit.get()); | |||
| 6570 | ||||
| 6571 | // Make sure that the type we are copying is complete. | |||
| 6572 | if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete)) | |||
| 6573 | return CurInit; | |||
| 6574 | ||||
| 6575 | // Perform overload resolution using the class's constructors. Per | |||
| 6576 | // C++11 [dcl.init]p16, second bullet for class types, this initialization | |||
| 6577 | // is direct-initialization. | |||
| 6578 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); | |||
| 6579 | DeclContext::lookup_result Ctors = S.LookupConstructors(Class); | |||
| 6580 | ||||
| 6581 | OverloadCandidateSet::iterator Best; | |||
| 6582 | switch (ResolveConstructorOverload( | |||
| 6583 | S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best, | |||
| 6584 | /*CopyInitializing=*/false, /*AllowExplicit=*/true, | |||
| 6585 | /*OnlyListConstructors=*/false, /*IsListInit=*/false, | |||
| 6586 | /*SecondStepOfCopyInit=*/true)) { | |||
| 6587 | case OR_Success: | |||
| 6588 | break; | |||
| 6589 | ||||
| 6590 | case OR_No_Viable_Function: | |||
| 6591 | CandidateSet.NoteCandidates( | |||
| 6592 | PartialDiagnosticAt( | |||
| 6593 | Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext() | |||
| 6594 | ? diag::ext_rvalue_to_reference_temp_copy_no_viable | |||
| 6595 | : diag::err_temp_copy_no_viable) | |||
| 6596 | << (int)Entity.getKind() << CurInitExpr->getType() | |||
| 6597 | << CurInitExpr->getSourceRange()), | |||
| 6598 | S, OCD_AllCandidates, CurInitExpr); | |||
| 6599 | if (!IsExtraneousCopy || S.isSFINAEContext()) | |||
| 6600 | return ExprError(); | |||
| 6601 | return CurInit; | |||
| 6602 | ||||
| 6603 | case OR_Ambiguous: | |||
| 6604 | CandidateSet.NoteCandidates( | |||
| 6605 | PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous) | |||
| 6606 | << (int)Entity.getKind() | |||
| 6607 | << CurInitExpr->getType() | |||
| 6608 | << CurInitExpr->getSourceRange()), | |||
| 6609 | S, OCD_AmbiguousCandidates, CurInitExpr); | |||
| 6610 | return ExprError(); | |||
| 6611 | ||||
| 6612 | case OR_Deleted: | |||
| 6613 | S.Diag(Loc, diag::err_temp_copy_deleted) | |||
| 6614 | << (int)Entity.getKind() << CurInitExpr->getType() | |||
| 6615 | << CurInitExpr->getSourceRange(); | |||
| 6616 | S.NoteDeletedFunction(Best->Function); | |||
| 6617 | return ExprError(); | |||
| 6618 | } | |||
| 6619 | ||||
| 6620 | bool HadMultipleCandidates = CandidateSet.size() > 1; | |||
| 6621 | ||||
| 6622 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); | |||
| 6623 | SmallVector<Expr*, 8> ConstructorArgs; | |||
| 6624 | CurInit.get(); // Ownership transferred into MultiExprArg, below. | |||
| 6625 | ||||
| 6626 | S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity, | |||
| 6627 | IsExtraneousCopy); | |||
| 6628 | ||||
| 6629 | if (IsExtraneousCopy) { | |||
| 6630 | // If this is a totally extraneous copy for C++03 reference | |||
| 6631 | // binding purposes, just return the original initialization | |||
| 6632 | // expression. We don't generate an (elided) copy operation here | |||
| 6633 | // because doing so would require us to pass down a flag to avoid | |||
| 6634 | // infinite recursion, where each step adds another extraneous, | |||
| 6635 | // elidable copy. | |||
| 6636 | ||||
| 6637 | // Instantiate the default arguments of any extra parameters in | |||
| 6638 | // the selected copy constructor, as if we were going to create a | |||
| 6639 | // proper call to the copy constructor. | |||
| 6640 | for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { | |||
| 6641 | ParmVarDecl *Parm = Constructor->getParamDecl(I); | |||
| 6642 | if (S.RequireCompleteType(Loc, Parm->getType(), | |||
| 6643 | diag::err_call_incomplete_argument)) | |||
| 6644 | break; | |||
| 6645 | ||||
| 6646 | // Build the default argument expression; we don't actually care | |||
| 6647 | // if this succeeds or not, because this routine will complain | |||
| 6648 | // if there was a problem. | |||
| 6649 | S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); | |||
| 6650 | } | |||
| 6651 | ||||
| 6652 | return CurInitExpr; | |||
| 6653 | } | |||
| 6654 | ||||
| 6655 | // Determine the arguments required to actually perform the | |||
| 6656 | // constructor call (we might have derived-to-base conversions, or | |||
| 6657 | // the copy constructor may have default arguments). | |||
| 6658 | if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc, | |||
| 6659 | ConstructorArgs)) | |||
| 6660 | return ExprError(); | |||
| 6661 | ||||
| 6662 | // C++0x [class.copy]p32: | |||
| 6663 | // When certain criteria are met, an implementation is allowed to | |||
| 6664 | // omit the copy/move construction of a class object, even if the | |||
| 6665 | // copy/move constructor and/or destructor for the object have | |||
| 6666 | // side effects. [...] | |||
| 6667 | // - when a temporary class object that has not been bound to a | |||
| 6668 | // reference (12.2) would be copied/moved to a class object | |||
| 6669 | // with the same cv-unqualified type, the copy/move operation | |||
| 6670 | // can be omitted by constructing the temporary object | |||
| 6671 | // directly into the target of the omitted copy/move | |||
| 6672 | // | |||
| 6673 | // Note that the other three bullets are handled elsewhere. Copy | |||
| 6674 | // elision for return statements and throw expressions are handled as part | |||
| 6675 | // of constructor initialization, while copy elision for exception handlers | |||
| 6676 | // is handled by the run-time. | |||
| 6677 | // | |||
| 6678 | // FIXME: If the function parameter is not the same type as the temporary, we | |||
| 6679 | // should still be able to elide the copy, but we don't have a way to | |||
| 6680 | // represent in the AST how much should be elided in this case. | |||
| 6681 | bool Elidable = | |||
| 6682 | CurInitExpr->isTemporaryObject(S.Context, Class) && | |||
| 6683 | S.Context.hasSameUnqualifiedType( | |||
| 6684 | Best->Function->getParamDecl(0)->getType().getNonReferenceType(), | |||
| 6685 | CurInitExpr->getType()); | |||
| 6686 | ||||
| 6687 | // Actually perform the constructor call. | |||
| 6688 | CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor, | |||
| 6689 | Elidable, | |||
| 6690 | ConstructorArgs, | |||
| 6691 | HadMultipleCandidates, | |||
| 6692 | /*ListInit*/ false, | |||
| 6693 | /*StdInitListInit*/ false, | |||
| 6694 | /*ZeroInit*/ false, | |||
| 6695 | CXXConstructExpr::CK_Complete, | |||
| 6696 | SourceRange()); | |||
| 6697 | ||||
| 6698 | // If we're supposed to bind temporaries, do so. | |||
| 6699 | if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) | |||
| 6700 | CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); | |||
| 6701 | return CurInit; | |||
| 6702 | } | |||
| 6703 | ||||
| 6704 | /// Check whether elidable copy construction for binding a reference to | |||
| 6705 | /// a temporary would have succeeded if we were building in C++98 mode, for | |||
| 6706 | /// -Wc++98-compat. | |||
| 6707 | static void CheckCXX98CompatAccessibleCopy(Sema &S, | |||
| 6708 | const InitializedEntity &Entity, | |||
| 6709 | Expr *CurInitExpr) { | |||
| 6710 | assert(S.getLangOpts().CPlusPlus11)(static_cast <bool> (S.getLangOpts().CPlusPlus11) ? void (0) : __assert_fail ("S.getLangOpts().CPlusPlus11", "clang/lib/Sema/SemaInit.cpp" , 6710, __extension__ __PRETTY_FUNCTION__)); | |||
| 6711 | ||||
| 6712 | const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>(); | |||
| 6713 | if (!Record) | |||
| 6714 | return; | |||
| 6715 | ||||
| 6716 | SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr); | |||
| 6717 | if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc)) | |||
| 6718 | return; | |||
| 6719 | ||||
| 6720 | // Find constructors which would have been considered. | |||
| 6721 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); | |||
| 6722 | DeclContext::lookup_result Ctors = | |||
| 6723 | S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl())); | |||
| 6724 | ||||
| 6725 | // Perform overload resolution. | |||
| 6726 | OverloadCandidateSet::iterator Best; | |||
| 6727 | OverloadingResult OR = ResolveConstructorOverload( | |||
| 6728 | S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best, | |||
| 6729 | /*CopyInitializing=*/false, /*AllowExplicit=*/true, | |||
| 6730 | /*OnlyListConstructors=*/false, /*IsListInit=*/false, | |||
| 6731 | /*SecondStepOfCopyInit=*/true); | |||
| 6732 | ||||
| 6733 | PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy) | |||
| 6734 | << OR << (int)Entity.getKind() << CurInitExpr->getType() | |||
| 6735 | << CurInitExpr->getSourceRange(); | |||
| 6736 | ||||
| 6737 | switch (OR) { | |||
| 6738 | case OR_Success: | |||
| 6739 | S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function), | |||
| 6740 | Best->FoundDecl, Entity, Diag); | |||
| 6741 | // FIXME: Check default arguments as far as that's possible. | |||
| 6742 | break; | |||
| 6743 | ||||
| 6744 | case OR_No_Viable_Function: | |||
| 6745 | CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, | |||
| 6746 | OCD_AllCandidates, CurInitExpr); | |||
| 6747 | break; | |||
| 6748 | ||||
| 6749 | case OR_Ambiguous: | |||
| 6750 | CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, | |||
| 6751 | OCD_AmbiguousCandidates, CurInitExpr); | |||
| 6752 | break; | |||
| 6753 | ||||
| 6754 | case OR_Deleted: | |||
| 6755 | S.Diag(Loc, Diag); | |||
| 6756 | S.NoteDeletedFunction(Best->Function); | |||
| 6757 | break; | |||
| 6758 | } | |||
| 6759 | } | |||
| 6760 | ||||
| 6761 | void InitializationSequence::PrintInitLocationNote(Sema &S, | |||
| 6762 | const InitializedEntity &Entity) { | |||
| 6763 | if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) { | |||
| 6764 | if (Entity.getDecl()->getLocation().isInvalid()) | |||
| 6765 | return; | |||
| 6766 | ||||
| 6767 | if (Entity.getDecl()->getDeclName()) | |||
| 6768 | S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) | |||
| 6769 | << Entity.getDecl()->getDeclName(); | |||
| 6770 | else | |||
| 6771 | S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); | |||
| 6772 | } | |||
| 6773 | else if (Entity.getKind() == InitializedEntity::EK_RelatedResult && | |||
| 6774 | Entity.getMethodDecl()) | |||
| 6775 | S.Diag(Entity.getMethodDecl()->getLocation(), | |||
| 6776 | diag::note_method_return_type_change) | |||
| 6777 | << Entity.getMethodDecl()->getDeclName(); | |||
| 6778 | } | |||
| 6779 | ||||
| 6780 | /// Returns true if the parameters describe a constructor initialization of | |||
| 6781 | /// an explicit temporary object, e.g. "Point(x, y)". | |||
| 6782 | static bool isExplicitTemporary(const InitializedEntity &Entity, | |||
| 6783 | const InitializationKind &Kind, | |||
| 6784 | unsigned NumArgs) { | |||
| 6785 | switch (Entity.getKind()) { | |||
| 6786 | case InitializedEntity::EK_Temporary: | |||
| 6787 | case InitializedEntity::EK_CompoundLiteralInit: | |||
| 6788 | case InitializedEntity::EK_RelatedResult: | |||
| 6789 | break; | |||
| 6790 | default: | |||
| 6791 | return false; | |||
| 6792 | } | |||
| 6793 | ||||
| 6794 | switch (Kind.getKind()) { | |||
| 6795 | case InitializationKind::IK_DirectList: | |||
| 6796 | return true; | |||
| 6797 | // FIXME: Hack to work around cast weirdness. | |||
| 6798 | case InitializationKind::IK_Direct: | |||
| 6799 | case InitializationKind::IK_Value: | |||
| 6800 | return NumArgs != 1; | |||
| 6801 | default: | |||
| 6802 | return false; | |||
| 6803 | } | |||
| 6804 | } | |||
| 6805 | ||||
| 6806 | static ExprResult | |||
| 6807 | PerformConstructorInitialization(Sema &S, | |||
| 6808 | const InitializedEntity &Entity, | |||
| 6809 | const InitializationKind &Kind, | |||
| 6810 | MultiExprArg Args, | |||
| 6811 | const InitializationSequence::Step& Step, | |||
| 6812 | bool &ConstructorInitRequiresZeroInit, | |||
| 6813 | bool IsListInitialization, | |||
| 6814 | bool IsStdInitListInitialization, | |||
| 6815 | SourceLocation LBraceLoc, | |||
| 6816 | SourceLocation RBraceLoc) { | |||
| 6817 | unsigned NumArgs = Args.size(); | |||
| 6818 | CXXConstructorDecl *Constructor | |||
| 6819 | = cast<CXXConstructorDecl>(Step.Function.Function); | |||
| 6820 | bool HadMultipleCandidates = Step.Function.HadMultipleCandidates; | |||
| 6821 | ||||
| 6822 | // Build a call to the selected constructor. | |||
| 6823 | SmallVector<Expr*, 8> ConstructorArgs; | |||
| 6824 | SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) | |||
| 6825 | ? Kind.getEqualLoc() | |||
| 6826 | : Kind.getLocation(); | |||
| 6827 | ||||
| 6828 | if (Kind.getKind() == InitializationKind::IK_Default) { | |||
| 6829 | // Force even a trivial, implicit default constructor to be | |||
| 6830 | // semantically checked. We do this explicitly because we don't build | |||
| 6831 | // the definition for completely trivial constructors. | |||
| 6832 | assert(Constructor->getParent() && "No parent class for constructor.")(static_cast <bool> (Constructor->getParent() && "No parent class for constructor.") ? void (0) : __assert_fail ("Constructor->getParent() && \"No parent class for constructor.\"" , "clang/lib/Sema/SemaInit.cpp", 6832, __extension__ __PRETTY_FUNCTION__ )); | |||
| 6833 | if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && | |||
| 6834 | Constructor->isTrivial() && !Constructor->isUsed(false)) { | |||
| 6835 | S.runWithSufficientStackSpace(Loc, [&] { | |||
| 6836 | S.DefineImplicitDefaultConstructor(Loc, Constructor); | |||
| 6837 | }); | |||
| 6838 | } | |||
| 6839 | } | |||
| 6840 | ||||
| 6841 | ExprResult CurInit((Expr *)nullptr); | |||
| 6842 | ||||
| 6843 | // C++ [over.match.copy]p1: | |||
| 6844 | // - When initializing a temporary to be bound to the first parameter | |||
| 6845 | // of a constructor that takes a reference to possibly cv-qualified | |||
| 6846 | // T as its first argument, called with a single argument in the | |||
| 6847 | // context of direct-initialization, explicit conversion functions | |||
| 6848 | // are also considered. | |||
| 6849 | bool AllowExplicitConv = | |||
| 6850 | Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 && | |||
| 6851 | hasCopyOrMoveCtorParam(S.Context, | |||
| 6852 | getConstructorInfo(Step.Function.FoundDecl)); | |||
| 6853 | ||||
| 6854 | // Determine the arguments required to actually perform the constructor | |||
| 6855 | // call. | |||
| 6856 | if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc, | |||
| 6857 | ConstructorArgs, AllowExplicitConv, | |||
| 6858 | IsListInitialization)) | |||
| 6859 | return ExprError(); | |||
| 6860 | ||||
| 6861 | if (isExplicitTemporary(Entity, Kind, NumArgs)) { | |||
| 6862 | // An explicitly-constructed temporary, e.g., X(1, 2). | |||
| 6863 | if (S.DiagnoseUseOfDecl(Constructor, Loc)) | |||
| 6864 | return ExprError(); | |||
| 6865 | ||||
| 6866 | TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); | |||
| 6867 | if (!TSInfo) | |||
| 6868 | TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc); | |||
| 6869 | SourceRange ParenOrBraceRange = | |||
| 6870 | (Kind.getKind() == InitializationKind::IK_DirectList) | |||
| 6871 | ? SourceRange(LBraceLoc, RBraceLoc) | |||
| 6872 | : Kind.getParenOrBraceRange(); | |||
| 6873 | ||||
| 6874 | CXXConstructorDecl *CalleeDecl = Constructor; | |||
| 6875 | if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>( | |||
| 6876 | Step.Function.FoundDecl.getDecl())) { | |||
| 6877 | CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow); | |||
| 6878 | if (S.DiagnoseUseOfDecl(CalleeDecl, Loc)) | |||
| 6879 | return ExprError(); | |||
| 6880 | } | |||
| 6881 | S.MarkFunctionReferenced(Loc, CalleeDecl); | |||
| 6882 | ||||
| 6883 | CurInit = S.CheckForImmediateInvocation( | |||
| 6884 | CXXTemporaryObjectExpr::Create( | |||
| 6885 | S.Context, CalleeDecl, | |||
| 6886 | Entity.getType().getNonLValueExprType(S.Context), TSInfo, | |||
| 6887 | ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates, | |||
| 6888 | IsListInitialization, IsStdInitListInitialization, | |||
| 6889 | ConstructorInitRequiresZeroInit), | |||
| 6890 | CalleeDecl); | |||
| 6891 | } else { | |||
| 6892 | CXXConstructExpr::ConstructionKind ConstructKind = | |||
| 6893 | CXXConstructExpr::CK_Complete; | |||
| 6894 | ||||
| 6895 | if (Entity.getKind() == InitializedEntity::EK_Base) { | |||
| 6896 | ConstructKind = Entity.getBaseSpecifier()->isVirtual() ? | |||
| 6897 | CXXConstructExpr::CK_VirtualBase : | |||
| 6898 | CXXConstructExpr::CK_NonVirtualBase; | |||
| 6899 | } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { | |||
| 6900 | ConstructKind = CXXConstructExpr::CK_Delegating; | |||
| 6901 | } | |||
| 6902 | ||||
| 6903 | // Only get the parenthesis or brace range if it is a list initialization or | |||
| 6904 | // direct construction. | |||
| 6905 | SourceRange ParenOrBraceRange; | |||
| 6906 | if (IsListInitialization) | |||
| 6907 | ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc); | |||
| 6908 | else if (Kind.getKind() == InitializationKind::IK_Direct) | |||
| 6909 | ParenOrBraceRange = Kind.getParenOrBraceRange(); | |||
| 6910 | ||||
| 6911 | // If the entity allows NRVO, mark the construction as elidable | |||
| 6912 | // unconditionally. | |||
| 6913 | if (Entity.allowsNRVO()) | |||
| 6914 | CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, | |||
| 6915 | Step.Function.FoundDecl, | |||
| 6916 | Constructor, /*Elidable=*/true, | |||
| 6917 | ConstructorArgs, | |||
| 6918 | HadMultipleCandidates, | |||
| 6919 | IsListInitialization, | |||
| 6920 | IsStdInitListInitialization, | |||
| 6921 | ConstructorInitRequiresZeroInit, | |||
| 6922 | ConstructKind, | |||
| 6923 | ParenOrBraceRange); | |||
| 6924 | else | |||
| 6925 | CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, | |||
| 6926 | Step.Function.FoundDecl, | |||
| 6927 | Constructor, | |||
| 6928 | ConstructorArgs, | |||
| 6929 | HadMultipleCandidates, | |||
| 6930 | IsListInitialization, | |||
| 6931 | IsStdInitListInitialization, | |||
| 6932 | ConstructorInitRequiresZeroInit, | |||
| 6933 | ConstructKind, | |||
| 6934 | ParenOrBraceRange); | |||
| 6935 | } | |||
| 6936 | if (CurInit.isInvalid()) | |||
| 6937 | return ExprError(); | |||
| 6938 | ||||
| 6939 | // Only check access if all of that succeeded. | |||
| 6940 | S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity); | |||
| 6941 | if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc)) | |||
| 6942 | return ExprError(); | |||
| 6943 | ||||
| 6944 | if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType())) | |||
| 6945 | if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S)) | |||
| 6946 | return ExprError(); | |||
| 6947 | ||||
| 6948 | if (shouldBindAsTemporary(Entity)) | |||
| 6949 | CurInit = S.MaybeBindToTemporary(CurInit.get()); | |||
| 6950 | ||||
| 6951 | return CurInit; | |||
| 6952 | } | |||
| 6953 | ||||
| 6954 | namespace { | |||
| 6955 | enum LifetimeKind { | |||
| 6956 | /// The lifetime of a temporary bound to this entity ends at the end of the | |||
| 6957 | /// full-expression, and that's (probably) fine. | |||
| 6958 | LK_FullExpression, | |||
| 6959 | ||||
| 6960 | /// The lifetime of a temporary bound to this entity is extended to the | |||
| 6961 | /// lifeitme of the entity itself. | |||
| 6962 | LK_Extended, | |||
| 6963 | ||||
| 6964 | /// The lifetime of a temporary bound to this entity probably ends too soon, | |||
| 6965 | /// because the entity is allocated in a new-expression. | |||
| 6966 | LK_New, | |||
| 6967 | ||||
| 6968 | /// The lifetime of a temporary bound to this entity ends too soon, because | |||
| 6969 | /// the entity is a return object. | |||
| 6970 | LK_Return, | |||
| 6971 | ||||
| 6972 | /// The lifetime of a temporary bound to this entity ends too soon, because | |||
| 6973 | /// the entity is the result of a statement expression. | |||
| 6974 | LK_StmtExprResult, | |||
| 6975 | ||||
| 6976 | /// This is a mem-initializer: if it would extend a temporary (other than via | |||
| 6977 | /// a default member initializer), the program is ill-formed. | |||
| 6978 | LK_MemInitializer, | |||
| 6979 | }; | |||
| 6980 | using LifetimeResult = | |||
| 6981 | llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>; | |||
| 6982 | } | |||
| 6983 | ||||
| 6984 | /// Determine the declaration which an initialized entity ultimately refers to, | |||
| 6985 | /// for the purpose of lifetime-extending a temporary bound to a reference in | |||
| 6986 | /// the initialization of \p Entity. | |||
| 6987 | static LifetimeResult getEntityLifetime( | |||
| 6988 | const InitializedEntity *Entity, | |||
| 6989 | const InitializedEntity *InitField = nullptr) { | |||
| 6990 | // C++11 [class.temporary]p5: | |||
| 6991 | switch (Entity->getKind()) { | |||
| 6992 | case InitializedEntity::EK_Variable: | |||
| 6993 | // The temporary [...] persists for the lifetime of the reference | |||
| 6994 | return {Entity, LK_Extended}; | |||
| 6995 | ||||
| 6996 | case InitializedEntity::EK_Member: | |||
| 6997 | // For subobjects, we look at the complete object. | |||
| 6998 | if (Entity->getParent()) | |||
| 6999 | return getEntityLifetime(Entity->getParent(), Entity); | |||
| 7000 | ||||
| 7001 | // except: | |||
| 7002 | // C++17 [class.base.init]p8: | |||
| 7003 | // A temporary expression bound to a reference member in a | |||
| 7004 | // mem-initializer is ill-formed. | |||
| 7005 | // C++17 [class.base.init]p11: | |||
| 7006 | // A temporary expression bound to a reference member from a | |||
| 7007 | // default member initializer is ill-formed. | |||
| 7008 | // | |||
| 7009 | // The context of p11 and its example suggest that it's only the use of a | |||
| 7010 | // default member initializer from a constructor that makes the program | |||
| 7011 | // ill-formed, not its mere existence, and that it can even be used by | |||
| 7012 | // aggregate initialization. | |||
| 7013 | return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended | |||
| 7014 | : LK_MemInitializer}; | |||
| 7015 | ||||
| 7016 | case InitializedEntity::EK_Binding: | |||
| 7017 | // Per [dcl.decomp]p3, the binding is treated as a variable of reference | |||
| 7018 | // type. | |||
| 7019 | return {Entity, LK_Extended}; | |||
| 7020 | ||||
| 7021 | case InitializedEntity::EK_Parameter: | |||
| 7022 | case InitializedEntity::EK_Parameter_CF_Audited: | |||
| 7023 | // -- A temporary bound to a reference parameter in a function call | |||
| 7024 | // persists until the completion of the full-expression containing | |||
| 7025 | // the call. | |||
| 7026 | return {nullptr, LK_FullExpression}; | |||
| 7027 | ||||
| 7028 | case InitializedEntity::EK_TemplateParameter: | |||
| 7029 | // FIXME: This will always be ill-formed; should we eagerly diagnose it here? | |||
| 7030 | return {nullptr, LK_FullExpression}; | |||
| 7031 | ||||
| 7032 | case InitializedEntity::EK_Result: | |||
| 7033 | // -- The lifetime of a temporary bound to the returned value in a | |||
| 7034 | // function return statement is not extended; the temporary is | |||
| 7035 | // destroyed at the end of the full-expression in the return statement. | |||
| 7036 | return {nullptr, LK_Return}; | |||
| 7037 | ||||
| 7038 | case InitializedEntity::EK_StmtExprResult: | |||
| 7039 | // FIXME: Should we lifetime-extend through the result of a statement | |||
| 7040 | // expression? | |||
| 7041 | return {nullptr, LK_StmtExprResult}; | |||
| 7042 | ||||
| 7043 | case InitializedEntity::EK_New: | |||
| 7044 | // -- A temporary bound to a reference in a new-initializer persists | |||
| 7045 | // until the completion of the full-expression containing the | |||
| 7046 | // new-initializer. | |||
| 7047 | return {nullptr, LK_New}; | |||
| 7048 | ||||
| 7049 | case InitializedEntity::EK_Temporary: | |||
| 7050 | case InitializedEntity::EK_CompoundLiteralInit: | |||
| 7051 | case InitializedEntity::EK_RelatedResult: | |||
| 7052 | // We don't yet know the storage duration of the surrounding temporary. | |||
| 7053 | // Assume it's got full-expression duration for now, it will patch up our | |||
| 7054 | // storage duration if that's not correct. | |||
| 7055 | return {nullptr, LK_FullExpression}; | |||
| 7056 | ||||
| 7057 | case InitializedEntity::EK_ArrayElement: | |||
| 7058 | // For subobjects, we look at the complete object. | |||
| 7059 | return getEntityLifetime(Entity->getParent(), InitField); | |||
| 7060 | ||||
| 7061 | case InitializedEntity::EK_Base: | |||
| 7062 | // For subobjects, we look at the complete object. | |||
| 7063 | if (Entity->getParent()) | |||
| 7064 | return getEntityLifetime(Entity->getParent(), InitField); | |||
| 7065 | return {InitField, LK_MemInitializer}; | |||
| 7066 | ||||
| 7067 | case InitializedEntity::EK_Delegating: | |||
| 7068 | // We can reach this case for aggregate initialization in a constructor: | |||
| 7069 | // struct A { int &&r; }; | |||
| 7070 | // struct B : A { B() : A{0} {} }; | |||
| 7071 | // In this case, use the outermost field decl as the context. | |||
| 7072 | return {InitField, LK_MemInitializer}; | |||
| 7073 | ||||
| 7074 | case InitializedEntity::EK_BlockElement: | |||
| 7075 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | |||
| 7076 | case InitializedEntity::EK_LambdaCapture: | |||
| 7077 | case InitializedEntity::EK_VectorElement: | |||
| 7078 | case InitializedEntity::EK_ComplexElement: | |||
| 7079 | return {nullptr, LK_FullExpression}; | |||
| 7080 | ||||
| 7081 | case InitializedEntity::EK_Exception: | |||
| 7082 | // FIXME: Can we diagnose lifetime problems with exceptions? | |||
| 7083 | return {nullptr, LK_FullExpression}; | |||
| 7084 | } | |||
| 7085 | llvm_unreachable("unknown entity kind")::llvm::llvm_unreachable_internal("unknown entity kind", "clang/lib/Sema/SemaInit.cpp" , 7085); | |||
| 7086 | } | |||
| 7087 | ||||
| 7088 | namespace { | |||
| 7089 | enum ReferenceKind { | |||
| 7090 | /// Lifetime would be extended by a reference binding to a temporary. | |||
| 7091 | RK_ReferenceBinding, | |||
| 7092 | /// Lifetime would be extended by a std::initializer_list object binding to | |||
| 7093 | /// its backing array. | |||
| 7094 | RK_StdInitializerList, | |||
| 7095 | }; | |||
| 7096 | ||||
| 7097 | /// A temporary or local variable. This will be one of: | |||
| 7098 | /// * A MaterializeTemporaryExpr. | |||
| 7099 | /// * A DeclRefExpr whose declaration is a local. | |||
| 7100 | /// * An AddrLabelExpr. | |||
| 7101 | /// * A BlockExpr for a block with captures. | |||
| 7102 | using Local = Expr*; | |||
| 7103 | ||||
| 7104 | /// Expressions we stepped over when looking for the local state. Any steps | |||
| 7105 | /// that would inhibit lifetime extension or take us out of subexpressions of | |||
| 7106 | /// the initializer are included. | |||
| 7107 | struct IndirectLocalPathEntry { | |||
| 7108 | enum EntryKind { | |||
| 7109 | DefaultInit, | |||
| 7110 | AddressOf, | |||
| 7111 | VarInit, | |||
| 7112 | LValToRVal, | |||
| 7113 | LifetimeBoundCall, | |||
| 7114 | TemporaryCopy, | |||
| 7115 | LambdaCaptureInit, | |||
| 7116 | GslReferenceInit, | |||
| 7117 | GslPointerInit | |||
| 7118 | } Kind; | |||
| 7119 | Expr *E; | |||
| 7120 | union { | |||
| 7121 | const Decl *D = nullptr; | |||
| 7122 | const LambdaCapture *Capture; | |||
| 7123 | }; | |||
| 7124 | IndirectLocalPathEntry() {} | |||
| 7125 | IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {} | |||
| 7126 | IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D) | |||
| 7127 | : Kind(K), E(E), D(D) {} | |||
| 7128 | IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture) | |||
| 7129 | : Kind(K), E(E), Capture(Capture) {} | |||
| 7130 | }; | |||
| 7131 | ||||
| 7132 | using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>; | |||
| 7133 | ||||
| 7134 | struct RevertToOldSizeRAII { | |||
| 7135 | IndirectLocalPath &Path; | |||
| 7136 | unsigned OldSize = Path.size(); | |||
| 7137 | RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {} | |||
| 7138 | ~RevertToOldSizeRAII() { Path.resize(OldSize); } | |||
| 7139 | }; | |||
| 7140 | ||||
| 7141 | using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L, | |||
| 7142 | ReferenceKind RK)>; | |||
| 7143 | } | |||
| 7144 | ||||
| 7145 | static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) { | |||
| 7146 | for (auto E : Path) | |||
| 7147 | if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD) | |||
| 7148 | return true; | |||
| 7149 | return false; | |||
| 7150 | } | |||
| 7151 | ||||
| 7152 | static bool pathContainsInit(IndirectLocalPath &Path) { | |||
| 7153 | return llvm::any_of(Path, [=](IndirectLocalPathEntry E) { | |||
| 7154 | return E.Kind == IndirectLocalPathEntry::DefaultInit || | |||
| 7155 | E.Kind == IndirectLocalPathEntry::VarInit; | |||
| 7156 | }); | |||
| 7157 | } | |||
| 7158 | ||||
| 7159 | static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, | |||
| 7160 | Expr *Init, LocalVisitor Visit, | |||
| 7161 | bool RevisitSubinits, | |||
| 7162 | bool EnableLifetimeWarnings); | |||
| 7163 | ||||
| 7164 | static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, | |||
| 7165 | Expr *Init, ReferenceKind RK, | |||
| 7166 | LocalVisitor Visit, | |||
| 7167 | bool EnableLifetimeWarnings); | |||
| 7168 | ||||
| 7169 | template <typename T> static bool isRecordWithAttr(QualType Type) { | |||
| 7170 | if (auto *RD = Type->getAsCXXRecordDecl()) | |||
| 7171 | return RD->hasAttr<T>(); | |||
| 7172 | return false; | |||
| 7173 | } | |||
| 7174 | ||||
| 7175 | // Decl::isInStdNamespace will return false for iterators in some STL | |||
| 7176 | // implementations due to them being defined in a namespace outside of the std | |||
| 7177 | // namespace. | |||
| 7178 | static bool isInStlNamespace(const Decl *D) { | |||
| 7179 | const DeclContext *DC = D->getDeclContext(); | |||
| 7180 | if (!DC) | |||
| 7181 | return false; | |||
| 7182 | if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) | |||
| 7183 | if (const IdentifierInfo *II = ND->getIdentifier()) { | |||
| 7184 | StringRef Name = II->getName(); | |||
| 7185 | if (Name.size() >= 2 && Name.front() == '_' && | |||
| 7186 | (Name[1] == '_' || isUppercase(Name[1]))) | |||
| 7187 | return true; | |||
| 7188 | } | |||
| 7189 | ||||
| 7190 | return DC->isStdNamespace(); | |||
| 7191 | } | |||
| 7192 | ||||
| 7193 | static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) { | |||
| 7194 | if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee)) | |||
| 7195 | if (isRecordWithAttr<PointerAttr>(Conv->getConversionType())) | |||
| 7196 | return true; | |||
| 7197 | if (!isInStlNamespace(Callee->getParent())) | |||
| 7198 | return false; | |||
| 7199 | if (!isRecordWithAttr<PointerAttr>(Callee->getThisObjectType()) && | |||
| 7200 | !isRecordWithAttr<OwnerAttr>(Callee->getThisObjectType())) | |||
| 7201 | return false; | |||
| 7202 | if (Callee->getReturnType()->isPointerType() || | |||
| 7203 | isRecordWithAttr<PointerAttr>(Callee->getReturnType())) { | |||
| 7204 | if (!Callee->getIdentifier()) | |||
| 7205 | return false; | |||
| 7206 | return llvm::StringSwitch<bool>(Callee->getName()) | |||
| 7207 | .Cases("begin", "rbegin", "cbegin", "crbegin", true) | |||
| 7208 | .Cases("end", "rend", "cend", "crend", true) | |||
| 7209 | .Cases("c_str", "data", "get", true) | |||
| 7210 | // Map and set types. | |||
| 7211 | .Cases("find", "equal_range", "lower_bound", "upper_bound", true) | |||
| 7212 | .Default(false); | |||
| 7213 | } else if (Callee->getReturnType()->isReferenceType()) { | |||
| 7214 | if (!Callee->getIdentifier()) { | |||
| 7215 | auto OO = Callee->getOverloadedOperator(); | |||
| 7216 | return OO == OverloadedOperatorKind::OO_Subscript || | |||
| 7217 | OO == OverloadedOperatorKind::OO_Star; | |||
| 7218 | } | |||
| 7219 | return llvm::StringSwitch<bool>(Callee->getName()) | |||
| 7220 | .Cases("front", "back", "at", "top", "value", true) | |||
| 7221 | .Default(false); | |||
| 7222 | } | |||
| 7223 | return false; | |||
| 7224 | } | |||
| 7225 | ||||
| 7226 | static bool shouldTrackFirstArgument(const FunctionDecl *FD) { | |||
| 7227 | if (!FD->getIdentifier() || FD->getNumParams() != 1) | |||
| 7228 | return false; | |||
| 7229 | const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl(); | |||
| 7230 | if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace()) | |||
| 7231 | return false; | |||
| 7232 | if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) && | |||
| 7233 | !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0))) | |||
| 7234 | return false; | |||
| 7235 | if (FD->getReturnType()->isPointerType() || | |||
| 7236 | isRecordWithAttr<PointerAttr>(FD->getReturnType())) { | |||
| 7237 | return llvm::StringSwitch<bool>(FD->getName()) | |||
| 7238 | .Cases("begin", "rbegin", "cbegin", "crbegin", true) | |||
| 7239 | .Cases("end", "rend", "cend", "crend", true) | |||
| 7240 | .Case("data", true) | |||
| 7241 | .Default(false); | |||
| 7242 | } else if (FD->getReturnType()->isReferenceType()) { | |||
| 7243 | return llvm::StringSwitch<bool>(FD->getName()) | |||
| 7244 | .Cases("get", "any_cast", true) | |||
| 7245 | .Default(false); | |||
| 7246 | } | |||
| 7247 | return false; | |||
| 7248 | } | |||
| 7249 | ||||
| 7250 | static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call, | |||
| 7251 | LocalVisitor Visit) { | |||
| 7252 | auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) { | |||
| 7253 | // We are not interested in the temporary base objects of gsl Pointers: | |||
| 7254 | // Temp().ptr; // Here ptr might not dangle. | |||
| 7255 | if (isa<MemberExpr>(Arg->IgnoreImpCasts())) | |||
| 7256 | return; | |||
| 7257 | // Once we initialized a value with a reference, it can no longer dangle. | |||
| 7258 | if (!Value) { | |||
| 7259 | for (const IndirectLocalPathEntry &PE : llvm::reverse(Path)) { | |||
| 7260 | if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit) | |||
| 7261 | continue; | |||
| 7262 | if (PE.Kind == IndirectLocalPathEntry::GslPointerInit) | |||
| 7263 | return; | |||
| 7264 | break; | |||
| 7265 | } | |||
| 7266 | } | |||
| 7267 | Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit | |||
| 7268 | : IndirectLocalPathEntry::GslReferenceInit, | |||
| 7269 | Arg, D}); | |||
| 7270 | if (Arg->isGLValue()) | |||
| 7271 | visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, | |||
| 7272 | Visit, | |||
| 7273 | /*EnableLifetimeWarnings=*/true); | |||
| 7274 | else | |||
| 7275 | visitLocalsRetainedByInitializer(Path, Arg, Visit, true, | |||
| 7276 | /*EnableLifetimeWarnings=*/true); | |||
| 7277 | Path.pop_back(); | |||
| 7278 | }; | |||
| 7279 | ||||
| 7280 | if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { | |||
| 7281 | const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee()); | |||
| 7282 | if (MD && shouldTrackImplicitObjectArg(MD)) | |||
| 7283 | VisitPointerArg(MD, MCE->getImplicitObjectArgument(), | |||
| 7284 | !MD->getReturnType()->isReferenceType()); | |||
| 7285 | return; | |||
| 7286 | } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) { | |||
| 7287 | FunctionDecl *Callee = OCE->getDirectCallee(); | |||
| 7288 | if (Callee && Callee->isCXXInstanceMember() && | |||
| 7289 | shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee))) | |||
| 7290 | VisitPointerArg(Callee, OCE->getArg(0), | |||
| 7291 | !Callee->getReturnType()->isReferenceType()); | |||
| 7292 | return; | |||
| 7293 | } else if (auto *CE = dyn_cast<CallExpr>(Call)) { | |||
| 7294 | FunctionDecl *Callee = CE->getDirectCallee(); | |||
| 7295 | if (Callee && shouldTrackFirstArgument(Callee)) | |||
| 7296 | VisitPointerArg(Callee, CE->getArg(0), | |||
| 7297 | !Callee->getReturnType()->isReferenceType()); | |||
| 7298 | return; | |||
| 7299 | } | |||
| 7300 | ||||
| 7301 | if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) { | |||
| 7302 | const auto *Ctor = CCE->getConstructor(); | |||
| 7303 | const CXXRecordDecl *RD = Ctor->getParent(); | |||
| 7304 | if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>()) | |||
| 7305 | VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true); | |||
| 7306 | } | |||
| 7307 | } | |||
| 7308 | ||||
| 7309 | static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) { | |||
| 7310 | const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); | |||
| 7311 | if (!TSI) | |||
| 7312 | return false; | |||
| 7313 | // Don't declare this variable in the second operand of the for-statement; | |||
| 7314 | // GCC miscompiles that by ending its lifetime before evaluating the | |||
| 7315 | // third operand. See gcc.gnu.org/PR86769. | |||
| 7316 | AttributedTypeLoc ATL; | |||
| 7317 | for (TypeLoc TL = TSI->getTypeLoc(); | |||
| 7318 | (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); | |||
| 7319 | TL = ATL.getModifiedLoc()) { | |||
| 7320 | if (ATL.getAttrAs<LifetimeBoundAttr>()) | |||
| 7321 | return true; | |||
| 7322 | } | |||
| 7323 | ||||
| 7324 | // Assume that all assignment operators with a "normal" return type return | |||
| 7325 | // *this, that is, an lvalue reference that is the same type as the implicit | |||
| 7326 | // object parameter (or the LHS for a non-member operator$=). | |||
| 7327 | OverloadedOperatorKind OO = FD->getDeclName().getCXXOverloadedOperator(); | |||
| 7328 | if (OO == OO_Equal || isCompoundAssignmentOperator(OO)) { | |||
| 7329 | QualType RetT = FD->getReturnType(); | |||
| 7330 | if (RetT->isLValueReferenceType()) { | |||
| 7331 | ASTContext &Ctx = FD->getASTContext(); | |||
| 7332 | QualType LHST; | |||
| 7333 | auto *MD = dyn_cast<CXXMethodDecl>(FD); | |||
| 7334 | if (MD && MD->isCXXInstanceMember()) | |||
| 7335 | LHST = Ctx.getLValueReferenceType(MD->getThisObjectType()); | |||
| 7336 | else | |||
| 7337 | LHST = MD->getParamDecl(0)->getType(); | |||
| 7338 | if (Ctx.hasSameType(RetT, LHST)) | |||
| 7339 | return true; | |||
| 7340 | } | |||
| 7341 | } | |||
| 7342 | ||||
| 7343 | return false; | |||
| 7344 | } | |||
| 7345 | ||||
| 7346 | static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call, | |||
| 7347 | LocalVisitor Visit) { | |||
| 7348 | const FunctionDecl *Callee; | |||
| 7349 | ArrayRef<Expr*> Args; | |||
| 7350 | ||||
| 7351 | if (auto *CE = dyn_cast<CallExpr>(Call)) { | |||
| 7352 | Callee = CE->getDirectCallee(); | |||
| 7353 | Args = llvm::ArrayRef(CE->getArgs(), CE->getNumArgs()); | |||
| 7354 | } else { | |||
| 7355 | auto *CCE = cast<CXXConstructExpr>(Call); | |||
| 7356 | Callee = CCE->getConstructor(); | |||
| 7357 | Args = llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()); | |||
| 7358 | } | |||
| 7359 | if (!Callee) | |||
| 7360 | return; | |||
| 7361 | ||||
| 7362 | Expr *ObjectArg = nullptr; | |||
| 7363 | if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) { | |||
| 7364 | ObjectArg = Args[0]; | |||
| 7365 | Args = Args.slice(1); | |||
| 7366 | } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { | |||
| 7367 | ObjectArg = MCE->getImplicitObjectArgument(); | |||
| 7368 | } | |||
| 7369 | ||||
| 7370 | auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) { | |||
| 7371 | Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D}); | |||
| 7372 | if (Arg->isGLValue()) | |||
| 7373 | visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, | |||
| 7374 | Visit, | |||
| 7375 | /*EnableLifetimeWarnings=*/false); | |||
| 7376 | else | |||
| 7377 | visitLocalsRetainedByInitializer(Path, Arg, Visit, true, | |||
| 7378 | /*EnableLifetimeWarnings=*/false); | |||
| 7379 | Path.pop_back(); | |||
| 7380 | }; | |||
| 7381 | ||||
| 7382 | if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee)) | |||
| 7383 | VisitLifetimeBoundArg(Callee, ObjectArg); | |||
| 7384 | ||||
| 7385 | for (unsigned I = 0, | |||
| 7386 | N = std::min<unsigned>(Callee->getNumParams(), Args.size()); | |||
| 7387 | I != N; ++I) { | |||
| 7388 | if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>()) | |||
| 7389 | VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]); | |||
| 7390 | } | |||
| 7391 | } | |||
| 7392 | ||||
| 7393 | /// Visit the locals that would be reachable through a reference bound to the | |||
| 7394 | /// glvalue expression \c Init. | |||
| 7395 | static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, | |||
| 7396 | Expr *Init, ReferenceKind RK, | |||
| 7397 | LocalVisitor Visit, | |||
| 7398 | bool EnableLifetimeWarnings) { | |||
| 7399 | RevertToOldSizeRAII RAII(Path); | |||
| 7400 | ||||
| 7401 | // Walk past any constructs which we can lifetime-extend across. | |||
| 7402 | Expr *Old; | |||
| 7403 | do { | |||
| 7404 | Old = Init; | |||
| 7405 | ||||
| 7406 | if (auto *FE = dyn_cast<FullExpr>(Init)) | |||
| 7407 | Init = FE->getSubExpr(); | |||
| 7408 | ||||
| 7409 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { | |||
| 7410 | // If this is just redundant braces around an initializer, step over it. | |||
| 7411 | if (ILE->isTransparent()) | |||
| 7412 | Init = ILE->getInit(0); | |||
| 7413 | } | |||
| 7414 | ||||
| 7415 | // Step over any subobject adjustments; we may have a materialized | |||
| 7416 | // temporary inside them. | |||
| 7417 | Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); | |||
| 7418 | ||||
| 7419 | // Per current approach for DR1376, look through casts to reference type | |||
| 7420 | // when performing lifetime extension. | |||
| 7421 | if (CastExpr *CE = dyn_cast<CastExpr>(Init)) | |||
| 7422 | if (CE->getSubExpr()->isGLValue()) | |||
| 7423 | Init = CE->getSubExpr(); | |||
| 7424 | ||||
| 7425 | // Per the current approach for DR1299, look through array element access | |||
| 7426 | // on array glvalues when performing lifetime extension. | |||
| 7427 | if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) { | |||
| 7428 | Init = ASE->getBase(); | |||
| 7429 | auto *ICE = dyn_cast<ImplicitCastExpr>(Init); | |||
| 7430 | if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay) | |||
| 7431 | Init = ICE->getSubExpr(); | |||
| 7432 | else | |||
| 7433 | // We can't lifetime extend through this but we might still find some | |||
| 7434 | // retained temporaries. | |||
| 7435 | return visitLocalsRetainedByInitializer(Path, Init, Visit, true, | |||
| 7436 | EnableLifetimeWarnings); | |||
| 7437 | } | |||
| 7438 | ||||
| 7439 | // Step into CXXDefaultInitExprs so we can diagnose cases where a | |||
| 7440 | // constructor inherits one as an implicit mem-initializer. | |||
| 7441 | if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { | |||
| 7442 | Path.push_back( | |||
| 7443 | {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); | |||
| 7444 | Init = DIE->getExpr(); | |||
| 7445 | } | |||
| 7446 | } while (Init != Old); | |||
| 7447 | ||||
| 7448 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) { | |||
| 7449 | if (Visit(Path, Local(MTE), RK)) | |||
| 7450 | visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true, | |||
| 7451 | EnableLifetimeWarnings); | |||
| 7452 | } | |||
| 7453 | ||||
| 7454 | if (isa<CallExpr>(Init)) { | |||
| 7455 | if (EnableLifetimeWarnings) | |||
| 7456 | handleGslAnnotatedTypes(Path, Init, Visit); | |||
| 7457 | return visitLifetimeBoundArguments(Path, Init, Visit); | |||
| 7458 | } | |||
| 7459 | ||||
| 7460 | switch (Init->getStmtClass()) { | |||
| 7461 | case Stmt::DeclRefExprClass: { | |||
| 7462 | // If we find the name of a local non-reference parameter, we could have a | |||
| 7463 | // lifetime problem. | |||
| 7464 | auto *DRE = cast<DeclRefExpr>(Init); | |||
| 7465 | auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); | |||
| 7466 | if (VD && VD->hasLocalStorage() && | |||
| 7467 | !DRE->refersToEnclosingVariableOrCapture()) { | |||
| 7468 | if (!VD->getType()->isReferenceType()) { | |||
| 7469 | Visit(Path, Local(DRE), RK); | |||
| 7470 | } else if (isa<ParmVarDecl>(DRE->getDecl())) { | |||
| 7471 | // The lifetime of a reference parameter is unknown; assume it's OK | |||
| 7472 | // for now. | |||
| 7473 | break; | |||
| 7474 | } else if (VD->getInit() && !isVarOnPath(Path, VD)) { | |||
| 7475 | Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); | |||
| 7476 | visitLocalsRetainedByReferenceBinding(Path, VD->getInit(), | |||
| 7477 | RK_ReferenceBinding, Visit, | |||
| 7478 | EnableLifetimeWarnings); | |||
| 7479 | } | |||
| 7480 | } | |||
| 7481 | break; | |||
| 7482 | } | |||
| 7483 | ||||
| 7484 | case Stmt::UnaryOperatorClass: { | |||
| 7485 | // The only unary operator that make sense to handle here | |||
| 7486 | // is Deref. All others don't resolve to a "name." This includes | |||
| 7487 | // handling all sorts of rvalues passed to a unary operator. | |||
| 7488 | const UnaryOperator *U = cast<UnaryOperator>(Init); | |||
| 7489 | if (U->getOpcode() == UO_Deref) | |||
| 7490 | visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true, | |||
| 7491 | EnableLifetimeWarnings); | |||
| 7492 | break; | |||
| 7493 | } | |||
| 7494 | ||||
| 7495 | case Stmt::OMPArraySectionExprClass: { | |||
| 7496 | visitLocalsRetainedByInitializer(Path, | |||
| 7497 | cast<OMPArraySectionExpr>(Init)->getBase(), | |||
| 7498 | Visit, true, EnableLifetimeWarnings); | |||
| 7499 | break; | |||
| 7500 | } | |||
| 7501 | ||||
| 7502 | case Stmt::ConditionalOperatorClass: | |||
| 7503 | case Stmt::BinaryConditionalOperatorClass: { | |||
| 7504 | auto *C = cast<AbstractConditionalOperator>(Init); | |||
| 7505 | if (!C->getTrueExpr()->getType()->isVoidType()) | |||
| 7506 | visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit, | |||
| 7507 | EnableLifetimeWarnings); | |||
| 7508 | if (!C->getFalseExpr()->getType()->isVoidType()) | |||
| 7509 | visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit, | |||
| 7510 | EnableLifetimeWarnings); | |||
| 7511 | break; | |||
| 7512 | } | |||
| 7513 | ||||
| 7514 | // FIXME: Visit the left-hand side of an -> or ->*. | |||
| 7515 | ||||
| 7516 | default: | |||
| 7517 | break; | |||
| 7518 | } | |||
| 7519 | } | |||
| 7520 | ||||
| 7521 | /// Visit the locals that would be reachable through an object initialized by | |||
| 7522 | /// the prvalue expression \c Init. | |||
| 7523 | static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, | |||
| 7524 | Expr *Init, LocalVisitor Visit, | |||
| 7525 | bool RevisitSubinits, | |||
| 7526 | bool EnableLifetimeWarnings) { | |||
| 7527 | RevertToOldSizeRAII RAII(Path); | |||
| 7528 | ||||
| 7529 | Expr *Old; | |||
| 7530 | do { | |||
| 7531 | Old = Init; | |||
| 7532 | ||||
| 7533 | // Step into CXXDefaultInitExprs so we can diagnose cases where a | |||
| 7534 | // constructor inherits one as an implicit mem-initializer. | |||
| 7535 | if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { | |||
| 7536 | Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); | |||
| 7537 | Init = DIE->getExpr(); | |||
| 7538 | } | |||
| 7539 | ||||
| 7540 | if (auto *FE = dyn_cast<FullExpr>(Init)) | |||
| 7541 | Init = FE->getSubExpr(); | |||
| 7542 | ||||
| 7543 | // Dig out the expression which constructs the extended temporary. | |||
| 7544 | Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); | |||
| 7545 | ||||
| 7546 | if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init)) | |||
| 7547 | Init = BTE->getSubExpr(); | |||
| 7548 | ||||
| 7549 | Init = Init->IgnoreParens(); | |||
| 7550 | ||||
| 7551 | // Step over value-preserving rvalue casts. | |||
| 7552 | if (auto *CE = dyn_cast<CastExpr>(Init)) { | |||
| 7553 | switch (CE->getCastKind()) { | |||
| 7554 | case CK_LValueToRValue: | |||
| 7555 | // If we can match the lvalue to a const object, we can look at its | |||
| 7556 | // initializer. | |||
| 7557 | Path.push_back({IndirectLocalPathEntry::LValToRVal, CE}); | |||
| 7558 | return visitLocalsRetainedByReferenceBinding( | |||
| 7559 | Path, Init, RK_ReferenceBinding, | |||
| 7560 | [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool { | |||
| 7561 | if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { | |||
| 7562 | auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); | |||
| 7563 | if (VD && VD->getType().isConstQualified() && VD->getInit() && | |||
| 7564 | !isVarOnPath(Path, VD)) { | |||
| 7565 | Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); | |||
| 7566 | visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true, | |||
| 7567 | EnableLifetimeWarnings); | |||
| 7568 | } | |||
| 7569 | } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) { | |||
| 7570 | if (MTE->getType().isConstQualified()) | |||
| 7571 | visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, | |||
| 7572 | true, EnableLifetimeWarnings); | |||
| 7573 | } | |||
| 7574 | return false; | |||
| 7575 | }, EnableLifetimeWarnings); | |||
| 7576 | ||||
| 7577 | // We assume that objects can be retained by pointers cast to integers, | |||
| 7578 | // but not if the integer is cast to floating-point type or to _Complex. | |||
| 7579 | // We assume that casts to 'bool' do not preserve enough information to | |||
| 7580 | // retain a local object. | |||
| 7581 | case CK_NoOp: | |||
| 7582 | case CK_BitCast: | |||
| 7583 | case CK_BaseToDerived: | |||
| 7584 | case CK_DerivedToBase: | |||
| 7585 | case CK_UncheckedDerivedToBase: | |||
| 7586 | case CK_Dynamic: | |||
| 7587 | case CK_ToUnion: | |||
| 7588 | case CK_UserDefinedConversion: | |||
| 7589 | case CK_ConstructorConversion: | |||
| 7590 | case CK_IntegralToPointer: | |||
| 7591 | case CK_PointerToIntegral: | |||
| 7592 | case CK_VectorSplat: | |||
| 7593 | case CK_IntegralCast: | |||
| 7594 | case CK_CPointerToObjCPointerCast: | |||
| 7595 | case CK_BlockPointerToObjCPointerCast: | |||
| 7596 | case CK_AnyPointerToBlockPointerCast: | |||
| 7597 | case CK_AddressSpaceConversion: | |||
| 7598 | break; | |||
| 7599 | ||||
| 7600 | case CK_ArrayToPointerDecay: | |||
| 7601 | // Model array-to-pointer decay as taking the address of the array | |||
| 7602 | // lvalue. | |||
| 7603 | Path.push_back({IndirectLocalPathEntry::AddressOf, CE}); | |||
| 7604 | return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(), | |||
| 7605 | RK_ReferenceBinding, Visit, | |||
| 7606 | EnableLifetimeWarnings); | |||
| 7607 | ||||
| 7608 | default: | |||
| 7609 | return; | |||
| 7610 | } | |||
| 7611 | ||||
| 7612 | Init = CE->getSubExpr(); | |||
| 7613 | } | |||
| 7614 | } while (Old != Init); | |||
| 7615 | ||||
| 7616 | // C++17 [dcl.init.list]p6: | |||
| 7617 | // initializing an initializer_list object from the array extends the | |||
| 7618 | // lifetime of the array exactly like binding a reference to a temporary. | |||
| 7619 | if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init)) | |||
| 7620 | return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(), | |||
| 7621 | RK_StdInitializerList, Visit, | |||
| 7622 | EnableLifetimeWarnings); | |||
| 7623 | ||||
| 7624 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { | |||
| 7625 | // We already visited the elements of this initializer list while | |||
| 7626 | // performing the initialization. Don't visit them again unless we've | |||
| 7627 | // changed the lifetime of the initialized entity. | |||
| 7628 | if (!RevisitSubinits) | |||
| 7629 | return; | |||
| 7630 | ||||
| 7631 | if (ILE->isTransparent()) | |||
| 7632 | return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit, | |||
| 7633 | RevisitSubinits, | |||
| 7634 | EnableLifetimeWarnings); | |||
| 7635 | ||||
| 7636 | if (ILE->getType()->isArrayType()) { | |||
| 7637 | for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I) | |||
| 7638 | visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit, | |||
| 7639 | RevisitSubinits, | |||
| 7640 | EnableLifetimeWarnings); | |||
| 7641 | return; | |||
| 7642 | } | |||
| 7643 | ||||
| 7644 | if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) { | |||
| 7645 | assert(RD->isAggregate() && "aggregate init on non-aggregate")(static_cast <bool> (RD->isAggregate() && "aggregate init on non-aggregate" ) ? void (0) : __assert_fail ("RD->isAggregate() && \"aggregate init on non-aggregate\"" , "clang/lib/Sema/SemaInit.cpp", 7645, __extension__ __PRETTY_FUNCTION__ )); | |||
| 7646 | ||||
| 7647 | // If we lifetime-extend a braced initializer which is initializing an | |||
| 7648 | // aggregate, and that aggregate contains reference members which are | |||
| 7649 | // bound to temporaries, those temporaries are also lifetime-extended. | |||
| 7650 | if (RD->isUnion() && ILE->getInitializedFieldInUnion() && | |||
| 7651 | ILE->getInitializedFieldInUnion()->getType()->isReferenceType()) | |||
| 7652 | visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0), | |||
| 7653 | RK_ReferenceBinding, Visit, | |||
| 7654 | EnableLifetimeWarnings); | |||
| 7655 | else { | |||
| 7656 | unsigned Index = 0; | |||
| 7657 | for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index) | |||
| 7658 | visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit, | |||
| 7659 | RevisitSubinits, | |||
| 7660 | EnableLifetimeWarnings); | |||
| 7661 | for (const auto *I : RD->fields()) { | |||
| 7662 | if (Index >= ILE->getNumInits()) | |||
| 7663 | break; | |||
| 7664 | if (I->isUnnamedBitfield()) | |||
| 7665 | continue; | |||
| 7666 | Expr *SubInit = ILE->getInit(Index); | |||
| 7667 | if (I->getType()->isReferenceType()) | |||
| 7668 | visitLocalsRetainedByReferenceBinding(Path, SubInit, | |||
| 7669 | RK_ReferenceBinding, Visit, | |||
| 7670 | EnableLifetimeWarnings); | |||
| 7671 | else | |||
| 7672 | // This might be either aggregate-initialization of a member or | |||
| 7673 | // initialization of a std::initializer_list object. Regardless, | |||
| 7674 | // we should recursively lifetime-extend that initializer. | |||
| 7675 | visitLocalsRetainedByInitializer(Path, SubInit, Visit, | |||
| 7676 | RevisitSubinits, | |||
| 7677 | EnableLifetimeWarnings); | |||
| 7678 | ++Index; | |||
| 7679 | } | |||
| 7680 | } | |||
| 7681 | } | |||
| 7682 | return; | |||
| 7683 | } | |||
| 7684 | ||||
| 7685 | // The lifetime of an init-capture is that of the closure object constructed | |||
| 7686 | // by a lambda-expression. | |||
| 7687 | if (auto *LE = dyn_cast<LambdaExpr>(Init)) { | |||
| 7688 | LambdaExpr::capture_iterator CapI = LE->capture_begin(); | |||
| 7689 | for (Expr *E : LE->capture_inits()) { | |||
| 7690 | assert(CapI != LE->capture_end())(static_cast <bool> (CapI != LE->capture_end()) ? void (0) : __assert_fail ("CapI != LE->capture_end()", "clang/lib/Sema/SemaInit.cpp" , 7690, __extension__ __PRETTY_FUNCTION__)); | |||
| 7691 | const LambdaCapture &Cap = *CapI++; | |||
| 7692 | if (!E) | |||
| 7693 | continue; | |||
| 7694 | if (Cap.capturesVariable()) | |||
| 7695 | Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap}); | |||
| 7696 | if (E->isGLValue()) | |||
| 7697 | visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding, | |||
| 7698 | Visit, EnableLifetimeWarnings); | |||
| 7699 | else | |||
| 7700 | visitLocalsRetainedByInitializer(Path, E, Visit, true, | |||
| 7701 | EnableLifetimeWarnings); | |||
| 7702 | if (Cap.capturesVariable()) | |||
| 7703 | Path.pop_back(); | |||
| 7704 | } | |||
| 7705 | } | |||
| 7706 | ||||
| 7707 | // Assume that a copy or move from a temporary references the same objects | |||
| 7708 | // that the temporary does. | |||
| 7709 | if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { | |||
| 7710 | if (CCE->getConstructor()->isCopyOrMoveConstructor()) { | |||
| 7711 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) { | |||
| 7712 | Expr *Arg = MTE->getSubExpr(); | |||
| 7713 | Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg, | |||
| 7714 | CCE->getConstructor()}); | |||
| 7715 | visitLocalsRetainedByInitializer(Path, Arg, Visit, true, | |||
| 7716 | /*EnableLifetimeWarnings*/false); | |||
| 7717 | Path.pop_back(); | |||
| 7718 | } | |||
| 7719 | } | |||
| 7720 | } | |||
| 7721 | ||||
| 7722 | if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) { | |||
| 7723 | if (EnableLifetimeWarnings) | |||
| 7724 | handleGslAnnotatedTypes(Path, Init, Visit); | |||
| 7725 | return visitLifetimeBoundArguments(Path, Init, Visit); | |||
| 7726 | } | |||
| 7727 | ||||
| 7728 | switch (Init->getStmtClass()) { | |||
| 7729 | case Stmt::UnaryOperatorClass: { | |||
| 7730 | auto *UO = cast<UnaryOperator>(Init); | |||
| 7731 | // If the initializer is the address of a local, we could have a lifetime | |||
| 7732 | // problem. | |||
| 7733 | if (UO->getOpcode() == UO_AddrOf) { | |||
| 7734 | // If this is &rvalue, then it's ill-formed and we have already diagnosed | |||
| 7735 | // it. Don't produce a redundant warning about the lifetime of the | |||
| 7736 | // temporary. | |||
| 7737 | if (isa<MaterializeTemporaryExpr>(UO->getSubExpr())) | |||
| 7738 | return; | |||
| 7739 | ||||
| 7740 | Path.push_back({IndirectLocalPathEntry::AddressOf, UO}); | |||
| 7741 | visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(), | |||
| 7742 | RK_ReferenceBinding, Visit, | |||
| 7743 | EnableLifetimeWarnings); | |||
| 7744 | } | |||
| 7745 | break; | |||
| 7746 | } | |||
| 7747 | ||||
| 7748 | case Stmt::BinaryOperatorClass: { | |||
| 7749 | // Handle pointer arithmetic. | |||
| 7750 | auto *BO = cast<BinaryOperator>(Init); | |||
| 7751 | BinaryOperatorKind BOK = BO->getOpcode(); | |||
| 7752 | if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub)) | |||
| 7753 | break; | |||
| 7754 | ||||
| 7755 | if (BO->getLHS()->getType()->isPointerType()) | |||
| 7756 | visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true, | |||
| 7757 | EnableLifetimeWarnings); | |||
| 7758 | else if (BO->getRHS()->getType()->isPointerType()) | |||
| 7759 | visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true, | |||
| 7760 | EnableLifetimeWarnings); | |||
| 7761 | break; | |||
| 7762 | } | |||
| 7763 | ||||
| 7764 | case Stmt::ConditionalOperatorClass: | |||
| 7765 | case Stmt::BinaryConditionalOperatorClass: { | |||
| 7766 | auto *C = cast<AbstractConditionalOperator>(Init); | |||
| 7767 | // In C++, we can have a throw-expression operand, which has 'void' type | |||
| 7768 | // and isn't interesting from a lifetime perspective. | |||
| 7769 | if (!C->getTrueExpr()->getType()->isVoidType()) | |||
| 7770 | visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true, | |||
| 7771 | EnableLifetimeWarnings); | |||
| 7772 | if (!C->getFalseExpr()->getType()->isVoidType()) | |||
| 7773 | visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true, | |||
| 7774 | EnableLifetimeWarnings); | |||
| 7775 | break; | |||
| 7776 | } | |||
| 7777 | ||||
| 7778 | case Stmt::BlockExprClass: | |||
| 7779 | if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) { | |||
| 7780 | // This is a local block, whose lifetime is that of the function. | |||
| 7781 | Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding); | |||
| 7782 | } | |||
| 7783 | break; | |||
| 7784 | ||||
| 7785 | case Stmt::AddrLabelExprClass: | |||
| 7786 | // We want to warn if the address of a label would escape the function. | |||
| 7787 | Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding); | |||
| 7788 | break; | |||
| 7789 | ||||
| 7790 | default: | |||
| 7791 | break; | |||
| 7792 | } | |||
| 7793 | } | |||
| 7794 | ||||
| 7795 | /// Whether a path to an object supports lifetime extension. | |||
| 7796 | enum PathLifetimeKind { | |||
| 7797 | /// Lifetime-extend along this path. | |||
| 7798 | Extend, | |||
| 7799 | /// We should lifetime-extend, but we don't because (due to technical | |||
| 7800 | /// limitations) we can't. This happens for default member initializers, | |||
| 7801 | /// which we don't clone for every use, so we don't have a unique | |||
| 7802 | /// MaterializeTemporaryExpr to update. | |||
| 7803 | ShouldExtend, | |||
| 7804 | /// Do not lifetime extend along this path. | |||
| 7805 | NoExtend | |||
| 7806 | }; | |||
| 7807 | ||||
| 7808 | /// Determine whether this is an indirect path to a temporary that we are | |||
| 7809 | /// supposed to lifetime-extend along. | |||
| 7810 | static PathLifetimeKind | |||
| 7811 | shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) { | |||
| 7812 | PathLifetimeKind Kind = PathLifetimeKind::Extend; | |||
| 7813 | for (auto Elem : Path) { | |||
| 7814 | if (Elem.Kind == IndirectLocalPathEntry::DefaultInit) | |||
| 7815 | Kind = PathLifetimeKind::ShouldExtend; | |||
| 7816 | else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit) | |||
| 7817 | return PathLifetimeKind::NoExtend; | |||
| 7818 | } | |||
| 7819 | return Kind; | |||
| 7820 | } | |||
| 7821 | ||||
| 7822 | /// Find the range for the first interesting entry in the path at or after I. | |||
| 7823 | static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I, | |||
| 7824 | Expr *E) { | |||
| 7825 | for (unsigned N = Path.size(); I != N; ++I) { | |||
| 7826 | switch (Path[I].Kind) { | |||
| 7827 | case IndirectLocalPathEntry::AddressOf: | |||
| 7828 | case IndirectLocalPathEntry::LValToRVal: | |||
| 7829 | case IndirectLocalPathEntry::LifetimeBoundCall: | |||
| 7830 | case IndirectLocalPathEntry::TemporaryCopy: | |||
| 7831 | case IndirectLocalPathEntry::GslReferenceInit: | |||
| 7832 | case IndirectLocalPathEntry::GslPointerInit: | |||
| 7833 | // These exist primarily to mark the path as not permitting or | |||
| 7834 | // supporting lifetime extension. | |||
| 7835 | break; | |||
| 7836 | ||||
| 7837 | case IndirectLocalPathEntry::VarInit: | |||
| 7838 | if (cast<VarDecl>(Path[I].D)->isImplicit()) | |||
| 7839 | return SourceRange(); | |||
| 7840 | [[fallthrough]]; | |||
| 7841 | case IndirectLocalPathEntry::DefaultInit: | |||
| 7842 | return Path[I].E->getSourceRange(); | |||
| 7843 | ||||
| 7844 | case IndirectLocalPathEntry::LambdaCaptureInit: | |||
| 7845 | if (!Path[I].Capture->capturesVariable()) | |||
| 7846 | continue; | |||
| 7847 | return Path[I].E->getSourceRange(); | |||
| 7848 | } | |||
| 7849 | } | |||
| 7850 | return E->getSourceRange(); | |||
| 7851 | } | |||
| 7852 | ||||
| 7853 | static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) { | |||
| 7854 | for (const auto &It : llvm::reverse(Path)) { | |||
| 7855 | if (It.Kind == IndirectLocalPathEntry::VarInit) | |||
| 7856 | continue; | |||
| 7857 | if (It.Kind == IndirectLocalPathEntry::AddressOf) | |||
| 7858 | continue; | |||
| 7859 | if (It.Kind == IndirectLocalPathEntry::LifetimeBoundCall) | |||
| 7860 | continue; | |||
| 7861 | return It.Kind == IndirectLocalPathEntry::GslPointerInit || | |||
| 7862 | It.Kind == IndirectLocalPathEntry::GslReferenceInit; | |||
| 7863 | } | |||
| 7864 | return false; | |||
| 7865 | } | |||
| 7866 | ||||
| 7867 | void Sema::checkInitializerLifetime(const InitializedEntity &Entity, | |||
| 7868 | Expr *Init) { | |||
| 7869 | LifetimeResult LR = getEntityLifetime(&Entity); | |||
| 7870 | LifetimeKind LK = LR.getInt(); | |||
| 7871 | const InitializedEntity *ExtendingEntity = LR.getPointer(); | |||
| 7872 | ||||
| 7873 | // If this entity doesn't have an interesting lifetime, don't bother looking | |||
| 7874 | // for temporaries within its initializer. | |||
| 7875 | if (LK == LK_FullExpression) | |||
| 7876 | return; | |||
| 7877 | ||||
| 7878 | auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L, | |||
| 7879 | ReferenceKind RK) -> bool { | |||
| 7880 | SourceRange DiagRange = nextPathEntryRange(Path, 0, L); | |||
| 7881 | SourceLocation DiagLoc = DiagRange.getBegin(); | |||
| 7882 | ||||
| 7883 | auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L); | |||
| 7884 | ||||
| 7885 | bool IsGslPtrInitWithGslTempOwner = false; | |||
| 7886 | bool IsLocalGslOwner = false; | |||
| 7887 | if (pathOnlyInitializesGslPointer(Path)) { | |||
| 7888 | if (isa<DeclRefExpr>(L)) { | |||
| 7889 | // We do not want to follow the references when returning a pointer originating | |||
| 7890 | // from a local owner to avoid the following false positive: | |||
| 7891 | // int &p = *localUniquePtr; | |||
| 7892 | // someContainer.add(std::move(localUniquePtr)); | |||
| 7893 | // return p; | |||
| 7894 | IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType()); | |||
| 7895 | if (pathContainsInit(Path) || !IsLocalGslOwner) | |||
| 7896 | return false; | |||
| 7897 | } else { | |||
| 7898 | IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() && | |||
| 7899 | isRecordWithAttr<OwnerAttr>(MTE->getType()); | |||
| 7900 | // Skipping a chain of initializing gsl::Pointer annotated objects. | |||
| 7901 | // We are looking only for the final source to find out if it was | |||
| 7902 | // a local or temporary owner or the address of a local variable/param. | |||
| 7903 | if (!IsGslPtrInitWithGslTempOwner) | |||
| 7904 | return true; | |||
| 7905 | } | |||
| 7906 | } | |||
| 7907 | ||||
| 7908 | switch (LK) { | |||
| 7909 | case LK_FullExpression: | |||
| 7910 | llvm_unreachable("already handled this")::llvm::llvm_unreachable_internal("already handled this", "clang/lib/Sema/SemaInit.cpp" , 7910); | |||
| 7911 | ||||
| 7912 | case LK_Extended: { | |||
| 7913 | if (!MTE) { | |||
| 7914 | // The initialized entity has lifetime beyond the full-expression, | |||
| 7915 | // and the local entity does too, so don't warn. | |||
| 7916 | // | |||
| 7917 | // FIXME: We should consider warning if a static / thread storage | |||
| 7918 | // duration variable retains an automatic storage duration local. | |||
| 7919 | return false; | |||
| 7920 | } | |||
| 7921 | ||||
| 7922 | if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) { | |||
| 7923 | Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange; | |||
| 7924 | return false; | |||
| 7925 | } | |||
| 7926 | ||||
| 7927 | switch (shouldLifetimeExtendThroughPath(Path)) { | |||
| 7928 | case PathLifetimeKind::Extend: | |||
| 7929 | // Update the storage duration of the materialized temporary. | |||
| 7930 | // FIXME: Rebuild the expression instead of mutating it. | |||
| 7931 | MTE->setExtendingDecl(ExtendingEntity->getDecl(), | |||
| 7932 | ExtendingEntity->allocateManglingNumber()); | |||
| 7933 | // Also visit the temporaries lifetime-extended by this initializer. | |||
| 7934 | return true; | |||
| 7935 | ||||
| 7936 | case PathLifetimeKind::ShouldExtend: | |||
| 7937 | // We're supposed to lifetime-extend the temporary along this path (per | |||
| 7938 | // the resolution of DR1815), but we don't support that yet. | |||
| 7939 | // | |||
| 7940 | // FIXME: Properly handle this situation. Perhaps the easiest approach | |||
| 7941 | // would be to clone the initializer expression on each use that would | |||
| 7942 | // lifetime extend its temporaries. | |||
| 7943 | Diag(DiagLoc, diag::warn_unsupported_lifetime_extension) | |||
| 7944 | << RK << DiagRange; | |||
| 7945 | break; | |||
| 7946 | ||||
| 7947 | case PathLifetimeKind::NoExtend: | |||
| 7948 | // If the path goes through the initialization of a variable or field, | |||
| 7949 | // it can't possibly reach a temporary created in this full-expression. | |||
| 7950 | // We will have already diagnosed any problems with the initializer. | |||
| 7951 | if (pathContainsInit(Path)) | |||
| 7952 | return false; | |||
| 7953 | ||||
| 7954 | Diag(DiagLoc, diag::warn_dangling_variable) | |||
| 7955 | << RK << !Entity.getParent() | |||
| 7956 | << ExtendingEntity->getDecl()->isImplicit() | |||
| 7957 | << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange; | |||
| 7958 | break; | |||
| 7959 | } | |||
| 7960 | break; | |||
| 7961 | } | |||
| 7962 | ||||
| 7963 | case LK_MemInitializer: { | |||
| 7964 | if (isa<MaterializeTemporaryExpr>(L)) { | |||
| 7965 | // Under C++ DR1696, if a mem-initializer (or a default member | |||
| 7966 | // initializer used by the absence of one) would lifetime-extend a | |||
| 7967 | // temporary, the program is ill-formed. | |||
| 7968 | if (auto *ExtendingDecl = | |||
| 7969 | ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { | |||
| 7970 | if (IsGslPtrInitWithGslTempOwner) { | |||
| 7971 | Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member) | |||
| 7972 | << ExtendingDecl << DiagRange; | |||
| 7973 | Diag(ExtendingDecl->getLocation(), | |||
| 7974 | diag::note_ref_or_ptr_member_declared_here) | |||
| 7975 | << true; | |||
| 7976 | return false; | |||
| 7977 | } | |||
| 7978 | bool IsSubobjectMember = ExtendingEntity != &Entity; | |||
| 7979 | Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) != | |||
| 7980 | PathLifetimeKind::NoExtend | |||
| 7981 | ? diag::err_dangling_member | |||
| 7982 | : diag::warn_dangling_member) | |||
| 7983 | << ExtendingDecl << IsSubobjectMember << RK << DiagRange; | |||
| 7984 | // Don't bother adding a note pointing to the field if we're inside | |||
| 7985 | // its default member initializer; our primary diagnostic points to | |||
| 7986 | // the same place in that case. | |||
| 7987 | if (Path.empty() || | |||
| 7988 | Path.back().Kind != IndirectLocalPathEntry::DefaultInit) { | |||
| 7989 | Diag(ExtendingDecl->getLocation(), | |||
| 7990 | diag::note_lifetime_extending_member_declared_here) | |||
| 7991 | << RK << IsSubobjectMember; | |||
| 7992 | } | |||
| 7993 | } else { | |||
| 7994 | // We have a mem-initializer but no particular field within it; this | |||
| 7995 | // is either a base class or a delegating initializer directly | |||
| 7996 | // initializing the base-class from something that doesn't live long | |||
| 7997 | // enough. | |||
| 7998 | // | |||
| 7999 | // FIXME: Warn on this. | |||
| 8000 | return false; | |||
| 8001 | } | |||
| 8002 | } else { | |||
| 8003 | // Paths via a default initializer can only occur during error recovery | |||
| 8004 | // (there's no other way that a default initializer can refer to a | |||
| 8005 | // local). Don't produce a bogus warning on those cases. | |||
| 8006 | if (pathContainsInit(Path)) | |||
| 8007 | return false; | |||
| 8008 | ||||
| 8009 | // Suppress false positives for code like the one below: | |||
| 8010 | // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {} | |||
| 8011 | if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path)) | |||
| 8012 | return false; | |||
| 8013 | ||||
| 8014 | auto *DRE = dyn_cast<DeclRefExpr>(L); | |||
| 8015 | auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr; | |||
| 8016 | if (!VD) { | |||
| 8017 | // A member was initialized to a local block. | |||
| 8018 | // FIXME: Warn on this. | |||
| 8019 | return false; | |||
| 8020 | } | |||
| 8021 | ||||
| 8022 | if (auto *Member = | |||
| 8023 | ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { | |||
| 8024 | bool IsPointer = !Member->getType()->isReferenceType(); | |||
| 8025 | Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr | |||
| 8026 | : diag::warn_bind_ref_member_to_parameter) | |||
| 8027 | << Member << VD << isa<ParmVarDecl>(VD) << DiagRange; | |||
| 8028 | Diag(Member->getLocation(), | |||
| 8029 | diag::note_ref_or_ptr_member_declared_here) | |||
| 8030 | << (unsigned)IsPointer; | |||
| 8031 | } | |||
| 8032 | } | |||
| 8033 | break; | |||
| 8034 | } | |||
| 8035 | ||||
| 8036 | case LK_New: | |||
| 8037 | if (isa<MaterializeTemporaryExpr>(L)) { | |||
| 8038 | if (IsGslPtrInitWithGslTempOwner) | |||
| 8039 | Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange; | |||
| 8040 | else | |||
| 8041 | Diag(DiagLoc, RK == RK_ReferenceBinding | |||
| 8042 | ? diag::warn_new_dangling_reference | |||
| 8043 | : diag::warn_new_dangling_initializer_list) | |||
| 8044 | << !Entity.getParent() << DiagRange; | |||
| 8045 | } else { | |||
| 8046 | // We can't determine if the allocation outlives the local declaration. | |||
| 8047 | return false; | |||
| 8048 | } | |||
| 8049 | break; | |||
| 8050 | ||||
| 8051 | case LK_Return: | |||
| 8052 | case LK_StmtExprResult: | |||
| 8053 | if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { | |||
| 8054 | // We can't determine if the local variable outlives the statement | |||
| 8055 | // expression. | |||
| 8056 | if (LK == LK_StmtExprResult) | |||
| 8057 | return false; | |||
| 8058 | Diag(DiagLoc, diag::warn_ret_stack_addr_ref) | |||
| 8059 | << Entity.getType()->isReferenceType() << DRE->getDecl() | |||
| 8060 | << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange; | |||
| 8061 | } else if (isa<BlockExpr>(L)) { | |||
| 8062 | Diag(DiagLoc, diag::err_ret_local_block) << DiagRange; | |||
| 8063 | } else if (isa<AddrLabelExpr>(L)) { | |||
| 8064 | // Don't warn when returning a label from a statement expression. | |||
| 8065 | // Leaving the scope doesn't end its lifetime. | |||
| 8066 | if (LK == LK_StmtExprResult) | |||
| 8067 | return false; | |||
| 8068 | Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange; | |||
| 8069 | } else { | |||
| 8070 | Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref) | |||
| 8071 | << Entity.getType()->isReferenceType() << DiagRange; | |||
| 8072 | } | |||
| 8073 | break; | |||
| 8074 | } | |||
| 8075 | ||||
| 8076 | for (unsigned I = 0; I != Path.size(); ++I) { | |||
| 8077 | auto Elem = Path[I]; | |||
| 8078 | ||||
| 8079 | switch (Elem.Kind) { | |||
| 8080 | case IndirectLocalPathEntry::AddressOf: | |||
| 8081 | case IndirectLocalPathEntry::LValToRVal: | |||
| 8082 | // These exist primarily to mark the path as not permitting or | |||
| 8083 | // supporting lifetime extension. | |||
| 8084 | break; | |||
| 8085 | ||||
| 8086 | case IndirectLocalPathEntry::LifetimeBoundCall: | |||
| 8087 | case IndirectLocalPathEntry::TemporaryCopy: | |||
| 8088 | case IndirectLocalPathEntry::GslPointerInit: | |||
| 8089 | case IndirectLocalPathEntry::GslReferenceInit: | |||
| 8090 | // FIXME: Consider adding a note for these. | |||
| 8091 | break; | |||
| 8092 | ||||
| 8093 | case IndirectLocalPathEntry::DefaultInit: { | |||
| 8094 | auto *FD = cast<FieldDecl>(Elem.D); | |||
| 8095 | Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer) | |||
| 8096 | << FD << nextPathEntryRange(Path, I + 1, L); | |||
| 8097 | break; | |||
| 8098 | } | |||
| 8099 | ||||
| 8100 | case IndirectLocalPathEntry::VarInit: { | |||
| 8101 | const VarDecl *VD = cast<VarDecl>(Elem.D); | |||
| 8102 | Diag(VD->getLocation(), diag::note_local_var_initializer) | |||
| 8103 | << VD->getType()->isReferenceType() | |||
| 8104 | << VD->isImplicit() << VD->getDeclName() | |||
| 8105 | << nextPathEntryRange(Path, I + 1, L); | |||
| 8106 | break; | |||
| 8107 | } | |||
| 8108 | ||||
| 8109 | case IndirectLocalPathEntry::LambdaCaptureInit: | |||
| 8110 | if (!Elem.Capture->capturesVariable()) | |||
| 8111 | break; | |||
| 8112 | // FIXME: We can't easily tell apart an init-capture from a nested | |||
| 8113 | // capture of an init-capture. | |||
| 8114 | const ValueDecl *VD = Elem.Capture->getCapturedVar(); | |||
| 8115 | Diag(Elem.Capture->getLocation(), diag::note_lambda_capture_initializer) | |||
| 8116 | << VD << VD->isInitCapture() << Elem.Capture->isExplicit() | |||
| 8117 | << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD | |||
| 8118 | << nextPathEntryRange(Path, I + 1, L); | |||
| 8119 | break; | |||
| 8120 | } | |||
| 8121 | } | |||
| 8122 | ||||
| 8123 | // We didn't lifetime-extend, so don't go any further; we don't need more | |||
| 8124 | // warnings or errors on inner temporaries within this one's initializer. | |||
| 8125 | return false; | |||
| 8126 | }; | |||
| 8127 | ||||
| 8128 | bool EnableLifetimeWarnings = !getDiagnostics().isIgnored( | |||
| 8129 | diag::warn_dangling_lifetime_pointer, SourceLocation()); | |||
| 8130 | llvm::SmallVector<IndirectLocalPathEntry, 8> Path; | |||
| 8131 | if (Init->isGLValue()) | |||
| 8132 | visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding, | |||
| 8133 | TemporaryVisitor, | |||
| 8134 | EnableLifetimeWarnings); | |||
| 8135 | else | |||
| 8136 | visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false, | |||
| 8137 | EnableLifetimeWarnings); | |||
| 8138 | } | |||
| 8139 | ||||
| 8140 | static void DiagnoseNarrowingInInitList(Sema &S, | |||
| 8141 | const ImplicitConversionSequence &ICS, | |||
| 8142 | QualType PreNarrowingType, | |||
| 8143 | QualType EntityType, | |||
| 8144 | const Expr *PostInit); | |||
| 8145 | ||||
| 8146 | /// Provide warnings when std::move is used on construction. | |||
| 8147 | static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, | |||
| 8148 | bool IsReturnStmt) { | |||
| 8149 | if (!InitExpr) | |||
| 8150 | return; | |||
| 8151 | ||||
| 8152 | if (S.inTemplateInstantiation()) | |||
| 8153 | return; | |||
| 8154 | ||||
| 8155 | QualType DestType = InitExpr->getType(); | |||
| 8156 | if (!DestType->isRecordType()) | |||
| 8157 | return; | |||
| 8158 | ||||
| 8159 | unsigned DiagID = 0; | |||
| 8160 | if (IsReturnStmt) { | |||
| 8161 | const CXXConstructExpr *CCE = | |||
| 8162 | dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens()); | |||
| 8163 | if (!CCE || CCE->getNumArgs() != 1) | |||
| 8164 | return; | |||
| 8165 | ||||
| 8166 | if (!CCE->getConstructor()->isCopyOrMoveConstructor()) | |||
| 8167 | return; | |||
| 8168 | ||||
| 8169 | InitExpr = CCE->getArg(0)->IgnoreImpCasts(); | |||
| 8170 | } | |||
| 8171 | ||||
| 8172 | // Find the std::move call and get the argument. | |||
| 8173 | const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens()); | |||
| 8174 | if (!CE || !CE->isCallToStdMove()) | |||
| 8175 | return; | |||
| 8176 | ||||
| 8177 | const Expr *Arg = CE->getArg(0)->IgnoreImplicit(); | |||
| 8178 | ||||
| 8179 | if (IsReturnStmt) { | |||
| 8180 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts()); | |||
| 8181 | if (!DRE || DRE->refersToEnclosingVariableOrCapture()) | |||
| 8182 | return; | |||
| 8183 | ||||
| 8184 | const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()); | |||
| 8185 | if (!VD || !VD->hasLocalStorage()) | |||
| 8186 | return; | |||
| 8187 | ||||
| 8188 | // __block variables are not moved implicitly. | |||
| 8189 | if (VD->hasAttr<BlocksAttr>()) | |||
| 8190 | return; | |||
| 8191 | ||||
| 8192 | QualType SourceType = VD->getType(); | |||
| 8193 | if (!SourceType->isRecordType()) | |||
| 8194 | return; | |||
| 8195 | ||||
| 8196 | if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) { | |||
| 8197 | return; | |||
| 8198 | } | |||
| 8199 | ||||
| 8200 | // If we're returning a function parameter, copy elision | |||
| 8201 | // is not possible. | |||
| 8202 | if (isa<ParmVarDecl>(VD)) | |||
| 8203 | DiagID = diag::warn_redundant_move_on_return; | |||
| 8204 | else | |||
| 8205 | DiagID = diag::warn_pessimizing_move_on_return; | |||
| 8206 | } else { | |||
| 8207 | DiagID = diag::warn_pessimizing_move_on_initialization; | |||
| 8208 | const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens(); | |||
| 8209 | if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType()) | |||
| 8210 | return; | |||
| 8211 | } | |||
| 8212 | ||||
| 8213 | S.Diag(CE->getBeginLoc(), DiagID); | |||
| 8214 | ||||
| 8215 | // Get all the locations for a fix-it. Don't emit the fix-it if any location | |||
| 8216 | // is within a macro. | |||
| 8217 | SourceLocation CallBegin = CE->getCallee()->getBeginLoc(); | |||
| 8218 | if (CallBegin.isMacroID()) | |||
| 8219 | return; | |||
| 8220 | SourceLocation RParen = CE->getRParenLoc(); | |||
| 8221 | if (RParen.isMacroID()) | |||
| 8222 | return; | |||
| 8223 | SourceLocation LParen; | |||
| 8224 | SourceLocation ArgLoc = Arg->getBeginLoc(); | |||
| 8225 | ||||
| 8226 | // Special testing for the argument location. Since the fix-it needs the | |||
| 8227 | // location right before the argument, the argument location can be in a | |||
| 8228 | // macro only if it is at the beginning of the macro. | |||
| 8229 | while (ArgLoc.isMacroID() && | |||
| 8230 | S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) { | |||
| 8231 | ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin(); | |||
| 8232 | } | |||
| 8233 | ||||
| 8234 | if (LParen.isMacroID()) | |||
| 8235 | return; | |||
| 8236 | ||||
| 8237 | LParen = ArgLoc.getLocWithOffset(-1); | |||
| 8238 | ||||
| 8239 | S.Diag(CE->getBeginLoc(), diag::note_remove_move) | |||
| 8240 | << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen)) | |||
| 8241 | << FixItHint::CreateRemoval(SourceRange(RParen, RParen)); | |||
| 8242 | } | |||
| 8243 | ||||
| 8244 | static void CheckForNullPointerDereference(Sema &S, const Expr *E) { | |||
| 8245 | // Check to see if we are dereferencing a null pointer. If so, this is | |||
| 8246 | // undefined behavior, so warn about it. This only handles the pattern | |||
| 8247 | // "*null", which is a very syntactic check. | |||
| 8248 | if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) | |||
| 8249 | if (UO->getOpcode() == UO_Deref && | |||
| 8250 | UO->getSubExpr()->IgnoreParenCasts()-> | |||
| 8251 | isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) { | |||
| 8252 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | |||
| 8253 | S.PDiag(diag::warn_binding_null_to_reference) | |||
| 8254 | << UO->getSubExpr()->getSourceRange()); | |||
| 8255 | } | |||
| 8256 | } | |||
| 8257 | ||||
| 8258 | MaterializeTemporaryExpr * | |||
| 8259 | Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, | |||
| 8260 | bool BoundToLvalueReference) { | |||
| 8261 | auto MTE = new (Context) | |||
| 8262 | MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference); | |||
| 8263 | ||||
| 8264 | // Order an ExprWithCleanups for lifetime marks. | |||
| 8265 | // | |||
| 8266 | // TODO: It'll be good to have a single place to check the access of the | |||
| 8267 | // destructor and generate ExprWithCleanups for various uses. Currently these | |||
| 8268 | // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary, | |||
| 8269 | // but there may be a chance to merge them. | |||
| 8270 | Cleanup.setExprNeedsCleanups(false); | |||
| 8271 | return MTE; | |||
| 8272 | } | |||
| 8273 | ||||
| 8274 | ExprResult Sema::TemporaryMaterializationConversion(Expr *E) { | |||
| 8275 | // In C++98, we don't want to implicitly create an xvalue. | |||
| 8276 | // FIXME: This means that AST consumers need to deal with "prvalues" that | |||
| 8277 | // denote materialized temporaries. Maybe we should add another ValueKind | |||
| 8278 | // for "xvalue pretending to be a prvalue" for C++98 support. | |||
| 8279 | if (!E->isPRValue() || !getLangOpts().CPlusPlus11) | |||
| 8280 | return E; | |||
| 8281 | ||||
| 8282 | // C++1z [conv.rval]/1: T shall be a complete type. | |||
| 8283 | // FIXME: Does this ever matter (can we form a prvalue of incomplete type)? | |||
| 8284 | // If so, we should check for a non-abstract class type here too. | |||
| 8285 | QualType T = E->getType(); | |||
| 8286 | if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type)) | |||
| 8287 | return ExprError(); | |||
| 8288 | ||||
| 8289 | return CreateMaterializeTemporaryExpr(E->getType(), E, false); | |||
| 8290 | } | |||
| 8291 | ||||
| 8292 | ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty, | |||
| 8293 | ExprValueKind VK, | |||
| 8294 | CheckedConversionKind CCK) { | |||
| 8295 | ||||
| 8296 | CastKind CK = CK_NoOp; | |||
| 8297 | ||||
| 8298 | if (VK == VK_PRValue) { | |||
| 8299 | auto PointeeTy = Ty->getPointeeType(); | |||
| 8300 | auto ExprPointeeTy = E->getType()->getPointeeType(); | |||
| 8301 | if (!PointeeTy.isNull() && | |||
| 8302 | PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace()) | |||
| 8303 | CK = CK_AddressSpaceConversion; | |||
| 8304 | } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) { | |||
| 8305 | CK = CK_AddressSpaceConversion; | |||
| 8306 | } | |||
| 8307 | ||||
| 8308 | return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK); | |||
| 8309 | } | |||
| 8310 | ||||
| 8311 | ExprResult InitializationSequence::Perform(Sema &S, | |||
| 8312 | const InitializedEntity &Entity, | |||
| 8313 | const InitializationKind &Kind, | |||
| 8314 | MultiExprArg Args, | |||
| 8315 | QualType *ResultType) { | |||
| 8316 | if (Failed()) { | |||
| 8317 | Diagnose(S, Entity, Kind, Args); | |||
| 8318 | return ExprError(); | |||
| 8319 | } | |||
| 8320 | if (!ZeroInitializationFixit.empty()) { | |||
| 8321 | const Decl *D = Entity.getDecl(); | |||
| 8322 | const auto *VD = dyn_cast_or_null<VarDecl>(D); | |||
| 8323 | QualType DestType = Entity.getType(); | |||
| 8324 | ||||
| 8325 | // The initialization would have succeeded with this fixit. Since the fixit | |||
| 8326 | // is on the error, we need to build a valid AST in this case, so this isn't | |||
| 8327 | // handled in the Failed() branch above. | |||
| 8328 | if (!DestType->isRecordType() && VD && VD->isConstexpr()) { | |||
| 8329 | // Use a more useful diagnostic for constexpr variables. | |||
| 8330 | S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init) | |||
| 8331 | << VD | |||
| 8332 | << FixItHint::CreateInsertion(ZeroInitializationFixitLoc, | |||
| 8333 | ZeroInitializationFixit); | |||
| 8334 | } else { | |||
| 8335 | unsigned DiagID = diag::err_default_init_const; | |||
| 8336 | if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>()) | |||
| 8337 | DiagID = diag::ext_default_init_const; | |||
| 8338 | ||||
| 8339 | S.Diag(Kind.getLocation(), DiagID) | |||
| 8340 | << DestType << (bool)DestType->getAs<RecordType>() | |||
| 8341 | << FixItHint::CreateInsertion(ZeroInitializationFixitLoc, | |||
| 8342 | ZeroInitializationFixit); | |||
| 8343 | } | |||
| 8344 | } | |||
| 8345 | ||||
| 8346 | if (getKind() == DependentSequence) { | |||
| 8347 | // If the declaration is a non-dependent, incomplete array type | |||
| 8348 | // that has an initializer, then its type will be completed once | |||
| 8349 | // the initializer is instantiated. | |||
| 8350 | if (ResultType && !Entity.getType()->isDependentType() && | |||
| 8351 | Args.size() == 1) { | |||
| 8352 | QualType DeclType = Entity.getType(); | |||
| 8353 | if (const IncompleteArrayType *ArrayT | |||
| 8354 | = S.Context.getAsIncompleteArrayType(DeclType)) { | |||
| 8355 | // FIXME: We don't currently have the ability to accurately | |||
| 8356 | // compute the length of an initializer list without | |||
| 8357 | // performing full type-checking of the initializer list | |||
| 8358 | // (since we have to determine where braces are implicitly | |||
| 8359 | // introduced and such). So, we fall back to making the array | |||
| 8360 | // type a dependently-sized array type with no specified | |||
| 8361 | // bound. | |||
| 8362 | if (isa<InitListExpr>((Expr *)Args[0])) { | |||
| 8363 | SourceRange Brackets; | |||
| 8364 | ||||
| 8365 | // Scavange the location of the brackets from the entity, if we can. | |||
| 8366 | if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) { | |||
| 8367 | if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { | |||
| 8368 | TypeLoc TL = TInfo->getTypeLoc(); | |||
| 8369 | if (IncompleteArrayTypeLoc ArrayLoc = | |||
| 8370 | TL.getAs<IncompleteArrayTypeLoc>()) | |||
| 8371 | Brackets = ArrayLoc.getBracketsRange(); | |||
| 8372 | } | |||
| 8373 | } | |||
| 8374 | ||||
| 8375 | *ResultType | |||
| 8376 | = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), | |||
| 8377 | /*NumElts=*/nullptr, | |||
| 8378 | ArrayT->getSizeModifier(), | |||
| 8379 | ArrayT->getIndexTypeCVRQualifiers(), | |||
| 8380 | Brackets); | |||
| 8381 | } | |||
| 8382 | ||||
| 8383 | } | |||
| 8384 | } | |||
| 8385 | if (Kind.getKind() == InitializationKind::IK_Direct && | |||
| 8386 | !Kind.isExplicitCast()) { | |||
| 8387 | // Rebuild the ParenListExpr. | |||
| 8388 | SourceRange ParenRange = Kind.getParenOrBraceRange(); | |||
| 8389 | return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(), | |||
| 8390 | Args); | |||
| 8391 | } | |||
| 8392 | assert(Kind.getKind() == InitializationKind::IK_Copy ||(static_cast <bool> (Kind.getKind() == InitializationKind ::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind ::IK_DirectList) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList" , "clang/lib/Sema/SemaInit.cpp", 8394, __extension__ __PRETTY_FUNCTION__ )) | |||
| 8393 | Kind.isExplicitCast() ||(static_cast <bool> (Kind.getKind() == InitializationKind ::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind ::IK_DirectList) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList" , "clang/lib/Sema/SemaInit.cpp", 8394, __extension__ __PRETTY_FUNCTION__ )) | |||
| 8394 | Kind.getKind() == InitializationKind::IK_DirectList)(static_cast <bool> (Kind.getKind() == InitializationKind ::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind ::IK_DirectList) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList" , "clang/lib/Sema/SemaInit.cpp", 8394, __extension__ __PRETTY_FUNCTION__ )); | |||
| 8395 | return ExprResult(Args[0]); | |||
| 8396 | } | |||
| 8397 | ||||
| 8398 | // No steps means no initialization. | |||
| 8399 | if (Steps.empty()) | |||
| 8400 | return ExprResult((Expr *)nullptr); | |||
| 8401 | ||||
| 8402 | if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() && | |||
| 8403 | Args.size() == 1 && isa<InitListExpr>(Args[0]) && | |||
| 8404 | !Entity.isParamOrTemplateParamKind()) { | |||
| 8405 | // Produce a C++98 compatibility warning if we are initializing a reference | |||
| 8406 | // from an initializer list. For parameters, we produce a better warning | |||
| 8407 | // elsewhere. | |||
| 8408 | Expr *Init = Args[0]; | |||
| 8409 | S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init) | |||
| 8410 | << Init->getSourceRange(); | |||
| 8411 | } | |||
| 8412 | ||||
| 8413 | // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope | |||
| 8414 | QualType ETy = Entity.getType(); | |||
| 8415 | bool HasGlobalAS = ETy.hasAddressSpace() && | |||
| 8416 | ETy.getAddressSpace() == LangAS::opencl_global; | |||
| 8417 | ||||
| 8418 | if (S.getLangOpts().OpenCLVersion >= 200 && | |||
| 8419 | ETy->isAtomicType() && !HasGlobalAS && | |||
| 8420 | Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) { | |||
| 8421 | S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init) | |||
| 8422 | << 1 | |||
| 8423 | << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc()); | |||
| 8424 | return ExprError(); | |||
| 8425 | } | |||
| 8426 | ||||
| 8427 | QualType DestType = Entity.getType().getNonReferenceType(); | |||
| 8428 | // FIXME: Ugly hack around the fact that Entity.getType() is not | |||
| 8429 | // the same as Entity.getDecl()->getType() in cases involving type merging, | |||
| 8430 | // and we want latter when it makes sense. | |||
| 8431 | if (ResultType) | |||
| 8432 | *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : | |||
| 8433 | Entity.getType(); | |||
| 8434 | ||||
| 8435 | ExprResult CurInit((Expr *)nullptr); | |||
| 8436 | SmallVector<Expr*, 4> ArrayLoopCommonExprs; | |||
| 8437 | ||||
| 8438 | // HLSL allows vector initialization to function like list initialization, but | |||
| 8439 | // use the syntax of a C++-like constructor. | |||
| 8440 | bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() && | |||
| 8441 | isa<InitListExpr>(Args[0]); | |||
| 8442 | (void)IsHLSLVectorInit; | |||
| 8443 | ||||
| 8444 | // For initialization steps that start with a single initializer, | |||
| 8445 | // grab the only argument out the Args and place it into the "current" | |||
| 8446 | // initializer. | |||
| 8447 | switch (Steps.front().Kind) { | |||
| 8448 | case SK_ResolveAddressOfOverloadedFunction: | |||
| 8449 | case SK_CastDerivedToBasePRValue: | |||
| 8450 | case SK_CastDerivedToBaseXValue: | |||
| 8451 | case SK_CastDerivedToBaseLValue: | |||
| 8452 | case SK_BindReference: | |||
| 8453 | case SK_BindReferenceToTemporary: | |||
| 8454 | case SK_FinalCopy: | |||
| 8455 | case SK_ExtraneousCopyToTemporary: | |||
| 8456 | case SK_UserConversion: | |||
| 8457 | case SK_QualificationConversionLValue: | |||
| 8458 | case SK_QualificationConversionXValue: | |||
| 8459 | case SK_QualificationConversionPRValue: | |||
| 8460 | case SK_FunctionReferenceConversion: | |||
| 8461 | case SK_AtomicConversion: | |||
| 8462 | case SK_ConversionSequence: | |||
| 8463 | case SK_ConversionSequenceNoNarrowing: | |||
| 8464 | case SK_ListInitialization: | |||
| 8465 | case SK_UnwrapInitList: | |||
| 8466 | case SK_RewrapInitList: | |||
| 8467 | case SK_CAssignment: | |||
| 8468 | case SK_StringInit: | |||
| 8469 | case SK_ObjCObjectConversion: | |||
| 8470 | case SK_ArrayLoopIndex: | |||
| 8471 | case SK_ArrayLoopInit: | |||
| 8472 | case SK_ArrayInit: | |||
| 8473 | case SK_GNUArrayInit: | |||
| 8474 | case SK_ParenthesizedArrayInit: | |||
| 8475 | case SK_PassByIndirectCopyRestore: | |||
| 8476 | case SK_PassByIndirectRestore: | |||
| 8477 | case SK_ProduceObjCObject: | |||
| 8478 | case SK_StdInitializerList: | |||
| 8479 | case SK_OCLSamplerInit: | |||
| 8480 | case SK_OCLZeroOpaqueType: { | |||
| 8481 | assert(Args.size() == 1 || IsHLSLVectorInit)(static_cast <bool> (Args.size() == 1 || IsHLSLVectorInit ) ? void (0) : __assert_fail ("Args.size() == 1 || IsHLSLVectorInit" , "clang/lib/Sema/SemaInit.cpp", 8481, __extension__ __PRETTY_FUNCTION__ )); | |||
| 8482 | CurInit = Args[0]; | |||
| 8483 | if (!CurInit.get()) return ExprError(); | |||
| 8484 | break; | |||
| 8485 | } | |||
| 8486 | ||||
| 8487 | case SK_ConstructorInitialization: | |||
| 8488 | case SK_ConstructorInitializationFromList: | |||
| 8489 | case SK_StdInitializerListConstructorCall: | |||
| 8490 | case SK_ZeroInitialization: | |||
| 8491 | case SK_ParenthesizedListInit: | |||
| 8492 | break; | |||
| 8493 | } | |||
| 8494 | ||||
| 8495 | // Promote from an unevaluated context to an unevaluated list context in | |||
| 8496 | // C++11 list-initialization; we need to instantiate entities usable in | |||
| 8497 | // constant expressions here in order to perform narrowing checks =( | |||
| 8498 | EnterExpressionEvaluationContext Evaluated( | |||
| 8499 | S, EnterExpressionEvaluationContext::InitList, | |||
| 8500 | CurInit.get() && isa<InitListExpr>(CurInit.get())); | |||
| 8501 | ||||
| 8502 | // C++ [class.abstract]p2: | |||
| 8503 | // no objects of an abstract class can be created except as subobjects | |||
| 8504 | // of a class derived from it | |||
| 8505 | auto checkAbstractType = [&](QualType T) -> bool { | |||
| 8506 | if (Entity.getKind() == InitializedEntity::EK_Base || | |||
| 8507 | Entity.getKind() == InitializedEntity::EK_Delegating) | |||
| 8508 | return false; | |||
| 8509 | return S.RequireNonAbstractType(Kind.getLocation(), T, | |||
| 8510 | diag::err_allocation_of_abstract_type); | |||
| 8511 | }; | |||
| 8512 | ||||
| 8513 | // Walk through the computed steps for the initialization sequence, | |||
| 8514 | // performing the specified conversions along the way. | |||
| 8515 | bool ConstructorInitRequiresZeroInit = false; | |||
| 8516 | for (step_iterator Step = step_begin(), StepEnd = step_end(); | |||
| 8517 | Step != StepEnd; ++Step) { | |||
| 8518 | if (CurInit.isInvalid()) | |||
| 8519 | return ExprError(); | |||
| 8520 | ||||
| 8521 | QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); | |||
| 8522 | ||||
| 8523 | switch (Step->Kind) { | |||
| 8524 | case SK_ResolveAddressOfOverloadedFunction: | |||
| 8525 | // Overload resolution determined which function invoke; update the | |||
| 8526 | // initializer to reflect that choice. | |||
| 8527 | S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl); | |||
| 8528 | if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation())) | |||
| 8529 | return ExprError(); | |||
| 8530 | CurInit = S.FixOverloadedFunctionReference(CurInit, | |||
| 8531 | Step->Function.FoundDecl, | |||
| 8532 | Step->Function.Function); | |||
| 8533 | // We might get back another placeholder expression if we resolved to a | |||
| 8534 | // builtin. | |||
| 8535 | if (!CurInit.isInvalid()) | |||
| 8536 | CurInit = S.CheckPlaceholderExpr(CurInit.get()); | |||
| 8537 | break; | |||
| 8538 | ||||
| 8539 | case SK_CastDerivedToBasePRValue: | |||
| 8540 | case SK_CastDerivedToBaseXValue: | |||
| 8541 | case SK_CastDerivedToBaseLValue: { | |||
| 8542 | // We have a derived-to-base cast that produces either an rvalue or an | |||
| 8543 | // lvalue. Perform that cast. | |||
| 8544 | ||||
| 8545 | CXXCastPath BasePath; | |||
| 8546 | ||||
| 8547 | // Casts to inaccessible base classes are allowed with C-style casts. | |||
| 8548 | bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); | |||
| 8549 | if (S.CheckDerivedToBaseConversion( | |||
| 8550 | SourceType, Step->Type, CurInit.get()->getBeginLoc(), | |||
| 8551 | CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess)) | |||
| 8552 | return ExprError(); | |||
| 8553 | ||||
| 8554 | ExprValueKind VK = | |||
| 8555 | Step->Kind == SK_CastDerivedToBaseLValue | |||
| 8556 | ? VK_LValue | |||
| 8557 | : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue | |||
| 8558 | : VK_PRValue); | |||
| 8559 | CurInit = ImplicitCastExpr::Create(S.Context, Step->Type, | |||
| 8560 | CK_DerivedToBase, CurInit.get(), | |||
| 8561 | &BasePath, VK, FPOptionsOverride()); | |||
| 8562 | break; | |||
| 8563 | } | |||
| 8564 | ||||
| 8565 | case SK_BindReference: | |||
| 8566 | // Reference binding does not have any corresponding ASTs. | |||
| 8567 | ||||
| 8568 | // Check exception specifications | |||
| 8569 | if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) | |||
| 8570 | return ExprError(); | |||
| 8571 | ||||
| 8572 | // We don't check for e.g. function pointers here, since address | |||
| 8573 | // availability checks should only occur when the function first decays | |||
| 8574 | // into a pointer or reference. | |||
| 8575 | if (CurInit.get()->getType()->isFunctionProtoType()) { | |||
| 8576 | if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) { | |||
| 8577 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { | |||
| 8578 | if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | |||
| 8579 | DRE->getBeginLoc())) | |||
| 8580 | return ExprError(); | |||
| 8581 | } | |||
| 8582 | } | |||
| 8583 | } | |||
| 8584 | ||||
| 8585 | CheckForNullPointerDereference(S, CurInit.get()); | |||
| 8586 | break; | |||
| 8587 | ||||
| 8588 | case SK_BindReferenceToTemporary: { | |||
| 8589 | // Make sure the "temporary" is actually an rvalue. | |||
| 8590 | assert(CurInit.get()->isPRValue() && "not a temporary")(static_cast <bool> (CurInit.get()->isPRValue() && "not a temporary") ? void (0) : __assert_fail ("CurInit.get()->isPRValue() && \"not a temporary\"" , "clang/lib/Sema/SemaInit.cpp", 8590, __extension__ __PRETTY_FUNCTION__ )); | |||
| 8591 | ||||
| 8592 | // Check exception specifications | |||
| 8593 | if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) | |||
| 8594 | return ExprError(); | |||
| 8595 | ||||
| 8596 | QualType MTETy = Step->Type; | |||
| 8597 | ||||
| 8598 | // When this is an incomplete array type (such as when this is | |||
| 8599 | // initializing an array of unknown bounds from an init list), use THAT | |||
| 8600 | // type instead so that we propagate the array bounds. | |||
| 8601 | if (MTETy->isIncompleteArrayType() && | |||
| 8602 | !CurInit.get()->getType()->isIncompleteArrayType() && | |||
| 8603 | S.Context.hasSameType( | |||
| 8604 | MTETy->getPointeeOrArrayElementType(), | |||
| 8605 | CurInit.get()->getType()->getPointeeOrArrayElementType())) | |||
| 8606 | MTETy = CurInit.get()->getType(); | |||
| 8607 | ||||
| 8608 | // Materialize the temporary into memory. | |||
| 8609 | MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( | |||
| 8610 | MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType()); | |||
| 8611 | CurInit = MTE; | |||
| 8612 | ||||
| 8613 | // If we're extending this temporary to automatic storage duration -- we | |||
| 8614 | // need to register its cleanup during the full-expression's cleanups. | |||
| 8615 | if (MTE->getStorageDuration() == SD_Automatic && | |||
| 8616 | MTE->getType().isDestructedType()) | |||
| 8617 | S.Cleanup.setExprNeedsCleanups(true); | |||
| 8618 | break; | |||
| 8619 | } | |||
| 8620 | ||||
| 8621 | case SK_FinalCopy: | |||
| 8622 | if (checkAbstractType(Step->Type)) | |||
| 8623 | return ExprError(); | |||
| 8624 | ||||
| 8625 | // If the overall initialization is initializing a temporary, we already | |||
| 8626 | // bound our argument if it was necessary to do so. If not (if we're | |||
| 8627 | // ultimately initializing a non-temporary), our argument needs to be | |||
| 8628 | // bound since it's initializing a function parameter. | |||
| 8629 | // FIXME: This is a mess. Rationalize temporary destruction. | |||
| 8630 | if (!shouldBindAsTemporary(Entity)) | |||
| 8631 | CurInit = S.MaybeBindToTemporary(CurInit.get()); | |||
| 8632 | CurInit = CopyObject(S, Step->Type, Entity, CurInit, | |||
| 8633 | /*IsExtraneousCopy=*/false); | |||
| 8634 | break; | |||
| 8635 | ||||
| 8636 | case SK_ExtraneousCopyToTemporary: | |||
| 8637 | CurInit = CopyObject(S, Step->Type, Entity, CurInit, | |||
| 8638 | /*IsExtraneousCopy=*/true); | |||
| 8639 | break; | |||
| 8640 | ||||
| 8641 | case SK_UserConversion: { | |||
| 8642 | // We have a user-defined conversion that invokes either a constructor | |||
| 8643 | // or a conversion function. | |||
| 8644 | CastKind CastKind; | |||
| 8645 | FunctionDecl *Fn = Step->Function.Function; | |||
| 8646 | DeclAccessPair FoundFn = Step->Function.FoundDecl; | |||
| 8647 | bool HadMultipleCandidates = Step->Function.HadMultipleCandidates; | |||
| 8648 | bool CreatedObject = false; | |||
| 8649 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) { | |||
| 8650 | // Build a call to the selected constructor. | |||
| 8651 | SmallVector<Expr*, 8> ConstructorArgs; | |||
| 8652 | SourceLocation Loc = CurInit.get()->getBeginLoc(); | |||
| 8653 | ||||
| 8654 | // Determine the arguments required to actually perform the constructor | |||
| 8655 | // call. | |||
| 8656 | Expr *Arg = CurInit.get(); | |||
| 8657 | if (S.CompleteConstructorCall(Constructor, Step->Type, | |||
| 8658 | MultiExprArg(&Arg, 1), Loc, | |||
| 8659 | ConstructorArgs)) | |||
| 8660 | return ExprError(); | |||
| 8661 | ||||
| 8662 | // Build an expression that constructs a temporary. | |||
| 8663 | CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, | |||
| 8664 | FoundFn, Constructor, | |||
| 8665 | ConstructorArgs, | |||
| 8666 | HadMultipleCandidates, | |||
| 8667 | /*ListInit*/ false, | |||
| 8668 | /*StdInitListInit*/ false, | |||
| 8669 | /*ZeroInit*/ false, | |||
| 8670 | CXXConstructExpr::CK_Complete, | |||
| 8671 | SourceRange()); | |||
| 8672 | if (CurInit.isInvalid()) | |||
| 8673 | return ExprError(); | |||
| 8674 | ||||
| 8675 | S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn, | |||
| 8676 | Entity); | |||
| 8677 | if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) | |||
| 8678 | return ExprError(); | |||
| 8679 | ||||
| 8680 | CastKind = CK_ConstructorConversion; | |||
| 8681 | CreatedObject = true; | |||
| 8682 | } else { | |||
| 8683 | // Build a call to the conversion function. | |||
| 8684 | CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn); | |||
| 8685 | S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr, | |||
| 8686 | FoundFn); | |||
| 8687 | if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) | |||
| 8688 | return ExprError(); | |||
| 8689 | ||||
| 8690 | CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion, | |||
| 8691 | HadMultipleCandidates); | |||
| 8692 | if (CurInit.isInvalid()) | |||
| 8693 | return ExprError(); | |||
| 8694 | ||||
| 8695 | CastKind = CK_UserDefinedConversion; | |||
| 8696 | CreatedObject = Conversion->getReturnType()->isRecordType(); | |||
| 8697 | } | |||
| 8698 | ||||
| 8699 | if (CreatedObject && checkAbstractType(CurInit.get()->getType())) | |||
| 8700 | return ExprError(); | |||
| 8701 | ||||
| 8702 | CurInit = ImplicitCastExpr::Create( | |||
| 8703 | S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr, | |||
| 8704 | CurInit.get()->getValueKind(), S.CurFPFeatureOverrides()); | |||
| 8705 | ||||
| 8706 | if (shouldBindAsTemporary(Entity)) | |||
| 8707 | // The overall entity is temporary, so this expression should be | |||
| 8708 | // destroyed at the end of its full-expression. | |||
| 8709 | CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); | |||
| 8710 | else if (CreatedObject && shouldDestroyEntity(Entity)) { | |||
| 8711 | // The object outlasts the full-expression, but we need to prepare for | |||
| 8712 | // a destructor being run on it. | |||
| 8713 | // FIXME: It makes no sense to do this here. This should happen | |||
| 8714 | // regardless of how we initialized the entity. | |||
| 8715 | QualType T = CurInit.get()->getType(); | |||
| 8716 | if (const RecordType *Record = T->getAs<RecordType>()) { | |||
| 8717 | CXXDestructorDecl *Destructor | |||
| 8718 | = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl())); | |||
| 8719 | S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor, | |||
| 8720 | S.PDiag(diag::err_access_dtor_temp) << T); | |||
| 8721 | S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor); | |||
| 8722 | if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc())) | |||
| 8723 | return ExprError(); | |||
| 8724 | } | |||
| 8725 | } | |||
| 8726 | break; | |||
| 8727 | } | |||
| 8728 | ||||
| 8729 | case SK_QualificationConversionLValue: | |||
| 8730 | case SK_QualificationConversionXValue: | |||
| 8731 | case SK_QualificationConversionPRValue: { | |||
| 8732 | // Perform a qualification conversion; these can never go wrong. | |||
| 8733 | ExprValueKind VK = | |||
| 8734 | Step->Kind == SK_QualificationConversionLValue | |||
| 8735 | ? VK_LValue | |||
| 8736 | : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue | |||
| 8737 | : VK_PRValue); | |||
| 8738 | CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK); | |||
| 8739 | break; | |||
| 8740 | } | |||
| 8741 | ||||
| 8742 | case SK_FunctionReferenceConversion: | |||
| 8743 | assert(CurInit.get()->isLValue() &&(static_cast <bool> (CurInit.get()->isLValue() && "function reference should be lvalue") ? void (0) : __assert_fail ("CurInit.get()->isLValue() && \"function reference should be lvalue\"" , "clang/lib/Sema/SemaInit.cpp", 8744, __extension__ __PRETTY_FUNCTION__ )) | |||
| 8744 | "function reference should be lvalue")(static_cast <bool> (CurInit.get()->isLValue() && "function reference should be lvalue") ? void (0) : __assert_fail ("CurInit.get()->isLValue() && \"function reference should be lvalue\"" , "clang/lib/Sema/SemaInit.cpp", 8744, __extension__ __PRETTY_FUNCTION__ )); | |||
| 8745 | CurInit = | |||
| 8746 | S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue); | |||
| 8747 | break; | |||
| 8748 | ||||
| 8749 | case SK_AtomicConversion: { | |||
| 8750 | assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic")(static_cast <bool> (CurInit.get()->isPRValue() && "cannot convert glvalue to atomic") ? void (0) : __assert_fail ("CurInit.get()->isPRValue() && \"cannot convert glvalue to atomic\"" , "clang/lib/Sema/SemaInit.cpp", 8750, __extension__ __PRETTY_FUNCTION__ )); | |||
| 8751 | CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, | |||
| 8752 | CK_NonAtomicToAtomic, VK_PRValue); | |||
| 8753 | break; | |||
| 8754 | } | |||
| 8755 | ||||
| 8756 | case SK_ConversionSequence: | |||
| 8757 | case SK_ConversionSequenceNoNarrowing: { | |||
| 8758 | if (const auto *FromPtrType = | |||
| 8759 | CurInit.get()->getType()->getAs<PointerType>()) { | |||
| 8760 | if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) { | |||
| 8761 | if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) && | |||
| 8762 | !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { | |||
| 8763 | // Do not check static casts here because they are checked earlier | |||
| 8764 | // in Sema::ActOnCXXNamedCast() | |||
| 8765 | if (!Kind.isStaticCast()) { | |||
| 8766 | S.Diag(CurInit.get()->getExprLoc(), | |||
| 8767 | diag::warn_noderef_to_dereferenceable_pointer) | |||
| 8768 | << CurInit.get()->getSourceRange(); | |||
| 8769 | } | |||
| 8770 | } | |||
| 8771 | } | |||
| 8772 | } | |||
| 8773 | ||||
| 8774 | Sema::CheckedConversionKind CCK | |||
| 8775 | = Kind.isCStyleCast()? Sema::CCK_CStyleCast | |||
| 8776 | : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast | |||
| 8777 | : Kind.isExplicitCast()? Sema::CCK_OtherCast | |||
| 8778 | : Sema::CCK_ImplicitConversion; | |||
| 8779 | ExprResult CurInitExprRes = | |||
| 8780 | S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS, | |||
| 8781 | getAssignmentAction(Entity), CCK); | |||
| 8782 | if (CurInitExprRes.isInvalid()) | |||
| 8783 | return ExprError(); | |||
| 8784 | ||||
| 8785 | S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get()); | |||
| 8786 | ||||
| 8787 | CurInit = CurInitExprRes; | |||
| 8788 | ||||
| 8789 | if (Step->Kind == SK_ConversionSequenceNoNarrowing && | |||
| 8790 | S.getLangOpts().CPlusPlus) | |||
| 8791 | DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(), | |||
| 8792 | CurInit.get()); | |||
| 8793 | ||||
| 8794 | break; | |||
| 8795 | } | |||
| 8796 | ||||
| 8797 | case SK_ListInitialization: { | |||
| 8798 | if (checkAbstractType(Step->Type)) | |||
| 8799 | return ExprError(); | |||
| 8800 | ||||
| 8801 | InitListExpr *InitList = cast<InitListExpr>(CurInit.get()); | |||
| 8802 | // If we're not initializing the top-level entity, we need to create an | |||
| 8803 | // InitializeTemporary entity for our target type. | |||
| 8804 | QualType Ty = Step->Type; | |||
| 8805 | bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty); | |||
| 8806 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty); | |||
| 8807 | InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity; | |||
| 8808 | InitListChecker PerformInitList(S, InitEntity, | |||
| 8809 | InitList, Ty, /*VerifyOnly=*/false, | |||
| 8810 | /*TreatUnavailableAsInvalid=*/false); | |||
| 8811 | if (PerformInitList.HadError()) | |||
| 8812 | return ExprError(); | |||
| 8813 | ||||
| 8814 | // Hack: We must update *ResultType if available in order to set the | |||
| 8815 | // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'. | |||
| 8816 | // Worst case: 'const int (&arref)[] = {1, 2, 3};'. | |||
| 8817 | if (ResultType && | |||
| 8818 | ResultType->getNonReferenceType()->isIncompleteArrayType()) { | |||
| 8819 | if ((*ResultType)->isRValueReferenceType()) | |||
| 8820 | Ty = S.Context.getRValueReferenceType(Ty); | |||
| 8821 | else if ((*ResultType)->isLValueReferenceType()) | |||
| 8822 | Ty = S.Context.getLValueReferenceType(Ty, | |||
| 8823 | (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue()); | |||
| 8824 | *ResultType = Ty; | |||
| 8825 | } | |||
| 8826 | ||||
| 8827 | InitListExpr *StructuredInitList = | |||
| 8828 | PerformInitList.getFullyStructuredList(); | |||
| 8829 | CurInit.get(); | |||
| 8830 | CurInit = shouldBindAsTemporary(InitEntity) | |||
| 8831 | ? S.MaybeBindToTemporary(StructuredInitList) | |||
| 8832 | : StructuredInitList; | |||
| 8833 | break; | |||
| 8834 | } | |||
| 8835 | ||||
| 8836 | case SK_ConstructorInitializationFromList: { | |||
| 8837 | if (checkAbstractType(Step->Type)) | |||
| 8838 | return ExprError(); | |||
| 8839 | ||||
| 8840 | // When an initializer list is passed for a parameter of type "reference | |||
| 8841 | // to object", we don't get an EK_Temporary entity, but instead an | |||
| 8842 | // EK_Parameter entity with reference type. | |||
| 8843 | // FIXME: This is a hack. What we really should do is create a user | |||
| 8844 | // conversion step for this case, but this makes it considerably more | |||
| 8845 | // complicated. For now, this will do. | |||
| 8846 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( | |||
| 8847 | Entity.getType().getNonReferenceType()); | |||
| 8848 | bool UseTemporary = Entity.getType()->isReferenceType(); | |||
| 8849 | assert(Args.size() == 1 && "expected a single argument for list init")(static_cast <bool> (Args.size() == 1 && "expected a single argument for list init" ) ? void (0) : __assert_fail ("Args.size() == 1 && \"expected a single argument for list init\"" , "clang/lib/Sema/SemaInit.cpp", 8849, __extension__ __PRETTY_FUNCTION__ )); | |||
| 8850 | InitListExpr *InitList = cast<InitListExpr>(Args[0]); | |||
| 8851 | S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init) | |||
| 8852 | << InitList->getSourceRange(); | |||
| 8853 | MultiExprArg Arg(InitList->getInits(), InitList->getNumInits()); | |||
| 8854 | CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity : | |||
| 8855 | Entity, | |||
| 8856 | Kind, Arg, *Step, | |||
| 8857 | ConstructorInitRequiresZeroInit, | |||
| 8858 | /*IsListInitialization*/true, | |||
| 8859 | /*IsStdInitListInit*/false, | |||
| 8860 | InitList->getLBraceLoc(), | |||
| 8861 | InitList->getRBraceLoc()); | |||
| 8862 | break; | |||
| 8863 | } | |||
| 8864 | ||||
| 8865 | case SK_UnwrapInitList: | |||
| 8866 | CurInit = cast<InitListExpr>(CurInit.get())->getInit(0); | |||
| 8867 | break; | |||
| 8868 | ||||
| 8869 | case SK_RewrapInitList: { | |||
| 8870 | Expr *E = CurInit.get(); | |||
| 8871 | InitListExpr *Syntactic = Step->WrappingSyntacticList; | |||
| 8872 | InitListExpr *ILE = new (S.Context) InitListExpr(S.Context, | |||
| 8873 | Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc()); | |||
| 8874 | ILE->setSyntacticForm(Syntactic); | |||
| 8875 | ILE->setType(E->getType()); | |||
| 8876 | ILE->setValueKind(E->getValueKind()); | |||
| 8877 | CurInit = ILE; | |||
| 8878 | break; | |||
| 8879 | } | |||
| 8880 | ||||
| 8881 | case SK_ConstructorInitialization: | |||
| 8882 | case SK_StdInitializerListConstructorCall: { | |||
| 8883 | if (checkAbstractType(Step->Type)) | |||
| 8884 | return ExprError(); | |||
| 8885 | ||||
| 8886 | // When an initializer list is passed for a parameter of type "reference | |||
| 8887 | // to object", we don't get an EK_Temporary entity, but instead an | |||
| 8888 | // EK_Parameter entity with reference type. | |||
| 8889 | // FIXME: This is a hack. What we really should do is create a user | |||
| 8890 | // conversion step for this case, but this makes it considerably more | |||
| 8891 | // complicated. For now, this will do. | |||
| 8892 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( | |||
| 8893 | Entity.getType().getNonReferenceType()); | |||
| 8894 | bool UseTemporary = Entity.getType()->isReferenceType(); | |||
| 8895 | bool IsStdInitListInit = | |||
| 8896 | Step->Kind == SK_StdInitializerListConstructorCall; | |||
| 8897 | Expr *Source = CurInit.get(); | |||
| 8898 | SourceRange Range = Kind.hasParenOrBraceRange() | |||
| 8899 | ? Kind.getParenOrBraceRange() | |||
| 8900 | : SourceRange(); | |||
| 8901 | CurInit = PerformConstructorInitialization( | |||
| 8902 | S, UseTemporary ? TempEntity : Entity, Kind, | |||
| 8903 | Source ? MultiExprArg(Source) : Args, *Step, | |||
| 8904 | ConstructorInitRequiresZeroInit, | |||
| 8905 | /*IsListInitialization*/ IsStdInitListInit, | |||
| 8906 | /*IsStdInitListInitialization*/ IsStdInitListInit, | |||
| 8907 | /*LBraceLoc*/ Range.getBegin(), | |||
| 8908 | /*RBraceLoc*/ Range.getEnd()); | |||
| 8909 | break; | |||
| 8910 | } | |||
| 8911 | ||||
| 8912 | case SK_ZeroInitialization: { | |||
| 8913 | step_iterator NextStep = Step; | |||
| 8914 | ++NextStep; | |||
| 8915 | if (NextStep != StepEnd && | |||
| 8916 | (NextStep->Kind == SK_ConstructorInitialization || | |||
| 8917 | NextStep->Kind == SK_ConstructorInitializationFromList)) { | |||
| 8918 | // The need for zero-initialization is recorded directly into | |||
| 8919 | // the call to the object's constructor within the next step. | |||
| 8920 | ConstructorInitRequiresZeroInit = true; | |||
| 8921 | } else if (Kind.getKind() == InitializationKind::IK_Value && | |||
| 8922 | S.getLangOpts().CPlusPlus && | |||
| 8923 | !Kind.isImplicitValueInit()) { | |||
| 8924 | TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); | |||
| 8925 | if (!TSInfo) | |||
| 8926 | TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type, | |||
| 8927 | Kind.getRange().getBegin()); | |||
| 8928 | ||||
| 8929 | CurInit = new (S.Context) CXXScalarValueInitExpr( | |||
| 8930 | Entity.getType().getNonLValueExprType(S.Context), TSInfo, | |||
| 8931 | Kind.getRange().getEnd()); | |||
| 8932 | } else { | |||
| 8933 | CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type); | |||
| 8934 | } | |||
| 8935 | break; | |||
| 8936 | } | |||
| 8937 | ||||
| 8938 | case SK_CAssignment: { | |||
| 8939 | QualType SourceType = CurInit.get()->getType(); | |||
| 8940 | ||||
| 8941 | // Save off the initial CurInit in case we need to emit a diagnostic | |||
| 8942 | ExprResult InitialCurInit = CurInit; | |||
| 8943 | ExprResult Result = CurInit; | |||
| 8944 | Sema::AssignConvertType ConvTy = | |||
| 8945 | S.CheckSingleAssignmentConstraints(Step->Type, Result, true, | |||
| 8946 | Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited); | |||
| 8947 | if (Result.isInvalid()) | |||
| 8948 | return ExprError(); | |||
| 8949 | CurInit = Result; | |||
| 8950 | ||||
| 8951 | // If this is a call, allow conversion to a transparent union. | |||
| 8952 | ExprResult CurInitExprRes = CurInit; | |||
| 8953 | if (ConvTy != Sema::Compatible && | |||
| 8954 | Entity.isParameterKind() && | |||
| 8955 | S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes) | |||
| 8956 | == Sema::Compatible) | |||
| 8957 | ConvTy = Sema::Compatible; | |||
| 8958 | if (CurInitExprRes.isInvalid()) | |||
| 8959 | return ExprError(); | |||
| 8960 | CurInit = CurInitExprRes; | |||
| 8961 | ||||
| 8962 | bool Complained; | |||
| 8963 | if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), | |||
| 8964 | Step->Type, SourceType, | |||
| 8965 | InitialCurInit.get(), | |||
| 8966 | getAssignmentAction(Entity, true), | |||
| 8967 | &Complained)) { | |||
| 8968 | PrintInitLocationNote(S, Entity); | |||
| 8969 | return ExprError(); | |||
| 8970 | } else if (Complained) | |||
| 8971 | PrintInitLocationNote(S, Entity); | |||
| 8972 | break; | |||
| 8973 | } | |||
| 8974 | ||||
| 8975 | case SK_StringInit: { | |||
| 8976 | QualType Ty = Step->Type; | |||
| 8977 | bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType(); | |||
| 8978 | CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty, | |||
| 8979 | S.Context.getAsArrayType(Ty), S); | |||
| 8980 | break; | |||
| 8981 | } | |||
| 8982 | ||||
| 8983 | case SK_ObjCObjectConversion: | |||
| 8984 | CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, | |||
| 8985 | CK_ObjCObjectLValueCast, | |||
| 8986 | CurInit.get()->getValueKind()); | |||
| 8987 | break; | |||
| 8988 | ||||
| 8989 | case SK_ArrayLoopIndex: { | |||
| 8990 | Expr *Cur = CurInit.get(); | |||
| 8991 | Expr *BaseExpr = new (S.Context) | |||
| 8992 | OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(), | |||
| 8993 | Cur->getValueKind(), Cur->getObjectKind(), Cur); | |||
| 8994 | Expr *IndexExpr = | |||
| 8995 | new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType()); | |||
| 8996 | CurInit = S.CreateBuiltinArraySubscriptExpr( | |||
| 8997 | BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation()); | |||
| 8998 | ArrayLoopCommonExprs.push_back(BaseExpr); | |||
| 8999 | break; | |||
| 9000 | } | |||
| 9001 | ||||
| 9002 | case SK_ArrayLoopInit: { | |||
| 9003 | assert(!ArrayLoopCommonExprs.empty() &&(static_cast <bool> (!ArrayLoopCommonExprs.empty() && "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit") ? void ( 0) : __assert_fail ("!ArrayLoopCommonExprs.empty() && \"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit\"" , "clang/lib/Sema/SemaInit.cpp", 9004, __extension__ __PRETTY_FUNCTION__ )) | |||
| 9004 | "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit")(static_cast <bool> (!ArrayLoopCommonExprs.empty() && "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit") ? void ( 0) : __assert_fail ("!ArrayLoopCommonExprs.empty() && \"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit\"" , "clang/lib/Sema/SemaInit.cpp", 9004, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9005 | Expr *Common = ArrayLoopCommonExprs.pop_back_val(); | |||
| 9006 | CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common, | |||
| 9007 | CurInit.get()); | |||
| 9008 | break; | |||
| 9009 | } | |||
| 9010 | ||||
| 9011 | case SK_GNUArrayInit: | |||
| 9012 | // Okay: we checked everything before creating this step. Note that | |||
| 9013 | // this is a GNU extension. | |||
| 9014 | S.Diag(Kind.getLocation(), diag::ext_array_init_copy) | |||
| 9015 | << Step->Type << CurInit.get()->getType() | |||
| 9016 | << CurInit.get()->getSourceRange(); | |||
| 9017 | updateGNUCompoundLiteralRValue(CurInit.get()); | |||
| 9018 | [[fallthrough]]; | |||
| 9019 | case SK_ArrayInit: | |||
| 9020 | // If the destination type is an incomplete array type, update the | |||
| 9021 | // type accordingly. | |||
| 9022 | if (ResultType) { | |||
| 9023 | if (const IncompleteArrayType *IncompleteDest | |||
| 9024 | = S.Context.getAsIncompleteArrayType(Step->Type)) { | |||
| 9025 | if (const ConstantArrayType *ConstantSource | |||
| 9026 | = S.Context.getAsConstantArrayType(CurInit.get()->getType())) { | |||
| 9027 | *ResultType = S.Context.getConstantArrayType( | |||
| 9028 | IncompleteDest->getElementType(), | |||
| 9029 | ConstantSource->getSize(), | |||
| 9030 | ConstantSource->getSizeExpr(), | |||
| 9031 | ArrayType::Normal, 0); | |||
| 9032 | } | |||
| 9033 | } | |||
| 9034 | } | |||
| 9035 | break; | |||
| 9036 | ||||
| 9037 | case SK_ParenthesizedArrayInit: | |||
| 9038 | // Okay: we checked everything before creating this step. Note that | |||
| 9039 | // this is a GNU extension. | |||
| 9040 | S.Diag(Kind.getLocation(), diag::ext_array_init_parens) | |||
| 9041 | << CurInit.get()->getSourceRange(); | |||
| 9042 | break; | |||
| 9043 | ||||
| 9044 | case SK_PassByIndirectCopyRestore: | |||
| 9045 | case SK_PassByIndirectRestore: | |||
| 9046 | checkIndirectCopyRestoreSource(S, CurInit.get()); | |||
| 9047 | CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr( | |||
| 9048 | CurInit.get(), Step->Type, | |||
| 9049 | Step->Kind == SK_PassByIndirectCopyRestore); | |||
| 9050 | break; | |||
| 9051 | ||||
| 9052 | case SK_ProduceObjCObject: | |||
| 9053 | CurInit = ImplicitCastExpr::Create( | |||
| 9054 | S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr, | |||
| 9055 | VK_PRValue, FPOptionsOverride()); | |||
| 9056 | break; | |||
| 9057 | ||||
| 9058 | case SK_StdInitializerList: { | |||
| 9059 | S.Diag(CurInit.get()->getExprLoc(), | |||
| 9060 | diag::warn_cxx98_compat_initializer_list_init) | |||
| 9061 | << CurInit.get()->getSourceRange(); | |||
| 9062 | ||||
| 9063 | // Materialize the temporary into memory. | |||
| 9064 | MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( | |||
| 9065 | CurInit.get()->getType(), CurInit.get(), | |||
| 9066 | /*BoundToLvalueReference=*/false); | |||
| 9067 | ||||
| 9068 | // Wrap it in a construction of a std::initializer_list<T>. | |||
| 9069 | CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE); | |||
| 9070 | ||||
| 9071 | // Bind the result, in case the library has given initializer_list a | |||
| 9072 | // non-trivial destructor. | |||
| 9073 | if (shouldBindAsTemporary(Entity)) | |||
| 9074 | CurInit = S.MaybeBindToTemporary(CurInit.get()); | |||
| 9075 | break; | |||
| 9076 | } | |||
| 9077 | ||||
| 9078 | case SK_OCLSamplerInit: { | |||
| 9079 | // Sampler initialization have 5 cases: | |||
| 9080 | // 1. function argument passing | |||
| 9081 | // 1a. argument is a file-scope variable | |||
| 9082 | // 1b. argument is a function-scope variable | |||
| 9083 | // 1c. argument is one of caller function's parameters | |||
| 9084 | // 2. variable initialization | |||
| 9085 | // 2a. initializing a file-scope variable | |||
| 9086 | // 2b. initializing a function-scope variable | |||
| 9087 | // | |||
| 9088 | // For file-scope variables, since they cannot be initialized by function | |||
| 9089 | // call of __translate_sampler_initializer in LLVM IR, their references | |||
| 9090 | // need to be replaced by a cast from their literal initializers to | |||
| 9091 | // sampler type. Since sampler variables can only be used in function | |||
| 9092 | // calls as arguments, we only need to replace them when handling the | |||
| 9093 | // argument passing. | |||
| 9094 | assert(Step->Type->isSamplerT() &&(static_cast <bool> (Step->Type->isSamplerT() && "Sampler initialization on non-sampler type.") ? void (0) : __assert_fail ("Step->Type->isSamplerT() && \"Sampler initialization on non-sampler type.\"" , "clang/lib/Sema/SemaInit.cpp", 9095, __extension__ __PRETTY_FUNCTION__ )) | |||
| 9095 | "Sampler initialization on non-sampler type.")(static_cast <bool> (Step->Type->isSamplerT() && "Sampler initialization on non-sampler type.") ? void (0) : __assert_fail ("Step->Type->isSamplerT() && \"Sampler initialization on non-sampler type.\"" , "clang/lib/Sema/SemaInit.cpp", 9095, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9096 | Expr *Init = CurInit.get()->IgnoreParens(); | |||
| 9097 | QualType SourceType = Init->getType(); | |||
| 9098 | // Case 1 | |||
| 9099 | if (Entity.isParameterKind()) { | |||
| 9100 | if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) { | |||
| 9101 | S.Diag(Kind.getLocation(), diag::err_sampler_argument_required) | |||
| 9102 | << SourceType; | |||
| 9103 | break; | |||
| 9104 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) { | |||
| 9105 | auto Var = cast<VarDecl>(DRE->getDecl()); | |||
| 9106 | // Case 1b and 1c | |||
| 9107 | // No cast from integer to sampler is needed. | |||
| 9108 | if (!Var->hasGlobalStorage()) { | |||
| 9109 | CurInit = ImplicitCastExpr::Create( | |||
| 9110 | S.Context, Step->Type, CK_LValueToRValue, Init, | |||
| 9111 | /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride()); | |||
| 9112 | break; | |||
| 9113 | } | |||
| 9114 | // Case 1a | |||
| 9115 | // For function call with a file-scope sampler variable as argument, | |||
| 9116 | // get the integer literal. | |||
| 9117 | // Do not diagnose if the file-scope variable does not have initializer | |||
| 9118 | // since this has already been diagnosed when parsing the variable | |||
| 9119 | // declaration. | |||
| 9120 | if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit())) | |||
| 9121 | break; | |||
| 9122 | Init = cast<ImplicitCastExpr>(const_cast<Expr*>( | |||
| 9123 | Var->getInit()))->getSubExpr(); | |||
| 9124 | SourceType = Init->getType(); | |||
| 9125 | } | |||
| 9126 | } else { | |||
| 9127 | // Case 2 | |||
| 9128 | // Check initializer is 32 bit integer constant. | |||
| 9129 | // If the initializer is taken from global variable, do not diagnose since | |||
| 9130 | // this has already been done when parsing the variable declaration. | |||
| 9131 | if (!Init->isConstantInitializer(S.Context, false)) | |||
| 9132 | break; | |||
| 9133 | ||||
| 9134 | if (!SourceType->isIntegerType() || | |||
| 9135 | 32 != S.Context.getIntWidth(SourceType)) { | |||
| 9136 | S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer) | |||
| 9137 | << SourceType; | |||
| 9138 | break; | |||
| 9139 | } | |||
| 9140 | ||||
| 9141 | Expr::EvalResult EVResult; | |||
| 9142 | Init->EvaluateAsInt(EVResult, S.Context); | |||
| 9143 | llvm::APSInt Result = EVResult.Val.getInt(); | |||
| 9144 | const uint64_t SamplerValue = Result.getLimitedValue(); | |||
| 9145 | // 32-bit value of sampler's initializer is interpreted as | |||
| 9146 | // bit-field with the following structure: | |||
| 9147 | // |unspecified|Filter|Addressing Mode| Normalized Coords| | |||
| 9148 | // |31 6|5 4|3 1| 0| | |||
| 9149 | // This structure corresponds to enum values of sampler properties | |||
| 9150 | // defined in SPIR spec v1.2 and also opencl-c.h | |||
| 9151 | unsigned AddressingMode = (0x0E & SamplerValue) >> 1; | |||
| 9152 | unsigned FilterMode = (0x30 & SamplerValue) >> 4; | |||
| 9153 | if (FilterMode != 1 && FilterMode != 2 && | |||
| 9154 | !S.getOpenCLOptions().isAvailableOption( | |||
| 9155 | "cl_intel_device_side_avc_motion_estimation", S.getLangOpts())) | |||
| 9156 | S.Diag(Kind.getLocation(), | |||
| 9157 | diag::warn_sampler_initializer_invalid_bits) | |||
| 9158 | << "Filter Mode"; | |||
| 9159 | if (AddressingMode > 4) | |||
| 9160 | S.Diag(Kind.getLocation(), | |||
| 9161 | diag::warn_sampler_initializer_invalid_bits) | |||
| 9162 | << "Addressing Mode"; | |||
| 9163 | } | |||
| 9164 | ||||
| 9165 | // Cases 1a, 2a and 2b | |||
| 9166 | // Insert cast from integer to sampler. | |||
| 9167 | CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy, | |||
| 9168 | CK_IntToOCLSampler); | |||
| 9169 | break; | |||
| 9170 | } | |||
| 9171 | case SK_OCLZeroOpaqueType: { | |||
| 9172 | assert((Step->Type->isEventT() || Step->Type->isQueueT() ||(static_cast <bool> ((Step->Type->isEventT() || Step ->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType ()) && "Wrong type for initialization of OpenCL opaque type." ) ? void (0) : __assert_fail ("(Step->Type->isEventT() || Step->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType()) && \"Wrong type for initialization of OpenCL opaque type.\"" , "clang/lib/Sema/SemaInit.cpp", 9174, __extension__ __PRETTY_FUNCTION__ )) | |||
| 9173 | Step->Type->isOCLIntelSubgroupAVCType()) &&(static_cast <bool> ((Step->Type->isEventT() || Step ->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType ()) && "Wrong type for initialization of OpenCL opaque type." ) ? void (0) : __assert_fail ("(Step->Type->isEventT() || Step->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType()) && \"Wrong type for initialization of OpenCL opaque type.\"" , "clang/lib/Sema/SemaInit.cpp", 9174, __extension__ __PRETTY_FUNCTION__ )) | |||
| 9174 | "Wrong type for initialization of OpenCL opaque type.")(static_cast <bool> ((Step->Type->isEventT() || Step ->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType ()) && "Wrong type for initialization of OpenCL opaque type." ) ? void (0) : __assert_fail ("(Step->Type->isEventT() || Step->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType()) && \"Wrong type for initialization of OpenCL opaque type.\"" , "clang/lib/Sema/SemaInit.cpp", 9174, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9175 | ||||
| 9176 | CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, | |||
| 9177 | CK_ZeroToOCLOpaqueType, | |||
| 9178 | CurInit.get()->getValueKind()); | |||
| 9179 | break; | |||
| 9180 | } | |||
| 9181 | case SK_ParenthesizedListInit: { | |||
| 9182 | CurInit = nullptr; | |||
| 9183 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this, | |||
| 9184 | /*VerifyOnly=*/false, &CurInit); | |||
| 9185 | if (CurInit.get() && ResultType) | |||
| 9186 | *ResultType = CurInit.get()->getType(); | |||
| 9187 | if (shouldBindAsTemporary(Entity)) | |||
| 9188 | CurInit = S.MaybeBindToTemporary(CurInit.get()); | |||
| 9189 | break; | |||
| 9190 | } | |||
| 9191 | } | |||
| 9192 | } | |||
| 9193 | ||||
| 9194 | // Check whether the initializer has a shorter lifetime than the initialized | |||
| 9195 | // entity, and if not, either lifetime-extend or warn as appropriate. | |||
| 9196 | if (auto *Init = CurInit.get()) | |||
| 9197 | S.checkInitializerLifetime(Entity, Init); | |||
| 9198 | ||||
| 9199 | // Diagnose non-fatal problems with the completed initialization. | |||
| 9200 | if (Entity.getKind() == InitializedEntity::EK_Member && | |||
| 9201 | cast<FieldDecl>(Entity.getDecl())->isBitField()) | |||
| 9202 | S.CheckBitFieldInitialization(Kind.getLocation(), | |||
| 9203 | cast<FieldDecl>(Entity.getDecl()), | |||
| 9204 | CurInit.get()); | |||
| 9205 | ||||
| 9206 | // Check for std::move on construction. | |||
| 9207 | if (const Expr *E = CurInit.get()) { | |||
| 9208 | CheckMoveOnConstruction(S, E, | |||
| 9209 | Entity.getKind() == InitializedEntity::EK_Result); | |||
| 9210 | } | |||
| 9211 | ||||
| 9212 | return CurInit; | |||
| 9213 | } | |||
| 9214 | ||||
| 9215 | /// Somewhere within T there is an uninitialized reference subobject. | |||
| 9216 | /// Dig it out and diagnose it. | |||
| 9217 | static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, | |||
| 9218 | QualType T) { | |||
| 9219 | if (T->isReferenceType()) { | |||
| 9220 | S.Diag(Loc, diag::err_reference_without_init) | |||
| 9221 | << T.getNonReferenceType(); | |||
| 9222 | return true; | |||
| 9223 | } | |||
| 9224 | ||||
| 9225 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | |||
| 9226 | if (!RD || !RD->hasUninitializedReferenceMember()) | |||
| 9227 | return false; | |||
| 9228 | ||||
| 9229 | for (const auto *FI : RD->fields()) { | |||
| 9230 | if (FI->isUnnamedBitfield()) | |||
| 9231 | continue; | |||
| 9232 | ||||
| 9233 | if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) { | |||
| 9234 | S.Diag(Loc, diag::note_value_initialization_here) << RD; | |||
| 9235 | return true; | |||
| 9236 | } | |||
| 9237 | } | |||
| 9238 | ||||
| 9239 | for (const auto &BI : RD->bases()) { | |||
| 9240 | if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) { | |||
| 9241 | S.Diag(Loc, diag::note_value_initialization_here) << RD; | |||
| 9242 | return true; | |||
| 9243 | } | |||
| 9244 | } | |||
| 9245 | ||||
| 9246 | return false; | |||
| 9247 | } | |||
| 9248 | ||||
| 9249 | ||||
| 9250 | //===----------------------------------------------------------------------===// | |||
| 9251 | // Diagnose initialization failures | |||
| 9252 | //===----------------------------------------------------------------------===// | |||
| 9253 | ||||
| 9254 | /// Emit notes associated with an initialization that failed due to a | |||
| 9255 | /// "simple" conversion failure. | |||
| 9256 | static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, | |||
| 9257 | Expr *op) { | |||
| 9258 | QualType destType = entity.getType(); | |||
| 9259 | if (destType.getNonReferenceType()->isObjCObjectPointerType() && | |||
| 9260 | op->getType()->isObjCObjectPointerType()) { | |||
| 9261 | ||||
| 9262 | // Emit a possible note about the conversion failing because the | |||
| 9263 | // operand is a message send with a related result type. | |||
| 9264 | S.EmitRelatedResultTypeNote(op); | |||
| 9265 | ||||
| 9266 | // Emit a possible note about a return failing because we're | |||
| 9267 | // expecting a related result type. | |||
| 9268 | if (entity.getKind() == InitializedEntity::EK_Result) | |||
| 9269 | S.EmitRelatedResultTypeNoteForReturn(destType); | |||
| 9270 | } | |||
| 9271 | QualType fromType = op->getType(); | |||
| 9272 | QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType(); | |||
| 9273 | QualType destPointeeType = destType.getCanonicalType()->getPointeeType(); | |||
| 9274 | auto *fromDecl = fromType->getPointeeCXXRecordDecl(); | |||
| 9275 | auto *destDecl = destType->getPointeeCXXRecordDecl(); | |||
| 9276 | if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord && | |||
| 9277 | destDecl->getDeclKind() == Decl::CXXRecord && | |||
| 9278 | !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() && | |||
| 9279 | !fromDecl->hasDefinition() && | |||
| 9280 | destPointeeType.getQualifiers().compatiblyIncludes( | |||
| 9281 | fromPointeeType.getQualifiers())) | |||
| 9282 | S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion) | |||
| 9283 | << S.getASTContext().getTagDeclType(fromDecl) | |||
| 9284 | << S.getASTContext().getTagDeclType(destDecl); | |||
| 9285 | } | |||
| 9286 | ||||
| 9287 | static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, | |||
| 9288 | InitListExpr *InitList) { | |||
| 9289 | QualType DestType = Entity.getType(); | |||
| 9290 | ||||
| 9291 | QualType E; | |||
| 9292 | if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) { | |||
| 9293 | QualType ArrayType = S.Context.getConstantArrayType( | |||
| 9294 | E.withConst(), | |||
| 9295 | llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), | |||
| 9296 | InitList->getNumInits()), | |||
| 9297 | nullptr, clang::ArrayType::Normal, 0); | |||
| 9298 | InitializedEntity HiddenArray = | |||
| 9299 | InitializedEntity::InitializeTemporary(ArrayType); | |||
| 9300 | return diagnoseListInit(S, HiddenArray, InitList); | |||
| 9301 | } | |||
| 9302 | ||||
| 9303 | if (DestType->isReferenceType()) { | |||
| 9304 | // A list-initialization failure for a reference means that we tried to | |||
| 9305 | // create a temporary of the inner type (per [dcl.init.list]p3.6) and the | |||
| 9306 | // inner initialization failed. | |||
| 9307 | QualType T = DestType->castAs<ReferenceType>()->getPointeeType(); | |||
| 9308 | diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList); | |||
| 9309 | SourceLocation Loc = InitList->getBeginLoc(); | |||
| 9310 | if (auto *D = Entity.getDecl()) | |||
| 9311 | Loc = D->getLocation(); | |||
| 9312 | S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T; | |||
| 9313 | return; | |||
| 9314 | } | |||
| 9315 | ||||
| 9316 | InitListChecker DiagnoseInitList(S, Entity, InitList, DestType, | |||
| 9317 | /*VerifyOnly=*/false, | |||
| 9318 | /*TreatUnavailableAsInvalid=*/false); | |||
| 9319 | assert(DiagnoseInitList.HadError() &&(static_cast <bool> (DiagnoseInitList.HadError() && "Inconsistent init list check result.") ? void (0) : __assert_fail ("DiagnoseInitList.HadError() && \"Inconsistent init list check result.\"" , "clang/lib/Sema/SemaInit.cpp", 9320, __extension__ __PRETTY_FUNCTION__ )) | |||
| 9320 | "Inconsistent init list check result.")(static_cast <bool> (DiagnoseInitList.HadError() && "Inconsistent init list check result.") ? void (0) : __assert_fail ("DiagnoseInitList.HadError() && \"Inconsistent init list check result.\"" , "clang/lib/Sema/SemaInit.cpp", 9320, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9321 | } | |||
| 9322 | ||||
| 9323 | bool InitializationSequence::Diagnose(Sema &S, | |||
| 9324 | const InitializedEntity &Entity, | |||
| 9325 | const InitializationKind &Kind, | |||
| 9326 | ArrayRef<Expr *> Args) { | |||
| 9327 | if (!Failed()) | |||
| 9328 | return false; | |||
| 9329 | ||||
| 9330 | // When we want to diagnose only one element of a braced-init-list, | |||
| 9331 | // we need to factor it out. | |||
| 9332 | Expr *OnlyArg; | |||
| 9333 | if (Args.size() == 1) { | |||
| 9334 | auto *List = dyn_cast<InitListExpr>(Args[0]); | |||
| 9335 | if (List && List->getNumInits() == 1) | |||
| 9336 | OnlyArg = List->getInit(0); | |||
| 9337 | else | |||
| 9338 | OnlyArg = Args[0]; | |||
| 9339 | } | |||
| 9340 | else | |||
| 9341 | OnlyArg = nullptr; | |||
| 9342 | ||||
| 9343 | QualType DestType = Entity.getType(); | |||
| 9344 | switch (Failure) { | |||
| 9345 | case FK_TooManyInitsForReference: | |||
| 9346 | // FIXME: Customize for the initialized entity? | |||
| 9347 | if (Args.empty()) { | |||
| 9348 | // Dig out the reference subobject which is uninitialized and diagnose it. | |||
| 9349 | // If this is value-initialization, this could be nested some way within | |||
| 9350 | // the target type. | |||
| 9351 | assert(Kind.getKind() == InitializationKind::IK_Value ||(static_cast <bool> (Kind.getKind() == InitializationKind ::IK_Value || DestType->isReferenceType()) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Value || DestType->isReferenceType()" , "clang/lib/Sema/SemaInit.cpp", 9352, __extension__ __PRETTY_FUNCTION__ )) | |||
| 9352 | DestType->isReferenceType())(static_cast <bool> (Kind.getKind() == InitializationKind ::IK_Value || DestType->isReferenceType()) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Value || DestType->isReferenceType()" , "clang/lib/Sema/SemaInit.cpp", 9352, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9353 | bool Diagnosed = | |||
| 9354 | DiagnoseUninitializedReference(S, Kind.getLocation(), DestType); | |||
| 9355 | assert(Diagnosed && "couldn't find uninitialized reference to diagnose")(static_cast <bool> (Diagnosed && "couldn't find uninitialized reference to diagnose" ) ? void (0) : __assert_fail ("Diagnosed && \"couldn't find uninitialized reference to diagnose\"" , "clang/lib/Sema/SemaInit.cpp", 9355, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9356 | (void)Diagnosed; | |||
| 9357 | } else // FIXME: diagnostic below could be better! | |||
| 9358 | S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) | |||
| 9359 | << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); | |||
| 9360 | break; | |||
| 9361 | case FK_ParenthesizedListInitForReference: | |||
| 9362 | S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) | |||
| 9363 | << 1 << Entity.getType() << Args[0]->getSourceRange(); | |||
| 9364 | break; | |||
| 9365 | ||||
| 9366 | case FK_ArrayNeedsInitList: | |||
| 9367 | S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0; | |||
| 9368 | break; | |||
| 9369 | case FK_ArrayNeedsInitListOrStringLiteral: | |||
| 9370 | S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1; | |||
| 9371 | break; | |||
| 9372 | case FK_ArrayNeedsInitListOrWideStringLiteral: | |||
| 9373 | S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2; | |||
| 9374 | break; | |||
| 9375 | case FK_NarrowStringIntoWideCharArray: | |||
| 9376 | S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar); | |||
| 9377 | break; | |||
| 9378 | case FK_WideStringIntoCharArray: | |||
| 9379 | S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char); | |||
| 9380 | break; | |||
| 9381 | case FK_IncompatWideStringIntoWideChar: | |||
| 9382 | S.Diag(Kind.getLocation(), | |||
| 9383 | diag::err_array_init_incompat_wide_string_into_wchar); | |||
| 9384 | break; | |||
| 9385 | case FK_PlainStringIntoUTF8Char: | |||
| 9386 | S.Diag(Kind.getLocation(), | |||
| 9387 | diag::err_array_init_plain_string_into_char8_t); | |||
| 9388 | S.Diag(Args.front()->getBeginLoc(), | |||
| 9389 | diag::note_array_init_plain_string_into_char8_t) | |||
| 9390 | << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8"); | |||
| 9391 | break; | |||
| 9392 | case FK_UTF8StringIntoPlainChar: | |||
| 9393 | S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char) | |||
| 9394 | << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20; | |||
| 9395 | break; | |||
| 9396 | case FK_ArrayTypeMismatch: | |||
| 9397 | case FK_NonConstantArrayInit: | |||
| 9398 | S.Diag(Kind.getLocation(), | |||
| 9399 | (Failure == FK_ArrayTypeMismatch | |||
| 9400 | ? diag::err_array_init_different_type | |||
| 9401 | : diag::err_array_init_non_constant_array)) | |||
| 9402 | << DestType.getNonReferenceType() | |||
| 9403 | << OnlyArg->getType() | |||
| 9404 | << Args[0]->getSourceRange(); | |||
| 9405 | break; | |||
| 9406 | ||||
| 9407 | case FK_VariableLengthArrayHasInitializer: | |||
| 9408 | S.Diag(Kind.getLocation(), diag::err_variable_object_no_init) | |||
| 9409 | << Args[0]->getSourceRange(); | |||
| 9410 | break; | |||
| 9411 | ||||
| 9412 | case FK_AddressOfOverloadFailed: { | |||
| 9413 | DeclAccessPair Found; | |||
| 9414 | S.ResolveAddressOfOverloadedFunction(OnlyArg, | |||
| 9415 | DestType.getNonReferenceType(), | |||
| 9416 | true, | |||
| 9417 | Found); | |||
| 9418 | break; | |||
| 9419 | } | |||
| 9420 | ||||
| 9421 | case FK_AddressOfUnaddressableFunction: { | |||
| 9422 | auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl()); | |||
| 9423 | S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | |||
| 9424 | OnlyArg->getBeginLoc()); | |||
| 9425 | break; | |||
| 9426 | } | |||
| 9427 | ||||
| 9428 | case FK_ReferenceInitOverloadFailed: | |||
| 9429 | case FK_UserConversionOverloadFailed: | |||
| 9430 | switch (FailedOverloadResult) { | |||
| 9431 | case OR_Ambiguous: | |||
| 9432 | ||||
| 9433 | FailedCandidateSet.NoteCandidates( | |||
| 9434 | PartialDiagnosticAt( | |||
| 9435 | Kind.getLocation(), | |||
| 9436 | Failure == FK_UserConversionOverloadFailed | |||
| 9437 | ? (S.PDiag(diag::err_typecheck_ambiguous_condition) | |||
| 9438 | << OnlyArg->getType() << DestType | |||
| 9439 | << Args[0]->getSourceRange()) | |||
| 9440 | : (S.PDiag(diag::err_ref_init_ambiguous) | |||
| 9441 | << DestType << OnlyArg->getType() | |||
| 9442 | << Args[0]->getSourceRange())), | |||
| 9443 | S, OCD_AmbiguousCandidates, Args); | |||
| 9444 | break; | |||
| 9445 | ||||
| 9446 | case OR_No_Viable_Function: { | |||
| 9447 | auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args); | |||
| 9448 | if (!S.RequireCompleteType(Kind.getLocation(), | |||
| 9449 | DestType.getNonReferenceType(), | |||
| 9450 | diag::err_typecheck_nonviable_condition_incomplete, | |||
| 9451 | OnlyArg->getType(), Args[0]->getSourceRange())) | |||
| 9452 | S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) | |||
| 9453 | << (Entity.getKind() == InitializedEntity::EK_Result) | |||
| 9454 | << OnlyArg->getType() << Args[0]->getSourceRange() | |||
| 9455 | << DestType.getNonReferenceType(); | |||
| 9456 | ||||
| 9457 | FailedCandidateSet.NoteCandidates(S, Args, Cands); | |||
| 9458 | break; | |||
| 9459 | } | |||
| 9460 | case OR_Deleted: { | |||
| 9461 | S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) | |||
| 9462 | << OnlyArg->getType() << DestType.getNonReferenceType() | |||
| 9463 | << Args[0]->getSourceRange(); | |||
| 9464 | OverloadCandidateSet::iterator Best; | |||
| 9465 | OverloadingResult Ovl | |||
| 9466 | = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); | |||
| 9467 | if (Ovl == OR_Deleted) { | |||
| 9468 | S.NoteDeletedFunction(Best->Function); | |||
| 9469 | } else { | |||
| 9470 | llvm_unreachable("Inconsistent overload resolution?")::llvm::llvm_unreachable_internal("Inconsistent overload resolution?" , "clang/lib/Sema/SemaInit.cpp", 9470); | |||
| 9471 | } | |||
| 9472 | break; | |||
| 9473 | } | |||
| 9474 | ||||
| 9475 | case OR_Success: | |||
| 9476 | llvm_unreachable("Conversion did not fail!")::llvm::llvm_unreachable_internal("Conversion did not fail!", "clang/lib/Sema/SemaInit.cpp", 9476); | |||
| 9477 | } | |||
| 9478 | break; | |||
| 9479 | ||||
| 9480 | case FK_NonConstLValueReferenceBindingToTemporary: | |||
| 9481 | if (isa<InitListExpr>(Args[0])) { | |||
| 9482 | S.Diag(Kind.getLocation(), | |||
| 9483 | diag::err_lvalue_reference_bind_to_initlist) | |||
| 9484 | << DestType.getNonReferenceType().isVolatileQualified() | |||
| 9485 | << DestType.getNonReferenceType() | |||
| 9486 | << Args[0]->getSourceRange(); | |||
| 9487 | break; | |||
| 9488 | } | |||
| 9489 | [[fallthrough]]; | |||
| 9490 | ||||
| 9491 | case FK_NonConstLValueReferenceBindingToUnrelated: | |||
| 9492 | S.Diag(Kind.getLocation(), | |||
| 9493 | Failure == FK_NonConstLValueReferenceBindingToTemporary | |||
| 9494 | ? diag::err_lvalue_reference_bind_to_temporary | |||
| 9495 | : diag::err_lvalue_reference_bind_to_unrelated) | |||
| 9496 | << DestType.getNonReferenceType().isVolatileQualified() | |||
| 9497 | << DestType.getNonReferenceType() | |||
| 9498 | << OnlyArg->getType() | |||
| 9499 | << Args[0]->getSourceRange(); | |||
| 9500 | break; | |||
| 9501 | ||||
| 9502 | case FK_NonConstLValueReferenceBindingToBitfield: { | |||
| 9503 | // We don't necessarily have an unambiguous source bit-field. | |||
| 9504 | FieldDecl *BitField = Args[0]->getSourceBitField(); | |||
| 9505 | S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) | |||
| 9506 | << DestType.isVolatileQualified() | |||
| 9507 | << (BitField ? BitField->getDeclName() : DeclarationName()) | |||
| 9508 | << (BitField != nullptr) | |||
| 9509 | << Args[0]->getSourceRange(); | |||
| 9510 | if (BitField) | |||
| 9511 | S.Diag(BitField->getLocation(), diag::note_bitfield_decl); | |||
| 9512 | break; | |||
| 9513 | } | |||
| 9514 | ||||
| 9515 | case FK_NonConstLValueReferenceBindingToVectorElement: | |||
| 9516 | S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element) | |||
| 9517 | << DestType.isVolatileQualified() | |||
| 9518 | << Args[0]->getSourceRange(); | |||
| 9519 | break; | |||
| 9520 | ||||
| 9521 | case FK_NonConstLValueReferenceBindingToMatrixElement: | |||
| 9522 | S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element) | |||
| 9523 | << DestType.isVolatileQualified() << Args[0]->getSourceRange(); | |||
| 9524 | break; | |||
| 9525 | ||||
| 9526 | case FK_RValueReferenceBindingToLValue: | |||
| 9527 | S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) | |||
| 9528 | << DestType.getNonReferenceType() << OnlyArg->getType() | |||
| 9529 | << Args[0]->getSourceRange(); | |||
| 9530 | break; | |||
| 9531 | ||||
| 9532 | case FK_ReferenceAddrspaceMismatchTemporary: | |||
| 9533 | S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace) | |||
| 9534 | << DestType << Args[0]->getSourceRange(); | |||
| 9535 | break; | |||
| 9536 | ||||
| 9537 | case FK_ReferenceInitDropsQualifiers: { | |||
| 9538 | QualType SourceType = OnlyArg->getType(); | |||
| 9539 | QualType NonRefType = DestType.getNonReferenceType(); | |||
| 9540 | Qualifiers DroppedQualifiers = | |||
| 9541 | SourceType.getQualifiers() - NonRefType.getQualifiers(); | |||
| 9542 | ||||
| 9543 | if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf( | |||
| 9544 | SourceType.getQualifiers())) | |||
| 9545 | S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) | |||
| 9546 | << NonRefType << SourceType << 1 /*addr space*/ | |||
| 9547 | << Args[0]->getSourceRange(); | |||
| 9548 | else if (DroppedQualifiers.hasQualifiers()) | |||
| 9549 | S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) | |||
| 9550 | << NonRefType << SourceType << 0 /*cv quals*/ | |||
| 9551 | << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers()) | |||
| 9552 | << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange(); | |||
| 9553 | else | |||
| 9554 | // FIXME: Consider decomposing the type and explaining which qualifiers | |||
| 9555 | // were dropped where, or on which level a 'const' is missing, etc. | |||
| 9556 | S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) | |||
| 9557 | << NonRefType << SourceType << 2 /*incompatible quals*/ | |||
| 9558 | << Args[0]->getSourceRange(); | |||
| 9559 | break; | |||
| 9560 | } | |||
| 9561 | ||||
| 9562 | case FK_ReferenceInitFailed: | |||
| 9563 | S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) | |||
| 9564 | << DestType.getNonReferenceType() | |||
| 9565 | << DestType.getNonReferenceType()->isIncompleteType() | |||
| 9566 | << OnlyArg->isLValue() | |||
| 9567 | << OnlyArg->getType() | |||
| 9568 | << Args[0]->getSourceRange(); | |||
| 9569 | emitBadConversionNotes(S, Entity, Args[0]); | |||
| 9570 | break; | |||
| 9571 | ||||
| 9572 | case FK_ConversionFailed: { | |||
| 9573 | QualType FromType = OnlyArg->getType(); | |||
| 9574 | PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed) | |||
| 9575 | << (int)Entity.getKind() | |||
| 9576 | << DestType | |||
| 9577 | << OnlyArg->isLValue() | |||
| 9578 | << FromType | |||
| 9579 | << Args[0]->getSourceRange(); | |||
| 9580 | S.HandleFunctionTypeMismatch(PDiag, FromType, DestType); | |||
| 9581 | S.Diag(Kind.getLocation(), PDiag); | |||
| 9582 | emitBadConversionNotes(S, Entity, Args[0]); | |||
| 9583 | break; | |||
| 9584 | } | |||
| 9585 | ||||
| 9586 | case FK_ConversionFromPropertyFailed: | |||
| 9587 | // No-op. This error has already been reported. | |||
| 9588 | break; | |||
| 9589 | ||||
| 9590 | case FK_TooManyInitsForScalar: { | |||
| 9591 | SourceRange R; | |||
| 9592 | ||||
| 9593 | auto *InitList = dyn_cast<InitListExpr>(Args[0]); | |||
| 9594 | if (InitList && InitList->getNumInits() >= 1) { | |||
| 9595 | R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc()); | |||
| 9596 | } else { | |||
| 9597 | assert(Args.size() > 1 && "Expected multiple initializers!")(static_cast <bool> (Args.size() > 1 && "Expected multiple initializers!" ) ? void (0) : __assert_fail ("Args.size() > 1 && \"Expected multiple initializers!\"" , "clang/lib/Sema/SemaInit.cpp", 9597, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9598 | R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc()); | |||
| 9599 | } | |||
| 9600 | ||||
| 9601 | R.setBegin(S.getLocForEndOfToken(R.getBegin())); | |||
| 9602 | if (Kind.isCStyleOrFunctionalCast()) | |||
| 9603 | S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg) | |||
| 9604 | << R; | |||
| 9605 | else | |||
| 9606 | S.Diag(Kind.getLocation(), diag::err_excess_initializers) | |||
| 9607 | << /*scalar=*/2 << R; | |||
| 9608 | break; | |||
| 9609 | } | |||
| 9610 | ||||
| 9611 | case FK_ParenthesizedListInitForScalar: | |||
| 9612 | S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) | |||
| 9613 | << 0 << Entity.getType() << Args[0]->getSourceRange(); | |||
| 9614 | break; | |||
| 9615 | ||||
| 9616 | case FK_ReferenceBindingToInitList: | |||
| 9617 | S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) | |||
| 9618 | << DestType.getNonReferenceType() << Args[0]->getSourceRange(); | |||
| 9619 | break; | |||
| 9620 | ||||
| 9621 | case FK_InitListBadDestinationType: | |||
| 9622 | S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) | |||
| 9623 | << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); | |||
| 9624 | break; | |||
| 9625 | ||||
| 9626 | case FK_ListConstructorOverloadFailed: | |||
| 9627 | case FK_ConstructorOverloadFailed: { | |||
| 9628 | SourceRange ArgsRange; | |||
| 9629 | if (Args.size()) | |||
| 9630 | ArgsRange = | |||
| 9631 | SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); | |||
| 9632 | ||||
| 9633 | if (Failure == FK_ListConstructorOverloadFailed) { | |||
| 9634 | assert(Args.size() == 1 &&(static_cast <bool> (Args.size() == 1 && "List construction from other than 1 argument." ) ? void (0) : __assert_fail ("Args.size() == 1 && \"List construction from other than 1 argument.\"" , "clang/lib/Sema/SemaInit.cpp", 9635, __extension__ __PRETTY_FUNCTION__ )) | |||
| 9635 | "List construction from other than 1 argument.")(static_cast <bool> (Args.size() == 1 && "List construction from other than 1 argument." ) ? void (0) : __assert_fail ("Args.size() == 1 && \"List construction from other than 1 argument.\"" , "clang/lib/Sema/SemaInit.cpp", 9635, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9636 | InitListExpr *InitList = cast<InitListExpr>(Args[0]); | |||
| 9637 | Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); | |||
| 9638 | } | |||
| 9639 | ||||
| 9640 | // FIXME: Using "DestType" for the entity we're printing is probably | |||
| 9641 | // bad. | |||
| 9642 | switch (FailedOverloadResult) { | |||
| 9643 | case OR_Ambiguous: | |||
| 9644 | FailedCandidateSet.NoteCandidates( | |||
| 9645 | PartialDiagnosticAt(Kind.getLocation(), | |||
| 9646 | S.PDiag(diag::err_ovl_ambiguous_init) | |||
| 9647 | << DestType << ArgsRange), | |||
| 9648 | S, OCD_AmbiguousCandidates, Args); | |||
| 9649 | break; | |||
| 9650 | ||||
| 9651 | case OR_No_Viable_Function: | |||
| 9652 | if (Kind.getKind() == InitializationKind::IK_Default && | |||
| 9653 | (Entity.getKind() == InitializedEntity::EK_Base || | |||
| 9654 | Entity.getKind() == InitializedEntity::EK_Member) && | |||
| 9655 | isa<CXXConstructorDecl>(S.CurContext)) { | |||
| 9656 | // This is implicit default initialization of a member or | |||
| 9657 | // base within a constructor. If no viable function was | |||
| 9658 | // found, notify the user that they need to explicitly | |||
| 9659 | // initialize this base/member. | |||
| 9660 | CXXConstructorDecl *Constructor | |||
| 9661 | = cast<CXXConstructorDecl>(S.CurContext); | |||
| 9662 | const CXXRecordDecl *InheritedFrom = nullptr; | |||
| 9663 | if (auto Inherited = Constructor->getInheritedConstructor()) | |||
| 9664 | InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass(); | |||
| 9665 | if (Entity.getKind() == InitializedEntity::EK_Base) { | |||
| 9666 | S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) | |||
| 9667 | << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) | |||
| 9668 | << S.Context.getTypeDeclType(Constructor->getParent()) | |||
| 9669 | << /*base=*/0 | |||
| 9670 | << Entity.getType() | |||
| 9671 | << InheritedFrom; | |||
| 9672 | ||||
| 9673 | RecordDecl *BaseDecl | |||
| 9674 | = Entity.getBaseSpecifier()->getType()->castAs<RecordType>() | |||
| 9675 | ->getDecl(); | |||
| 9676 | S.Diag(BaseDecl->getLocation(), diag::note_previous_decl) | |||
| 9677 | << S.Context.getTagDeclType(BaseDecl); | |||
| 9678 | } else { | |||
| 9679 | S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) | |||
| 9680 | << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) | |||
| 9681 | << S.Context.getTypeDeclType(Constructor->getParent()) | |||
| 9682 | << /*member=*/1 | |||
| 9683 | << Entity.getName() | |||
| 9684 | << InheritedFrom; | |||
| 9685 | S.Diag(Entity.getDecl()->getLocation(), | |||
| 9686 | diag::note_member_declared_at); | |||
| 9687 | ||||
| 9688 | if (const RecordType *Record | |||
| 9689 | = Entity.getType()->getAs<RecordType>()) | |||
| 9690 | S.Diag(Record->getDecl()->getLocation(), | |||
| 9691 | diag::note_previous_decl) | |||
| 9692 | << S.Context.getTagDeclType(Record->getDecl()); | |||
| 9693 | } | |||
| 9694 | break; | |||
| 9695 | } | |||
| 9696 | ||||
| 9697 | FailedCandidateSet.NoteCandidates( | |||
| 9698 | PartialDiagnosticAt( | |||
| 9699 | Kind.getLocation(), | |||
| 9700 | S.PDiag(diag::err_ovl_no_viable_function_in_init) | |||
| 9701 | << DestType << ArgsRange), | |||
| 9702 | S, OCD_AllCandidates, Args); | |||
| 9703 | break; | |||
| 9704 | ||||
| 9705 | case OR_Deleted: { | |||
| 9706 | OverloadCandidateSet::iterator Best; | |||
| 9707 | OverloadingResult Ovl | |||
| 9708 | = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); | |||
| 9709 | if (Ovl != OR_Deleted) { | |||
| 9710 | S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) | |||
| 9711 | << DestType << ArgsRange; | |||
| 9712 | llvm_unreachable("Inconsistent overload resolution?")::llvm::llvm_unreachable_internal("Inconsistent overload resolution?" , "clang/lib/Sema/SemaInit.cpp", 9712); | |||
| 9713 | break; | |||
| 9714 | } | |||
| 9715 | ||||
| 9716 | // If this is a defaulted or implicitly-declared function, then | |||
| 9717 | // it was implicitly deleted. Make it clear that the deletion was | |||
| 9718 | // implicit. | |||
| 9719 | if (S.isImplicitlyDeleted(Best->Function)) | |||
| 9720 | S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init) | |||
| 9721 | << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)) | |||
| 9722 | << DestType << ArgsRange; | |||
| 9723 | else | |||
| 9724 | S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) | |||
| 9725 | << DestType << ArgsRange; | |||
| 9726 | ||||
| 9727 | S.NoteDeletedFunction(Best->Function); | |||
| 9728 | break; | |||
| 9729 | } | |||
| 9730 | ||||
| 9731 | case OR_Success: | |||
| 9732 | llvm_unreachable("Conversion did not fail!")::llvm::llvm_unreachable_internal("Conversion did not fail!", "clang/lib/Sema/SemaInit.cpp", 9732); | |||
| 9733 | } | |||
| 9734 | } | |||
| 9735 | break; | |||
| 9736 | ||||
| 9737 | case FK_DefaultInitOfConst: | |||
| 9738 | if (Entity.getKind() == InitializedEntity::EK_Member && | |||
| 9739 | isa<CXXConstructorDecl>(S.CurContext)) { | |||
| 9740 | // This is implicit default-initialization of a const member in | |||
| 9741 | // a constructor. Complain that it needs to be explicitly | |||
| 9742 | // initialized. | |||
| 9743 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext); | |||
| 9744 | S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor) | |||
| 9745 | << (Constructor->getInheritedConstructor() ? 2 : | |||
| 9746 | Constructor->isImplicit() ? 1 : 0) | |||
| 9747 | << S.Context.getTypeDeclType(Constructor->getParent()) | |||
| 9748 | << /*const=*/1 | |||
| 9749 | << Entity.getName(); | |||
| 9750 | S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl) | |||
| 9751 | << Entity.getName(); | |||
| 9752 | } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl()); | |||
| 9753 | VD && VD->isConstexpr()) { | |||
| 9754 | S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init) | |||
| 9755 | << VD; | |||
| 9756 | } else { | |||
| 9757 | S.Diag(Kind.getLocation(), diag::err_default_init_const) | |||
| 9758 | << DestType << (bool)DestType->getAs<RecordType>(); | |||
| 9759 | } | |||
| 9760 | break; | |||
| 9761 | ||||
| 9762 | case FK_Incomplete: | |||
| 9763 | S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType, | |||
| 9764 | diag::err_init_incomplete_type); | |||
| 9765 | break; | |||
| 9766 | ||||
| 9767 | case FK_ListInitializationFailed: { | |||
| 9768 | // Run the init list checker again to emit diagnostics. | |||
| 9769 | InitListExpr *InitList = cast<InitListExpr>(Args[0]); | |||
| 9770 | diagnoseListInit(S, Entity, InitList); | |||
| 9771 | break; | |||
| 9772 | } | |||
| 9773 | ||||
| 9774 | case FK_PlaceholderType: { | |||
| 9775 | // FIXME: Already diagnosed! | |||
| 9776 | break; | |||
| 9777 | } | |||
| 9778 | ||||
| 9779 | case FK_ExplicitConstructor: { | |||
| 9780 | S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor) | |||
| 9781 | << Args[0]->getSourceRange(); | |||
| 9782 | OverloadCandidateSet::iterator Best; | |||
| 9783 | OverloadingResult Ovl | |||
| 9784 | = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); | |||
| 9785 | (void)Ovl; | |||
| 9786 | assert(Ovl == OR_Success && "Inconsistent overload resolution")(static_cast <bool> (Ovl == OR_Success && "Inconsistent overload resolution" ) ? void (0) : __assert_fail ("Ovl == OR_Success && \"Inconsistent overload resolution\"" , "clang/lib/Sema/SemaInit.cpp", 9786, __extension__ __PRETTY_FUNCTION__ )); | |||
| 9787 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); | |||
| 9788 | S.Diag(CtorDecl->getLocation(), | |||
| 9789 | diag::note_explicit_ctor_deduction_guide_here) << false; | |||
| 9790 | break; | |||
| 9791 | } | |||
| 9792 | ||||
| 9793 | case FK_ParenthesizedListInitFailed: | |||
| 9794 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this, | |||
| 9795 | /*VerifyOnly=*/false); | |||
| 9796 | break; | |||
| 9797 | } | |||
| 9798 | ||||
| 9799 | PrintInitLocationNote(S, Entity); | |||
| 9800 | return true; | |||
| 9801 | } | |||
| 9802 | ||||
| 9803 | void InitializationSequence::dump(raw_ostream &OS) const { | |||
| 9804 | switch (SequenceKind) { | |||
| 9805 | case FailedSequence: { | |||
| 9806 | OS << "Failed sequence: "; | |||
| 9807 | switch (Failure) { | |||
| 9808 | case FK_TooManyInitsForReference: | |||
| 9809 | OS << "too many initializers for reference"; | |||
| 9810 | break; | |||
| 9811 | ||||
| 9812 | case FK_ParenthesizedListInitForReference: | |||
| 9813 | OS << "parenthesized list init for reference"; | |||
| 9814 | break; | |||
| 9815 | ||||
| 9816 | case FK_ArrayNeedsInitList: | |||
| 9817 | OS << "array requires initializer list"; | |||
| 9818 | break; | |||
| 9819 | ||||
| 9820 | case FK_AddressOfUnaddressableFunction: | |||
| 9821 | OS << "address of unaddressable function was taken"; | |||
| 9822 | break; | |||
| 9823 | ||||
| 9824 | case FK_ArrayNeedsInitListOrStringLiteral: | |||
| 9825 | OS << "array requires initializer list or string literal"; | |||
| 9826 | break; | |||
| 9827 | ||||
| 9828 | case FK_ArrayNeedsInitListOrWideStringLiteral: | |||
| 9829 | OS << "array requires initializer list or wide string literal"; | |||
| 9830 | break; | |||
| 9831 | ||||
| 9832 | case FK_NarrowStringIntoWideCharArray: | |||
| 9833 | OS << "narrow string into wide char array"; | |||
| 9834 | break; | |||
| 9835 | ||||
| 9836 | case FK_WideStringIntoCharArray: | |||
| 9837 | OS << "wide string into char array"; | |||
| 9838 | break; | |||
| 9839 | ||||
| 9840 | case FK_IncompatWideStringIntoWideChar: | |||
| 9841 | OS << "incompatible wide string into wide char array"; | |||
| 9842 | break; | |||
| 9843 | ||||
| 9844 | case FK_PlainStringIntoUTF8Char: | |||
| 9845 | OS << "plain string literal into char8_t array"; | |||
| 9846 | break; | |||
| 9847 | ||||
| 9848 | case FK_UTF8StringIntoPlainChar: | |||
| 9849 | OS << "u8 string literal into char array"; | |||
| 9850 | break; | |||
| 9851 | ||||
| 9852 | case FK_ArrayTypeMismatch: | |||
| 9853 | OS << "array type mismatch"; | |||
| 9854 | break; | |||
| 9855 | ||||
| 9856 | case FK_NonConstantArrayInit: | |||
| 9857 | OS << "non-constant array initializer"; | |||
| 9858 | break; | |||
| 9859 | ||||
| 9860 | case FK_AddressOfOverloadFailed: | |||
| 9861 | OS << "address of overloaded function failed"; | |||
| 9862 | break; | |||
| 9863 | ||||
| 9864 | case FK_ReferenceInitOverloadFailed: | |||
| 9865 | OS << "overload resolution for reference initialization failed"; | |||
| 9866 | break; | |||
| 9867 | ||||
| 9868 | case FK_NonConstLValueReferenceBindingToTemporary: | |||
| 9869 | OS << "non-const lvalue reference bound to temporary"; | |||
| 9870 | break; | |||
| 9871 | ||||
| 9872 | case FK_NonConstLValueReferenceBindingToBitfield: | |||
| 9873 | OS << "non-const lvalue reference bound to bit-field"; | |||
| 9874 | break; | |||
| 9875 | ||||
| 9876 | case FK_NonConstLValueReferenceBindingToVectorElement: | |||
| 9877 | OS << "non-const lvalue reference bound to vector element"; | |||
| 9878 | break; | |||
| 9879 | ||||
| 9880 | case FK_NonConstLValueReferenceBindingToMatrixElement: | |||
| 9881 | OS << "non-const lvalue reference bound to matrix element"; | |||
| 9882 | break; | |||
| 9883 | ||||
| 9884 | case FK_NonConstLValueReferenceBindingToUnrelated: | |||
| 9885 | OS << "non-const lvalue reference bound to unrelated type"; | |||
| 9886 | break; | |||
| 9887 | ||||
| 9888 | case FK_RValueReferenceBindingToLValue: | |||
| 9889 | OS << "rvalue reference bound to an lvalue"; | |||
| 9890 | break; | |||
| 9891 | ||||
| 9892 | case FK_ReferenceInitDropsQualifiers: | |||
| 9893 | OS << "reference initialization drops qualifiers"; | |||
| 9894 | break; | |||
| 9895 | ||||
| 9896 | case FK_ReferenceAddrspaceMismatchTemporary: | |||
| 9897 | OS << "reference with mismatching address space bound to temporary"; | |||
| 9898 | break; | |||
| 9899 | ||||
| 9900 | case FK_ReferenceInitFailed: | |||
| 9901 | OS << "reference initialization failed"; | |||
| 9902 | break; | |||
| 9903 | ||||
| 9904 | case FK_ConversionFailed: | |||
| 9905 | OS << "conversion failed"; | |||
| 9906 | break; | |||
| 9907 | ||||
| 9908 | case FK_ConversionFromPropertyFailed: | |||
| 9909 | OS << "conversion from property failed"; | |||
| 9910 | break; | |||
| 9911 | ||||
| 9912 | case FK_TooManyInitsForScalar: | |||
| 9913 | OS << "too many initializers for scalar"; | |||
| 9914 | break; | |||
| 9915 | ||||
| 9916 | case FK_ParenthesizedListInitForScalar: | |||
| 9917 | OS << "parenthesized list init for reference"; | |||
| 9918 | break; | |||
| 9919 | ||||
| 9920 | case FK_ReferenceBindingToInitList: | |||
| 9921 | OS << "referencing binding to initializer list"; | |||
| 9922 | break; | |||
| 9923 | ||||
| 9924 | case FK_InitListBadDestinationType: | |||
| 9925 | OS << "initializer list for non-aggregate, non-scalar type"; | |||
| 9926 | break; | |||
| 9927 | ||||
| 9928 | case FK_UserConversionOverloadFailed: | |||
| 9929 | OS << "overloading failed for user-defined conversion"; | |||
| 9930 | break; | |||
| 9931 | ||||
| 9932 | case FK_ConstructorOverloadFailed: | |||
| 9933 | OS << "constructor overloading failed"; | |||
| 9934 | break; | |||
| 9935 | ||||
| 9936 | case FK_DefaultInitOfConst: | |||
| 9937 | OS << "default initialization of a const variable"; | |||
| 9938 | break; | |||
| 9939 | ||||
| 9940 | case FK_Incomplete: | |||
| 9941 | OS << "initialization of incomplete type"; | |||
| 9942 | break; | |||
| 9943 | ||||
| 9944 | case FK_ListInitializationFailed: | |||
| 9945 | OS << "list initialization checker failure"; | |||
| 9946 | break; | |||
| 9947 | ||||
| 9948 | case FK_VariableLengthArrayHasInitializer: | |||
| 9949 | OS << "variable length array has an initializer"; | |||
| 9950 | break; | |||
| 9951 | ||||
| 9952 | case FK_PlaceholderType: | |||
| 9953 | OS << "initializer expression isn't contextually valid"; | |||
| 9954 | break; | |||
| 9955 | ||||
| 9956 | case FK_ListConstructorOverloadFailed: | |||
| 9957 | OS << "list constructor overloading failed"; | |||
| 9958 | break; | |||
| 9959 | ||||
| 9960 | case FK_ExplicitConstructor: | |||
| 9961 | OS << "list copy initialization chose explicit constructor"; | |||
| 9962 | break; | |||
| 9963 | ||||
| 9964 | case FK_ParenthesizedListInitFailed: | |||
| 9965 | OS << "parenthesized list initialization failed"; | |||
| 9966 | break; | |||
| 9967 | } | |||
| 9968 | OS << '\n'; | |||
| 9969 | return; | |||
| 9970 | } | |||
| 9971 | ||||
| 9972 | case DependentSequence: | |||
| 9973 | OS << "Dependent sequence\n"; | |||
| 9974 | return; | |||
| 9975 | ||||
| 9976 | case NormalSequence: | |||
| 9977 | OS << "Normal sequence: "; | |||
| 9978 | break; | |||
| 9979 | } | |||
| 9980 | ||||
| 9981 | for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { | |||
| 9982 | if (S != step_begin()) { | |||
| 9983 | OS << " -> "; | |||
| 9984 | } | |||
| 9985 | ||||
| 9986 | switch (S->Kind) { | |||
| 9987 | case SK_ResolveAddressOfOverloadedFunction: | |||
| 9988 | OS << "resolve address of overloaded function"; | |||
| 9989 | break; | |||
| 9990 | ||||
| 9991 | case SK_CastDerivedToBasePRValue: | |||
| 9992 | OS << "derived-to-base (prvalue)"; | |||
| 9993 | break; | |||
| 9994 | ||||
| 9995 | case SK_CastDerivedToBaseXValue: | |||
| 9996 | OS << "derived-to-base (xvalue)"; | |||
| 9997 | break; | |||
| 9998 | ||||
| 9999 | case SK_CastDerivedToBaseLValue: | |||
| 10000 | OS << "derived-to-base (lvalue)"; | |||
| 10001 | break; | |||
| 10002 | ||||
| 10003 | case SK_BindReference: | |||
| 10004 | OS << "bind reference to lvalue"; | |||
| 10005 | break; | |||
| 10006 | ||||
| 10007 | case SK_BindReferenceToTemporary: | |||
| 10008 | OS << "bind reference to a temporary"; | |||
| 10009 | break; | |||
| 10010 | ||||
| 10011 | case SK_FinalCopy: | |||
| 10012 | OS << "final copy in class direct-initialization"; | |||
| 10013 | break; | |||
| 10014 | ||||
| 10015 | case SK_ExtraneousCopyToTemporary: | |||
| 10016 | OS << "extraneous C++03 copy to temporary"; | |||
| 10017 | break; | |||
| 10018 | ||||
| 10019 | case SK_UserConversion: | |||
| 10020 | OS << "user-defined conversion via " << *S->Function.Function; | |||
| 10021 | break; | |||
| 10022 | ||||
| 10023 | case SK_QualificationConversionPRValue: | |||
| 10024 | OS << "qualification conversion (prvalue)"; | |||
| 10025 | break; | |||
| 10026 | ||||
| 10027 | case SK_QualificationConversionXValue: | |||
| 10028 | OS << "qualification conversion (xvalue)"; | |||
| 10029 | break; | |||
| 10030 | ||||
| 10031 | case SK_QualificationConversionLValue: | |||
| 10032 | OS << "qualification conversion (lvalue)"; | |||
| 10033 | break; | |||
| 10034 | ||||
| 10035 | case SK_FunctionReferenceConversion: | |||
| 10036 | OS << "function reference conversion"; | |||
| 10037 | break; | |||
| 10038 | ||||
| 10039 | case SK_AtomicConversion: | |||
| 10040 | OS << "non-atomic-to-atomic conversion"; | |||
| 10041 | break; | |||
| 10042 | ||||
| 10043 | case SK_ConversionSequence: | |||
| 10044 | OS << "implicit conversion sequence ("; | |||
| 10045 | S->ICS->dump(); // FIXME: use OS | |||
| 10046 | OS << ")"; | |||
| 10047 | break; | |||
| 10048 | ||||
| 10049 | case SK_ConversionSequenceNoNarrowing: | |||
| 10050 | OS << "implicit conversion sequence with narrowing prohibited ("; | |||
| 10051 | S->ICS->dump(); // FIXME: use OS | |||
| 10052 | OS << ")"; | |||
| 10053 | break; | |||
| 10054 | ||||
| 10055 | case SK_ListInitialization: | |||
| 10056 | OS << "list aggregate initialization"; | |||
| 10057 | break; | |||
| 10058 | ||||
| 10059 | case SK_UnwrapInitList: | |||
| 10060 | OS << "unwrap reference initializer list"; | |||
| 10061 | break; | |||
| 10062 | ||||
| 10063 | case SK_RewrapInitList: | |||
| 10064 | OS << "rewrap reference initializer list"; | |||
| 10065 | break; | |||
| 10066 | ||||
| 10067 | case SK_ConstructorInitialization: | |||
| 10068 | OS << "constructor initialization"; | |||
| 10069 | break; | |||
| 10070 | ||||
| 10071 | case SK_ConstructorInitializationFromList: | |||
| 10072 | OS << "list initialization via constructor"; | |||
| 10073 | break; | |||
| 10074 | ||||
| 10075 | case SK_ZeroInitialization: | |||
| 10076 | OS << "zero initialization"; | |||
| 10077 | break; | |||
| 10078 | ||||
| 10079 | case SK_CAssignment: | |||
| 10080 | OS << "C assignment"; | |||
| 10081 | break; | |||
| 10082 | ||||
| 10083 | case SK_StringInit: | |||
| 10084 | OS << "string initialization"; | |||
| 10085 | break; | |||
| 10086 | ||||
| 10087 | case SK_ObjCObjectConversion: | |||
| 10088 | OS << "Objective-C object conversion"; | |||
| 10089 | break; | |||
| 10090 | ||||
| 10091 | case SK_ArrayLoopIndex: | |||
| 10092 | OS << "indexing for array initialization loop"; | |||
| 10093 | break; | |||
| 10094 | ||||
| 10095 | case SK_ArrayLoopInit: | |||
| 10096 | OS << "array initialization loop"; | |||
| 10097 | break; | |||
| 10098 | ||||
| 10099 | case SK_ArrayInit: | |||
| 10100 | OS << "array initialization"; | |||
| 10101 | break; | |||
| 10102 | ||||
| 10103 | case SK_GNUArrayInit: | |||
| 10104 | OS << "array initialization (GNU extension)"; | |||
| 10105 | break; | |||
| 10106 | ||||
| 10107 | case SK_ParenthesizedArrayInit: | |||
| 10108 | OS << "parenthesized array initialization"; | |||
| 10109 | break; | |||
| 10110 | ||||
| 10111 | case SK_PassByIndirectCopyRestore: | |||
| 10112 | OS << "pass by indirect copy and restore"; | |||
| 10113 | break; | |||
| 10114 | ||||
| 10115 | case SK_PassByIndirectRestore: | |||
| 10116 | OS << "pass by indirect restore"; | |||
| 10117 | break; | |||
| 10118 | ||||
| 10119 | case SK_ProduceObjCObject: | |||
| 10120 | OS << "Objective-C object retension"; | |||
| 10121 | break; | |||
| 10122 | ||||
| 10123 | case SK_StdInitializerList: | |||
| 10124 | OS << "std::initializer_list from initializer list"; | |||
| 10125 | break; | |||
| 10126 | ||||
| 10127 | case SK_StdInitializerListConstructorCall: | |||
| 10128 | OS << "list initialization from std::initializer_list"; | |||
| 10129 | break; | |||
| 10130 | ||||
| 10131 | case SK_OCLSamplerInit: | |||
| 10132 | OS << "OpenCL sampler_t from integer constant"; | |||
| 10133 | break; | |||
| 10134 | ||||
| 10135 | case SK_OCLZeroOpaqueType: | |||
| 10136 | OS << "OpenCL opaque type from zero"; | |||
| 10137 | break; | |||
| 10138 | case SK_ParenthesizedListInit: | |||
| 10139 | OS << "initialization from a parenthesized list of values"; | |||
| 10140 | break; | |||
| 10141 | } | |||
| 10142 | ||||
| 10143 | OS << " [" << S->Type << ']'; | |||
| 10144 | } | |||
| 10145 | ||||
| 10146 | OS << '\n'; | |||
| 10147 | } | |||
| 10148 | ||||
| 10149 | void InitializationSequence::dump() const { | |||
| 10150 | dump(llvm::errs()); | |||
| 10151 | } | |||
| 10152 | ||||
| 10153 | static bool NarrowingErrs(const LangOptions &L) { | |||
| 10154 | return L.CPlusPlus11 && | |||
| 10155 | (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)); | |||
| 10156 | } | |||
| 10157 | ||||
| 10158 | static void DiagnoseNarrowingInInitList(Sema &S, | |||
| 10159 | const ImplicitConversionSequence &ICS, | |||
| 10160 | QualType PreNarrowingType, | |||
| 10161 | QualType EntityType, | |||
| 10162 | const Expr *PostInit) { | |||
| 10163 | const StandardConversionSequence *SCS = nullptr; | |||
| 10164 | switch (ICS.getKind()) { | |||
| 10165 | case ImplicitConversionSequence::StandardConversion: | |||
| 10166 | SCS = &ICS.Standard; | |||
| 10167 | break; | |||
| 10168 | case ImplicitConversionSequence::UserDefinedConversion: | |||
| 10169 | SCS = &ICS.UserDefined.After; | |||
| 10170 | break; | |||
| 10171 | case ImplicitConversionSequence::AmbiguousConversion: | |||
| 10172 | case ImplicitConversionSequence::StaticObjectArgumentConversion: | |||
| 10173 | case ImplicitConversionSequence::EllipsisConversion: | |||
| 10174 | case ImplicitConversionSequence::BadConversion: | |||
| 10175 | return; | |||
| 10176 | } | |||
| 10177 | ||||
| 10178 | // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion. | |||
| 10179 | APValue ConstantValue; | |||
| 10180 | QualType ConstantType; | |||
| 10181 | switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue, | |||
| 10182 | ConstantType)) { | |||
| 10183 | case NK_Not_Narrowing: | |||
| 10184 | case NK_Dependent_Narrowing: | |||
| 10185 | // No narrowing occurred. | |||
| 10186 | return; | |||
| 10187 | ||||
| 10188 | case NK_Type_Narrowing: | |||
| 10189 | // This was a floating-to-integer conversion, which is always considered a | |||
| 10190 | // narrowing conversion even if the value is a constant and can be | |||
| 10191 | // represented exactly as an integer. | |||
| 10192 | S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts()) | |||
| 10193 | ? diag::ext_init_list_type_narrowing | |||
| 10194 | : diag::warn_init_list_type_narrowing) | |||
| 10195 | << PostInit->getSourceRange() | |||
| 10196 | << PreNarrowingType.getLocalUnqualifiedType() | |||
| 10197 | << EntityType.getLocalUnqualifiedType(); | |||
| 10198 | break; | |||
| 10199 | ||||
| 10200 | case NK_Constant_Narrowing: | |||
| 10201 | // A constant value was narrowed. | |||
| 10202 | S.Diag(PostInit->getBeginLoc(), | |||
| 10203 | NarrowingErrs(S.getLangOpts()) | |||
| 10204 | ? diag::ext_init_list_constant_narrowing | |||
| 10205 | : diag::warn_init_list_constant_narrowing) | |||
| 10206 | << PostInit->getSourceRange() | |||
| 10207 | << ConstantValue.getAsString(S.getASTContext(), ConstantType) | |||
| 10208 | << EntityType.getLocalUnqualifiedType(); | |||
| 10209 | break; | |||
| 10210 | ||||
| 10211 | case NK_Variable_Narrowing: | |||
| 10212 | // A variable's value may have been narrowed. | |||
| 10213 | S.Diag(PostInit->getBeginLoc(), | |||
| 10214 | NarrowingErrs(S.getLangOpts()) | |||
| 10215 | ? diag::ext_init_list_variable_narrowing | |||
| 10216 | : diag::warn_init_list_variable_narrowing) | |||
| 10217 | << PostInit->getSourceRange() | |||
| 10218 | << PreNarrowingType.getLocalUnqualifiedType() | |||
| 10219 | << EntityType.getLocalUnqualifiedType(); | |||
| 10220 | break; | |||
| 10221 | } | |||
| 10222 | ||||
| 10223 | SmallString<128> StaticCast; | |||
| 10224 | llvm::raw_svector_ostream OS(StaticCast); | |||
| 10225 | OS << "static_cast<"; | |||
| 10226 | if (const TypedefType *TT = EntityType->getAs<TypedefType>()) { | |||
| 10227 | // It's important to use the typedef's name if there is one so that the | |||
| 10228 | // fixit doesn't break code using types like int64_t. | |||
| 10229 | // | |||
| 10230 | // FIXME: This will break if the typedef requires qualification. But | |||
| 10231 | // getQualifiedNameAsString() includes non-machine-parsable components. | |||
| 10232 | OS << *TT->getDecl(); | |||
| 10233 | } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>()) | |||
| 10234 | OS << BT->getName(S.getLangOpts()); | |||
| 10235 | else { | |||
| 10236 | // Oops, we didn't find the actual type of the variable. Don't emit a fixit | |||
| 10237 | // with a broken cast. | |||
| 10238 | return; | |||
| 10239 | } | |||
| 10240 | OS << ">("; | |||
| 10241 | S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence) | |||
| 10242 | << PostInit->getSourceRange() | |||
| 10243 | << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str()) | |||
| 10244 | << FixItHint::CreateInsertion( | |||
| 10245 | S.getLocForEndOfToken(PostInit->getEndLoc()), ")"); | |||
| 10246 | } | |||
| 10247 | ||||
| 10248 | //===----------------------------------------------------------------------===// | |||
| 10249 | // Initialization helper functions | |||
| 10250 | //===----------------------------------------------------------------------===// | |||
| 10251 | bool | |||
| 10252 | Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, | |||
| 10253 | ExprResult Init) { | |||
| 10254 | if (Init.isInvalid()) | |||
| 10255 | return false; | |||
| 10256 | ||||
| 10257 | Expr *InitE = Init.get(); | |||
| 10258 | assert(InitE && "No initialization expression")(static_cast <bool> (InitE && "No initialization expression" ) ? void (0) : __assert_fail ("InitE && \"No initialization expression\"" , "clang/lib/Sema/SemaInit.cpp", 10258, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10259 | ||||
| 10260 | InitializationKind Kind = | |||
| 10261 | InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation()); | |||
| 10262 | InitializationSequence Seq(*this, Entity, Kind, InitE); | |||
| 10263 | return !Seq.Failed(); | |||
| 10264 | } | |||
| 10265 | ||||
| 10266 | ExprResult | |||
| 10267 | Sema::PerformCopyInitialization(const InitializedEntity &Entity, | |||
| 10268 | SourceLocation EqualLoc, | |||
| 10269 | ExprResult Init, | |||
| 10270 | bool TopLevelOfInitList, | |||
| 10271 | bool AllowExplicit) { | |||
| 10272 | if (Init.isInvalid()) | |||
| 10273 | return ExprError(); | |||
| 10274 | ||||
| 10275 | Expr *InitE = Init.get(); | |||
| 10276 | assert(InitE && "No initialization expression?")(static_cast <bool> (InitE && "No initialization expression?" ) ? void (0) : __assert_fail ("InitE && \"No initialization expression?\"" , "clang/lib/Sema/SemaInit.cpp", 10276, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10277 | ||||
| 10278 | if (EqualLoc.isInvalid()) | |||
| 10279 | EqualLoc = InitE->getBeginLoc(); | |||
| 10280 | ||||
| 10281 | InitializationKind Kind = InitializationKind::CreateCopy( | |||
| 10282 | InitE->getBeginLoc(), EqualLoc, AllowExplicit); | |||
| 10283 | InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList); | |||
| 10284 | ||||
| 10285 | // Prevent infinite recursion when performing parameter copy-initialization. | |||
| 10286 | const bool ShouldTrackCopy = | |||
| 10287 | Entity.isParameterKind() && Seq.isConstructorInitialization(); | |||
| 10288 | if (ShouldTrackCopy) { | |||
| 10289 | if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) { | |||
| 10290 | Seq.SetOverloadFailure( | |||
| 10291 | InitializationSequence::FK_ConstructorOverloadFailed, | |||
| 10292 | OR_No_Viable_Function); | |||
| 10293 | ||||
| 10294 | // Try to give a meaningful diagnostic note for the problematic | |||
| 10295 | // constructor. | |||
| 10296 | const auto LastStep = Seq.step_end() - 1; | |||
| 10297 | assert(LastStep->Kind ==(static_cast <bool> (LastStep->Kind == InitializationSequence ::SK_ConstructorInitialization) ? void (0) : __assert_fail ("LastStep->Kind == InitializationSequence::SK_ConstructorInitialization" , "clang/lib/Sema/SemaInit.cpp", 10298, __extension__ __PRETTY_FUNCTION__ )) | |||
| 10298 | InitializationSequence::SK_ConstructorInitialization)(static_cast <bool> (LastStep->Kind == InitializationSequence ::SK_ConstructorInitialization) ? void (0) : __assert_fail ("LastStep->Kind == InitializationSequence::SK_ConstructorInitialization" , "clang/lib/Sema/SemaInit.cpp", 10298, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10299 | const FunctionDecl *Function = LastStep->Function.Function; | |||
| 10300 | auto Candidate = | |||
| 10301 | llvm::find_if(Seq.getFailedCandidateSet(), | |||
| 10302 | [Function](const OverloadCandidate &Candidate) -> bool { | |||
| 10303 | return Candidate.Viable && | |||
| 10304 | Candidate.Function == Function && | |||
| 10305 | Candidate.Conversions.size() > 0; | |||
| 10306 | }); | |||
| 10307 | if (Candidate != Seq.getFailedCandidateSet().end() && | |||
| 10308 | Function->getNumParams() > 0) { | |||
| 10309 | Candidate->Viable = false; | |||
| 10310 | Candidate->FailureKind = ovl_fail_bad_conversion; | |||
| 10311 | Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion, | |||
| 10312 | InitE, | |||
| 10313 | Function->getParamDecl(0)->getType()); | |||
| 10314 | } | |||
| 10315 | } | |||
| 10316 | CurrentParameterCopyTypes.push_back(Entity.getType()); | |||
| 10317 | } | |||
| 10318 | ||||
| 10319 | ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE); | |||
| 10320 | ||||
| 10321 | if (ShouldTrackCopy) | |||
| 10322 | CurrentParameterCopyTypes.pop_back(); | |||
| 10323 | ||||
| 10324 | return Result; | |||
| 10325 | } | |||
| 10326 | ||||
| 10327 | /// Determine whether RD is, or is derived from, a specialization of CTD. | |||
| 10328 | static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, | |||
| 10329 | ClassTemplateDecl *CTD) { | |||
| 10330 | auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) { | |||
| 10331 | auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate); | |||
| 10332 | return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD); | |||
| 10333 | }; | |||
| 10334 | return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization)); | |||
| 10335 | } | |||
| 10336 | ||||
| 10337 | QualType Sema::DeduceTemplateSpecializationFromInitializer( | |||
| 10338 | TypeSourceInfo *TSInfo, const InitializedEntity &Entity, | |||
| 10339 | const InitializationKind &Kind, MultiExprArg Inits) { | |||
| 10340 | auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>( | |||
| 10341 | TSInfo->getType()->getContainedDeducedType()); | |||
| 10342 | assert(DeducedTST && "not a deduced template specialization type")(static_cast <bool> (DeducedTST && "not a deduced template specialization type" ) ? void (0) : __assert_fail ("DeducedTST && \"not a deduced template specialization type\"" , "clang/lib/Sema/SemaInit.cpp", 10342, __extension__ __PRETTY_FUNCTION__ )); | |||
| 10343 | ||||
| 10344 | auto TemplateName = DeducedTST->getTemplateName(); | |||
| 10345 | if (TemplateName.isDependent()) | |||
| 10346 | return SubstAutoTypeDependent(TSInfo->getType()); | |||
| 10347 | ||||
| 10348 | // We can only perform deduction for class templates. | |||
| 10349 | auto *Template = | |||
| 10350 | dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl()); | |||
| 10351 | if (!Template) { | |||
| 10352 | Diag(Kind.getLocation(), | |||
| 10353 | diag::err_deduced_non_class_template_specialization_type) | |||
| 10354 | << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName; | |||
| 10355 | if (auto *TD = TemplateName.getAsTemplateDecl()) | |||
| 10356 | Diag(TD->getLocation(), diag::note_template_decl_here); | |||
| 10357 | return QualType(); | |||
| 10358 | } | |||
| 10359 | ||||
| 10360 | // Can't deduce from dependent arguments. | |||
| 10361 | if (Expr::hasAnyTypeDependentArguments(Inits)) { | |||
| 10362 | Diag(TSInfo->getTypeLoc().getBeginLoc(), | |||
| 10363 | diag::warn_cxx14_compat_class_template_argument_deduction) | |||
| 10364 | << TSInfo->getTypeLoc().getSourceRange() << 0; | |||
| 10365 | return SubstAutoTypeDependent(TSInfo->getType()); | |||
| 10366 | } | |||
| 10367 | ||||
| 10368 | // FIXME: Perform "exact type" matching first, per CWG discussion? | |||
| 10369 | // Or implement this via an implied 'T(T) -> T' deduction guide? | |||
| 10370 | ||||
| 10371 | // FIXME: Do we need/want a std::initializer_list<T> special case? | |||
| 10372 | ||||
| 10373 | // Look up deduction guides, including those synthesized from constructors. | |||
| 10374 | // | |||
| 10375 | // C++1z [over.match.class.deduct]p1: | |||
| 10376 | // A set of functions and function templates is formed comprising: | |||
| 10377 | // - For each constructor of the class template designated by the | |||
| 10378 | // template-name, a function template [...] | |||
| 10379 | // - For each deduction-guide, a function or function template [...] | |||
| 10380 | DeclarationNameInfo NameInfo( | |||
| 10381 | Context.DeclarationNames.getCXXDeductionGuideName(Template), | |||
| 10382 | TSInfo->getTypeLoc().getEndLoc()); | |||
| 10383 | LookupResult Guides(*this, NameInfo, LookupOrdinaryName); | |||
| 10384 | LookupQualifiedName(Guides, Template->getDeclContext()); | |||
| 10385 | ||||
| 10386 | // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't | |||
| 10387 | // clear on this, but they're not found by name so access does not apply. | |||
| 10388 | Guides.suppressDiagnostics(); | |||
| 10389 | ||||
| 10390 | // Figure out if this is list-initialization. | |||
| 10391 | InitListExpr *ListInit = | |||
| 10392 | (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct) | |||
| 10393 | ? dyn_cast<InitListExpr>(Inits[0]) | |||
| 10394 | : nullptr; | |||
| 10395 | ||||
| 10396 | // C++1z [over.match.class.deduct]p1: | |||
| 10397 | // Initialization and overload resolution are performed as described in | |||
| 10398 | // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list] | |||
| 10399 | // (as appropriate for the type of initialization performed) for an object | |||
| 10400 | // of a hypothetical class type, where the selected functions and function | |||
| 10401 | // templates are considered to be the constructors of that class type | |||
| 10402 | // | |||
| 10403 | // Since we know we're initializing a class type of a type unrelated to that | |||
| 10404 | // of the initializer, this reduces to something fairly reasonable. | |||
| 10405 | OverloadCandidateSet Candidates(Kind.getLocation(), | |||
| 10406 | OverloadCandidateSet::CSK_Normal); | |||
| 10407 | OverloadCandidateSet::iterator Best; | |||
| 10408 | ||||
| 10409 | bool HasAnyDeductionGuide = false; | |||
| 10410 | bool AllowExplicit = !Kind.isCopyInit() || ListInit; | |||
| 10411 | ||||
| 10412 | auto tryToResolveOverload = | |||
| 10413 | [&](bool OnlyListConstructors) -> OverloadingResult { | |||
| 10414 | Candidates.clear(OverloadCandidateSet::CSK_Normal); | |||
| 10415 | HasAnyDeductionGuide = false; | |||
| 10416 | ||||
| 10417 | for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) { | |||
| 10418 | NamedDecl *D = (*I)->getUnderlyingDecl(); | |||
| 10419 | if (D->isInvalidDecl()) | |||
| 10420 | continue; | |||
| 10421 | ||||
| 10422 | auto *TD = dyn_cast<FunctionTemplateDecl>(D); | |||
| 10423 | auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>( | |||
| 10424 | TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D)); | |||
| 10425 | if (!GD) | |||
| 10426 | continue; | |||
| 10427 | ||||
| 10428 | if (!GD->isImplicit()) | |||
| 10429 | HasAnyDeductionGuide = true; | |||
| 10430 | ||||
| 10431 | // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class) | |||
| 10432 | // For copy-initialization, the candidate functions are all the | |||
| 10433 | // converting constructors (12.3.1) of that class. | |||
| 10434 | // C++ [over.match.copy]p1: (non-list copy-initialization from class) | |||
| 10435 | // The converting constructors of T are candidate functions. | |||
| 10436 | if (!AllowExplicit) { | |||
| 10437 | // Overload resolution checks whether the deduction guide is declared | |||
| 10438 | // explicit for us. | |||
| 10439 | ||||
| 10440 | // When looking for a converting constructor, deduction guides that | |||
| 10441 | // could never be called with one argument are not interesting to | |||
| 10442 | // check or note. | |||
| 10443 | if (GD->getMinRequiredArguments() > 1 || | |||
| 10444 | (GD->getNumParams() == 0 && !GD->isVariadic())) | |||
| 10445 | continue; | |||
| 10446 | } | |||
| 10447 | ||||
| 10448 | // C++ [over.match.list]p1.1: (first phase list initialization) | |||
| 10449 | // Initially, the candidate functions are the initializer-list | |||
| 10450 | // constructors of the class T | |||
| 10451 | if (OnlyListConstructors && !isInitListConstructor(GD)) | |||
| 10452 | continue; | |||
| 10453 | ||||
| 10454 | // C++ [over.match.list]p1.2: (second phase list initialization) | |||
| 10455 | // the candidate functions are all the constructors of the class T | |||
| 10456 | // C++ [over.match.ctor]p1: (all other cases) | |||
| 10457 | // the candidate functions are all the constructors of the class of | |||
| 10458 | // the object being initialized | |||
| 10459 | ||||
| 10460 | // C++ [over.best.ics]p4: | |||
| 10461 | // When [...] the constructor [...] is a candidate by | |||
| 10462 | // - [over.match.copy] (in all cases) | |||
| 10463 | // FIXME: The "second phase of [over.match.list] case can also | |||
| 10464 | // theoretically happen here, but it's not clear whether we can | |||
| 10465 | // ever have a parameter of the right type. | |||
| 10466 | bool SuppressUserConversions = Kind.isCopyInit(); | |||
| 10467 | ||||
| 10468 | if (TD) | |||
| 10469 | AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr, | |||
| 10470 | Inits, Candidates, SuppressUserConversions, | |||
| 10471 | /*PartialOverloading*/ false, | |||
| 10472 | AllowExplicit); | |||
| 10473 | else | |||
| 10474 | AddOverloadCandidate(GD, I.getPair(), Inits, Candidates, | |||
| 10475 | SuppressUserConversions, | |||
| 10476 | /*PartialOverloading*/ false, AllowExplicit); | |||
| 10477 | } | |||
| 10478 | return Candidates.BestViableFunction(*this, Kind.getLocation(), Best); | |||
| 10479 | }; | |||
| 10480 | ||||
| 10481 | OverloadingResult Result = OR_No_Viable_Function; | |||
| 10482 | ||||
| 10483 | // C++11 [over.match.list]p1, per DR1467: for list-initialization, first | |||
| 10484 | // try initializer-list constructors. | |||
| 10485 | if (ListInit) { | |||
| 10486 | bool TryListConstructors = true; | |||
| 10487 | ||||
| 10488 | // Try list constructors unless the list is empty and the class has one or | |||
| 10489 | // more default constructors, in which case those constructors win. | |||
| 10490 | if (!ListInit->getNumInits()) { | |||
| 10491 | for (NamedDecl *D : Guides) { | |||
| 10492 | auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl()); | |||
| 10493 | if (FD && FD->getMinRequiredArguments() == 0) { | |||
| 10494 | TryListConstructors = false; | |||
| 10495 | break; | |||
| 10496 | } | |||
| 10497 | } | |||
| 10498 | } else if (ListInit->getNumInits() == 1) { | |||
| 10499 | // C++ [over.match.class.deduct]: | |||
| 10500 | // As an exception, the first phase in [over.match.list] (considering | |||
| 10501 | // initializer-list constructors) is omitted if the initializer list | |||
| 10502 | // consists of a single expression of type cv U, where U is a | |||
| 10503 | // specialization of C or a class derived from a specialization of C. | |||
| 10504 | Expr *E = ListInit->getInit(0); | |||
| 10505 | auto *RD = E->getType()->getAsCXXRecordDecl(); | |||
| 10506 | if (!isa<InitListExpr>(E) && RD && | |||
| 10507 | isCompleteType(Kind.getLocation(), E->getType()) && | |||
| 10508 | isOrIsDerivedFromSpecializationOf(RD, Template)) | |||
| 10509 | TryListConstructors = false; | |||
| 10510 | } | |||
| 10511 | ||||
| 10512 | if (TryListConstructors) | |||
| 10513 | Result = tryToResolveOverload(/*OnlyListConstructor*/true); | |||
| 10514 | // Then unwrap the initializer list and try again considering all | |||
| 10515 | // constructors. | |||
| 10516 | Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits()); | |||
| 10517 | } | |||
| 10518 | ||||
| 10519 | // If list-initialization fails, or if we're doing any other kind of | |||
| 10520 | // initialization, we (eventually) consider constructors. | |||
| 10521 | if (Result == OR_No_Viable_Function) | |||
| 10522 | Result = tryToResolveOverload(/*OnlyListConstructor*/false); | |||
| 10523 | ||||
| 10524 | switch (Result) { | |||
| 10525 | case OR_Ambiguous: | |||
| 10526 | // FIXME: For list-initialization candidates, it'd usually be better to | |||
| 10527 | // list why they were not viable when given the initializer list itself as | |||
| 10528 | // an argument. | |||
| 10529 | Candidates.NoteCandidates( | |||
| 10530 | PartialDiagnosticAt( | |||
| 10531 | Kind.getLocation(), | |||
| 10532 | PDiag(diag::err_deduced_class_template_ctor_ambiguous) | |||
| 10533 | << TemplateName), | |||
| 10534 | *this, OCD_AmbiguousCandidates, Inits); | |||
| 10535 | return QualType(); | |||
| 10536 | ||||
| 10537 | case OR_No_Viable_Function: { | |||
| 10538 | CXXRecordDecl *Primary = | |||
| 10539 | cast<ClassTemplateDecl>(Template)->getTemplatedDecl(); | |||
| 10540 | bool Complete = | |||
| 10541 | isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary)); | |||
| 10542 | Candidates.NoteCandidates( | |||
| 10543 | PartialDiagnosticAt( | |||
| 10544 | Kind.getLocation(), | |||
| 10545 | PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable | |||
| 10546 | : diag::err_deduced_class_template_incomplete) | |||
| 10547 | << TemplateName << !Guides.empty()), | |||
| 10548 | *this, OCD_AllCandidates, Inits); | |||
| 10549 | return QualType(); | |||
| 10550 | } | |||
| 10551 | ||||
| 10552 | case OR_Deleted: { | |||
| 10553 | Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted) | |||
| 10554 | << TemplateName; | |||
| 10555 | NoteDeletedFunction(Best->Function); | |||
| 10556 | return QualType(); | |||
| 10557 | } | |||
| 10558 | ||||
| 10559 | case OR_Success: | |||
| 10560 | // C++ [over.match.list]p1: | |||
| 10561 | // In copy-list-initialization, if an explicit constructor is chosen, the | |||
| 10562 | // initialization is ill-formed. | |||
| 10563 | if (Kind.isCopyInit() && ListInit && | |||
| 10564 | cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) { | |||
| 10565 | bool IsDeductionGuide = !Best->Function->isImplicit(); | |||
| 10566 | Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit) | |||
| 10567 | << TemplateName << IsDeductionGuide; | |||
| 10568 | Diag(Best->Function->getLocation(), | |||
| 10569 | diag::note_explicit_ctor_deduction_guide_here) | |||
| 10570 | << IsDeductionGuide; | |||
| 10571 | return QualType(); | |||
| 10572 | } | |||
| 10573 | ||||
| 10574 | // Make sure we didn't select an unusable deduction guide, and mark it | |||
| 10575 | // as referenced. | |||
| 10576 | DiagnoseUseOfDecl(Best->Function, Kind.getLocation()); | |||
| 10577 | MarkFunctionReferenced(Kind.getLocation(), Best->Function); | |||
| 10578 | break; | |||
| 10579 | } | |||
| 10580 | ||||
| 10581 | // C++ [dcl.type.class.deduct]p1: | |||
| 10582 | // The placeholder is replaced by the return type of the function selected | |||
| 10583 | // by overload resolution for class template deduction. | |||
| 10584 | QualType DeducedType = | |||
| 10585 | SubstAutoType(TSInfo->getType(), Best->Function->getReturnType()); | |||
| 10586 | Diag(TSInfo->getTypeLoc().getBeginLoc(), | |||
| 10587 | diag::warn_cxx14_compat_class_template_argument_deduction) | |||
| 10588 | << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType; | |||
| 10589 | ||||
| 10590 | // Warn if CTAD was used on a type that does not have any user-defined | |||
| 10591 | // deduction guides. | |||
| 10592 | if (!HasAnyDeductionGuide) { | |||
| 10593 | Diag(TSInfo->getTypeLoc().getBeginLoc(), | |||
| 10594 | diag::warn_ctad_maybe_unsupported) | |||
| 10595 | << TemplateName; | |||
| 10596 | Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported); | |||
| 10597 | } | |||
| 10598 | ||||
| 10599 | return DeducedType; | |||
| 10600 | } |