| File: | build/source/clang/lib/Sema/SemaInit.cpp |
| Warning: | line 7435, column 16 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/EnterExpressionEvaluationContext.h" | ||||
| 24 | #include "clang/Sema/Initialization.h" | ||||
| 25 | #include "clang/Sema/Lookup.h" | ||||
| 26 | #include "clang/Sema/SemaInternal.h" | ||||
| 27 | #include "llvm/ADT/APInt.h" | ||||
| 28 | #include "llvm/ADT/PointerIntPair.h" | ||||
| 29 | #include "llvm/ADT/SmallString.h" | ||||
| 30 | #include "llvm/Support/ErrorHandling.h" | ||||
| 31 | #include "llvm/Support/raw_ostream.h" | ||||
| 32 | |||||
| 33 | using namespace clang; | ||||
| 34 | |||||
| 35 | //===----------------------------------------------------------------------===// | ||||
| 36 | // Sema Initialization Checking | ||||
| 37 | //===----------------------------------------------------------------------===// | ||||
| 38 | |||||
| 39 | /// Check whether T is compatible with a wide character type (wchar_t, | ||||
| 40 | /// char16_t or char32_t). | ||||
| 41 | static bool IsWideCharCompatible(QualType T, ASTContext &Context) { | ||||
| 42 | if (Context.typesAreCompatible(Context.getWideCharType(), T)) | ||||
| 43 | return true; | ||||
| 44 | if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) { | ||||
| 45 | return Context.typesAreCompatible(Context.Char16Ty, T) || | ||||
| 46 | Context.typesAreCompatible(Context.Char32Ty, T); | ||||
| 47 | } | ||||
| 48 | return false; | ||||
| 49 | } | ||||
| 50 | |||||
| 51 | enum StringInitFailureKind { | ||||
| 52 | SIF_None, | ||||
| 53 | SIF_NarrowStringIntoWideChar, | ||||
| 54 | SIF_WideStringIntoChar, | ||||
| 55 | SIF_IncompatWideStringIntoWideChar, | ||||
| 56 | SIF_UTF8StringIntoPlainChar, | ||||
| 57 | SIF_PlainStringIntoUTF8Char, | ||||
| 58 | SIF_Other | ||||
| 59 | }; | ||||
| 60 | |||||
| 61 | /// Check whether the array of type AT can be initialized by the Init | ||||
| 62 | /// expression by means of string initialization. Returns SIF_None if so, | ||||
| 63 | /// otherwise returns a StringInitFailureKind that describes why the | ||||
| 64 | /// initialization would not work. | ||||
| 65 | static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT, | ||||
| 66 | ASTContext &Context) { | ||||
| 67 | if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT)) | ||||
| 68 | return SIF_Other; | ||||
| 69 | |||||
| 70 | // See if this is a string literal or @encode. | ||||
| 71 | Init = Init->IgnoreParens(); | ||||
| 72 | |||||
| 73 | // Handle @encode, which is a narrow string. | ||||
| 74 | if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType()) | ||||
| 75 | return SIF_None; | ||||
| 76 | |||||
| 77 | // Otherwise we can only handle string literals. | ||||
| 78 | StringLiteral *SL = dyn_cast<StringLiteral>(Init); | ||||
| 79 | if (!SL) | ||||
| 80 | return SIF_Other; | ||||
| 81 | |||||
| 82 | const QualType ElemTy = | ||||
| 83 | Context.getCanonicalType(AT->getElementType()).getUnqualifiedType(); | ||||
| 84 | |||||
| 85 | auto IsCharOrUnsignedChar = [](const QualType &T) { | ||||
| 86 | const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr()); | ||||
| 87 | return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar; | ||||
| 88 | }; | ||||
| 89 | |||||
| 90 | switch (SL->getKind()) { | ||||
| 91 | case StringLiteral::UTF8: | ||||
| 92 | // char8_t array can be initialized with a UTF-8 string. | ||||
| 93 | // - C++20 [dcl.init.string] (DR) | ||||
| 94 | // Additionally, an array of char or unsigned char may be initialized | ||||
| 95 | // by a UTF-8 string literal. | ||||
| 96 | if (ElemTy->isChar8Type() || | ||||
| 97 | (Context.getLangOpts().Char8 && | ||||
| 98 | IsCharOrUnsignedChar(ElemTy.getCanonicalType()))) | ||||
| 99 | return SIF_None; | ||||
| 100 | [[fallthrough]]; | ||||
| 101 | case StringLiteral::Ordinary: | ||||
| 102 | // char array can be initialized with a narrow string. | ||||
| 103 | // Only allow char x[] = "foo"; not char x[] = L"foo"; | ||||
| 104 | if (ElemTy->isCharType()) | ||||
| 105 | return (SL->getKind() == StringLiteral::UTF8 && | ||||
| 106 | Context.getLangOpts().Char8) | ||||
| 107 | ? SIF_UTF8StringIntoPlainChar | ||||
| 108 | : SIF_None; | ||||
| 109 | if (ElemTy->isChar8Type()) | ||||
| 110 | return SIF_PlainStringIntoUTF8Char; | ||||
| 111 | if (IsWideCharCompatible(ElemTy, Context)) | ||||
| 112 | return SIF_NarrowStringIntoWideChar; | ||||
| 113 | return SIF_Other; | ||||
| 114 | // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15: | ||||
| 115 | // "An array with element type compatible with a qualified or unqualified | ||||
| 116 | // version of wchar_t, char16_t, or char32_t may be initialized by a wide | ||||
| 117 | // string literal with the corresponding encoding prefix (L, u, or U, | ||||
| 118 | // respectively), optionally enclosed in braces. | ||||
| 119 | case StringLiteral::UTF16: | ||||
| 120 | if (Context.typesAreCompatible(Context.Char16Ty, ElemTy)) | ||||
| 121 | return SIF_None; | ||||
| 122 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) | ||||
| 123 | return SIF_WideStringIntoChar; | ||||
| 124 | if (IsWideCharCompatible(ElemTy, Context)) | ||||
| 125 | return SIF_IncompatWideStringIntoWideChar; | ||||
| 126 | return SIF_Other; | ||||
| 127 | case StringLiteral::UTF32: | ||||
| 128 | if (Context.typesAreCompatible(Context.Char32Ty, ElemTy)) | ||||
| 129 | return SIF_None; | ||||
| 130 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) | ||||
| 131 | return SIF_WideStringIntoChar; | ||||
| 132 | if (IsWideCharCompatible(ElemTy, Context)) | ||||
| 133 | return SIF_IncompatWideStringIntoWideChar; | ||||
| 134 | return SIF_Other; | ||||
| 135 | case StringLiteral::Wide: | ||||
| 136 | if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy)) | ||||
| 137 | return SIF_None; | ||||
| 138 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) | ||||
| 139 | return SIF_WideStringIntoChar; | ||||
| 140 | if (IsWideCharCompatible(ElemTy, Context)) | ||||
| 141 | return SIF_IncompatWideStringIntoWideChar; | ||||
| 142 | return SIF_Other; | ||||
| 143 | } | ||||
| 144 | |||||
| 145 | llvm_unreachable("missed a StringLiteral kind?")::llvm::llvm_unreachable_internal("missed a StringLiteral kind?" , "clang/lib/Sema/SemaInit.cpp", 145); | ||||
| 146 | } | ||||
| 147 | |||||
| 148 | static StringInitFailureKind IsStringInit(Expr *init, QualType declType, | ||||
| 149 | ASTContext &Context) { | ||||
| 150 | const ArrayType *arrayType = Context.getAsArrayType(declType); | ||||
| 151 | if (!arrayType) | ||||
| 152 | return SIF_Other; | ||||
| 153 | return IsStringInit(init, arrayType, Context); | ||||
| 154 | } | ||||
| 155 | |||||
| 156 | bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) { | ||||
| 157 | return ::IsStringInit(Init, AT, Context) == SIF_None; | ||||
| 158 | } | ||||
| 159 | |||||
| 160 | /// Update the type of a string literal, including any surrounding parentheses, | ||||
| 161 | /// to match the type of the object which it is initializing. | ||||
| 162 | static void updateStringLiteralType(Expr *E, QualType Ty) { | ||||
| 163 | while (true) { | ||||
| 164 | E->setType(Ty); | ||||
| 165 | E->setValueKind(VK_PRValue); | ||||
| 166 | if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) { | ||||
| 167 | break; | ||||
| 168 | } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { | ||||
| 169 | E = PE->getSubExpr(); | ||||
| 170 | } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { | ||||
| 171 | 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", 171, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 172 | E = UO->getSubExpr(); | ||||
| 173 | } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) { | ||||
| 174 | E = GSE->getResultExpr(); | ||||
| 175 | } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) { | ||||
| 176 | E = CE->getChosenSubExpr(); | ||||
| 177 | } else { | ||||
| 178 | llvm_unreachable("unexpected expr in string literal init")::llvm::llvm_unreachable_internal("unexpected expr in string literal init" , "clang/lib/Sema/SemaInit.cpp", 178); | ||||
| 179 | } | ||||
| 180 | } | ||||
| 181 | } | ||||
| 182 | |||||
| 183 | /// Fix a compound literal initializing an array so it's correctly marked | ||||
| 184 | /// as an rvalue. | ||||
| 185 | static void updateGNUCompoundLiteralRValue(Expr *E) { | ||||
| 186 | while (true) { | ||||
| 187 | E->setValueKind(VK_PRValue); | ||||
| 188 | if (isa<CompoundLiteralExpr>(E)) { | ||||
| 189 | break; | ||||
| 190 | } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { | ||||
| 191 | E = PE->getSubExpr(); | ||||
| 192 | } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { | ||||
| 193 | 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", 193, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 194 | E = UO->getSubExpr(); | ||||
| 195 | } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) { | ||||
| 196 | E = GSE->getResultExpr(); | ||||
| 197 | } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) { | ||||
| 198 | E = CE->getChosenSubExpr(); | ||||
| 199 | } else { | ||||
| 200 | 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", 200); | ||||
| 201 | } | ||||
| 202 | } | ||||
| 203 | } | ||||
| 204 | |||||
| 205 | static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, | ||||
| 206 | Sema &S) { | ||||
| 207 | // Get the length of the string as parsed. | ||||
| 208 | auto *ConstantArrayTy = | ||||
| 209 | cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe()); | ||||
| 210 | uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue(); | ||||
| 211 | |||||
| 212 | if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { | ||||
| 213 | // C99 6.7.8p14. We have an array of character type with unknown size | ||||
| 214 | // being initialized to a string literal. | ||||
| 215 | llvm::APInt ConstVal(32, StrLength); | ||||
| 216 | // Return a new array type (C99 6.7.8p22). | ||||
| 217 | DeclT = S.Context.getConstantArrayType(IAT->getElementType(), | ||||
| 218 | ConstVal, nullptr, | ||||
| 219 | ArrayType::Normal, 0); | ||||
| 220 | updateStringLiteralType(Str, DeclT); | ||||
| 221 | return; | ||||
| 222 | } | ||||
| 223 | |||||
| 224 | const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); | ||||
| 225 | |||||
| 226 | // We have an array of character type with known size. However, | ||||
| 227 | // the size may be smaller or larger than the string we are initializing. | ||||
| 228 | // FIXME: Avoid truncation for 64-bit length strings. | ||||
| 229 | if (S.getLangOpts().CPlusPlus) { | ||||
| 230 | if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) { | ||||
| 231 | // For Pascal strings it's OK to strip off the terminating null character, | ||||
| 232 | // so the example below is valid: | ||||
| 233 | // | ||||
| 234 | // unsigned char a[2] = "\pa"; | ||||
| 235 | if (SL->isPascal()) | ||||
| 236 | StrLength--; | ||||
| 237 | } | ||||
| 238 | |||||
| 239 | // [dcl.init.string]p2 | ||||
| 240 | if (StrLength > CAT->getSize().getZExtValue()) | ||||
| 241 | S.Diag(Str->getBeginLoc(), | ||||
| 242 | diag::err_initializer_string_for_char_array_too_long) | ||||
| 243 | << CAT->getSize().getZExtValue() << StrLength | ||||
| 244 | << Str->getSourceRange(); | ||||
| 245 | } else { | ||||
| 246 | // C99 6.7.8p14. | ||||
| 247 | if (StrLength-1 > CAT->getSize().getZExtValue()) | ||||
| 248 | S.Diag(Str->getBeginLoc(), | ||||
| 249 | diag::ext_initializer_string_for_char_array_too_long) | ||||
| 250 | << Str->getSourceRange(); | ||||
| 251 | } | ||||
| 252 | |||||
| 253 | // Set the type to the actual size that we are initializing. If we have | ||||
| 254 | // something like: | ||||
| 255 | // char x[1] = "foo"; | ||||
| 256 | // then this will set the string literal's type to char[1]. | ||||
| 257 | updateStringLiteralType(Str, DeclT); | ||||
| 258 | } | ||||
| 259 | |||||
| 260 | //===----------------------------------------------------------------------===// | ||||
| 261 | // Semantic checking for initializer lists. | ||||
| 262 | //===----------------------------------------------------------------------===// | ||||
| 263 | |||||
| 264 | namespace { | ||||
| 265 | |||||
| 266 | /// Semantic checking for initializer lists. | ||||
| 267 | /// | ||||
| 268 | /// The InitListChecker class contains a set of routines that each | ||||
| 269 | /// handle the initialization of a certain kind of entity, e.g., | ||||
| 270 | /// arrays, vectors, struct/union types, scalars, etc. The | ||||
| 271 | /// InitListChecker itself performs a recursive walk of the subobject | ||||
| 272 | /// structure of the type to be initialized, while stepping through | ||||
| 273 | /// the initializer list one element at a time. The IList and Index | ||||
| 274 | /// parameters to each of the Check* routines contain the active | ||||
| 275 | /// (syntactic) initializer list and the index into that initializer | ||||
| 276 | /// list that represents the current initializer. Each routine is | ||||
| 277 | /// responsible for moving that Index forward as it consumes elements. | ||||
| 278 | /// | ||||
| 279 | /// Each Check* routine also has a StructuredList/StructuredIndex | ||||
| 280 | /// arguments, which contains the current "structured" (semantic) | ||||
| 281 | /// initializer list and the index into that initializer list where we | ||||
| 282 | /// are copying initializers as we map them over to the semantic | ||||
| 283 | /// list. Once we have completed our recursive walk of the subobject | ||||
| 284 | /// structure, we will have constructed a full semantic initializer | ||||
| 285 | /// list. | ||||
| 286 | /// | ||||
| 287 | /// C99 designators cause changes in the initializer list traversal, | ||||
| 288 | /// because they make the initialization "jump" into a specific | ||||
| 289 | /// subobject and then continue the initialization from that | ||||
| 290 | /// point. CheckDesignatedInitializer() recursively steps into the | ||||
| 291 | /// designated subobject and manages backing out the recursion to | ||||
| 292 | /// initialize the subobjects after the one designated. | ||||
| 293 | /// | ||||
| 294 | /// If an initializer list contains any designators, we build a placeholder | ||||
| 295 | /// structured list even in 'verify only' mode, so that we can track which | ||||
| 296 | /// elements need 'empty' initializtion. | ||||
| 297 | class InitListChecker { | ||||
| 298 | Sema &SemaRef; | ||||
| 299 | bool hadError = false; | ||||
| 300 | bool VerifyOnly; // No diagnostics. | ||||
| 301 | bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode. | ||||
| 302 | bool InOverloadResolution; | ||||
| 303 | InitListExpr *FullyStructuredList = nullptr; | ||||
| 304 | NoInitExpr *DummyExpr = nullptr; | ||||
| 305 | |||||
| 306 | NoInitExpr *getDummyInit() { | ||||
| 307 | if (!DummyExpr) | ||||
| 308 | DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy); | ||||
| 309 | return DummyExpr; | ||||
| 310 | } | ||||
| 311 | |||||
| 312 | void CheckImplicitInitList(const InitializedEntity &Entity, | ||||
| 313 | InitListExpr *ParentIList, QualType T, | ||||
| 314 | unsigned &Index, InitListExpr *StructuredList, | ||||
| 315 | unsigned &StructuredIndex); | ||||
| 316 | void CheckExplicitInitList(const InitializedEntity &Entity, | ||||
| 317 | InitListExpr *IList, QualType &T, | ||||
| 318 | InitListExpr *StructuredList, | ||||
| 319 | bool TopLevelObject = false); | ||||
| 320 | void CheckListElementTypes(const InitializedEntity &Entity, | ||||
| 321 | InitListExpr *IList, QualType &DeclType, | ||||
| 322 | bool SubobjectIsDesignatorContext, | ||||
| 323 | unsigned &Index, | ||||
| 324 | InitListExpr *StructuredList, | ||||
| 325 | unsigned &StructuredIndex, | ||||
| 326 | bool TopLevelObject = false); | ||||
| 327 | void CheckSubElementType(const InitializedEntity &Entity, | ||||
| 328 | InitListExpr *IList, QualType ElemType, | ||||
| 329 | unsigned &Index, | ||||
| 330 | InitListExpr *StructuredList, | ||||
| 331 | unsigned &StructuredIndex, | ||||
| 332 | bool DirectlyDesignated = false); | ||||
| 333 | void CheckComplexType(const InitializedEntity &Entity, | ||||
| 334 | InitListExpr *IList, QualType DeclType, | ||||
| 335 | unsigned &Index, | ||||
| 336 | InitListExpr *StructuredList, | ||||
| 337 | unsigned &StructuredIndex); | ||||
| 338 | void CheckScalarType(const InitializedEntity &Entity, | ||||
| 339 | InitListExpr *IList, QualType DeclType, | ||||
| 340 | unsigned &Index, | ||||
| 341 | InitListExpr *StructuredList, | ||||
| 342 | unsigned &StructuredIndex); | ||||
| 343 | void CheckReferenceType(const InitializedEntity &Entity, | ||||
| 344 | InitListExpr *IList, QualType DeclType, | ||||
| 345 | unsigned &Index, | ||||
| 346 | InitListExpr *StructuredList, | ||||
| 347 | unsigned &StructuredIndex); | ||||
| 348 | void CheckVectorType(const InitializedEntity &Entity, | ||||
| 349 | InitListExpr *IList, QualType DeclType, unsigned &Index, | ||||
| 350 | InitListExpr *StructuredList, | ||||
| 351 | unsigned &StructuredIndex); | ||||
| 352 | void CheckStructUnionTypes(const InitializedEntity &Entity, | ||||
| 353 | InitListExpr *IList, QualType DeclType, | ||||
| 354 | CXXRecordDecl::base_class_range Bases, | ||||
| 355 | RecordDecl::field_iterator Field, | ||||
| 356 | bool SubobjectIsDesignatorContext, unsigned &Index, | ||||
| 357 | InitListExpr *StructuredList, | ||||
| 358 | unsigned &StructuredIndex, | ||||
| 359 | bool TopLevelObject = false); | ||||
| 360 | void CheckArrayType(const InitializedEntity &Entity, | ||||
| 361 | InitListExpr *IList, QualType &DeclType, | ||||
| 362 | llvm::APSInt elementIndex, | ||||
| 363 | bool SubobjectIsDesignatorContext, unsigned &Index, | ||||
| 364 | InitListExpr *StructuredList, | ||||
| 365 | unsigned &StructuredIndex); | ||||
| 366 | bool CheckDesignatedInitializer(const InitializedEntity &Entity, | ||||
| 367 | InitListExpr *IList, DesignatedInitExpr *DIE, | ||||
| 368 | unsigned DesigIdx, | ||||
| 369 | QualType &CurrentObjectType, | ||||
| 370 | RecordDecl::field_iterator *NextField, | ||||
| 371 | llvm::APSInt *NextElementIndex, | ||||
| 372 | unsigned &Index, | ||||
| 373 | InitListExpr *StructuredList, | ||||
| 374 | unsigned &StructuredIndex, | ||||
| 375 | bool FinishSubobjectInit, | ||||
| 376 | bool TopLevelObject); | ||||
| 377 | InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, | ||||
| 378 | QualType CurrentObjectType, | ||||
| 379 | InitListExpr *StructuredList, | ||||
| 380 | unsigned StructuredIndex, | ||||
| 381 | SourceRange InitRange, | ||||
| 382 | bool IsFullyOverwritten = false); | ||||
| 383 | void UpdateStructuredListElement(InitListExpr *StructuredList, | ||||
| 384 | unsigned &StructuredIndex, | ||||
| 385 | Expr *expr); | ||||
| 386 | InitListExpr *createInitListExpr(QualType CurrentObjectType, | ||||
| 387 | SourceRange InitRange, | ||||
| 388 | unsigned ExpectedNumInits); | ||||
| 389 | int numArrayElements(QualType DeclType); | ||||
| 390 | int numStructUnionElements(QualType DeclType); | ||||
| 391 | |||||
| 392 | ExprResult PerformEmptyInit(SourceLocation Loc, | ||||
| 393 | const InitializedEntity &Entity); | ||||
| 394 | |||||
| 395 | /// Diagnose that OldInit (or part thereof) has been overridden by NewInit. | ||||
| 396 | void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange, | ||||
| 397 | bool UnionOverride = false, | ||||
| 398 | bool FullyOverwritten = true) { | ||||
| 399 | // Overriding an initializer via a designator is valid with C99 designated | ||||
| 400 | // initializers, but ill-formed with C++20 designated initializers. | ||||
| 401 | unsigned DiagID = | ||||
| 402 | SemaRef.getLangOpts().CPlusPlus | ||||
| 403 | ? (UnionOverride ? diag::ext_initializer_union_overrides | ||||
| 404 | : diag::ext_initializer_overrides) | ||||
| 405 | : diag::warn_initializer_overrides; | ||||
| 406 | |||||
| 407 | if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) { | ||||
| 408 | // In overload resolution, we have to strictly enforce the rules, and so | ||||
| 409 | // don't allow any overriding of prior initializers. This matters for a | ||||
| 410 | // case such as: | ||||
| 411 | // | ||||
| 412 | // union U { int a, b; }; | ||||
| 413 | // struct S { int a, b; }; | ||||
| 414 | // void f(U), f(S); | ||||
| 415 | // | ||||
| 416 | // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For | ||||
| 417 | // consistency, we disallow all overriding of prior initializers in | ||||
| 418 | // overload resolution, not only overriding of union members. | ||||
| 419 | hadError = true; | ||||
| 420 | } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) { | ||||
| 421 | // If we'll be keeping around the old initializer but overwriting part of | ||||
| 422 | // the object it initialized, and that object is not trivially | ||||
| 423 | // destructible, this can leak. Don't allow that, not even as an | ||||
| 424 | // extension. | ||||
| 425 | // | ||||
| 426 | // FIXME: It might be reasonable to allow this in cases where the part of | ||||
| 427 | // the initializer that we're overriding has trivial destruction. | ||||
| 428 | DiagID = diag::err_initializer_overrides_destructed; | ||||
| 429 | } else if (!OldInit->getSourceRange().isValid()) { | ||||
| 430 | // We need to check on source range validity because the previous | ||||
| 431 | // initializer does not have to be an explicit initializer. e.g., | ||||
| 432 | // | ||||
| 433 | // struct P { int a, b; }; | ||||
| 434 | // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 }; | ||||
| 435 | // | ||||
| 436 | // There is an overwrite taking place because the first braced initializer | ||||
| 437 | // list "{ .a = 2 }" already provides value for .p.b (which is zero). | ||||
| 438 | // | ||||
| 439 | // Such overwrites are harmless, so we don't diagnose them. (Note that in | ||||
| 440 | // C++, this cannot be reached unless we've already seen and diagnosed a | ||||
| 441 | // different conformance issue, such as a mixture of designated and | ||||
| 442 | // non-designated initializers or a multi-level designator.) | ||||
| 443 | return; | ||||
| 444 | } | ||||
| 445 | |||||
| 446 | if (!VerifyOnly) { | ||||
| 447 | SemaRef.Diag(NewInitRange.getBegin(), DiagID) | ||||
| 448 | << NewInitRange << FullyOverwritten << OldInit->getType(); | ||||
| 449 | SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer) | ||||
| 450 | << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten) | ||||
| 451 | << OldInit->getSourceRange(); | ||||
| 452 | } | ||||
| 453 | } | ||||
| 454 | |||||
| 455 | // Explanation on the "FillWithNoInit" mode: | ||||
| 456 | // | ||||
| 457 | // Assume we have the following definitions (Case#1): | ||||
| 458 | // struct P { char x[6][6]; } xp = { .x[1] = "bar" }; | ||||
| 459 | // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' }; | ||||
| 460 | // | ||||
| 461 | // l.lp.x[1][0..1] should not be filled with implicit initializers because the | ||||
| 462 | // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf". | ||||
| 463 | // | ||||
| 464 | // But if we have (Case#2): | ||||
| 465 | // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } }; | ||||
| 466 | // | ||||
| 467 | // l.lp.x[1][0..1] are implicitly initialized and do not use values from the | ||||
| 468 | // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0". | ||||
| 469 | // | ||||
| 470 | // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes" | ||||
| 471 | // in the InitListExpr, the "holes" in Case#1 are filled not with empty | ||||
| 472 | // initializers but with special "NoInitExpr" place holders, which tells the | ||||
| 473 | // CodeGen not to generate any initializers for these parts. | ||||
| 474 | void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base, | ||||
| 475 | const InitializedEntity &ParentEntity, | ||||
| 476 | InitListExpr *ILE, bool &RequiresSecondPass, | ||||
| 477 | bool FillWithNoInit); | ||||
| 478 | void FillInEmptyInitForField(unsigned Init, FieldDecl *Field, | ||||
| 479 | const InitializedEntity &ParentEntity, | ||||
| 480 | InitListExpr *ILE, bool &RequiresSecondPass, | ||||
| 481 | bool FillWithNoInit = false); | ||||
| 482 | void FillInEmptyInitializations(const InitializedEntity &Entity, | ||||
| 483 | InitListExpr *ILE, bool &RequiresSecondPass, | ||||
| 484 | InitListExpr *OuterILE, unsigned OuterIndex, | ||||
| 485 | bool FillWithNoInit = false); | ||||
| 486 | bool CheckFlexibleArrayInit(const InitializedEntity &Entity, | ||||
| 487 | Expr *InitExpr, FieldDecl *Field, | ||||
| 488 | bool TopLevelObject); | ||||
| 489 | void CheckEmptyInitializable(const InitializedEntity &Entity, | ||||
| 490 | SourceLocation Loc); | ||||
| 491 | |||||
| 492 | public: | ||||
| 493 | InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL, | ||||
| 494 | QualType &T, bool VerifyOnly, bool TreatUnavailableAsInvalid, | ||||
| 495 | bool InOverloadResolution = false); | ||||
| 496 | bool HadError() { return hadError; } | ||||
| 497 | |||||
| 498 | // Retrieves the fully-structured initializer list used for | ||||
| 499 | // semantic analysis and code generation. | ||||
| 500 | InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } | ||||
| 501 | }; | ||||
| 502 | |||||
| 503 | } // end anonymous namespace | ||||
| 504 | |||||
| 505 | ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc, | ||||
| 506 | const InitializedEntity &Entity) { | ||||
| 507 | InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, | ||||
| 508 | true); | ||||
| 509 | MultiExprArg SubInit; | ||||
| 510 | Expr *InitExpr; | ||||
| 511 | InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc); | ||||
| 512 | |||||
| 513 | // C++ [dcl.init.aggr]p7: | ||||
| 514 | // If there are fewer initializer-clauses in the list than there are | ||||
| 515 | // members in the aggregate, then each member not explicitly initialized | ||||
| 516 | // ... | ||||
| 517 | bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 && | ||||
| 518 | Entity.getType()->getBaseElementTypeUnsafe()->isRecordType(); | ||||
| 519 | if (EmptyInitList) { | ||||
| 520 | // C++1y / DR1070: | ||||
| 521 | // shall be initialized [...] from an empty initializer list. | ||||
| 522 | // | ||||
| 523 | // We apply the resolution of this DR to C++11 but not C++98, since C++98 | ||||
| 524 | // does not have useful semantics for initialization from an init list. | ||||
| 525 | // We treat this as copy-initialization, because aggregate initialization | ||||
| 526 | // always performs copy-initialization on its elements. | ||||
| 527 | // | ||||
| 528 | // Only do this if we're initializing a class type, to avoid filling in | ||||
| 529 | // the initializer list where possible. | ||||
| 530 | InitExpr = VerifyOnly | ||||
| 531 | ? &DummyInitList | ||||
| 532 | : new (SemaRef.Context) | ||||
| 533 | InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc); | ||||
| 534 | InitExpr->setType(SemaRef.Context.VoidTy); | ||||
| 535 | SubInit = InitExpr; | ||||
| 536 | Kind = InitializationKind::CreateCopy(Loc, Loc); | ||||
| 537 | } else { | ||||
| 538 | // C++03: | ||||
| 539 | // shall be value-initialized. | ||||
| 540 | } | ||||
| 541 | |||||
| 542 | InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit); | ||||
| 543 | // libstdc++4.6 marks the vector default constructor as explicit in | ||||
| 544 | // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case. | ||||
| 545 | // stlport does so too. Look for std::__debug for libstdc++, and for | ||||
| 546 | // std:: for stlport. This is effectively a compiler-side implementation of | ||||
| 547 | // LWG2193. | ||||
| 548 | if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() == | ||||
| 549 | InitializationSequence::FK_ExplicitConstructor) { | ||||
| 550 | OverloadCandidateSet::iterator Best; | ||||
| 551 | OverloadingResult O = | ||||
| 552 | InitSeq.getFailedCandidateSet() | ||||
| 553 | .BestViableFunction(SemaRef, Kind.getLocation(), Best); | ||||
| 554 | (void)O; | ||||
| 555 | 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", 555, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 556 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); | ||||
| 557 | CXXRecordDecl *R = CtorDecl->getParent(); | ||||
| 558 | |||||
| 559 | if (CtorDecl->getMinRequiredArguments() == 0 && | ||||
| 560 | CtorDecl->isExplicit() && R->getDeclName() && | ||||
| 561 | SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) { | ||||
| 562 | bool IsInStd = false; | ||||
| 563 | for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext()); | ||||
| 564 | ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) { | ||||
| 565 | if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND)) | ||||
| 566 | IsInStd = true; | ||||
| 567 | } | ||||
| 568 | |||||
| 569 | if (IsInStd && llvm::StringSwitch<bool>(R->getName()) | ||||
| 570 | .Cases("basic_string", "deque", "forward_list", true) | ||||
| 571 | .Cases("list", "map", "multimap", "multiset", true) | ||||
| 572 | .Cases("priority_queue", "queue", "set", "stack", true) | ||||
| 573 | .Cases("unordered_map", "unordered_set", "vector", true) | ||||
| 574 | .Default(false)) { | ||||
| 575 | InitSeq.InitializeFrom( | ||||
| 576 | SemaRef, Entity, | ||||
| 577 | InitializationKind::CreateValue(Loc, Loc, Loc, true), | ||||
| 578 | MultiExprArg(), /*TopLevelOfInitList=*/false, | ||||
| 579 | TreatUnavailableAsInvalid); | ||||
| 580 | // Emit a warning for this. System header warnings aren't shown | ||||
| 581 | // by default, but people working on system headers should see it. | ||||
| 582 | if (!VerifyOnly) { | ||||
| 583 | SemaRef.Diag(CtorDecl->getLocation(), | ||||
| 584 | diag::warn_invalid_initializer_from_system_header); | ||||
| 585 | if (Entity.getKind() == InitializedEntity::EK_Member) | ||||
| 586 | SemaRef.Diag(Entity.getDecl()->getLocation(), | ||||
| 587 | diag::note_used_in_initialization_here); | ||||
| 588 | else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) | ||||
| 589 | SemaRef.Diag(Loc, diag::note_used_in_initialization_here); | ||||
| 590 | } | ||||
| 591 | } | ||||
| 592 | } | ||||
| 593 | } | ||||
| 594 | if (!InitSeq) { | ||||
| 595 | if (!VerifyOnly) { | ||||
| 596 | InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit); | ||||
| 597 | if (Entity.getKind() == InitializedEntity::EK_Member) | ||||
| 598 | SemaRef.Diag(Entity.getDecl()->getLocation(), | ||||
| 599 | diag::note_in_omitted_aggregate_initializer) | ||||
| 600 | << /*field*/1 << Entity.getDecl(); | ||||
| 601 | else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) { | ||||
| 602 | bool IsTrailingArrayNewMember = | ||||
| 603 | Entity.getParent() && | ||||
| 604 | Entity.getParent()->isVariableLengthArrayNew(); | ||||
| 605 | SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer) | ||||
| 606 | << (IsTrailingArrayNewMember ? 2 : /*array element*/0) | ||||
| 607 | << Entity.getElementIndex(); | ||||
| 608 | } | ||||
| 609 | } | ||||
| 610 | hadError = true; | ||||
| 611 | return ExprError(); | ||||
| 612 | } | ||||
| 613 | |||||
| 614 | return VerifyOnly ? ExprResult() | ||||
| 615 | : InitSeq.Perform(SemaRef, Entity, Kind, SubInit); | ||||
| 616 | } | ||||
| 617 | |||||
| 618 | void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity, | ||||
| 619 | SourceLocation Loc) { | ||||
| 620 | // If we're building a fully-structured list, we'll check this at the end | ||||
| 621 | // once we know which elements are actually initialized. Otherwise, we know | ||||
| 622 | // that there are no designators so we can just check now. | ||||
| 623 | if (FullyStructuredList) | ||||
| 624 | return; | ||||
| 625 | PerformEmptyInit(Loc, Entity); | ||||
| 626 | } | ||||
| 627 | |||||
| 628 | void InitListChecker::FillInEmptyInitForBase( | ||||
| 629 | unsigned Init, const CXXBaseSpecifier &Base, | ||||
| 630 | const InitializedEntity &ParentEntity, InitListExpr *ILE, | ||||
| 631 | bool &RequiresSecondPass, bool FillWithNoInit) { | ||||
| 632 | InitializedEntity BaseEntity = InitializedEntity::InitializeBase( | ||||
| 633 | SemaRef.Context, &Base, false, &ParentEntity); | ||||
| 634 | |||||
| 635 | if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) { | ||||
| 636 | ExprResult BaseInit = FillWithNoInit | ||||
| 637 | ? new (SemaRef.Context) NoInitExpr(Base.getType()) | ||||
| 638 | : PerformEmptyInit(ILE->getEndLoc(), BaseEntity); | ||||
| 639 | if (BaseInit.isInvalid()) { | ||||
| 640 | hadError = true; | ||||
| 641 | return; | ||||
| 642 | } | ||||
| 643 | |||||
| 644 | if (!VerifyOnly) { | ||||
| 645 | 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", 645, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 646 | ILE->setInit(Init, BaseInit.getAs<Expr>()); | ||||
| 647 | } | ||||
| 648 | } else if (InitListExpr *InnerILE = | ||||
| 649 | dyn_cast<InitListExpr>(ILE->getInit(Init))) { | ||||
| 650 | FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass, | ||||
| 651 | ILE, Init, FillWithNoInit); | ||||
| 652 | } else if (DesignatedInitUpdateExpr *InnerDIUE = | ||||
| 653 | dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) { | ||||
| 654 | FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(), | ||||
| 655 | RequiresSecondPass, ILE, Init, | ||||
| 656 | /*FillWithNoInit =*/true); | ||||
| 657 | } | ||||
| 658 | } | ||||
| 659 | |||||
| 660 | void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field, | ||||
| 661 | const InitializedEntity &ParentEntity, | ||||
| 662 | InitListExpr *ILE, | ||||
| 663 | bool &RequiresSecondPass, | ||||
| 664 | bool FillWithNoInit) { | ||||
| 665 | SourceLocation Loc = ILE->getEndLoc(); | ||||
| 666 | unsigned NumInits = ILE->getNumInits(); | ||||
| 667 | InitializedEntity MemberEntity | ||||
| 668 | = InitializedEntity::InitializeMember(Field, &ParentEntity); | ||||
| 669 | |||||
| 670 | if (Init >= NumInits || !ILE->getInit(Init)) { | ||||
| 671 | if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) | ||||
| 672 | if (!RType->getDecl()->isUnion()) | ||||
| 673 | 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", 674, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 674 | "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", 674, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 675 | |||||
| 676 | if (FillWithNoInit) { | ||||
| 677 | 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", 677, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 678 | Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType()); | ||||
| 679 | if (Init < NumInits) | ||||
| 680 | ILE->setInit(Init, Filler); | ||||
| 681 | else | ||||
| 682 | ILE->updateInit(SemaRef.Context, Init, Filler); | ||||
| 683 | return; | ||||
| 684 | } | ||||
| 685 | // C++1y [dcl.init.aggr]p7: | ||||
| 686 | // If there are fewer initializer-clauses in the list than there are | ||||
| 687 | // members in the aggregate, then each member not explicitly initialized | ||||
| 688 | // shall be initialized from its brace-or-equal-initializer [...] | ||||
| 689 | if (Field->hasInClassInitializer()) { | ||||
| 690 | if (VerifyOnly) | ||||
| 691 | return; | ||||
| 692 | |||||
| 693 | ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field); | ||||
| 694 | if (DIE.isInvalid()) { | ||||
| 695 | hadError = true; | ||||
| 696 | return; | ||||
| 697 | } | ||||
| 698 | SemaRef.checkInitializerLifetime(MemberEntity, DIE.get()); | ||||
| 699 | if (Init < NumInits) | ||||
| 700 | ILE->setInit(Init, DIE.get()); | ||||
| 701 | else { | ||||
| 702 | ILE->updateInit(SemaRef.Context, Init, DIE.get()); | ||||
| 703 | RequiresSecondPass = true; | ||||
| 704 | } | ||||
| 705 | return; | ||||
| 706 | } | ||||
| 707 | |||||
| 708 | if (Field->getType()->isReferenceType()) { | ||||
| 709 | if (!VerifyOnly) { | ||||
| 710 | // C++ [dcl.init.aggr]p9: | ||||
| 711 | // If an incomplete or empty initializer-list leaves a | ||||
| 712 | // member of reference type uninitialized, the program is | ||||
| 713 | // ill-formed. | ||||
| 714 | SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) | ||||
| 715 | << Field->getType() | ||||
| 716 | << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm()) | ||||
| 717 | ->getSourceRange(); | ||||
| 718 | SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member); | ||||
| 719 | } | ||||
| 720 | hadError = true; | ||||
| 721 | return; | ||||
| 722 | } | ||||
| 723 | |||||
| 724 | ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity); | ||||
| 725 | if (MemberInit.isInvalid()) { | ||||
| 726 | hadError = true; | ||||
| 727 | return; | ||||
| 728 | } | ||||
| 729 | |||||
| 730 | if (hadError || VerifyOnly) { | ||||
| 731 | // Do nothing | ||||
| 732 | } else if (Init < NumInits) { | ||||
| 733 | ILE->setInit(Init, MemberInit.getAs<Expr>()); | ||||
| 734 | } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) { | ||||
| 735 | // Empty initialization requires a constructor call, so | ||||
| 736 | // extend the initializer list to include the constructor | ||||
| 737 | // call and make a note that we'll need to take another pass | ||||
| 738 | // through the initializer list. | ||||
| 739 | ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>()); | ||||
| 740 | RequiresSecondPass = true; | ||||
| 741 | } | ||||
| 742 | } else if (InitListExpr *InnerILE | ||||
| 743 | = dyn_cast<InitListExpr>(ILE->getInit(Init))) { | ||||
| 744 | FillInEmptyInitializations(MemberEntity, InnerILE, | ||||
| 745 | RequiresSecondPass, ILE, Init, FillWithNoInit); | ||||
| 746 | } else if (DesignatedInitUpdateExpr *InnerDIUE = | ||||
| 747 | dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) { | ||||
| 748 | FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(), | ||||
| 749 | RequiresSecondPass, ILE, Init, | ||||
| 750 | /*FillWithNoInit =*/true); | ||||
| 751 | } | ||||
| 752 | } | ||||
| 753 | |||||
| 754 | /// Recursively replaces NULL values within the given initializer list | ||||
| 755 | /// with expressions that perform value-initialization of the | ||||
| 756 | /// appropriate type, and finish off the InitListExpr formation. | ||||
| 757 | void | ||||
| 758 | InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity, | ||||
| 759 | InitListExpr *ILE, | ||||
| 760 | bool &RequiresSecondPass, | ||||
| 761 | InitListExpr *OuterILE, | ||||
| 762 | unsigned OuterIndex, | ||||
| 763 | bool FillWithNoInit) { | ||||
| 764 | 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", 765, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 765 | "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", 765, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 766 | |||||
| 767 | // We don't need to do any checks when just filling NoInitExprs; that can't | ||||
| 768 | // fail. | ||||
| 769 | if (FillWithNoInit && VerifyOnly) | ||||
| 770 | return; | ||||
| 771 | |||||
| 772 | // If this is a nested initializer list, we might have changed its contents | ||||
| 773 | // (and therefore some of its properties, such as instantiation-dependence) | ||||
| 774 | // while filling it in. Inform the outer initializer list so that its state | ||||
| 775 | // can be updated to match. | ||||
| 776 | // FIXME: We should fully build the inner initializers before constructing | ||||
| 777 | // the outer InitListExpr instead of mutating AST nodes after they have | ||||
| 778 | // been used as subexpressions of other nodes. | ||||
| 779 | struct UpdateOuterILEWithUpdatedInit { | ||||
| 780 | InitListExpr *Outer; | ||||
| 781 | unsigned OuterIndex; | ||||
| 782 | ~UpdateOuterILEWithUpdatedInit() { | ||||
| 783 | if (Outer) | ||||
| 784 | Outer->setInit(OuterIndex, Outer->getInit(OuterIndex)); | ||||
| 785 | } | ||||
| 786 | } UpdateOuterRAII = {OuterILE, OuterIndex}; | ||||
| 787 | |||||
| 788 | // A transparent ILE is not performing aggregate initialization and should | ||||
| 789 | // not be filled in. | ||||
| 790 | if (ILE->isTransparent()) | ||||
| 791 | return; | ||||
| 792 | |||||
| 793 | if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { | ||||
| 794 | const RecordDecl *RDecl = RType->getDecl(); | ||||
| 795 | if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) | ||||
| 796 | FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), | ||||
| 797 | Entity, ILE, RequiresSecondPass, FillWithNoInit); | ||||
| 798 | else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) && | ||||
| 799 | cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) { | ||||
| 800 | for (auto *Field : RDecl->fields()) { | ||||
| 801 | if (Field->hasInClassInitializer()) { | ||||
| 802 | FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass, | ||||
| 803 | FillWithNoInit); | ||||
| 804 | break; | ||||
| 805 | } | ||||
| 806 | } | ||||
| 807 | } else { | ||||
| 808 | // The fields beyond ILE->getNumInits() are default initialized, so in | ||||
| 809 | // order to leave them uninitialized, the ILE is expanded and the extra | ||||
| 810 | // fields are then filled with NoInitExpr. | ||||
| 811 | unsigned NumElems = numStructUnionElements(ILE->getType()); | ||||
| 812 | if (RDecl->hasFlexibleArrayMember()) | ||||
| 813 | ++NumElems; | ||||
| 814 | if (!VerifyOnly && ILE->getNumInits() < NumElems) | ||||
| 815 | ILE->resizeInits(SemaRef.Context, NumElems); | ||||
| 816 | |||||
| 817 | unsigned Init = 0; | ||||
| 818 | |||||
| 819 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) { | ||||
| 820 | for (auto &Base : CXXRD->bases()) { | ||||
| 821 | if (hadError) | ||||
| 822 | return; | ||||
| 823 | |||||
| 824 | FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass, | ||||
| 825 | FillWithNoInit); | ||||
| 826 | ++Init; | ||||
| 827 | } | ||||
| 828 | } | ||||
| 829 | |||||
| 830 | for (auto *Field : RDecl->fields()) { | ||||
| 831 | if (Field->isUnnamedBitfield()) | ||||
| 832 | continue; | ||||
| 833 | |||||
| 834 | if (hadError) | ||||
| 835 | return; | ||||
| 836 | |||||
| 837 | FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass, | ||||
| 838 | FillWithNoInit); | ||||
| 839 | if (hadError) | ||||
| 840 | return; | ||||
| 841 | |||||
| 842 | ++Init; | ||||
| 843 | |||||
| 844 | // Only look at the first initialization of a union. | ||||
| 845 | if (RDecl->isUnion()) | ||||
| 846 | break; | ||||
| 847 | } | ||||
| 848 | } | ||||
| 849 | |||||
| 850 | return; | ||||
| 851 | } | ||||
| 852 | |||||
| 853 | QualType ElementType; | ||||
| 854 | |||||
| 855 | InitializedEntity ElementEntity = Entity; | ||||
| 856 | unsigned NumInits = ILE->getNumInits(); | ||||
| 857 | unsigned NumElements = NumInits; | ||||
| 858 | if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { | ||||
| 859 | ElementType = AType->getElementType(); | ||||
| 860 | if (const auto *CAType = dyn_cast<ConstantArrayType>(AType)) | ||||
| 861 | NumElements = CAType->getSize().getZExtValue(); | ||||
| 862 | // For an array new with an unknown bound, ask for one additional element | ||||
| 863 | // in order to populate the array filler. | ||||
| 864 | if (Entity.isVariableLengthArrayNew()) | ||||
| 865 | ++NumElements; | ||||
| 866 | ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, | ||||
| 867 | 0, Entity); | ||||
| 868 | } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { | ||||
| 869 | ElementType = VType->getElementType(); | ||||
| 870 | NumElements = VType->getNumElements(); | ||||
| 871 | ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, | ||||
| 872 | 0, Entity); | ||||
| 873 | } else | ||||
| 874 | ElementType = ILE->getType(); | ||||
| 875 | |||||
| 876 | bool SkipEmptyInitChecks = false; | ||||
| 877 | for (unsigned Init = 0; Init != NumElements; ++Init) { | ||||
| 878 | if (hadError) | ||||
| 879 | return; | ||||
| 880 | |||||
| 881 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement || | ||||
| 882 | ElementEntity.getKind() == InitializedEntity::EK_VectorElement) | ||||
| 883 | ElementEntity.setElementIndex(Init); | ||||
| 884 | |||||
| 885 | if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks)) | ||||
| 886 | return; | ||||
| 887 | |||||
| 888 | Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr); | ||||
| 889 | if (!InitExpr && Init < NumInits && ILE->hasArrayFiller()) | ||||
| 890 | ILE->setInit(Init, ILE->getArrayFiller()); | ||||
| 891 | else if (!InitExpr && !ILE->hasArrayFiller()) { | ||||
| 892 | // In VerifyOnly mode, there's no point performing empty initialization | ||||
| 893 | // more than once. | ||||
| 894 | if (SkipEmptyInitChecks) | ||||
| 895 | continue; | ||||
| 896 | |||||
| 897 | Expr *Filler = nullptr; | ||||
| 898 | |||||
| 899 | if (FillWithNoInit) | ||||
| 900 | Filler = new (SemaRef.Context) NoInitExpr(ElementType); | ||||
| 901 | else { | ||||
| 902 | ExprResult ElementInit = | ||||
| 903 | PerformEmptyInit(ILE->getEndLoc(), ElementEntity); | ||||
| 904 | if (ElementInit.isInvalid()) { | ||||
| 905 | hadError = true; | ||||
| 906 | return; | ||||
| 907 | } | ||||
| 908 | |||||
| 909 | Filler = ElementInit.getAs<Expr>(); | ||||
| 910 | } | ||||
| 911 | |||||
| 912 | if (hadError) { | ||||
| 913 | // Do nothing | ||||
| 914 | } else if (VerifyOnly) { | ||||
| 915 | SkipEmptyInitChecks = true; | ||||
| 916 | } else if (Init < NumInits) { | ||||
| 917 | // For arrays, just set the expression used for value-initialization | ||||
| 918 | // of the "holes" in the array. | ||||
| 919 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) | ||||
| 920 | ILE->setArrayFiller(Filler); | ||||
| 921 | else | ||||
| 922 | ILE->setInit(Init, Filler); | ||||
| 923 | } else { | ||||
| 924 | // For arrays, just set the expression used for value-initialization | ||||
| 925 | // of the rest of elements and exit. | ||||
| 926 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) { | ||||
| 927 | ILE->setArrayFiller(Filler); | ||||
| 928 | return; | ||||
| 929 | } | ||||
| 930 | |||||
| 931 | if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) { | ||||
| 932 | // Empty initialization requires a constructor call, so | ||||
| 933 | // extend the initializer list to include the constructor | ||||
| 934 | // call and make a note that we'll need to take another pass | ||||
| 935 | // through the initializer list. | ||||
| 936 | ILE->updateInit(SemaRef.Context, Init, Filler); | ||||
| 937 | RequiresSecondPass = true; | ||||
| 938 | } | ||||
| 939 | } | ||||
| 940 | } else if (InitListExpr *InnerILE | ||||
| 941 | = dyn_cast_or_null<InitListExpr>(InitExpr)) { | ||||
| 942 | FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass, | ||||
| 943 | ILE, Init, FillWithNoInit); | ||||
| 944 | } else if (DesignatedInitUpdateExpr *InnerDIUE = | ||||
| 945 | dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) { | ||||
| 946 | FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(), | ||||
| 947 | RequiresSecondPass, ILE, Init, | ||||
| 948 | /*FillWithNoInit =*/true); | ||||
| 949 | } | ||||
| 950 | } | ||||
| 951 | } | ||||
| 952 | |||||
| 953 | static bool hasAnyDesignatedInits(const InitListExpr *IL) { | ||||
| 954 | for (const Stmt *Init : *IL) | ||||
| 955 | if (Init && isa<DesignatedInitExpr>(Init)) | ||||
| 956 | return true; | ||||
| 957 | return false; | ||||
| 958 | } | ||||
| 959 | |||||
| 960 | InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity, | ||||
| 961 | InitListExpr *IL, QualType &T, bool VerifyOnly, | ||||
| 962 | bool TreatUnavailableAsInvalid, | ||||
| 963 | bool InOverloadResolution) | ||||
| 964 | : SemaRef(S), VerifyOnly(VerifyOnly), | ||||
| 965 | TreatUnavailableAsInvalid(TreatUnavailableAsInvalid), | ||||
| 966 | InOverloadResolution(InOverloadResolution) { | ||||
| 967 | if (!VerifyOnly || hasAnyDesignatedInits(IL)) { | ||||
| 968 | FullyStructuredList = | ||||
| 969 | createInitListExpr(T, IL->getSourceRange(), IL->getNumInits()); | ||||
| 970 | |||||
| 971 | // FIXME: Check that IL isn't already the semantic form of some other | ||||
| 972 | // InitListExpr. If it is, we'd create a broken AST. | ||||
| 973 | if (!VerifyOnly) | ||||
| 974 | FullyStructuredList->setSyntacticForm(IL); | ||||
| 975 | } | ||||
| 976 | |||||
| 977 | CheckExplicitInitList(Entity, IL, T, FullyStructuredList, | ||||
| 978 | /*TopLevelObject=*/true); | ||||
| 979 | |||||
| 980 | if (!hadError && FullyStructuredList) { | ||||
| 981 | bool RequiresSecondPass = false; | ||||
| 982 | FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass, | ||||
| 983 | /*OuterILE=*/nullptr, /*OuterIndex=*/0); | ||||
| 984 | if (RequiresSecondPass && !hadError) | ||||
| 985 | FillInEmptyInitializations(Entity, FullyStructuredList, | ||||
| 986 | RequiresSecondPass, nullptr, 0); | ||||
| 987 | } | ||||
| 988 | if (hadError && FullyStructuredList) | ||||
| 989 | FullyStructuredList->markError(); | ||||
| 990 | } | ||||
| 991 | |||||
| 992 | int InitListChecker::numArrayElements(QualType DeclType) { | ||||
| 993 | // FIXME: use a proper constant | ||||
| 994 | int maxElements = 0x7FFFFFFF; | ||||
| 995 | if (const ConstantArrayType *CAT = | ||||
| 996 | SemaRef.Context.getAsConstantArrayType(DeclType)) { | ||||
| 997 | maxElements = static_cast<int>(CAT->getSize().getZExtValue()); | ||||
| 998 | } | ||||
| 999 | return maxElements; | ||||
| 1000 | } | ||||
| 1001 | |||||
| 1002 | int InitListChecker::numStructUnionElements(QualType DeclType) { | ||||
| 1003 | RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl(); | ||||
| 1004 | int InitializableMembers = 0; | ||||
| 1005 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl)) | ||||
| 1006 | InitializableMembers += CXXRD->getNumBases(); | ||||
| 1007 | for (const auto *Field : structDecl->fields()) | ||||
| 1008 | if (!Field->isUnnamedBitfield()) | ||||
| 1009 | ++InitializableMembers; | ||||
| 1010 | |||||
| 1011 | if (structDecl->isUnion()) | ||||
| 1012 | return std::min(InitializableMembers, 1); | ||||
| 1013 | return InitializableMembers - structDecl->hasFlexibleArrayMember(); | ||||
| 1014 | } | ||||
| 1015 | |||||
| 1016 | /// Determine whether Entity is an entity for which it is idiomatic to elide | ||||
| 1017 | /// the braces in aggregate initialization. | ||||
| 1018 | static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) { | ||||
| 1019 | // Recursive initialization of the one and only field within an aggregate | ||||
| 1020 | // class is considered idiomatic. This case arises in particular for | ||||
| 1021 | // initialization of std::array, where the C++ standard suggests the idiom of | ||||
| 1022 | // | ||||
| 1023 | // std::array<T, N> arr = {1, 2, 3}; | ||||
| 1024 | // | ||||
| 1025 | // (where std::array is an aggregate struct containing a single array field. | ||||
| 1026 | |||||
| 1027 | if (!Entity.getParent()) | ||||
| 1028 | return false; | ||||
| 1029 | |||||
| 1030 | // Allows elide brace initialization for aggregates with empty base. | ||||
| 1031 | if (Entity.getKind() == InitializedEntity::EK_Base) { | ||||
| 1032 | auto *ParentRD = | ||||
| 1033 | Entity.getParent()->getType()->castAs<RecordType>()->getDecl(); | ||||
| 1034 | CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD); | ||||
| 1035 | return CXXRD->getNumBases() == 1 && CXXRD->field_empty(); | ||||
| 1036 | } | ||||
| 1037 | |||||
| 1038 | // Allow brace elision if the only subobject is a field. | ||||
| 1039 | if (Entity.getKind() == InitializedEntity::EK_Member) { | ||||
| 1040 | auto *ParentRD = | ||||
| 1041 | Entity.getParent()->getType()->castAs<RecordType>()->getDecl(); | ||||
| 1042 | if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) { | ||||
| 1043 | if (CXXRD->getNumBases()) { | ||||
| 1044 | return false; | ||||
| 1045 | } | ||||
| 1046 | } | ||||
| 1047 | auto FieldIt = ParentRD->field_begin(); | ||||
| 1048 | 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", 1049, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 1049 | "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", 1049, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 1050 | return ++FieldIt == ParentRD->field_end(); | ||||
| 1051 | } | ||||
| 1052 | |||||
| 1053 | return false; | ||||
| 1054 | } | ||||
| 1055 | |||||
| 1056 | /// Check whether the range of the initializer \p ParentIList from element | ||||
| 1057 | /// \p Index onwards can be used to initialize an object of type \p T. Update | ||||
| 1058 | /// \p Index to indicate how many elements of the list were consumed. | ||||
| 1059 | /// | ||||
| 1060 | /// This also fills in \p StructuredList, from element \p StructuredIndex | ||||
| 1061 | /// onwards, with the fully-braced, desugared form of the initialization. | ||||
| 1062 | void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity, | ||||
| 1063 | InitListExpr *ParentIList, | ||||
| 1064 | QualType T, unsigned &Index, | ||||
| 1065 | InitListExpr *StructuredList, | ||||
| 1066 | unsigned &StructuredIndex) { | ||||
| 1067 | int maxElements = 0; | ||||
| 1068 | |||||
| 1069 | if (T->isArrayType()) | ||||
| 1070 | maxElements = numArrayElements(T); | ||||
| 1071 | else if (T->isRecordType()) | ||||
| 1072 | maxElements = numStructUnionElements(T); | ||||
| 1073 | else if (T->isVectorType()) | ||||
| 1074 | maxElements = T->castAs<VectorType>()->getNumElements(); | ||||
| 1075 | else | ||||
| 1076 | llvm_unreachable("CheckImplicitInitList(): Illegal type")::llvm::llvm_unreachable_internal("CheckImplicitInitList(): Illegal type" , "clang/lib/Sema/SemaInit.cpp", 1076); | ||||
| 1077 | |||||
| 1078 | if (maxElements == 0) { | ||||
| 1079 | if (!VerifyOnly) | ||||
| 1080 | SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(), | ||||
| 1081 | diag::err_implicit_empty_initializer); | ||||
| 1082 | ++Index; | ||||
| 1083 | hadError = true; | ||||
| 1084 | return; | ||||
| 1085 | } | ||||
| 1086 | |||||
| 1087 | // Build a structured initializer list corresponding to this subobject. | ||||
| 1088 | InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit( | ||||
| 1089 | ParentIList, Index, T, StructuredList, StructuredIndex, | ||||
| 1090 | SourceRange(ParentIList->getInit(Index)->getBeginLoc(), | ||||
| 1091 | ParentIList->getSourceRange().getEnd())); | ||||
| 1092 | unsigned StructuredSubobjectInitIndex = 0; | ||||
| 1093 | |||||
| 1094 | // Check the element types and build the structural subobject. | ||||
| 1095 | unsigned StartIndex = Index; | ||||
| 1096 | CheckListElementTypes(Entity, ParentIList, T, | ||||
| 1097 | /*SubobjectIsDesignatorContext=*/false, Index, | ||||
| 1098 | StructuredSubobjectInitList, | ||||
| 1099 | StructuredSubobjectInitIndex); | ||||
| 1100 | |||||
| 1101 | if (StructuredSubobjectInitList) { | ||||
| 1102 | StructuredSubobjectInitList->setType(T); | ||||
| 1103 | |||||
| 1104 | unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); | ||||
| 1105 | // Update the structured sub-object initializer so that it's ending | ||||
| 1106 | // range corresponds with the end of the last initializer it used. | ||||
| 1107 | if (EndIndex < ParentIList->getNumInits() && | ||||
| 1108 | ParentIList->getInit(EndIndex)) { | ||||
| 1109 | SourceLocation EndLoc | ||||
| 1110 | = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); | ||||
| 1111 | StructuredSubobjectInitList->setRBraceLoc(EndLoc); | ||||
| 1112 | } | ||||
| 1113 | |||||
| 1114 | // Complain about missing braces. | ||||
| 1115 | if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) && | ||||
| 1116 | !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) && | ||||
| 1117 | !isIdiomaticBraceElisionEntity(Entity)) { | ||||
| 1118 | SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(), | ||||
| 1119 | diag::warn_missing_braces) | ||||
| 1120 | << StructuredSubobjectInitList->getSourceRange() | ||||
| 1121 | << FixItHint::CreateInsertion( | ||||
| 1122 | StructuredSubobjectInitList->getBeginLoc(), "{") | ||||
| 1123 | << FixItHint::CreateInsertion( | ||||
| 1124 | SemaRef.getLocForEndOfToken( | ||||
| 1125 | StructuredSubobjectInitList->getEndLoc()), | ||||
| 1126 | "}"); | ||||
| 1127 | } | ||||
| 1128 | |||||
| 1129 | // Warn if this type won't be an aggregate in future versions of C++. | ||||
| 1130 | auto *CXXRD = T->getAsCXXRecordDecl(); | ||||
| 1131 | if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) { | ||||
| 1132 | SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(), | ||||
| 1133 | diag::warn_cxx20_compat_aggregate_init_with_ctors) | ||||
| 1134 | << StructuredSubobjectInitList->getSourceRange() << T; | ||||
| 1135 | } | ||||
| 1136 | } | ||||
| 1137 | } | ||||
| 1138 | |||||
| 1139 | /// Warn that \p Entity was of scalar type and was initialized by a | ||||
| 1140 | /// single-element braced initializer list. | ||||
| 1141 | static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity, | ||||
| 1142 | SourceRange Braces) { | ||||
| 1143 | // Don't warn during template instantiation. If the initialization was | ||||
| 1144 | // non-dependent, we warned during the initial parse; otherwise, the | ||||
| 1145 | // type might not be scalar in some uses of the template. | ||||
| 1146 | if (S.inTemplateInstantiation()) | ||||
| 1147 | return; | ||||
| 1148 | |||||
| 1149 | unsigned DiagID = 0; | ||||
| 1150 | |||||
| 1151 | switch (Entity.getKind()) { | ||||
| 1152 | case InitializedEntity::EK_VectorElement: | ||||
| 1153 | case InitializedEntity::EK_ComplexElement: | ||||
| 1154 | case InitializedEntity::EK_ArrayElement: | ||||
| 1155 | case InitializedEntity::EK_Parameter: | ||||
| 1156 | case InitializedEntity::EK_Parameter_CF_Audited: | ||||
| 1157 | case InitializedEntity::EK_TemplateParameter: | ||||
| 1158 | case InitializedEntity::EK_Result: | ||||
| 1159 | // Extra braces here are suspicious. | ||||
| 1160 | DiagID = diag::warn_braces_around_init; | ||||
| 1161 | break; | ||||
| 1162 | |||||
| 1163 | case InitializedEntity::EK_Member: | ||||
| 1164 | // Warn on aggregate initialization but not on ctor init list or | ||||
| 1165 | // default member initializer. | ||||
| 1166 | if (Entity.getParent()) | ||||
| 1167 | DiagID = diag::warn_braces_around_init; | ||||
| 1168 | break; | ||||
| 1169 | |||||
| 1170 | case InitializedEntity::EK_Variable: | ||||
| 1171 | case InitializedEntity::EK_LambdaCapture: | ||||
| 1172 | // No warning, might be direct-list-initialization. | ||||
| 1173 | // FIXME: Should we warn for copy-list-initialization in these cases? | ||||
| 1174 | break; | ||||
| 1175 | |||||
| 1176 | case InitializedEntity::EK_New: | ||||
| 1177 | case InitializedEntity::EK_Temporary: | ||||
| 1178 | case InitializedEntity::EK_CompoundLiteralInit: | ||||
| 1179 | // No warning, braces are part of the syntax of the underlying construct. | ||||
| 1180 | break; | ||||
| 1181 | |||||
| 1182 | case InitializedEntity::EK_RelatedResult: | ||||
| 1183 | // No warning, we already warned when initializing the result. | ||||
| 1184 | break; | ||||
| 1185 | |||||
| 1186 | case InitializedEntity::EK_Exception: | ||||
| 1187 | case InitializedEntity::EK_Base: | ||||
| 1188 | case InitializedEntity::EK_Delegating: | ||||
| 1189 | case InitializedEntity::EK_BlockElement: | ||||
| 1190 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | ||||
| 1191 | case InitializedEntity::EK_Binding: | ||||
| 1192 | case InitializedEntity::EK_StmtExprResult: | ||||
| 1193 | case InitializedEntity::EK_ParenAggInitMember: | ||||
| 1194 | llvm_unreachable("unexpected braced scalar init")::llvm::llvm_unreachable_internal("unexpected braced scalar init" , "clang/lib/Sema/SemaInit.cpp", 1194); | ||||
| 1195 | } | ||||
| 1196 | |||||
| 1197 | if (DiagID) { | ||||
| 1198 | S.Diag(Braces.getBegin(), DiagID) | ||||
| 1199 | << Entity.getType()->isSizelessBuiltinType() << Braces | ||||
| 1200 | << FixItHint::CreateRemoval(Braces.getBegin()) | ||||
| 1201 | << FixItHint::CreateRemoval(Braces.getEnd()); | ||||
| 1202 | } | ||||
| 1203 | } | ||||
| 1204 | |||||
| 1205 | /// Check whether the initializer \p IList (that was written with explicit | ||||
| 1206 | /// braces) can be used to initialize an object of type \p T. | ||||
| 1207 | /// | ||||
| 1208 | /// This also fills in \p StructuredList with the fully-braced, desugared | ||||
| 1209 | /// form of the initialization. | ||||
| 1210 | void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity, | ||||
| 1211 | InitListExpr *IList, QualType &T, | ||||
| 1212 | InitListExpr *StructuredList, | ||||
| 1213 | bool TopLevelObject) { | ||||
| 1214 | unsigned Index = 0, StructuredIndex = 0; | ||||
| 1215 | CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true, | ||||
| 1216 | Index, StructuredList, StructuredIndex, TopLevelObject); | ||||
| 1217 | if (StructuredList) { | ||||
| 1218 | QualType ExprTy = T; | ||||
| 1219 | if (!ExprTy->isArrayType()) | ||||
| 1220 | ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context); | ||||
| 1221 | if (!VerifyOnly) | ||||
| 1222 | IList->setType(ExprTy); | ||||
| 1223 | StructuredList->setType(ExprTy); | ||||
| 1224 | } | ||||
| 1225 | if (hadError) | ||||
| 1226 | return; | ||||
| 1227 | |||||
| 1228 | // Don't complain for incomplete types, since we'll get an error elsewhere. | ||||
| 1229 | if (Index < IList->getNumInits() && !T->isIncompleteType()) { | ||||
| 1230 | // We have leftover initializers | ||||
| 1231 | bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus || | ||||
| 1232 | (SemaRef.getLangOpts().OpenCL && T->isVectorType()); | ||||
| 1233 | hadError = ExtraInitsIsError; | ||||
| 1234 | if (VerifyOnly) { | ||||
| 1235 | return; | ||||
| 1236 | } else if (StructuredIndex == 1 && | ||||
| 1237 | IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) == | ||||
| 1238 | SIF_None) { | ||||
| 1239 | unsigned DK = | ||||
| 1240 | ExtraInitsIsError | ||||
| 1241 | ? diag::err_excess_initializers_in_char_array_initializer | ||||
| 1242 | : diag::ext_excess_initializers_in_char_array_initializer; | ||||
| 1243 | SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) | ||||
| 1244 | << IList->getInit(Index)->getSourceRange(); | ||||
| 1245 | } else if (T->isSizelessBuiltinType()) { | ||||
| 1246 | unsigned DK = ExtraInitsIsError | ||||
| 1247 | ? diag::err_excess_initializers_for_sizeless_type | ||||
| 1248 | : diag::ext_excess_initializers_for_sizeless_type; | ||||
| 1249 | SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) | ||||
| 1250 | << T << IList->getInit(Index)->getSourceRange(); | ||||
| 1251 | } else { | ||||
| 1252 | int initKind = T->isArrayType() ? 0 : | ||||
| 1253 | T->isVectorType() ? 1 : | ||||
| 1254 | T->isScalarType() ? 2 : | ||||
| 1255 | T->isUnionType() ? 3 : | ||||
| 1256 | 4; | ||||
| 1257 | |||||
| 1258 | unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers | ||||
| 1259 | : diag::ext_excess_initializers; | ||||
| 1260 | SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) | ||||
| 1261 | << initKind << IList->getInit(Index)->getSourceRange(); | ||||
| 1262 | } | ||||
| 1263 | } | ||||
| 1264 | |||||
| 1265 | if (!VerifyOnly) { | ||||
| 1266 | if (T->isScalarType() && IList->getNumInits() == 1 && | ||||
| 1267 | !isa<InitListExpr>(IList->getInit(0))) | ||||
| 1268 | warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange()); | ||||
| 1269 | |||||
| 1270 | // Warn if this is a class type that won't be an aggregate in future | ||||
| 1271 | // versions of C++. | ||||
| 1272 | auto *CXXRD = T->getAsCXXRecordDecl(); | ||||
| 1273 | if (CXXRD && CXXRD->hasUserDeclaredConstructor()) { | ||||
| 1274 | // Don't warn if there's an equivalent default constructor that would be | ||||
| 1275 | // used instead. | ||||
| 1276 | bool HasEquivCtor = false; | ||||
| 1277 | if (IList->getNumInits() == 0) { | ||||
| 1278 | auto *CD = SemaRef.LookupDefaultConstructor(CXXRD); | ||||
| 1279 | HasEquivCtor = CD && !CD->isDeleted(); | ||||
| 1280 | } | ||||
| 1281 | |||||
| 1282 | if (!HasEquivCtor) { | ||||
| 1283 | SemaRef.Diag(IList->getBeginLoc(), | ||||
| 1284 | diag::warn_cxx20_compat_aggregate_init_with_ctors) | ||||
| 1285 | << IList->getSourceRange() << T; | ||||
| 1286 | } | ||||
| 1287 | } | ||||
| 1288 | } | ||||
| 1289 | } | ||||
| 1290 | |||||
| 1291 | void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity, | ||||
| 1292 | InitListExpr *IList, | ||||
| 1293 | QualType &DeclType, | ||||
| 1294 | bool SubobjectIsDesignatorContext, | ||||
| 1295 | unsigned &Index, | ||||
| 1296 | InitListExpr *StructuredList, | ||||
| 1297 | unsigned &StructuredIndex, | ||||
| 1298 | bool TopLevelObject) { | ||||
| 1299 | if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) { | ||||
| 1300 | // Explicitly braced initializer for complex type can be real+imaginary | ||||
| 1301 | // parts. | ||||
| 1302 | CheckComplexType(Entity, IList, DeclType, Index, | ||||
| 1303 | StructuredList, StructuredIndex); | ||||
| 1304 | } else if (DeclType->isScalarType()) { | ||||
| 1305 | CheckScalarType(Entity, IList, DeclType, Index, | ||||
| 1306 | StructuredList, StructuredIndex); | ||||
| 1307 | } else if (DeclType->isVectorType()) { | ||||
| 1308 | CheckVectorType(Entity, IList, DeclType, Index, | ||||
| 1309 | StructuredList, StructuredIndex); | ||||
| 1310 | } else if (DeclType->isRecordType()) { | ||||
| 1311 | 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", 1312, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 1312 | "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", 1312, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 1313 | RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); | ||||
| 1314 | auto Bases = | ||||
| 1315 | CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), | ||||
| 1316 | CXXRecordDecl::base_class_iterator()); | ||||
| 1317 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) | ||||
| 1318 | Bases = CXXRD->bases(); | ||||
| 1319 | CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(), | ||||
| 1320 | SubobjectIsDesignatorContext, Index, StructuredList, | ||||
| 1321 | StructuredIndex, TopLevelObject); | ||||
| 1322 | } else if (DeclType->isArrayType()) { | ||||
| 1323 | llvm::APSInt Zero( | ||||
| 1324 | SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), | ||||
| 1325 | false); | ||||
| 1326 | CheckArrayType(Entity, IList, DeclType, Zero, | ||||
| 1327 | SubobjectIsDesignatorContext, Index, | ||||
| 1328 | StructuredList, StructuredIndex); | ||||
| 1329 | } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { | ||||
| 1330 | // This type is invalid, issue a diagnostic. | ||||
| 1331 | ++Index; | ||||
| 1332 | if (!VerifyOnly) | ||||
| 1333 | SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type) | ||||
| 1334 | << DeclType; | ||||
| 1335 | hadError = true; | ||||
| 1336 | } else if (DeclType->isReferenceType()) { | ||||
| 1337 | CheckReferenceType(Entity, IList, DeclType, Index, | ||||
| 1338 | StructuredList, StructuredIndex); | ||||
| 1339 | } else if (DeclType->isObjCObjectType()) { | ||||
| 1340 | if (!VerifyOnly) | ||||
| 1341 | SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType; | ||||
| 1342 | hadError = true; | ||||
| 1343 | } else if (DeclType->isOCLIntelSubgroupAVCType() || | ||||
| 1344 | DeclType->isSizelessBuiltinType()) { | ||||
| 1345 | // Checks for scalar type are sufficient for these types too. | ||||
| 1346 | CheckScalarType(Entity, IList, DeclType, Index, StructuredList, | ||||
| 1347 | StructuredIndex); | ||||
| 1348 | } else { | ||||
| 1349 | if (!VerifyOnly) | ||||
| 1350 | SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type) | ||||
| 1351 | << DeclType; | ||||
| 1352 | hadError = true; | ||||
| 1353 | } | ||||
| 1354 | } | ||||
| 1355 | |||||
| 1356 | void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, | ||||
| 1357 | InitListExpr *IList, | ||||
| 1358 | QualType ElemType, | ||||
| 1359 | unsigned &Index, | ||||
| 1360 | InitListExpr *StructuredList, | ||||
| 1361 | unsigned &StructuredIndex, | ||||
| 1362 | bool DirectlyDesignated) { | ||||
| 1363 | Expr *expr = IList->getInit(Index); | ||||
| 1364 | |||||
| 1365 | if (ElemType->isReferenceType()) | ||||
| 1366 | return CheckReferenceType(Entity, IList, ElemType, Index, | ||||
| 1367 | StructuredList, StructuredIndex); | ||||
| 1368 | |||||
| 1369 | if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { | ||||
| 1370 | if (SubInitList->getNumInits() == 1 && | ||||
| 1371 | IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) == | ||||
| 1372 | SIF_None) { | ||||
| 1373 | // FIXME: It would be more faithful and no less correct to include an | ||||
| 1374 | // InitListExpr in the semantic form of the initializer list in this case. | ||||
| 1375 | expr = SubInitList->getInit(0); | ||||
| 1376 | } | ||||
| 1377 | // Nested aggregate initialization and C++ initialization are handled later. | ||||
| 1378 | } else if (isa<ImplicitValueInitExpr>(expr)) { | ||||
| 1379 | // This happens during template instantiation when we see an InitListExpr | ||||
| 1380 | // that we've already checked once. | ||||
| 1381 | 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", 1382, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 1382 | "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", 1382, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 1383 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); | ||||
| 1384 | ++Index; | ||||
| 1385 | return; | ||||
| 1386 | } | ||||
| 1387 | |||||
| 1388 | if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) { | ||||
| 1389 | // C++ [dcl.init.aggr]p2: | ||||
| 1390 | // Each member is copy-initialized from the corresponding | ||||
| 1391 | // initializer-clause. | ||||
| 1392 | |||||
| 1393 | // FIXME: Better EqualLoc? | ||||
| 1394 | InitializationKind Kind = | ||||
| 1395 | InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation()); | ||||
| 1396 | |||||
| 1397 | // Vector elements can be initialized from other vectors in which case | ||||
| 1398 | // we need initialization entity with a type of a vector (and not a vector | ||||
| 1399 | // element!) initializing multiple vector elements. | ||||
| 1400 | auto TmpEntity = | ||||
| 1401 | (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType()) | ||||
| 1402 | ? InitializedEntity::InitializeTemporary(ElemType) | ||||
| 1403 | : Entity; | ||||
| 1404 | |||||
| 1405 | InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr, | ||||
| 1406 | /*TopLevelOfInitList*/ true); | ||||
| 1407 | |||||
| 1408 | // C++14 [dcl.init.aggr]p13: | ||||
| 1409 | // If the assignment-expression can initialize a member, the member is | ||||
| 1410 | // initialized. Otherwise [...] brace elision is assumed | ||||
| 1411 | // | ||||
| 1412 | // Brace elision is never performed if the element is not an | ||||
| 1413 | // assignment-expression. | ||||
| 1414 | if (Seq || isa<InitListExpr>(expr)) { | ||||
| 1415 | if (!VerifyOnly) { | ||||
| 1416 | ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr); | ||||
| 1417 | if (Result.isInvalid()) | ||||
| 1418 | hadError = true; | ||||
| 1419 | |||||
| 1420 | UpdateStructuredListElement(StructuredList, StructuredIndex, | ||||
| 1421 | Result.getAs<Expr>()); | ||||
| 1422 | } else if (!Seq) { | ||||
| 1423 | hadError = true; | ||||
| 1424 | } else if (StructuredList) { | ||||
| 1425 | UpdateStructuredListElement(StructuredList, StructuredIndex, | ||||
| 1426 | getDummyInit()); | ||||
| 1427 | } | ||||
| 1428 | ++Index; | ||||
| 1429 | return; | ||||
| 1430 | } | ||||
| 1431 | |||||
| 1432 | // Fall through for subaggregate initialization | ||||
| 1433 | } else if (ElemType->isScalarType() || ElemType->isAtomicType()) { | ||||
| 1434 | // FIXME: Need to handle atomic aggregate types with implicit init lists. | ||||
| 1435 | return CheckScalarType(Entity, IList, ElemType, Index, | ||||
| 1436 | StructuredList, StructuredIndex); | ||||
| 1437 | } else if (const ArrayType *arrayType = | ||||
| 1438 | SemaRef.Context.getAsArrayType(ElemType)) { | ||||
| 1439 | // arrayType can be incomplete if we're initializing a flexible | ||||
| 1440 | // array member. There's nothing we can do with the completed | ||||
| 1441 | // type here, though. | ||||
| 1442 | |||||
| 1443 | if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) { | ||||
| 1444 | // FIXME: Should we do this checking in verify-only mode? | ||||
| 1445 | if (!VerifyOnly) | ||||
| 1446 | CheckStringInit(expr, ElemType, arrayType, SemaRef); | ||||
| 1447 | if (StructuredList) | ||||
| 1448 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); | ||||
| 1449 | ++Index; | ||||
| 1450 | return; | ||||
| 1451 | } | ||||
| 1452 | |||||
| 1453 | // Fall through for subaggregate initialization. | ||||
| 1454 | |||||
| 1455 | } else { | ||||
| 1456 | 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", 1457, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 1457 | 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", 1457, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 1458 | |||||
| 1459 | // C99 6.7.8p13: | ||||
| 1460 | // | ||||
| 1461 | // The initializer for a structure or union object that has | ||||
| 1462 | // automatic storage duration shall be either an initializer | ||||
| 1463 | // list as described below, or a single expression that has | ||||
| 1464 | // compatible structure or union type. In the latter case, the | ||||
| 1465 | // initial value of the object, including unnamed members, is | ||||
| 1466 | // that of the expression. | ||||
| 1467 | ExprResult ExprRes = expr; | ||||
| 1468 | if (SemaRef.CheckSingleAssignmentConstraints( | ||||
| 1469 | ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) { | ||||
| 1470 | if (ExprRes.isInvalid()) | ||||
| 1471 | hadError = true; | ||||
| 1472 | else { | ||||
| 1473 | ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get()); | ||||
| 1474 | if (ExprRes.isInvalid()) | ||||
| 1475 | hadError = true; | ||||
| 1476 | } | ||||
| 1477 | UpdateStructuredListElement(StructuredList, StructuredIndex, | ||||
| 1478 | ExprRes.getAs<Expr>()); | ||||
| 1479 | ++Index; | ||||
| 1480 | return; | ||||
| 1481 | } | ||||
| 1482 | ExprRes.get(); | ||||
| 1483 | // Fall through for subaggregate initialization | ||||
| 1484 | } | ||||
| 1485 | |||||
| 1486 | // C++ [dcl.init.aggr]p12: | ||||
| 1487 | // | ||||
| 1488 | // [...] Otherwise, if the member is itself a non-empty | ||||
| 1489 | // subaggregate, brace elision is assumed and the initializer is | ||||
| 1490 | // considered for the initialization of the first member of | ||||
| 1491 | // the subaggregate. | ||||
| 1492 | // OpenCL vector initializer is handled elsewhere. | ||||
| 1493 | if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) || | ||||
| 1494 | ElemType->isAggregateType()) { | ||||
| 1495 | CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList, | ||||
| 1496 | StructuredIndex); | ||||
| 1497 | ++StructuredIndex; | ||||
| 1498 | |||||
| 1499 | // In C++20, brace elision is not permitted for a designated initializer. | ||||
| 1500 | if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) { | ||||
| 1501 | if (InOverloadResolution) | ||||
| 1502 | hadError = true; | ||||
| 1503 | if (!VerifyOnly) { | ||||
| 1504 | SemaRef.Diag(expr->getBeginLoc(), | ||||
| 1505 | diag::ext_designated_init_brace_elision) | ||||
| 1506 | << expr->getSourceRange() | ||||
| 1507 | << FixItHint::CreateInsertion(expr->getBeginLoc(), "{") | ||||
| 1508 | << FixItHint::CreateInsertion( | ||||
| 1509 | SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}"); | ||||
| 1510 | } | ||||
| 1511 | } | ||||
| 1512 | } else { | ||||
| 1513 | if (!VerifyOnly) { | ||||
| 1514 | // We cannot initialize this element, so let PerformCopyInitialization | ||||
| 1515 | // produce the appropriate diagnostic. We already checked that this | ||||
| 1516 | // initialization will fail. | ||||
| 1517 | ExprResult Copy = | ||||
| 1518 | SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr, | ||||
| 1519 | /*TopLevelOfInitList=*/true); | ||||
| 1520 | (void)Copy; | ||||
| 1521 | 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", 1522, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 1522 | "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", 1522, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 1523 | } | ||||
| 1524 | hadError = true; | ||||
| 1525 | ++Index; | ||||
| 1526 | ++StructuredIndex; | ||||
| 1527 | } | ||||
| 1528 | } | ||||
| 1529 | |||||
| 1530 | void InitListChecker::CheckComplexType(const InitializedEntity &Entity, | ||||
| 1531 | InitListExpr *IList, QualType DeclType, | ||||
| 1532 | unsigned &Index, | ||||
| 1533 | InitListExpr *StructuredList, | ||||
| 1534 | unsigned &StructuredIndex) { | ||||
| 1535 | 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", 1535, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 1536 | |||||
| 1537 | // As an extension, clang supports complex initializers, which initialize | ||||
| 1538 | // a complex number component-wise. When an explicit initializer list for | ||||
| 1539 | // a complex number contains two initializers, this extension kicks in: | ||||
| 1540 | // it expects the initializer list to contain two elements convertible to | ||||
| 1541 | // the element type of the complex type. The first element initializes | ||||
| 1542 | // the real part, and the second element intitializes the imaginary part. | ||||
| 1543 | |||||
| 1544 | if (IList->getNumInits() < 2) | ||||
| 1545 | return CheckScalarType(Entity, IList, DeclType, Index, StructuredList, | ||||
| 1546 | StructuredIndex); | ||||
| 1547 | |||||
| 1548 | // This is an extension in C. (The builtin _Complex type does not exist | ||||
| 1549 | // in the C++ standard.) | ||||
| 1550 | if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly) | ||||
| 1551 | SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init) | ||||
| 1552 | << IList->getSourceRange(); | ||||
| 1553 | |||||
| 1554 | // Initialize the complex number. | ||||
| 1555 | QualType elementType = DeclType->castAs<ComplexType>()->getElementType(); | ||||
| 1556 | InitializedEntity ElementEntity = | ||||
| 1557 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); | ||||
| 1558 | |||||
| 1559 | for (unsigned i = 0; i < 2; ++i) { | ||||
| 1560 | ElementEntity.setElementIndex(Index); | ||||
| 1561 | CheckSubElementType(ElementEntity, IList, elementType, Index, | ||||
| 1562 | StructuredList, StructuredIndex); | ||||
| 1563 | } | ||||
| 1564 | } | ||||
| 1565 | |||||
| 1566 | void InitListChecker::CheckScalarType(const InitializedEntity &Entity, | ||||
| 1567 | InitListExpr *IList, QualType DeclType, | ||||
| 1568 | unsigned &Index, | ||||
| 1569 | InitListExpr *StructuredList, | ||||
| 1570 | unsigned &StructuredIndex) { | ||||
| 1571 | if (Index >= IList->getNumInits()) { | ||||
| 1572 | if (!VerifyOnly) { | ||||
| 1573 | if (SemaRef.getLangOpts().CPlusPlus) { | ||||
| 1574 | if (DeclType->isSizelessBuiltinType()) | ||||
| 1575 | SemaRef.Diag(IList->getBeginLoc(), | ||||
| 1576 | SemaRef.getLangOpts().CPlusPlus11 | ||||
| 1577 | ? diag::warn_cxx98_compat_empty_sizeless_initializer | ||||
| 1578 | : diag::err_empty_sizeless_initializer) | ||||
| 1579 | << DeclType << IList->getSourceRange(); | ||||
| 1580 | else | ||||
| 1581 | SemaRef.Diag(IList->getBeginLoc(), | ||||
| 1582 | SemaRef.getLangOpts().CPlusPlus11 | ||||
| 1583 | ? diag::warn_cxx98_compat_empty_scalar_initializer | ||||
| 1584 | : diag::err_empty_scalar_initializer) | ||||
| 1585 | << IList->getSourceRange(); | ||||
| 1586 | } | ||||
| 1587 | } | ||||
| 1588 | hadError = | ||||
| 1589 | SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11; | ||||
| 1590 | ++Index; | ||||
| 1591 | ++StructuredIndex; | ||||
| 1592 | return; | ||||
| 1593 | } | ||||
| 1594 | |||||
| 1595 | Expr *expr = IList->getInit(Index); | ||||
| 1596 | if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) { | ||||
| 1597 | // FIXME: This is invalid, and accepting it causes overload resolution | ||||
| 1598 | // to pick the wrong overload in some corner cases. | ||||
| 1599 | if (!VerifyOnly) | ||||
| 1600 | SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init) | ||||
| 1601 | << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange(); | ||||
| 1602 | |||||
| 1603 | CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList, | ||||
| 1604 | StructuredIndex); | ||||
| 1605 | return; | ||||
| 1606 | } else if (isa<DesignatedInitExpr>(expr)) { | ||||
| 1607 | if (!VerifyOnly) | ||||
| 1608 | SemaRef.Diag(expr->getBeginLoc(), | ||||
| 1609 | diag::err_designator_for_scalar_or_sizeless_init) | ||||
| 1610 | << DeclType->isSizelessBuiltinType() << DeclType | ||||
| 1611 | << expr->getSourceRange(); | ||||
| 1612 | hadError = true; | ||||
| 1613 | ++Index; | ||||
| 1614 | ++StructuredIndex; | ||||
| 1615 | return; | ||||
| 1616 | } | ||||
| 1617 | |||||
| 1618 | ExprResult Result; | ||||
| 1619 | if (VerifyOnly) { | ||||
| 1620 | if (SemaRef.CanPerformCopyInitialization(Entity, expr)) | ||||
| 1621 | Result = getDummyInit(); | ||||
| 1622 | else | ||||
| 1623 | Result = ExprError(); | ||||
| 1624 | } else { | ||||
| 1625 | Result = | ||||
| 1626 | SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr, | ||||
| 1627 | /*TopLevelOfInitList=*/true); | ||||
| 1628 | } | ||||
| 1629 | |||||
| 1630 | Expr *ResultExpr = nullptr; | ||||
| 1631 | |||||
| 1632 | if (Result.isInvalid()) | ||||
| 1633 | hadError = true; // types weren't compatible. | ||||
| 1634 | else { | ||||
| 1635 | ResultExpr = Result.getAs<Expr>(); | ||||
| 1636 | |||||
| 1637 | if (ResultExpr != expr && !VerifyOnly) { | ||||
| 1638 | // The type was promoted, update initializer list. | ||||
| 1639 | // FIXME: Why are we updating the syntactic init list? | ||||
| 1640 | IList->setInit(Index, ResultExpr); | ||||
| 1641 | } | ||||
| 1642 | } | ||||
| 1643 | UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); | ||||
| 1644 | ++Index; | ||||
| 1645 | } | ||||
| 1646 | |||||
| 1647 | void InitListChecker::CheckReferenceType(const InitializedEntity &Entity, | ||||
| 1648 | InitListExpr *IList, QualType DeclType, | ||||
| 1649 | unsigned &Index, | ||||
| 1650 | InitListExpr *StructuredList, | ||||
| 1651 | unsigned &StructuredIndex) { | ||||
| 1652 | if (Index >= IList->getNumInits()) { | ||||
| 1653 | // FIXME: It would be wonderful if we could point at the actual member. In | ||||
| 1654 | // general, it would be useful to pass location information down the stack, | ||||
| 1655 | // so that we know the location (or decl) of the "current object" being | ||||
| 1656 | // initialized. | ||||
| 1657 | if (!VerifyOnly) | ||||
| 1658 | SemaRef.Diag(IList->getBeginLoc(), | ||||
| 1659 | diag::err_init_reference_member_uninitialized) | ||||
| 1660 | << DeclType << IList->getSourceRange(); | ||||
| 1661 | hadError = true; | ||||
| 1662 | ++Index; | ||||
| 1663 | ++StructuredIndex; | ||||
| 1664 | return; | ||||
| 1665 | } | ||||
| 1666 | |||||
| 1667 | Expr *expr = IList->getInit(Index); | ||||
| 1668 | if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) { | ||||
| 1669 | if (!VerifyOnly) | ||||
| 1670 | SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list) | ||||
| 1671 | << DeclType << IList->getSourceRange(); | ||||
| 1672 | hadError = true; | ||||
| 1673 | ++Index; | ||||
| 1674 | ++StructuredIndex; | ||||
| 1675 | return; | ||||
| 1676 | } | ||||
| 1677 | |||||
| 1678 | ExprResult Result; | ||||
| 1679 | if (VerifyOnly) { | ||||
| 1680 | if (SemaRef.CanPerformCopyInitialization(Entity,expr)) | ||||
| 1681 | Result = getDummyInit(); | ||||
| 1682 | else | ||||
| 1683 | Result = ExprError(); | ||||
| 1684 | } else { | ||||
| 1685 | Result = | ||||
| 1686 | SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr, | ||||
| 1687 | /*TopLevelOfInitList=*/true); | ||||
| 1688 | } | ||||
| 1689 | |||||
| 1690 | if (Result.isInvalid()) | ||||
| 1691 | hadError = true; | ||||
| 1692 | |||||
| 1693 | expr = Result.getAs<Expr>(); | ||||
| 1694 | // FIXME: Why are we updating the syntactic init list? | ||||
| 1695 | if (!VerifyOnly && expr) | ||||
| 1696 | IList->setInit(Index, expr); | ||||
| 1697 | |||||
| 1698 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); | ||||
| 1699 | ++Index; | ||||
| 1700 | } | ||||
| 1701 | |||||
| 1702 | void InitListChecker::CheckVectorType(const InitializedEntity &Entity, | ||||
| 1703 | InitListExpr *IList, QualType DeclType, | ||||
| 1704 | unsigned &Index, | ||||
| 1705 | InitListExpr *StructuredList, | ||||
| 1706 | unsigned &StructuredIndex) { | ||||
| 1707 | const VectorType *VT = DeclType->castAs<VectorType>(); | ||||
| 1708 | unsigned maxElements = VT->getNumElements(); | ||||
| 1709 | unsigned numEltsInit = 0; | ||||
| 1710 | QualType elementType = VT->getElementType(); | ||||
| 1711 | |||||
| 1712 | if (Index >= IList->getNumInits()) { | ||||
| 1713 | // Make sure the element type can be value-initialized. | ||||
| 1714 | CheckEmptyInitializable( | ||||
| 1715 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity), | ||||
| 1716 | IList->getEndLoc()); | ||||
| 1717 | return; | ||||
| 1718 | } | ||||
| 1719 | |||||
| 1720 | if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) { | ||||
| 1721 | // If the initializing element is a vector, try to copy-initialize | ||||
| 1722 | // instead of breaking it apart (which is doomed to failure anyway). | ||||
| 1723 | Expr *Init = IList->getInit(Index); | ||||
| 1724 | if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) { | ||||
| 1725 | ExprResult Result; | ||||
| 1726 | if (VerifyOnly) { | ||||
| 1727 | if (SemaRef.CanPerformCopyInitialization(Entity, Init)) | ||||
| 1728 | Result = getDummyInit(); | ||||
| 1729 | else | ||||
| 1730 | Result = ExprError(); | ||||
| 1731 | } else { | ||||
| 1732 | Result = | ||||
| 1733 | SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init, | ||||
| 1734 | /*TopLevelOfInitList=*/true); | ||||
| 1735 | } | ||||
| 1736 | |||||
| 1737 | Expr *ResultExpr = nullptr; | ||||
| 1738 | if (Result.isInvalid()) | ||||
| 1739 | hadError = true; // types weren't compatible. | ||||
| 1740 | else { | ||||
| 1741 | ResultExpr = Result.getAs<Expr>(); | ||||
| 1742 | |||||
| 1743 | if (ResultExpr != Init && !VerifyOnly) { | ||||
| 1744 | // The type was promoted, update initializer list. | ||||
| 1745 | // FIXME: Why are we updating the syntactic init list? | ||||
| 1746 | IList->setInit(Index, ResultExpr); | ||||
| 1747 | } | ||||
| 1748 | } | ||||
| 1749 | UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); | ||||
| 1750 | ++Index; | ||||
| 1751 | return; | ||||
| 1752 | } | ||||
| 1753 | |||||
| 1754 | InitializedEntity ElementEntity = | ||||
| 1755 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); | ||||
| 1756 | |||||
| 1757 | for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { | ||||
| 1758 | // Don't attempt to go past the end of the init list | ||||
| 1759 | if (Index >= IList->getNumInits()) { | ||||
| 1760 | CheckEmptyInitializable(ElementEntity, IList->getEndLoc()); | ||||
| 1761 | break; | ||||
| 1762 | } | ||||
| 1763 | |||||
| 1764 | ElementEntity.setElementIndex(Index); | ||||
| 1765 | CheckSubElementType(ElementEntity, IList, elementType, Index, | ||||
| 1766 | StructuredList, StructuredIndex); | ||||
| 1767 | } | ||||
| 1768 | |||||
| 1769 | if (VerifyOnly) | ||||
| 1770 | return; | ||||
| 1771 | |||||
| 1772 | bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian(); | ||||
| 1773 | const VectorType *T = Entity.getType()->castAs<VectorType>(); | ||||
| 1774 | if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector || | ||||
| 1775 | T->getVectorKind() == VectorType::NeonPolyVector)) { | ||||
| 1776 | // The ability to use vector initializer lists is a GNU vector extension | ||||
| 1777 | // and is unrelated to the NEON intrinsics in arm_neon.h. On little | ||||
| 1778 | // endian machines it works fine, however on big endian machines it | ||||
| 1779 | // exhibits surprising behaviour: | ||||
| 1780 | // | ||||
| 1781 | // uint32x2_t x = {42, 64}; | ||||
| 1782 | // return vget_lane_u32(x, 0); // Will return 64. | ||||
| 1783 | // | ||||
| 1784 | // Because of this, explicitly call out that it is non-portable. | ||||
| 1785 | // | ||||
| 1786 | SemaRef.Diag(IList->getBeginLoc(), | ||||
| 1787 | diag::warn_neon_vector_initializer_non_portable); | ||||
| 1788 | |||||
| 1789 | const char *typeCode; | ||||
| 1790 | unsigned typeSize = SemaRef.Context.getTypeSize(elementType); | ||||
| 1791 | |||||
| 1792 | if (elementType->isFloatingType()) | ||||
| 1793 | typeCode = "f"; | ||||
| 1794 | else if (elementType->isSignedIntegerType()) | ||||
| 1795 | typeCode = "s"; | ||||
| 1796 | else if (elementType->isUnsignedIntegerType()) | ||||
| 1797 | typeCode = "u"; | ||||
| 1798 | else | ||||
| 1799 | llvm_unreachable("Invalid element type!")::llvm::llvm_unreachable_internal("Invalid element type!", "clang/lib/Sema/SemaInit.cpp" , 1799); | ||||
| 1800 | |||||
| 1801 | SemaRef.Diag(IList->getBeginLoc(), | ||||
| 1802 | SemaRef.Context.getTypeSize(VT) > 64 | ||||
| 1803 | ? diag::note_neon_vector_initializer_non_portable_q | ||||
| 1804 | : diag::note_neon_vector_initializer_non_portable) | ||||
| 1805 | << typeCode << typeSize; | ||||
| 1806 | } | ||||
| 1807 | |||||
| 1808 | return; | ||||
| 1809 | } | ||||
| 1810 | |||||
| 1811 | InitializedEntity ElementEntity = | ||||
| 1812 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); | ||||
| 1813 | |||||
| 1814 | // OpenCL and HLSL initializers allow vectors to be constructed from vectors. | ||||
| 1815 | for (unsigned i = 0; i < maxElements; ++i) { | ||||
| 1816 | // Don't attempt to go past the end of the init list | ||||
| 1817 | if (Index >= IList->getNumInits()) | ||||
| 1818 | break; | ||||
| 1819 | |||||
| 1820 | ElementEntity.setElementIndex(Index); | ||||
| 1821 | |||||
| 1822 | QualType IType = IList->getInit(Index)->getType(); | ||||
| 1823 | if (!IType->isVectorType()) { | ||||
| 1824 | CheckSubElementType(ElementEntity, IList, elementType, Index, | ||||
| 1825 | StructuredList, StructuredIndex); | ||||
| 1826 | ++numEltsInit; | ||||
| 1827 | } else { | ||||
| 1828 | QualType VecType; | ||||
| 1829 | const VectorType *IVT = IType->castAs<VectorType>(); | ||||
| 1830 | unsigned numIElts = IVT->getNumElements(); | ||||
| 1831 | |||||
| 1832 | if (IType->isExtVectorType()) | ||||
| 1833 | VecType = SemaRef.Context.getExtVectorType(elementType, numIElts); | ||||
| 1834 | else | ||||
| 1835 | VecType = SemaRef.Context.getVectorType(elementType, numIElts, | ||||
| 1836 | IVT->getVectorKind()); | ||||
| 1837 | CheckSubElementType(ElementEntity, IList, VecType, Index, | ||||
| 1838 | StructuredList, StructuredIndex); | ||||
| 1839 | numEltsInit += numIElts; | ||||
| 1840 | } | ||||
| 1841 | } | ||||
| 1842 | |||||
| 1843 | // OpenCL and HLSL require all elements to be initialized. | ||||
| 1844 | if (numEltsInit != maxElements) { | ||||
| 1845 | if (!VerifyOnly) | ||||
| 1846 | SemaRef.Diag(IList->getBeginLoc(), | ||||
| 1847 | diag::err_vector_incorrect_num_initializers) | ||||
| 1848 | << (numEltsInit < maxElements) << maxElements << numEltsInit; | ||||
| 1849 | hadError = true; | ||||
| 1850 | } | ||||
| 1851 | } | ||||
| 1852 | |||||
| 1853 | /// Check if the type of a class element has an accessible destructor, and marks | ||||
| 1854 | /// it referenced. Returns true if we shouldn't form a reference to the | ||||
| 1855 | /// destructor. | ||||
| 1856 | /// | ||||
| 1857 | /// Aggregate initialization requires a class element's destructor be | ||||
| 1858 | /// accessible per 11.6.1 [dcl.init.aggr]: | ||||
| 1859 | /// | ||||
| 1860 | /// The destructor for each element of class type is potentially invoked | ||||
| 1861 | /// (15.4 [class.dtor]) from the context where the aggregate initialization | ||||
| 1862 | /// occurs. | ||||
| 1863 | static bool checkDestructorReference(QualType ElementType, SourceLocation Loc, | ||||
| 1864 | Sema &SemaRef) { | ||||
| 1865 | auto *CXXRD = ElementType->getAsCXXRecordDecl(); | ||||
| 1866 | if (!CXXRD) | ||||
| 1867 | return false; | ||||
| 1868 | |||||
| 1869 | CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD); | ||||
| 1870 | SemaRef.CheckDestructorAccess(Loc, Destructor, | ||||
| 1871 | SemaRef.PDiag(diag::err_access_dtor_temp) | ||||
| 1872 | << ElementType); | ||||
| 1873 | SemaRef.MarkFunctionReferenced(Loc, Destructor); | ||||
| 1874 | return SemaRef.DiagnoseUseOfDecl(Destructor, Loc); | ||||
| 1875 | } | ||||
| 1876 | |||||
| 1877 | void InitListChecker::CheckArrayType(const InitializedEntity &Entity, | ||||
| 1878 | InitListExpr *IList, QualType &DeclType, | ||||
| 1879 | llvm::APSInt elementIndex, | ||||
| 1880 | bool SubobjectIsDesignatorContext, | ||||
| 1881 | unsigned &Index, | ||||
| 1882 | InitListExpr *StructuredList, | ||||
| 1883 | unsigned &StructuredIndex) { | ||||
| 1884 | const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType); | ||||
| 1885 | |||||
| 1886 | if (!VerifyOnly) { | ||||
| 1887 | if (checkDestructorReference(arrayType->getElementType(), | ||||
| 1888 | IList->getEndLoc(), SemaRef)) { | ||||
| 1889 | hadError = true; | ||||
| 1890 | return; | ||||
| 1891 | } | ||||
| 1892 | } | ||||
| 1893 | |||||
| 1894 | // Check for the special-case of initializing an array with a string. | ||||
| 1895 | if (Index < IList->getNumInits()) { | ||||
| 1896 | if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) == | ||||
| 1897 | SIF_None) { | ||||
| 1898 | // We place the string literal directly into the resulting | ||||
| 1899 | // initializer list. This is the only place where the structure | ||||
| 1900 | // of the structured initializer list doesn't match exactly, | ||||
| 1901 | // because doing so would involve allocating one character | ||||
| 1902 | // constant for each string. | ||||
| 1903 | // FIXME: Should we do these checks in verify-only mode too? | ||||
| 1904 | if (!VerifyOnly) | ||||
| 1905 | CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef); | ||||
| 1906 | if (StructuredList) { | ||||
| 1907 | UpdateStructuredListElement(StructuredList, StructuredIndex, | ||||
| 1908 | IList->getInit(Index)); | ||||
| 1909 | StructuredList->resizeInits(SemaRef.Context, StructuredIndex); | ||||
| 1910 | } | ||||
| 1911 | ++Index; | ||||
| 1912 | return; | ||||
| 1913 | } | ||||
| 1914 | } | ||||
| 1915 | if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) { | ||||
| 1916 | // Check for VLAs; in standard C it would be possible to check this | ||||
| 1917 | // earlier, but I don't know where clang accepts VLAs (gcc accepts | ||||
| 1918 | // them in all sorts of strange places). | ||||
| 1919 | bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus; | ||||
| 1920 | if (!VerifyOnly) { | ||||
| 1921 | // C2x 6.7.9p4: An entity of variable length array type shall not be | ||||
| 1922 | // initialized except by an empty initializer. | ||||
| 1923 | // | ||||
| 1924 | // The C extension warnings are issued from ParseBraceInitializer() and | ||||
| 1925 | // do not need to be issued here. However, we continue to issue an error | ||||
| 1926 | // in the case there are initializers or we are compiling C++. We allow | ||||
| 1927 | // use of VLAs in C++, but it's not clear we want to allow {} to zero | ||||
| 1928 | // init a VLA in C++ in all cases (such as with non-trivial constructors). | ||||
| 1929 | // FIXME: should we allow this construct in C++ when it makes sense to do | ||||
| 1930 | // so? | ||||
| 1931 | if (HasErr) | ||||
| 1932 | SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(), | ||||
| 1933 | diag::err_variable_object_no_init) | ||||
| 1934 | << VAT->getSizeExpr()->getSourceRange(); | ||||
| 1935 | } | ||||
| 1936 | hadError = HasErr; | ||||
| 1937 | ++Index; | ||||
| 1938 | ++StructuredIndex; | ||||
| 1939 | return; | ||||
| 1940 | } | ||||
| 1941 | |||||
| 1942 | // We might know the maximum number of elements in advance. | ||||
| 1943 | llvm::APSInt maxElements(elementIndex.getBitWidth(), | ||||
| 1944 | elementIndex.isUnsigned()); | ||||
| 1945 | bool maxElementsKnown = false; | ||||
| 1946 | if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) { | ||||
| 1947 | maxElements = CAT->getSize(); | ||||
| 1948 | elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth()); | ||||
| 1949 | elementIndex.setIsUnsigned(maxElements.isUnsigned()); | ||||
| 1950 | maxElementsKnown = true; | ||||
| 1951 | } | ||||
| 1952 | |||||
| 1953 | QualType elementType = arrayType->getElementType(); | ||||
| 1954 | while (Index < IList->getNumInits()) { | ||||
| 1955 | Expr *Init = IList->getInit(Index); | ||||
| 1956 | if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { | ||||
| 1957 | // If we're not the subobject that matches up with the '{' for | ||||
| 1958 | // the designator, we shouldn't be handling the | ||||
| 1959 | // designator. Return immediately. | ||||
| 1960 | if (!SubobjectIsDesignatorContext) | ||||
| 1961 | return; | ||||
| 1962 | |||||
| 1963 | // Handle this designated initializer. elementIndex will be | ||||
| 1964 | // updated to be the next array element we'll initialize. | ||||
| 1965 | if (CheckDesignatedInitializer(Entity, IList, DIE, 0, | ||||
| 1966 | DeclType, nullptr, &elementIndex, Index, | ||||
| 1967 | StructuredList, StructuredIndex, true, | ||||
| 1968 | false)) { | ||||
| 1969 | hadError = true; | ||||
| 1970 | continue; | ||||
| 1971 | } | ||||
| 1972 | |||||
| 1973 | if (elementIndex.getBitWidth() > maxElements.getBitWidth()) | ||||
| 1974 | maxElements = maxElements.extend(elementIndex.getBitWidth()); | ||||
| 1975 | else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) | ||||
| 1976 | elementIndex = elementIndex.extend(maxElements.getBitWidth()); | ||||
| 1977 | elementIndex.setIsUnsigned(maxElements.isUnsigned()); | ||||
| 1978 | |||||
| 1979 | // If the array is of incomplete type, keep track of the number of | ||||
| 1980 | // elements in the initializer. | ||||
| 1981 | if (!maxElementsKnown && elementIndex > maxElements) | ||||
| 1982 | maxElements = elementIndex; | ||||
| 1983 | |||||
| 1984 | continue; | ||||
| 1985 | } | ||||
| 1986 | |||||
| 1987 | // If we know the maximum number of elements, and we've already | ||||
| 1988 | // hit it, stop consuming elements in the initializer list. | ||||
| 1989 | if (maxElementsKnown && elementIndex == maxElements) | ||||
| 1990 | break; | ||||
| 1991 | |||||
| 1992 | InitializedEntity ElementEntity = | ||||
| 1993 | InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex, | ||||
| 1994 | Entity); | ||||
| 1995 | // Check this element. | ||||
| 1996 | CheckSubElementType(ElementEntity, IList, elementType, Index, | ||||
| 1997 | StructuredList, StructuredIndex); | ||||
| 1998 | ++elementIndex; | ||||
| 1999 | |||||
| 2000 | // If the array is of incomplete type, keep track of the number of | ||||
| 2001 | // elements in the initializer. | ||||
| 2002 | if (!maxElementsKnown && elementIndex > maxElements) | ||||
| 2003 | maxElements = elementIndex; | ||||
| 2004 | } | ||||
| 2005 | if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) { | ||||
| 2006 | // If this is an incomplete array type, the actual type needs to | ||||
| 2007 | // be calculated here. | ||||
| 2008 | llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); | ||||
| 2009 | if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) { | ||||
| 2010 | // Sizing an array implicitly to zero is not allowed by ISO C, | ||||
| 2011 | // but is supported by GNU. | ||||
| 2012 | SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size); | ||||
| 2013 | } | ||||
| 2014 | |||||
| 2015 | DeclType = SemaRef.Context.getConstantArrayType( | ||||
| 2016 | elementType, maxElements, nullptr, ArrayType::Normal, 0); | ||||
| 2017 | } | ||||
| 2018 | if (!hadError) { | ||||
| 2019 | // If there are any members of the array that get value-initialized, check | ||||
| 2020 | // that is possible. That happens if we know the bound and don't have | ||||
| 2021 | // enough elements, or if we're performing an array new with an unknown | ||||
| 2022 | // bound. | ||||
| 2023 | if ((maxElementsKnown && elementIndex < maxElements) || | ||||
| 2024 | Entity.isVariableLengthArrayNew()) | ||||
| 2025 | CheckEmptyInitializable( | ||||
| 2026 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity), | ||||
| 2027 | IList->getEndLoc()); | ||||
| 2028 | } | ||||
| 2029 | } | ||||
| 2030 | |||||
| 2031 | bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity, | ||||
| 2032 | Expr *InitExpr, | ||||
| 2033 | FieldDecl *Field, | ||||
| 2034 | bool TopLevelObject) { | ||||
| 2035 | // Handle GNU flexible array initializers. | ||||
| 2036 | unsigned FlexArrayDiag; | ||||
| 2037 | if (isa<InitListExpr>(InitExpr) && | ||||
| 2038 | cast<InitListExpr>(InitExpr)->getNumInits() == 0) { | ||||
| 2039 | // Empty flexible array init always allowed as an extension | ||||
| 2040 | FlexArrayDiag = diag::ext_flexible_array_init; | ||||
| 2041 | } else if (!TopLevelObject) { | ||||
| 2042 | // Disallow flexible array init on non-top-level object | ||||
| 2043 | FlexArrayDiag = diag::err_flexible_array_init; | ||||
| 2044 | } else if (Entity.getKind() != InitializedEntity::EK_Variable) { | ||||
| 2045 | // Disallow flexible array init on anything which is not a variable. | ||||
| 2046 | FlexArrayDiag = diag::err_flexible_array_init; | ||||
| 2047 | } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) { | ||||
| 2048 | // Disallow flexible array init on local variables. | ||||
| 2049 | FlexArrayDiag = diag::err_flexible_array_init; | ||||
| 2050 | } else { | ||||
| 2051 | // Allow other cases. | ||||
| 2052 | FlexArrayDiag = diag::ext_flexible_array_init; | ||||
| 2053 | } | ||||
| 2054 | |||||
| 2055 | if (!VerifyOnly) { | ||||
| 2056 | SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag) | ||||
| 2057 | << InitExpr->getBeginLoc(); | ||||
| 2058 | SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) | ||||
| 2059 | << Field; | ||||
| 2060 | } | ||||
| 2061 | |||||
| 2062 | return FlexArrayDiag != diag::ext_flexible_array_init; | ||||
| 2063 | } | ||||
| 2064 | |||||
| 2065 | void InitListChecker::CheckStructUnionTypes( | ||||
| 2066 | const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, | ||||
| 2067 | CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field, | ||||
| 2068 | bool SubobjectIsDesignatorContext, unsigned &Index, | ||||
| 2069 | InitListExpr *StructuredList, unsigned &StructuredIndex, | ||||
| 2070 | bool TopLevelObject) { | ||||
| 2071 | RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl(); | ||||
| 2072 | |||||
| 2073 | // If the record is invalid, some of it's members are invalid. To avoid | ||||
| 2074 | // confusion, we forgo checking the initializer for the entire record. | ||||
| 2075 | if (structDecl->isInvalidDecl()) { | ||||
| 2076 | // Assume it was supposed to consume a single initializer. | ||||
| 2077 | ++Index; | ||||
| 2078 | hadError = true; | ||||
| 2079 | return; | ||||
| 2080 | } | ||||
| 2081 | |||||
| 2082 | if (DeclType->isUnionType() && IList->getNumInits() == 0) { | ||||
| 2083 | RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); | ||||
| 2084 | |||||
| 2085 | if (!VerifyOnly) | ||||
| 2086 | for (FieldDecl *FD : RD->fields()) { | ||||
| 2087 | QualType ET = SemaRef.Context.getBaseElementType(FD->getType()); | ||||
| 2088 | if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) { | ||||
| 2089 | hadError = true; | ||||
| 2090 | return; | ||||
| 2091 | } | ||||
| 2092 | } | ||||
| 2093 | |||||
| 2094 | // If there's a default initializer, use it. | ||||
| 2095 | if (isa<CXXRecordDecl>(RD) && | ||||
| 2096 | cast<CXXRecordDecl>(RD)->hasInClassInitializer()) { | ||||
| 2097 | if (!StructuredList) | ||||
| 2098 | return; | ||||
| 2099 | for (RecordDecl::field_iterator FieldEnd = RD->field_end(); | ||||
| 2100 | Field != FieldEnd; ++Field) { | ||||
| 2101 | if (Field->hasInClassInitializer()) { | ||||
| 2102 | StructuredList->setInitializedFieldInUnion(*Field); | ||||
| 2103 | // FIXME: Actually build a CXXDefaultInitExpr? | ||||
| 2104 | return; | ||||
| 2105 | } | ||||
| 2106 | } | ||||
| 2107 | } | ||||
| 2108 | |||||
| 2109 | // Value-initialize the first member of the union that isn't an unnamed | ||||
| 2110 | // bitfield. | ||||
| 2111 | for (RecordDecl::field_iterator FieldEnd = RD->field_end(); | ||||
| 2112 | Field != FieldEnd; ++Field) { | ||||
| 2113 | if (!Field->isUnnamedBitfield()) { | ||||
| 2114 | CheckEmptyInitializable( | ||||
| 2115 | InitializedEntity::InitializeMember(*Field, &Entity), | ||||
| 2116 | IList->getEndLoc()); | ||||
| 2117 | if (StructuredList) | ||||
| 2118 | StructuredList->setInitializedFieldInUnion(*Field); | ||||
| 2119 | break; | ||||
| 2120 | } | ||||
| 2121 | } | ||||
| 2122 | return; | ||||
| 2123 | } | ||||
| 2124 | |||||
| 2125 | bool InitializedSomething = false; | ||||
| 2126 | |||||
| 2127 | // If we have any base classes, they are initialized prior to the fields. | ||||
| 2128 | for (auto &Base : Bases) { | ||||
| 2129 | Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr; | ||||
| 2130 | |||||
| 2131 | // Designated inits always initialize fields, so if we see one, all | ||||
| 2132 | // remaining base classes have no explicit initializer. | ||||
| 2133 | if (Init && isa<DesignatedInitExpr>(Init)) | ||||
| 2134 | Init = nullptr; | ||||
| 2135 | |||||
| 2136 | SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc(); | ||||
| 2137 | InitializedEntity BaseEntity = InitializedEntity::InitializeBase( | ||||
| 2138 | SemaRef.Context, &Base, false, &Entity); | ||||
| 2139 | if (Init) { | ||||
| 2140 | CheckSubElementType(BaseEntity, IList, Base.getType(), Index, | ||||
| 2141 | StructuredList, StructuredIndex); | ||||
| 2142 | InitializedSomething = true; | ||||
| 2143 | } else { | ||||
| 2144 | CheckEmptyInitializable(BaseEntity, InitLoc); | ||||
| 2145 | } | ||||
| 2146 | |||||
| 2147 | if (!VerifyOnly) | ||||
| 2148 | if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) { | ||||
| 2149 | hadError = true; | ||||
| 2150 | return; | ||||
| 2151 | } | ||||
| 2152 | } | ||||
| 2153 | |||||
| 2154 | // If structDecl is a forward declaration, this loop won't do | ||||
| 2155 | // anything except look at designated initializers; That's okay, | ||||
| 2156 | // because an error should get printed out elsewhere. It might be | ||||
| 2157 | // worthwhile to skip over the rest of the initializer, though. | ||||
| 2158 | RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); | ||||
| 2159 | RecordDecl::field_iterator FieldEnd = RD->field_end(); | ||||
| 2160 | size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) { | ||||
| 2161 | return isa<FieldDecl>(D) || isa<RecordDecl>(D); | ||||
| 2162 | }); | ||||
| 2163 | bool CheckForMissingFields = | ||||
| 2164 | !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()); | ||||
| 2165 | bool HasDesignatedInit = false; | ||||
| 2166 | |||||
| 2167 | while (Index < IList->getNumInits()) { | ||||
| 2168 | Expr *Init = IList->getInit(Index); | ||||
| 2169 | SourceLocation InitLoc = Init->getBeginLoc(); | ||||
| 2170 | |||||
| 2171 | if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { | ||||
| 2172 | // If we're not the subobject that matches up with the '{' for | ||||
| 2173 | // the designator, we shouldn't be handling the | ||||
| 2174 | // designator. Return immediately. | ||||
| 2175 | if (!SubobjectIsDesignatorContext) | ||||
| 2176 | return; | ||||
| 2177 | |||||
| 2178 | HasDesignatedInit = true; | ||||
| 2179 | |||||
| 2180 | // Handle this designated initializer. Field will be updated to | ||||
| 2181 | // the next field that we'll be initializing. | ||||
| 2182 | if (CheckDesignatedInitializer(Entity, IList, DIE, 0, | ||||
| 2183 | DeclType, &Field, nullptr, Index, | ||||
| 2184 | StructuredList, StructuredIndex, | ||||
| 2185 | true, TopLevelObject)) | ||||
| 2186 | hadError = true; | ||||
| 2187 | else if (!VerifyOnly) { | ||||
| 2188 | // Find the field named by the designated initializer. | ||||
| 2189 | RecordDecl::field_iterator F = RD->field_begin(); | ||||
| 2190 | while (std::next(F) != Field) | ||||
| 2191 | ++F; | ||||
| 2192 | QualType ET = SemaRef.Context.getBaseElementType(F->getType()); | ||||
| 2193 | if (checkDestructorReference(ET, InitLoc, SemaRef)) { | ||||
| 2194 | hadError = true; | ||||
| 2195 | return; | ||||
| 2196 | } | ||||
| 2197 | } | ||||
| 2198 | |||||
| 2199 | InitializedSomething = true; | ||||
| 2200 | |||||
| 2201 | // Disable check for missing fields when designators are used. | ||||
| 2202 | // This matches gcc behaviour. | ||||
| 2203 | CheckForMissingFields = false; | ||||
| 2204 | continue; | ||||
| 2205 | } | ||||
| 2206 | |||||
| 2207 | // Check if this is an initializer of forms: | ||||
| 2208 | // | ||||
| 2209 | // struct foo f = {}; | ||||
| 2210 | // struct foo g = {0}; | ||||
| 2211 | // | ||||
| 2212 | // These are okay for randomized structures. [C99 6.7.8p19] | ||||
| 2213 | // | ||||
| 2214 | // Also, if there is only one element in the structure, we allow something | ||||
| 2215 | // like this, because it's really not randomized in the tranditional sense. | ||||
| 2216 | // | ||||
| 2217 | // struct foo h = {bar}; | ||||
| 2218 | auto IsZeroInitializer = [&](const Expr *I) { | ||||
| 2219 | if (IList->getNumInits() == 1) { | ||||
| 2220 | if (NumRecordDecls == 1) | ||||
| 2221 | return true; | ||||
| 2222 | if (const auto *IL = dyn_cast<IntegerLiteral>(I)) | ||||
| 2223 | return IL->getValue().isZero(); | ||||
| 2224 | } | ||||
| 2225 | return false; | ||||
| 2226 | }; | ||||
| 2227 | |||||
| 2228 | // Don't allow non-designated initializers on randomized structures. | ||||
| 2229 | if (RD->isRandomized() && !IsZeroInitializer(Init)) { | ||||
| 2230 | if (!VerifyOnly) | ||||
| 2231 | SemaRef.Diag(InitLoc, diag::err_non_designated_init_used); | ||||
| 2232 | hadError = true; | ||||
| 2233 | break; | ||||
| 2234 | } | ||||
| 2235 | |||||
| 2236 | if (Field == FieldEnd) { | ||||
| 2237 | // We've run out of fields. We're done. | ||||
| 2238 | break; | ||||
| 2239 | } | ||||
| 2240 | |||||
| 2241 | // We've already initialized a member of a union. We're done. | ||||
| 2242 | if (InitializedSomething && DeclType->isUnionType()) | ||||
| 2243 | break; | ||||
| 2244 | |||||
| 2245 | // If we've hit the flexible array member at the end, we're done. | ||||
| 2246 | if (Field->getType()->isIncompleteArrayType()) | ||||
| 2247 | break; | ||||
| 2248 | |||||
| 2249 | if (Field->isUnnamedBitfield()) { | ||||
| 2250 | // Don't initialize unnamed bitfields, e.g. "int : 20;" | ||||
| 2251 | ++Field; | ||||
| 2252 | continue; | ||||
| 2253 | } | ||||
| 2254 | |||||
| 2255 | // Make sure we can use this declaration. | ||||
| 2256 | bool InvalidUse; | ||||
| 2257 | if (VerifyOnly) | ||||
| 2258 | InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); | ||||
| 2259 | else | ||||
| 2260 | InvalidUse = SemaRef.DiagnoseUseOfDecl( | ||||
| 2261 | *Field, IList->getInit(Index)->getBeginLoc()); | ||||
| 2262 | if (InvalidUse) { | ||||
| 2263 | ++Index; | ||||
| 2264 | ++Field; | ||||
| 2265 | hadError = true; | ||||
| 2266 | continue; | ||||
| 2267 | } | ||||
| 2268 | |||||
| 2269 | if (!VerifyOnly) { | ||||
| 2270 | QualType ET = SemaRef.Context.getBaseElementType(Field->getType()); | ||||
| 2271 | if (checkDestructorReference(ET, InitLoc, SemaRef)) { | ||||
| 2272 | hadError = true; | ||||
| 2273 | return; | ||||
| 2274 | } | ||||
| 2275 | } | ||||
| 2276 | |||||
| 2277 | InitializedEntity MemberEntity = | ||||
| 2278 | InitializedEntity::InitializeMember(*Field, &Entity); | ||||
| 2279 | CheckSubElementType(MemberEntity, IList, Field->getType(), Index, | ||||
| 2280 | StructuredList, StructuredIndex); | ||||
| 2281 | InitializedSomething = true; | ||||
| 2282 | |||||
| 2283 | if (DeclType->isUnionType() && StructuredList) { | ||||
| 2284 | // Initialize the first field within the union. | ||||
| 2285 | StructuredList->setInitializedFieldInUnion(*Field); | ||||
| 2286 | } | ||||
| 2287 | |||||
| 2288 | ++Field; | ||||
| 2289 | } | ||||
| 2290 | |||||
| 2291 | // Emit warnings for missing struct field initializers. | ||||
| 2292 | if (!VerifyOnly && InitializedSomething && CheckForMissingFields && | ||||
| 2293 | Field != FieldEnd && !Field->getType()->isIncompleteArrayType() && | ||||
| 2294 | !DeclType->isUnionType()) { | ||||
| 2295 | // It is possible we have one or more unnamed bitfields remaining. | ||||
| 2296 | // Find first (if any) named field and emit warning. | ||||
| 2297 | for (RecordDecl::field_iterator it = Field, end = RD->field_end(); | ||||
| 2298 | it != end; ++it) { | ||||
| 2299 | if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) { | ||||
| 2300 | SemaRef.Diag(IList->getSourceRange().getEnd(), | ||||
| 2301 | diag::warn_missing_field_initializers) << *it; | ||||
| 2302 | break; | ||||
| 2303 | } | ||||
| 2304 | } | ||||
| 2305 | } | ||||
| 2306 | |||||
| 2307 | // Check that any remaining fields can be value-initialized if we're not | ||||
| 2308 | // building a structured list. (If we are, we'll check this later.) | ||||
| 2309 | if (!StructuredList && Field != FieldEnd && !DeclType->isUnionType() && | ||||
| 2310 | !Field->getType()->isIncompleteArrayType()) { | ||||
| 2311 | for (; Field != FieldEnd && !hadError; ++Field) { | ||||
| 2312 | if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer()) | ||||
| 2313 | CheckEmptyInitializable( | ||||
| 2314 | InitializedEntity::InitializeMember(*Field, &Entity), | ||||
| 2315 | IList->getEndLoc()); | ||||
| 2316 | } | ||||
| 2317 | } | ||||
| 2318 | |||||
| 2319 | // Check that the types of the remaining fields have accessible destructors. | ||||
| 2320 | if (!VerifyOnly) { | ||||
| 2321 | // If the initializer expression has a designated initializer, check the | ||||
| 2322 | // elements for which a designated initializer is not provided too. | ||||
| 2323 | RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin() | ||||
| 2324 | : Field; | ||||
| 2325 | for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) { | ||||
| 2326 | QualType ET = SemaRef.Context.getBaseElementType(I->getType()); | ||||
| 2327 | if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) { | ||||
| 2328 | hadError = true; | ||||
| 2329 | return; | ||||
| 2330 | } | ||||
| 2331 | } | ||||
| 2332 | } | ||||
| 2333 | |||||
| 2334 | if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || | ||||
| 2335 | Index >= IList->getNumInits()) | ||||
| 2336 | return; | ||||
| 2337 | |||||
| 2338 | if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field, | ||||
| 2339 | TopLevelObject)) { | ||||
| 2340 | hadError = true; | ||||
| 2341 | ++Index; | ||||
| 2342 | return; | ||||
| 2343 | } | ||||
| 2344 | |||||
| 2345 | InitializedEntity MemberEntity = | ||||
| 2346 | InitializedEntity::InitializeMember(*Field, &Entity); | ||||
| 2347 | |||||
| 2348 | if (isa<InitListExpr>(IList->getInit(Index))) | ||||
| 2349 | CheckSubElementType(MemberEntity, IList, Field->getType(), Index, | ||||
| 2350 | StructuredList, StructuredIndex); | ||||
| 2351 | else | ||||
| 2352 | CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index, | ||||
| 2353 | StructuredList, StructuredIndex); | ||||
| 2354 | } | ||||
| 2355 | |||||
| 2356 | /// Expand a field designator that refers to a member of an | ||||
| 2357 | /// anonymous struct or union into a series of field designators that | ||||
| 2358 | /// refers to the field within the appropriate subobject. | ||||
| 2359 | /// | ||||
| 2360 | static void ExpandAnonymousFieldDesignator(Sema &SemaRef, | ||||
| 2361 | DesignatedInitExpr *DIE, | ||||
| 2362 | unsigned DesigIdx, | ||||
| 2363 | IndirectFieldDecl *IndirectField) { | ||||
| 2364 | typedef DesignatedInitExpr::Designator Designator; | ||||
| 2365 | |||||
| 2366 | // Build the replacement designators. | ||||
| 2367 | SmallVector<Designator, 4> Replacements; | ||||
| 2368 | for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(), | ||||
| 2369 | PE = IndirectField->chain_end(); PI != PE; ++PI) { | ||||
| 2370 | if (PI + 1 == PE) | ||||
| 2371 | Replacements.push_back(Designator::CreateFieldDesignator( | ||||
| 2372 | (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(), | ||||
| 2373 | DIE->getDesignator(DesigIdx)->getFieldLoc())); | ||||
| 2374 | else | ||||
| 2375 | Replacements.push_back(Designator::CreateFieldDesignator( | ||||
| 2376 | (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation())); | ||||
| 2377 | assert(isa<FieldDecl>(*PI))(static_cast <bool> (isa<FieldDecl>(*PI)) ? void ( 0) : __assert_fail ("isa<FieldDecl>(*PI)", "clang/lib/Sema/SemaInit.cpp" , 2377, __extension__ __PRETTY_FUNCTION__)); | ||||
| 2378 | Replacements.back().setFieldDecl(cast<FieldDecl>(*PI)); | ||||
| 2379 | } | ||||
| 2380 | |||||
| 2381 | // Expand the current designator into the set of replacement | ||||
| 2382 | // designators, so we have a full subobject path down to where the | ||||
| 2383 | // member of the anonymous struct/union is actually stored. | ||||
| 2384 | DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0], | ||||
| 2385 | &Replacements[0] + Replacements.size()); | ||||
| 2386 | } | ||||
| 2387 | |||||
| 2388 | static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef, | ||||
| 2389 | DesignatedInitExpr *DIE) { | ||||
| 2390 | unsigned NumIndexExprs = DIE->getNumSubExprs() - 1; | ||||
| 2391 | SmallVector<Expr*, 4> IndexExprs(NumIndexExprs); | ||||
| 2392 | for (unsigned I = 0; I < NumIndexExprs; ++I) | ||||
| 2393 | IndexExprs[I] = DIE->getSubExpr(I + 1); | ||||
| 2394 | return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(), | ||||
| 2395 | IndexExprs, | ||||
| 2396 | DIE->getEqualOrColonLoc(), | ||||
| 2397 | DIE->usesGNUSyntax(), DIE->getInit()); | ||||
| 2398 | } | ||||
| 2399 | |||||
| 2400 | namespace { | ||||
| 2401 | |||||
| 2402 | // Callback to only accept typo corrections that are for field members of | ||||
| 2403 | // the given struct or union. | ||||
| 2404 | class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback { | ||||
| 2405 | public: | ||||
| 2406 | explicit FieldInitializerValidatorCCC(RecordDecl *RD) | ||||
| 2407 | : Record(RD) {} | ||||
| 2408 | |||||
| 2409 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||
| 2410 | FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>(); | ||||
| 2411 | return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record); | ||||
| 2412 | } | ||||
| 2413 | |||||
| 2414 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||
| 2415 | return std::make_unique<FieldInitializerValidatorCCC>(*this); | ||||
| 2416 | } | ||||
| 2417 | |||||
| 2418 | private: | ||||
| 2419 | RecordDecl *Record; | ||||
| 2420 | }; | ||||
| 2421 | |||||
| 2422 | } // end anonymous namespace | ||||
| 2423 | |||||
| 2424 | /// Check the well-formedness of a C99 designated initializer. | ||||
| 2425 | /// | ||||
| 2426 | /// Determines whether the designated initializer @p DIE, which | ||||
| 2427 | /// resides at the given @p Index within the initializer list @p | ||||
| 2428 | /// IList, is well-formed for a current object of type @p DeclType | ||||
| 2429 | /// (C99 6.7.8). The actual subobject that this designator refers to | ||||
| 2430 | /// within the current subobject is returned in either | ||||
| 2431 | /// @p NextField or @p NextElementIndex (whichever is appropriate). | ||||
| 2432 | /// | ||||
| 2433 | /// @param IList The initializer list in which this designated | ||||
| 2434 | /// initializer occurs. | ||||
| 2435 | /// | ||||
| 2436 | /// @param DIE The designated initializer expression. | ||||
| 2437 | /// | ||||
| 2438 | /// @param DesigIdx The index of the current designator. | ||||
| 2439 | /// | ||||
| 2440 | /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17), | ||||
| 2441 | /// into which the designation in @p DIE should refer. | ||||
| 2442 | /// | ||||
| 2443 | /// @param NextField If non-NULL and the first designator in @p DIE is | ||||
| 2444 | /// a field, this will be set to the field declaration corresponding | ||||
| 2445 | /// to the field named by the designator. On input, this is expected to be | ||||
| 2446 | /// the next field that would be initialized in the absence of designation, | ||||
| 2447 | /// if the complete object being initialized is a struct. | ||||
| 2448 | /// | ||||
| 2449 | /// @param NextElementIndex If non-NULL and the first designator in @p | ||||
| 2450 | /// DIE is an array designator or GNU array-range designator, this | ||||
| 2451 | /// will be set to the last index initialized by this designator. | ||||
| 2452 | /// | ||||
| 2453 | /// @param Index Index into @p IList where the designated initializer | ||||
| 2454 | /// @p DIE occurs. | ||||
| 2455 | /// | ||||
| 2456 | /// @param StructuredList The initializer list expression that | ||||
| 2457 | /// describes all of the subobject initializers in the order they'll | ||||
| 2458 | /// actually be initialized. | ||||
| 2459 | /// | ||||
| 2460 | /// @returns true if there was an error, false otherwise. | ||||
| 2461 | bool | ||||
| 2462 | InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, | ||||
| 2463 | InitListExpr *IList, | ||||
| 2464 | DesignatedInitExpr *DIE, | ||||
| 2465 | unsigned DesigIdx, | ||||
| 2466 | QualType &CurrentObjectType, | ||||
| 2467 | RecordDecl::field_iterator *NextField, | ||||
| 2468 | llvm::APSInt *NextElementIndex, | ||||
| 2469 | unsigned &Index, | ||||
| 2470 | InitListExpr *StructuredList, | ||||
| 2471 | unsigned &StructuredIndex, | ||||
| 2472 | bool FinishSubobjectInit, | ||||
| 2473 | bool TopLevelObject) { | ||||
| 2474 | if (DesigIdx == DIE->size()) { | ||||
| 2475 | // C++20 designated initialization can result in direct-list-initialization | ||||
| 2476 | // of the designated subobject. This is the only way that we can end up | ||||
| 2477 | // performing direct initialization as part of aggregate initialization, so | ||||
| 2478 | // it needs special handling. | ||||
| 2479 | if (DIE->isDirectInit()) { | ||||
| 2480 | Expr *Init = DIE->getInit(); | ||||
| 2481 | 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", 2482, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 2482 | "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", 2482, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 2483 | InitializationKind Kind = InitializationKind::CreateDirectList( | ||||
| 2484 | DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc()); | ||||
| 2485 | InitializationSequence Seq(SemaRef, Entity, Kind, Init, | ||||
| 2486 | /*TopLevelOfInitList*/ true); | ||||
| 2487 | if (StructuredList) { | ||||
| 2488 | ExprResult Result = VerifyOnly | ||||
| 2489 | ? getDummyInit() | ||||
| 2490 | : Seq.Perform(SemaRef, Entity, Kind, Init); | ||||
| 2491 | UpdateStructuredListElement(StructuredList, StructuredIndex, | ||||
| 2492 | Result.get()); | ||||
| 2493 | } | ||||
| 2494 | ++Index; | ||||
| 2495 | return !Seq; | ||||
| 2496 | } | ||||
| 2497 | |||||
| 2498 | // Check the actual initialization for the designated object type. | ||||
| 2499 | bool prevHadError = hadError; | ||||
| 2500 | |||||
| 2501 | // Temporarily remove the designator expression from the | ||||
| 2502 | // initializer list that the child calls see, so that we don't try | ||||
| 2503 | // to re-process the designator. | ||||
| 2504 | unsigned OldIndex = Index; | ||||
| 2505 | IList->setInit(OldIndex, DIE->getInit()); | ||||
| 2506 | |||||
| 2507 | CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList, | ||||
| 2508 | StructuredIndex, /*DirectlyDesignated=*/true); | ||||
| 2509 | |||||
| 2510 | // Restore the designated initializer expression in the syntactic | ||||
| 2511 | // form of the initializer list. | ||||
| 2512 | if (IList->getInit(OldIndex) != DIE->getInit()) | ||||
| 2513 | DIE->setInit(IList->getInit(OldIndex)); | ||||
| 2514 | IList->setInit(OldIndex, DIE); | ||||
| 2515 | |||||
| 2516 | return hadError && !prevHadError; | ||||
| 2517 | } | ||||
| 2518 | |||||
| 2519 | DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); | ||||
| 2520 | bool IsFirstDesignator = (DesigIdx == 0); | ||||
| 2521 | if (IsFirstDesignator ? FullyStructuredList : StructuredList) { | ||||
| 2522 | // Determine the structural initializer list that corresponds to the | ||||
| 2523 | // current subobject. | ||||
| 2524 | if (IsFirstDesignator) | ||||
| 2525 | StructuredList = FullyStructuredList; | ||||
| 2526 | else { | ||||
| 2527 | Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ? | ||||
| 2528 | StructuredList->getInit(StructuredIndex) : nullptr; | ||||
| 2529 | if (!ExistingInit && StructuredList->hasArrayFiller()) | ||||
| 2530 | ExistingInit = StructuredList->getArrayFiller(); | ||||
| 2531 | |||||
| 2532 | if (!ExistingInit) | ||||
| 2533 | StructuredList = getStructuredSubobjectInit( | ||||
| 2534 | IList, Index, CurrentObjectType, StructuredList, StructuredIndex, | ||||
| 2535 | SourceRange(D->getBeginLoc(), DIE->getEndLoc())); | ||||
| 2536 | else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit)) | ||||
| 2537 | StructuredList = Result; | ||||
| 2538 | else { | ||||
| 2539 | // We are creating an initializer list that initializes the | ||||
| 2540 | // subobjects of the current object, but there was already an | ||||
| 2541 | // initialization that completely initialized the current | ||||
| 2542 | // subobject, e.g., by a compound literal: | ||||
| 2543 | // | ||||
| 2544 | // struct X { int a, b; }; | ||||
| 2545 | // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; | ||||
| 2546 | // | ||||
| 2547 | // Here, xs[0].a == 1 and xs[0].b == 3, since the second, | ||||
| 2548 | // designated initializer re-initializes only its current object | ||||
| 2549 | // subobject [0].b. | ||||
| 2550 | diagnoseInitOverride(ExistingInit, | ||||
| 2551 | SourceRange(D->getBeginLoc(), DIE->getEndLoc()), | ||||
| 2552 | /*UnionOverride=*/false, | ||||
| 2553 | /*FullyOverwritten=*/false); | ||||
| 2554 | |||||
| 2555 | if (!VerifyOnly) { | ||||
| 2556 | if (DesignatedInitUpdateExpr *E = | ||||
| 2557 | dyn_cast<DesignatedInitUpdateExpr>(ExistingInit)) | ||||
| 2558 | StructuredList = E->getUpdater(); | ||||
| 2559 | else { | ||||
| 2560 | DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context) | ||||
| 2561 | DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(), | ||||
| 2562 | ExistingInit, DIE->getEndLoc()); | ||||
| 2563 | StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE); | ||||
| 2564 | StructuredList = DIUE->getUpdater(); | ||||
| 2565 | } | ||||
| 2566 | } else { | ||||
| 2567 | // We don't need to track the structured representation of a | ||||
| 2568 | // designated init update of an already-fully-initialized object in | ||||
| 2569 | // verify-only mode. The only reason we would need the structure is | ||||
| 2570 | // to determine where the uninitialized "holes" are, and in this | ||||
| 2571 | // case, we know there aren't any and we can't introduce any. | ||||
| 2572 | StructuredList = nullptr; | ||||
| 2573 | } | ||||
| 2574 | } | ||||
| 2575 | } | ||||
| 2576 | } | ||||
| 2577 | |||||
| 2578 | if (D->isFieldDesignator()) { | ||||
| 2579 | // C99 6.7.8p7: | ||||
| 2580 | // | ||||
| 2581 | // If a designator has the form | ||||
| 2582 | // | ||||
| 2583 | // . identifier | ||||
| 2584 | // | ||||
| 2585 | // then the current object (defined below) shall have | ||||
| 2586 | // structure or union type and the identifier shall be the | ||||
| 2587 | // name of a member of that type. | ||||
| 2588 | const RecordType *RT = CurrentObjectType->getAs<RecordType>(); | ||||
| 2589 | if (!RT) { | ||||
| 2590 | SourceLocation Loc = D->getDotLoc(); | ||||
| 2591 | if (Loc.isInvalid()) | ||||
| 2592 | Loc = D->getFieldLoc(); | ||||
| 2593 | if (!VerifyOnly) | ||||
| 2594 | SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) | ||||
| 2595 | << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType; | ||||
| 2596 | ++Index; | ||||
| 2597 | return true; | ||||
| 2598 | } | ||||
| 2599 | |||||
| 2600 | FieldDecl *KnownField = D->getFieldDecl(); | ||||
| 2601 | if (!KnownField) { | ||||
| 2602 | const IdentifierInfo *FieldName = D->getFieldName(); | ||||
| 2603 | DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); | ||||
| 2604 | for (NamedDecl *ND : Lookup) { | ||||
| 2605 | if (auto *FD = dyn_cast<FieldDecl>(ND)) { | ||||
| 2606 | KnownField = FD; | ||||
| 2607 | break; | ||||
| 2608 | } | ||||
| 2609 | if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) { | ||||
| 2610 | // In verify mode, don't modify the original. | ||||
| 2611 | if (VerifyOnly) | ||||
| 2612 | DIE = CloneDesignatedInitExpr(SemaRef, DIE); | ||||
| 2613 | ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD); | ||||
| 2614 | D = DIE->getDesignator(DesigIdx); | ||||
| 2615 | KnownField = cast<FieldDecl>(*IFD->chain_begin()); | ||||
| 2616 | break; | ||||
| 2617 | } | ||||
| 2618 | } | ||||
| 2619 | if (!KnownField) { | ||||
| 2620 | if (VerifyOnly) { | ||||
| 2621 | ++Index; | ||||
| 2622 | return true; // No typo correction when just trying this out. | ||||
| 2623 | } | ||||
| 2624 | |||||
| 2625 | // Name lookup found something, but it wasn't a field. | ||||
| 2626 | if (!Lookup.empty()) { | ||||
| 2627 | SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) | ||||
| 2628 | << FieldName; | ||||
| 2629 | SemaRef.Diag(Lookup.front()->getLocation(), | ||||
| 2630 | diag::note_field_designator_found); | ||||
| 2631 | ++Index; | ||||
| 2632 | return true; | ||||
| 2633 | } | ||||
| 2634 | |||||
| 2635 | // Name lookup didn't find anything. | ||||
| 2636 | // Determine whether this was a typo for another field name. | ||||
| 2637 | FieldInitializerValidatorCCC CCC(RT->getDecl()); | ||||
| 2638 | if (TypoCorrection Corrected = SemaRef.CorrectTypo( | ||||
| 2639 | DeclarationNameInfo(FieldName, D->getFieldLoc()), | ||||
| 2640 | Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC, | ||||
| 2641 | Sema::CTK_ErrorRecovery, RT->getDecl())) { | ||||
| 2642 | SemaRef.diagnoseTypo( | ||||
| 2643 | Corrected, | ||||
| 2644 | SemaRef.PDiag(diag::err_field_designator_unknown_suggest) | ||||
| 2645 | << FieldName << CurrentObjectType); | ||||
| 2646 | KnownField = Corrected.getCorrectionDeclAs<FieldDecl>(); | ||||
| 2647 | hadError = true; | ||||
| 2648 | } else { | ||||
| 2649 | // Typo correction didn't find anything. | ||||
| 2650 | SourceLocation Loc = D->getFieldLoc(); | ||||
| 2651 | |||||
| 2652 | // The loc can be invalid with a "null" designator (i.e. an anonymous | ||||
| 2653 | // union/struct). Do our best to approximate the location. | ||||
| 2654 | if (Loc.isInvalid()) | ||||
| 2655 | Loc = IList->getBeginLoc(); | ||||
| 2656 | |||||
| 2657 | SemaRef.Diag(Loc, diag::err_field_designator_unknown) | ||||
| 2658 | << FieldName << CurrentObjectType << DIE->getSourceRange(); | ||||
| 2659 | ++Index; | ||||
| 2660 | return true; | ||||
| 2661 | } | ||||
| 2662 | } | ||||
| 2663 | } | ||||
| 2664 | |||||
| 2665 | unsigned NumBases = 0; | ||||
| 2666 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) | ||||
| 2667 | NumBases = CXXRD->getNumBases(); | ||||
| 2668 | |||||
| 2669 | unsigned FieldIndex = NumBases; | ||||
| 2670 | |||||
| 2671 | for (auto *FI : RT->getDecl()->fields()) { | ||||
| 2672 | if (FI->isUnnamedBitfield()) | ||||
| 2673 | continue; | ||||
| 2674 | if (declaresSameEntity(KnownField, FI)) { | ||||
| 2675 | KnownField = FI; | ||||
| 2676 | break; | ||||
| 2677 | } | ||||
| 2678 | ++FieldIndex; | ||||
| 2679 | } | ||||
| 2680 | |||||
| 2681 | RecordDecl::field_iterator Field = | ||||
| 2682 | RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField)); | ||||
| 2683 | |||||
| 2684 | // All of the fields of a union are located at the same place in | ||||
| 2685 | // the initializer list. | ||||
| 2686 | if (RT->getDecl()->isUnion()) { | ||||
| 2687 | FieldIndex = 0; | ||||
| 2688 | if (StructuredList) { | ||||
| 2689 | FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion(); | ||||
| 2690 | if (CurrentField && !declaresSameEntity(CurrentField, *Field)) { | ||||
| 2691 | 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", 2692, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 2692 | && "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", 2692, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 2693 | |||||
| 2694 | Expr *ExistingInit = StructuredList->getInit(0); | ||||
| 2695 | if (ExistingInit) { | ||||
| 2696 | // We're about to throw away an initializer, emit warning. | ||||
| 2697 | diagnoseInitOverride( | ||||
| 2698 | ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()), | ||||
| 2699 | /*UnionOverride=*/true, | ||||
| 2700 | /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false | ||||
| 2701 | : true); | ||||
| 2702 | } | ||||
| 2703 | |||||
| 2704 | // remove existing initializer | ||||
| 2705 | StructuredList->resizeInits(SemaRef.Context, 0); | ||||
| 2706 | StructuredList->setInitializedFieldInUnion(nullptr); | ||||
| 2707 | } | ||||
| 2708 | |||||
| 2709 | StructuredList->setInitializedFieldInUnion(*Field); | ||||
| 2710 | } | ||||
| 2711 | } | ||||
| 2712 | |||||
| 2713 | // Make sure we can use this declaration. | ||||
| 2714 | bool InvalidUse; | ||||
| 2715 | if (VerifyOnly) | ||||
| 2716 | InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); | ||||
| 2717 | else | ||||
| 2718 | InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc()); | ||||
| 2719 | if (InvalidUse) { | ||||
| 2720 | ++Index; | ||||
| 2721 | return true; | ||||
| 2722 | } | ||||
| 2723 | |||||
| 2724 | // C++20 [dcl.init.list]p3: | ||||
| 2725 | // The ordered identifiers in the designators of the designated- | ||||
| 2726 | // initializer-list shall form a subsequence of the ordered identifiers | ||||
| 2727 | // in the direct non-static data members of T. | ||||
| 2728 | // | ||||
| 2729 | // Note that this is not a condition on forming the aggregate | ||||
| 2730 | // initialization, only on actually performing initialization, | ||||
| 2731 | // so it is not checked in VerifyOnly mode. | ||||
| 2732 | // | ||||
| 2733 | // FIXME: This is the only reordering diagnostic we produce, and it only | ||||
| 2734 | // catches cases where we have a top-level field designator that jumps | ||||
| 2735 | // backwards. This is the only such case that is reachable in an | ||||
| 2736 | // otherwise-valid C++20 program, so is the only case that's required for | ||||
| 2737 | // conformance, but for consistency, we should diagnose all the other | ||||
| 2738 | // cases where a designator takes us backwards too. | ||||
| 2739 | if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus && | ||||
| 2740 | NextField && | ||||
| 2741 | (*NextField == RT->getDecl()->field_end() || | ||||
| 2742 | (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) { | ||||
| 2743 | // Find the field that we just initialized. | ||||
| 2744 | FieldDecl *PrevField = nullptr; | ||||
| 2745 | for (auto FI = RT->getDecl()->field_begin(); | ||||
| 2746 | FI != RT->getDecl()->field_end(); ++FI) { | ||||
| 2747 | if (FI->isUnnamedBitfield()) | ||||
| 2748 | continue; | ||||
| 2749 | if (*NextField != RT->getDecl()->field_end() && | ||||
| 2750 | declaresSameEntity(*FI, **NextField)) | ||||
| 2751 | break; | ||||
| 2752 | PrevField = *FI; | ||||
| 2753 | } | ||||
| 2754 | |||||
| 2755 | if (PrevField && | ||||
| 2756 | PrevField->getFieldIndex() > KnownField->getFieldIndex()) { | ||||
| 2757 | SemaRef.Diag(DIE->getBeginLoc(), diag::ext_designated_init_reordered) | ||||
| 2758 | << KnownField << PrevField << DIE->getSourceRange(); | ||||
| 2759 | |||||
| 2760 | unsigned OldIndex = NumBases + PrevField->getFieldIndex(); | ||||
| 2761 | if (StructuredList && OldIndex <= StructuredList->getNumInits()) { | ||||
| 2762 | if (Expr *PrevInit = StructuredList->getInit(OldIndex)) { | ||||
| 2763 | SemaRef.Diag(PrevInit->getBeginLoc(), | ||||
| 2764 | diag::note_previous_field_init) | ||||
| 2765 | << PrevField << PrevInit->getSourceRange(); | ||||
| 2766 | } | ||||
| 2767 | } | ||||
| 2768 | } | ||||
| 2769 | } | ||||
| 2770 | |||||
| 2771 | |||||
| 2772 | // Update the designator with the field declaration. | ||||
| 2773 | if (!VerifyOnly) | ||||
| 2774 | D->setFieldDecl(*Field); | ||||
| 2775 | |||||
| 2776 | // Make sure that our non-designated initializer list has space | ||||
| 2777 | // for a subobject corresponding to this field. | ||||
| 2778 | if (StructuredList && FieldIndex >= StructuredList->getNumInits()) | ||||
| 2779 | StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); | ||||
| 2780 | |||||
| 2781 | // This designator names a flexible array member. | ||||
| 2782 | if (Field->getType()->isIncompleteArrayType()) { | ||||
| 2783 | bool Invalid = false; | ||||
| 2784 | if ((DesigIdx + 1) != DIE->size()) { | ||||
| 2785 | // We can't designate an object within the flexible array | ||||
| 2786 | // member (because GCC doesn't allow it). | ||||
| 2787 | if (!VerifyOnly) { | ||||
| 2788 | DesignatedInitExpr::Designator *NextD | ||||
| 2789 | = DIE->getDesignator(DesigIdx + 1); | ||||
| 2790 | SemaRef.Diag(NextD->getBeginLoc(), | ||||
| 2791 | diag::err_designator_into_flexible_array_member) | ||||
| 2792 | << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc()); | ||||
| 2793 | SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) | ||||
| 2794 | << *Field; | ||||
| 2795 | } | ||||
| 2796 | Invalid = true; | ||||
| 2797 | } | ||||
| 2798 | |||||
| 2799 | if (!hadError && !isa<InitListExpr>(DIE->getInit()) && | ||||
| 2800 | !isa<StringLiteral>(DIE->getInit())) { | ||||
| 2801 | // The initializer is not an initializer list. | ||||
| 2802 | if (!VerifyOnly) { | ||||
| 2803 | SemaRef.Diag(DIE->getInit()->getBeginLoc(), | ||||
| 2804 | diag::err_flexible_array_init_needs_braces) | ||||
| 2805 | << DIE->getInit()->getSourceRange(); | ||||
| 2806 | SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) | ||||
| 2807 | << *Field; | ||||
| 2808 | } | ||||
| 2809 | Invalid = true; | ||||
| 2810 | } | ||||
| 2811 | |||||
| 2812 | // Check GNU flexible array initializer. | ||||
| 2813 | if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field, | ||||
| 2814 | TopLevelObject)) | ||||
| 2815 | Invalid = true; | ||||
| 2816 | |||||
| 2817 | if (Invalid) { | ||||
| 2818 | ++Index; | ||||
| 2819 | return true; | ||||
| 2820 | } | ||||
| 2821 | |||||
| 2822 | // Initialize the array. | ||||
| 2823 | bool prevHadError = hadError; | ||||
| 2824 | unsigned newStructuredIndex = FieldIndex; | ||||
| 2825 | unsigned OldIndex = Index; | ||||
| 2826 | IList->setInit(Index, DIE->getInit()); | ||||
| 2827 | |||||
| 2828 | InitializedEntity MemberEntity = | ||||
| 2829 | InitializedEntity::InitializeMember(*Field, &Entity); | ||||
| 2830 | CheckSubElementType(MemberEntity, IList, Field->getType(), Index, | ||||
| 2831 | StructuredList, newStructuredIndex); | ||||
| 2832 | |||||
| 2833 | IList->setInit(OldIndex, DIE); | ||||
| 2834 | if (hadError && !prevHadError) { | ||||
| 2835 | ++Field; | ||||
| 2836 | ++FieldIndex; | ||||
| 2837 | if (NextField) | ||||
| 2838 | *NextField = Field; | ||||
| 2839 | StructuredIndex = FieldIndex; | ||||
| 2840 | return true; | ||||
| 2841 | } | ||||
| 2842 | } else { | ||||
| 2843 | // Recurse to check later designated subobjects. | ||||
| 2844 | QualType FieldType = Field->getType(); | ||||
| 2845 | unsigned newStructuredIndex = FieldIndex; | ||||
| 2846 | |||||
| 2847 | InitializedEntity MemberEntity = | ||||
| 2848 | InitializedEntity::InitializeMember(*Field, &Entity); | ||||
| 2849 | if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1, | ||||
| 2850 | FieldType, nullptr, nullptr, Index, | ||||
| 2851 | StructuredList, newStructuredIndex, | ||||
| 2852 | FinishSubobjectInit, false)) | ||||
| 2853 | return true; | ||||
| 2854 | } | ||||
| 2855 | |||||
| 2856 | // Find the position of the next field to be initialized in this | ||||
| 2857 | // subobject. | ||||
| 2858 | ++Field; | ||||
| 2859 | ++FieldIndex; | ||||
| 2860 | |||||
| 2861 | // If this the first designator, our caller will continue checking | ||||
| 2862 | // the rest of this struct/class/union subobject. | ||||
| 2863 | if (IsFirstDesignator) { | ||||
| 2864 | if (NextField) | ||||
| 2865 | *NextField = Field; | ||||
| 2866 | StructuredIndex = FieldIndex; | ||||
| 2867 | return false; | ||||
| 2868 | } | ||||
| 2869 | |||||
| 2870 | if (!FinishSubobjectInit) | ||||
| 2871 | return false; | ||||
| 2872 | |||||
| 2873 | // We've already initialized something in the union; we're done. | ||||
| 2874 | if (RT->getDecl()->isUnion()) | ||||
| 2875 | return hadError; | ||||
| 2876 | |||||
| 2877 | // Check the remaining fields within this class/struct/union subobject. | ||||
| 2878 | bool prevHadError = hadError; | ||||
| 2879 | |||||
| 2880 | auto NoBases = | ||||
| 2881 | CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), | ||||
| 2882 | CXXRecordDecl::base_class_iterator()); | ||||
| 2883 | CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field, | ||||
| 2884 | false, Index, StructuredList, FieldIndex); | ||||
| 2885 | return hadError && !prevHadError; | ||||
| 2886 | } | ||||
| 2887 | |||||
| 2888 | // C99 6.7.8p6: | ||||
| 2889 | // | ||||
| 2890 | // If a designator has the form | ||||
| 2891 | // | ||||
| 2892 | // [ constant-expression ] | ||||
| 2893 | // | ||||
| 2894 | // then the current object (defined below) shall have array | ||||
| 2895 | // type and the expression shall be an integer constant | ||||
| 2896 | // expression. If the array is of unknown size, any | ||||
| 2897 | // nonnegative value is valid. | ||||
| 2898 | // | ||||
| 2899 | // Additionally, cope with the GNU extension that permits | ||||
| 2900 | // designators of the form | ||||
| 2901 | // | ||||
| 2902 | // [ constant-expression ... constant-expression ] | ||||
| 2903 | const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); | ||||
| 2904 | if (!AT) { | ||||
| 2905 | if (!VerifyOnly) | ||||
| 2906 | SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) | ||||
| 2907 | << CurrentObjectType; | ||||
| 2908 | ++Index; | ||||
| 2909 | return true; | ||||
| 2910 | } | ||||
| 2911 | |||||
| 2912 | Expr *IndexExpr = nullptr; | ||||
| 2913 | llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; | ||||
| 2914 | if (D->isArrayDesignator()) { | ||||
| 2915 | IndexExpr = DIE->getArrayIndex(*D); | ||||
| 2916 | DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context); | ||||
| 2917 | DesignatedEndIndex = DesignatedStartIndex; | ||||
| 2918 | } else { | ||||
| 2919 | 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", 2919, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 2920 | |||||
| 2921 | DesignatedStartIndex = | ||||
| 2922 | DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context); | ||||
| 2923 | DesignatedEndIndex = | ||||
| 2924 | DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context); | ||||
| 2925 | IndexExpr = DIE->getArrayRangeEnd(*D); | ||||
| 2926 | |||||
| 2927 | // Codegen can't handle evaluating array range designators that have side | ||||
| 2928 | // effects, because we replicate the AST value for each initialized element. | ||||
| 2929 | // As such, set the sawArrayRangeDesignator() bit if we initialize multiple | ||||
| 2930 | // elements with something that has a side effect, so codegen can emit an | ||||
| 2931 | // "error unsupported" error instead of miscompiling the app. | ||||
| 2932 | if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&& | ||||
| 2933 | DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly) | ||||
| 2934 | FullyStructuredList->sawArrayRangeDesignator(); | ||||
| 2935 | } | ||||
| 2936 | |||||
| 2937 | if (isa<ConstantArrayType>(AT)) { | ||||
| 2938 | llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); | ||||
| 2939 | DesignatedStartIndex | ||||
| 2940 | = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); | ||||
| 2941 | DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); | ||||
| 2942 | DesignatedEndIndex | ||||
| 2943 | = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); | ||||
| 2944 | DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); | ||||
| 2945 | if (DesignatedEndIndex >= MaxElements) { | ||||
| 2946 | if (!VerifyOnly) | ||||
| 2947 | SemaRef.Diag(IndexExpr->getBeginLoc(), | ||||
| 2948 | diag::err_array_designator_too_large) | ||||
| 2949 | << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10) | ||||
| 2950 | << IndexExpr->getSourceRange(); | ||||
| 2951 | ++Index; | ||||
| 2952 | return true; | ||||
| 2953 | } | ||||
| 2954 | } else { | ||||
| 2955 | unsigned DesignatedIndexBitWidth = | ||||
| 2956 | ConstantArrayType::getMaxSizeBits(SemaRef.Context); | ||||
| 2957 | DesignatedStartIndex = | ||||
| 2958 | DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth); | ||||
| 2959 | DesignatedEndIndex = | ||||
| 2960 | DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth); | ||||
| 2961 | DesignatedStartIndex.setIsUnsigned(true); | ||||
| 2962 | DesignatedEndIndex.setIsUnsigned(true); | ||||
| 2963 | } | ||||
| 2964 | |||||
| 2965 | bool IsStringLiteralInitUpdate = | ||||
| 2966 | StructuredList && StructuredList->isStringLiteralInit(); | ||||
| 2967 | if (IsStringLiteralInitUpdate && VerifyOnly) { | ||||
| 2968 | // We're just verifying an update to a string literal init. We don't need | ||||
| 2969 | // to split the string up into individual characters to do that. | ||||
| 2970 | StructuredList = nullptr; | ||||
| 2971 | } else if (IsStringLiteralInitUpdate) { | ||||
| 2972 | // We're modifying a string literal init; we have to decompose the string | ||||
| 2973 | // so we can modify the individual characters. | ||||
| 2974 | ASTContext &Context = SemaRef.Context; | ||||
| 2975 | Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts(); | ||||
| 2976 | |||||
| 2977 | // Compute the character type | ||||
| 2978 | QualType CharTy = AT->getElementType(); | ||||
| 2979 | |||||
| 2980 | // Compute the type of the integer literals. | ||||
| 2981 | QualType PromotedCharTy = CharTy; | ||||
| 2982 | if (Context.isPromotableIntegerType(CharTy)) | ||||
| 2983 | PromotedCharTy = Context.getPromotedIntegerType(CharTy); | ||||
| 2984 | unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy); | ||||
| 2985 | |||||
| 2986 | if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) { | ||||
| 2987 | // Get the length of the string. | ||||
| 2988 | uint64_t StrLen = SL->getLength(); | ||||
| 2989 | if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) | ||||
| 2990 | StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); | ||||
| 2991 | StructuredList->resizeInits(Context, StrLen); | ||||
| 2992 | |||||
| 2993 | // Build a literal for each character in the string, and put them into | ||||
| 2994 | // the init list. | ||||
| 2995 | for (unsigned i = 0, e = StrLen; i != e; ++i) { | ||||
| 2996 | llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i)); | ||||
| 2997 | Expr *Init = new (Context) IntegerLiteral( | ||||
| 2998 | Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); | ||||
| 2999 | if (CharTy != PromotedCharTy) | ||||
| 3000 | Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, | ||||
| 3001 | Init, nullptr, VK_PRValue, | ||||
| 3002 | FPOptionsOverride()); | ||||
| 3003 | StructuredList->updateInit(Context, i, Init); | ||||
| 3004 | } | ||||
| 3005 | } else { | ||||
| 3006 | ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr); | ||||
| 3007 | std::string Str; | ||||
| 3008 | Context.getObjCEncodingForType(E->getEncodedType(), Str); | ||||
| 3009 | |||||
| 3010 | // Get the length of the string. | ||||
| 3011 | uint64_t StrLen = Str.size(); | ||||
| 3012 | if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) | ||||
| 3013 | StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); | ||||
| 3014 | StructuredList->resizeInits(Context, StrLen); | ||||
| 3015 | |||||
| 3016 | // Build a literal for each character in the string, and put them into | ||||
| 3017 | // the init list. | ||||
| 3018 | for (unsigned i = 0, e = StrLen; i != e; ++i) { | ||||
| 3019 | llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]); | ||||
| 3020 | Expr *Init = new (Context) IntegerLiteral( | ||||
| 3021 | Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); | ||||
| 3022 | if (CharTy != PromotedCharTy) | ||||
| 3023 | Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, | ||||
| 3024 | Init, nullptr, VK_PRValue, | ||||
| 3025 | FPOptionsOverride()); | ||||
| 3026 | StructuredList->updateInit(Context, i, Init); | ||||
| 3027 | } | ||||
| 3028 | } | ||||
| 3029 | } | ||||
| 3030 | |||||
| 3031 | // Make sure that our non-designated initializer list has space | ||||
| 3032 | // for a subobject corresponding to this array element. | ||||
| 3033 | if (StructuredList && | ||||
| 3034 | DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) | ||||
| 3035 | StructuredList->resizeInits(SemaRef.Context, | ||||
| 3036 | DesignatedEndIndex.getZExtValue() + 1); | ||||
| 3037 | |||||
| 3038 | // Repeatedly perform subobject initializations in the range | ||||
| 3039 | // [DesignatedStartIndex, DesignatedEndIndex]. | ||||
| 3040 | |||||
| 3041 | // Move to the next designator | ||||
| 3042 | unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); | ||||
| 3043 | unsigned OldIndex = Index; | ||||
| 3044 | |||||
| 3045 | InitializedEntity ElementEntity = | ||||
| 3046 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); | ||||
| 3047 | |||||
| 3048 | while (DesignatedStartIndex <= DesignatedEndIndex) { | ||||
| 3049 | // Recurse to check later designated subobjects. | ||||
| 3050 | QualType ElementType = AT->getElementType(); | ||||
| 3051 | Index = OldIndex; | ||||
| 3052 | |||||
| 3053 | ElementEntity.setElementIndex(ElementIndex); | ||||
| 3054 | if (CheckDesignatedInitializer( | ||||
| 3055 | ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr, | ||||
| 3056 | nullptr, Index, StructuredList, ElementIndex, | ||||
| 3057 | FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex), | ||||
| 3058 | false)) | ||||
| 3059 | return true; | ||||
| 3060 | |||||
| 3061 | // Move to the next index in the array that we'll be initializing. | ||||
| 3062 | ++DesignatedStartIndex; | ||||
| 3063 | ElementIndex = DesignatedStartIndex.getZExtValue(); | ||||
| 3064 | } | ||||
| 3065 | |||||
| 3066 | // If this the first designator, our caller will continue checking | ||||
| 3067 | // the rest of this array subobject. | ||||
| 3068 | if (IsFirstDesignator) { | ||||
| 3069 | if (NextElementIndex) | ||||
| 3070 | *NextElementIndex = DesignatedStartIndex; | ||||
| 3071 | StructuredIndex = ElementIndex; | ||||
| 3072 | return false; | ||||
| 3073 | } | ||||
| 3074 | |||||
| 3075 | if (!FinishSubobjectInit) | ||||
| 3076 | return false; | ||||
| 3077 | |||||
| 3078 | // Check the remaining elements within this array subobject. | ||||
| 3079 | bool prevHadError = hadError; | ||||
| 3080 | CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex, | ||||
| 3081 | /*SubobjectIsDesignatorContext=*/false, Index, | ||||
| 3082 | StructuredList, ElementIndex); | ||||
| 3083 | return hadError && !prevHadError; | ||||
| 3084 | } | ||||
| 3085 | |||||
| 3086 | // Get the structured initializer list for a subobject of type | ||||
| 3087 | // @p CurrentObjectType. | ||||
| 3088 | InitListExpr * | ||||
| 3089 | InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, | ||||
| 3090 | QualType CurrentObjectType, | ||||
| 3091 | InitListExpr *StructuredList, | ||||
| 3092 | unsigned StructuredIndex, | ||||
| 3093 | SourceRange InitRange, | ||||
| 3094 | bool IsFullyOverwritten) { | ||||
| 3095 | if (!StructuredList) | ||||
| 3096 | return nullptr; | ||||
| 3097 | |||||
| 3098 | Expr *ExistingInit = nullptr; | ||||
| 3099 | if (StructuredIndex < StructuredList->getNumInits()) | ||||
| 3100 | ExistingInit = StructuredList->getInit(StructuredIndex); | ||||
| 3101 | |||||
| 3102 | if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) | ||||
| 3103 | // There might have already been initializers for subobjects of the current | ||||
| 3104 | // object, but a subsequent initializer list will overwrite the entirety | ||||
| 3105 | // of the current object. (See DR 253 and C99 6.7.8p21). e.g., | ||||
| 3106 | // | ||||
| 3107 | // struct P { char x[6]; }; | ||||
| 3108 | // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } }; | ||||
| 3109 | // | ||||
| 3110 | // The first designated initializer is ignored, and l.x is just "f". | ||||
| 3111 | if (!IsFullyOverwritten) | ||||
| 3112 | return Result; | ||||
| 3113 | |||||
| 3114 | if (ExistingInit) { | ||||
| 3115 | // We are creating an initializer list that initializes the | ||||
| 3116 | // subobjects of the current object, but there was already an | ||||
| 3117 | // initialization that completely initialized the current | ||||
| 3118 | // subobject: | ||||
| 3119 | // | ||||
| 3120 | // struct X { int a, b; }; | ||||
| 3121 | // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 }; | ||||
| 3122 | // | ||||
| 3123 | // Here, xs[0].a == 1 and xs[0].b == 3, since the second, | ||||
| 3124 | // designated initializer overwrites the [0].b initializer | ||||
| 3125 | // from the prior initialization. | ||||
| 3126 | // | ||||
| 3127 | // When the existing initializer is an expression rather than an | ||||
| 3128 | // initializer list, we cannot decompose and update it in this way. | ||||
| 3129 | // For example: | ||||
| 3130 | // | ||||
| 3131 | // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; | ||||
| 3132 | // | ||||
| 3133 | // This case is handled by CheckDesignatedInitializer. | ||||
| 3134 | diagnoseInitOverride(ExistingInit, InitRange); | ||||
| 3135 | } | ||||
| 3136 | |||||
| 3137 | unsigned ExpectedNumInits = 0; | ||||
| 3138 | if (Index < IList->getNumInits()) { | ||||
| 3139 | if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index))) | ||||
| 3140 | ExpectedNumInits = Init->getNumInits(); | ||||
| 3141 | else | ||||
| 3142 | ExpectedNumInits = IList->getNumInits() - Index; | ||||
| 3143 | } | ||||
| 3144 | |||||
| 3145 | InitListExpr *Result = | ||||
| 3146 | createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits); | ||||
| 3147 | |||||
| 3148 | // Link this new initializer list into the structured initializer | ||||
| 3149 | // lists. | ||||
| 3150 | StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result); | ||||
| 3151 | return Result; | ||||
| 3152 | } | ||||
| 3153 | |||||
| 3154 | InitListExpr * | ||||
| 3155 | InitListChecker::createInitListExpr(QualType CurrentObjectType, | ||||
| 3156 | SourceRange InitRange, | ||||
| 3157 | unsigned ExpectedNumInits) { | ||||
| 3158 | InitListExpr *Result = new (SemaRef.Context) InitListExpr( | ||||
| 3159 | SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd()); | ||||
| 3160 | |||||
| 3161 | QualType ResultType = CurrentObjectType; | ||||
| 3162 | if (!ResultType->isArrayType()) | ||||
| 3163 | ResultType = ResultType.getNonLValueExprType(SemaRef.Context); | ||||
| 3164 | Result->setType(ResultType); | ||||
| 3165 | |||||
| 3166 | // Pre-allocate storage for the structured initializer list. | ||||
| 3167 | unsigned NumElements = 0; | ||||
| 3168 | |||||
| 3169 | if (const ArrayType *AType | ||||
| 3170 | = SemaRef.Context.getAsArrayType(CurrentObjectType)) { | ||||
| 3171 | if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { | ||||
| 3172 | NumElements = CAType->getSize().getZExtValue(); | ||||
| 3173 | // Simple heuristic so that we don't allocate a very large | ||||
| 3174 | // initializer with many empty entries at the end. | ||||
| 3175 | if (NumElements > ExpectedNumInits) | ||||
| 3176 | NumElements = 0; | ||||
| 3177 | } | ||||
| 3178 | } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) { | ||||
| 3179 | NumElements = VType->getNumElements(); | ||||
| 3180 | } else if (CurrentObjectType->isRecordType()) { | ||||
| 3181 | NumElements = numStructUnionElements(CurrentObjectType); | ||||
| 3182 | } | ||||
| 3183 | |||||
| 3184 | Result->reserveInits(SemaRef.Context, NumElements); | ||||
| 3185 | |||||
| 3186 | return Result; | ||||
| 3187 | } | ||||
| 3188 | |||||
| 3189 | /// Update the initializer at index @p StructuredIndex within the | ||||
| 3190 | /// structured initializer list to the value @p expr. | ||||
| 3191 | void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, | ||||
| 3192 | unsigned &StructuredIndex, | ||||
| 3193 | Expr *expr) { | ||||
| 3194 | // No structured initializer list to update | ||||
| 3195 | if (!StructuredList) | ||||
| 3196 | return; | ||||
| 3197 | |||||
| 3198 | if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context, | ||||
| 3199 | StructuredIndex, expr)) { | ||||
| 3200 | // This initializer overwrites a previous initializer. | ||||
| 3201 | // No need to diagnose when `expr` is nullptr because a more relevant | ||||
| 3202 | // diagnostic has already been issued and this diagnostic is potentially | ||||
| 3203 | // noise. | ||||
| 3204 | if (expr) | ||||
| 3205 | diagnoseInitOverride(PrevInit, expr->getSourceRange()); | ||||
| 3206 | } | ||||
| 3207 | |||||
| 3208 | ++StructuredIndex; | ||||
| 3209 | } | ||||
| 3210 | |||||
| 3211 | /// Determine whether we can perform aggregate initialization for the purposes | ||||
| 3212 | /// of overload resolution. | ||||
| 3213 | bool Sema::CanPerformAggregateInitializationForOverloadResolution( | ||||
| 3214 | const InitializedEntity &Entity, InitListExpr *From) { | ||||
| 3215 | QualType Type = Entity.getType(); | ||||
| 3216 | InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true, | ||||
| 3217 | /*TreatUnavailableAsInvalid=*/false, | ||||
| 3218 | /*InOverloadResolution=*/true); | ||||
| 3219 | return !Check.HadError(); | ||||
| 3220 | } | ||||
| 3221 | |||||
| 3222 | /// Check that the given Index expression is a valid array designator | ||||
| 3223 | /// value. This is essentially just a wrapper around | ||||
| 3224 | /// VerifyIntegerConstantExpression that also checks for negative values | ||||
| 3225 | /// and produces a reasonable diagnostic if there is a | ||||
| 3226 | /// failure. Returns the index expression, possibly with an implicit cast | ||||
| 3227 | /// added, on success. If everything went okay, Value will receive the | ||||
| 3228 | /// value of the constant expression. | ||||
| 3229 | static ExprResult | ||||
| 3230 | CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { | ||||
| 3231 | SourceLocation Loc = Index->getBeginLoc(); | ||||
| 3232 | |||||
| 3233 | // Make sure this is an integer constant expression. | ||||
| 3234 | ExprResult Result = | ||||
| 3235 | S.VerifyIntegerConstantExpression(Index, &Value, Sema::AllowFold); | ||||
| 3236 | if (Result.isInvalid()) | ||||
| 3237 | return Result; | ||||
| 3238 | |||||
| 3239 | if (Value.isSigned() && Value.isNegative()) | ||||
| 3240 | return S.Diag(Loc, diag::err_array_designator_negative) | ||||
| 3241 | << toString(Value, 10) << Index->getSourceRange(); | ||||
| 3242 | |||||
| 3243 | Value.setIsUnsigned(true); | ||||
| 3244 | return Result; | ||||
| 3245 | } | ||||
| 3246 | |||||
| 3247 | ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, | ||||
| 3248 | SourceLocation EqualOrColonLoc, | ||||
| 3249 | bool GNUSyntax, | ||||
| 3250 | ExprResult Init) { | ||||
| 3251 | typedef DesignatedInitExpr::Designator ASTDesignator; | ||||
| 3252 | |||||
| 3253 | bool Invalid = false; | ||||
| 3254 | SmallVector<ASTDesignator, 32> Designators; | ||||
| 3255 | SmallVector<Expr *, 32> InitExpressions; | ||||
| 3256 | |||||
| 3257 | // Build designators and check array designator expressions. | ||||
| 3258 | for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { | ||||
| 3259 | const Designator &D = Desig.getDesignator(Idx); | ||||
| 3260 | |||||
| 3261 | if (D.isFieldDesignator()) { | ||||
| 3262 | Designators.push_back(ASTDesignator::CreateFieldDesignator( | ||||
| 3263 | D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc())); | ||||
| 3264 | } else if (D.isArrayDesignator()) { | ||||
| 3265 | Expr *Index = static_cast<Expr *>(D.getArrayIndex()); | ||||
| 3266 | llvm::APSInt IndexValue; | ||||
| 3267 | if (!Index->isTypeDependent() && !Index->isValueDependent()) | ||||
| 3268 | Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get(); | ||||
| 3269 | if (!Index) | ||||
| 3270 | Invalid = true; | ||||
| 3271 | else { | ||||
| 3272 | Designators.push_back(ASTDesignator::CreateArrayDesignator( | ||||
| 3273 | InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc())); | ||||
| 3274 | InitExpressions.push_back(Index); | ||||
| 3275 | } | ||||
| 3276 | } else if (D.isArrayRangeDesignator()) { | ||||
| 3277 | Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); | ||||
| 3278 | Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); | ||||
| 3279 | llvm::APSInt StartValue; | ||||
| 3280 | llvm::APSInt EndValue; | ||||
| 3281 | bool StartDependent = StartIndex->isTypeDependent() || | ||||
| 3282 | StartIndex->isValueDependent(); | ||||
| 3283 | bool EndDependent = EndIndex->isTypeDependent() || | ||||
| 3284 | EndIndex->isValueDependent(); | ||||
| 3285 | if (!StartDependent) | ||||
| 3286 | StartIndex = | ||||
| 3287 | CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get(); | ||||
| 3288 | if (!EndDependent) | ||||
| 3289 | EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get(); | ||||
| 3290 | |||||
| 3291 | if (!StartIndex || !EndIndex) | ||||
| 3292 | Invalid = true; | ||||
| 3293 | else { | ||||
| 3294 | // Make sure we're comparing values with the same bit width. | ||||
| 3295 | if (StartDependent || EndDependent) { | ||||
| 3296 | // Nothing to compute. | ||||
| 3297 | } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) | ||||
| 3298 | EndValue = EndValue.extend(StartValue.getBitWidth()); | ||||
| 3299 | else if (StartValue.getBitWidth() < EndValue.getBitWidth()) | ||||
| 3300 | StartValue = StartValue.extend(EndValue.getBitWidth()); | ||||
| 3301 | |||||
| 3302 | if (!StartDependent && !EndDependent && EndValue < StartValue) { | ||||
| 3303 | Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) | ||||
| 3304 | << toString(StartValue, 10) << toString(EndValue, 10) | ||||
| 3305 | << StartIndex->getSourceRange() << EndIndex->getSourceRange(); | ||||
| 3306 | Invalid = true; | ||||
| 3307 | } else { | ||||
| 3308 | Designators.push_back(ASTDesignator::CreateArrayRangeDesignator( | ||||
| 3309 | InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(), | ||||
| 3310 | D.getRBracketLoc())); | ||||
| 3311 | InitExpressions.push_back(StartIndex); | ||||
| 3312 | InitExpressions.push_back(EndIndex); | ||||
| 3313 | } | ||||
| 3314 | } | ||||
| 3315 | } | ||||
| 3316 | } | ||||
| 3317 | |||||
| 3318 | if (Invalid || Init.isInvalid()) | ||||
| 3319 | return ExprError(); | ||||
| 3320 | |||||
| 3321 | return DesignatedInitExpr::Create(Context, Designators, InitExpressions, | ||||
| 3322 | EqualOrColonLoc, GNUSyntax, | ||||
| 3323 | Init.getAs<Expr>()); | ||||
| 3324 | } | ||||
| 3325 | |||||
| 3326 | //===----------------------------------------------------------------------===// | ||||
| 3327 | // Initialization entity | ||||
| 3328 | //===----------------------------------------------------------------------===// | ||||
| 3329 | |||||
| 3330 | InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, | ||||
| 3331 | const InitializedEntity &Parent) | ||||
| 3332 | : Parent(&Parent), Index(Index) | ||||
| 3333 | { | ||||
| 3334 | if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) { | ||||
| 3335 | Kind = EK_ArrayElement; | ||||
| 3336 | Type = AT->getElementType(); | ||||
| 3337 | } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) { | ||||
| 3338 | Kind = EK_VectorElement; | ||||
| 3339 | Type = VT->getElementType(); | ||||
| 3340 | } else { | ||||
| 3341 | const ComplexType *CT = Parent.getType()->getAs<ComplexType>(); | ||||
| 3342 | assert(CT && "Unexpected type")(static_cast <bool> (CT && "Unexpected type") ? void (0) : __assert_fail ("CT && \"Unexpected type\"" , "clang/lib/Sema/SemaInit.cpp", 3342, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 3343 | Kind = EK_ComplexElement; | ||||
| 3344 | Type = CT->getElementType(); | ||||
| 3345 | } | ||||
| 3346 | } | ||||
| 3347 | |||||
| 3348 | InitializedEntity | ||||
| 3349 | InitializedEntity::InitializeBase(ASTContext &Context, | ||||
| 3350 | const CXXBaseSpecifier *Base, | ||||
| 3351 | bool IsInheritedVirtualBase, | ||||
| 3352 | const InitializedEntity *Parent) { | ||||
| 3353 | InitializedEntity Result; | ||||
| 3354 | Result.Kind = EK_Base; | ||||
| 3355 | Result.Parent = Parent; | ||||
| 3356 | Result.Base = {Base, IsInheritedVirtualBase}; | ||||
| 3357 | Result.Type = Base->getType(); | ||||
| 3358 | return Result; | ||||
| 3359 | } | ||||
| 3360 | |||||
| 3361 | DeclarationName InitializedEntity::getName() const { | ||||
| 3362 | switch (getKind()) { | ||||
| 3363 | case EK_Parameter: | ||||
| 3364 | case EK_Parameter_CF_Audited: { | ||||
| 3365 | ParmVarDecl *D = Parameter.getPointer(); | ||||
| 3366 | return (D ? D->getDeclName() : DeclarationName()); | ||||
| 3367 | } | ||||
| 3368 | |||||
| 3369 | case EK_Variable: | ||||
| 3370 | case EK_Member: | ||||
| 3371 | case EK_ParenAggInitMember: | ||||
| 3372 | case EK_Binding: | ||||
| 3373 | case EK_TemplateParameter: | ||||
| 3374 | return Variable.VariableOrMember->getDeclName(); | ||||
| 3375 | |||||
| 3376 | case EK_LambdaCapture: | ||||
| 3377 | return DeclarationName(Capture.VarID); | ||||
| 3378 | |||||
| 3379 | case EK_Result: | ||||
| 3380 | case EK_StmtExprResult: | ||||
| 3381 | case EK_Exception: | ||||
| 3382 | case EK_New: | ||||
| 3383 | case EK_Temporary: | ||||
| 3384 | case EK_Base: | ||||
| 3385 | case EK_Delegating: | ||||
| 3386 | case EK_ArrayElement: | ||||
| 3387 | case EK_VectorElement: | ||||
| 3388 | case EK_ComplexElement: | ||||
| 3389 | case EK_BlockElement: | ||||
| 3390 | case EK_LambdaToBlockConversionBlockElement: | ||||
| 3391 | case EK_CompoundLiteralInit: | ||||
| 3392 | case EK_RelatedResult: | ||||
| 3393 | return DeclarationName(); | ||||
| 3394 | } | ||||
| 3395 | |||||
| 3396 | llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp" , 3396); | ||||
| 3397 | } | ||||
| 3398 | |||||
| 3399 | ValueDecl *InitializedEntity::getDecl() const { | ||||
| 3400 | switch (getKind()) { | ||||
| 3401 | case EK_Variable: | ||||
| 3402 | case EK_Member: | ||||
| 3403 | case EK_ParenAggInitMember: | ||||
| 3404 | case EK_Binding: | ||||
| 3405 | case EK_TemplateParameter: | ||||
| 3406 | return Variable.VariableOrMember; | ||||
| 3407 | |||||
| 3408 | case EK_Parameter: | ||||
| 3409 | case EK_Parameter_CF_Audited: | ||||
| 3410 | return Parameter.getPointer(); | ||||
| 3411 | |||||
| 3412 | case EK_Result: | ||||
| 3413 | case EK_StmtExprResult: | ||||
| 3414 | case EK_Exception: | ||||
| 3415 | case EK_New: | ||||
| 3416 | case EK_Temporary: | ||||
| 3417 | case EK_Base: | ||||
| 3418 | case EK_Delegating: | ||||
| 3419 | case EK_ArrayElement: | ||||
| 3420 | case EK_VectorElement: | ||||
| 3421 | case EK_ComplexElement: | ||||
| 3422 | case EK_BlockElement: | ||||
| 3423 | case EK_LambdaToBlockConversionBlockElement: | ||||
| 3424 | case EK_LambdaCapture: | ||||
| 3425 | case EK_CompoundLiteralInit: | ||||
| 3426 | case EK_RelatedResult: | ||||
| 3427 | return nullptr; | ||||
| 3428 | } | ||||
| 3429 | |||||
| 3430 | llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp" , 3430); | ||||
| 3431 | } | ||||
| 3432 | |||||
| 3433 | bool InitializedEntity::allowsNRVO() const { | ||||
| 3434 | switch (getKind()) { | ||||
| 3435 | case EK_Result: | ||||
| 3436 | case EK_Exception: | ||||
| 3437 | return LocAndNRVO.NRVO; | ||||
| 3438 | |||||
| 3439 | case EK_StmtExprResult: | ||||
| 3440 | case EK_Variable: | ||||
| 3441 | case EK_Parameter: | ||||
| 3442 | case EK_Parameter_CF_Audited: | ||||
| 3443 | case EK_TemplateParameter: | ||||
| 3444 | case EK_Member: | ||||
| 3445 | case EK_ParenAggInitMember: | ||||
| 3446 | case EK_Binding: | ||||
| 3447 | case EK_New: | ||||
| 3448 | case EK_Temporary: | ||||
| 3449 | case EK_CompoundLiteralInit: | ||||
| 3450 | case EK_Base: | ||||
| 3451 | case EK_Delegating: | ||||
| 3452 | case EK_ArrayElement: | ||||
| 3453 | case EK_VectorElement: | ||||
| 3454 | case EK_ComplexElement: | ||||
| 3455 | case EK_BlockElement: | ||||
| 3456 | case EK_LambdaToBlockConversionBlockElement: | ||||
| 3457 | case EK_LambdaCapture: | ||||
| 3458 | case EK_RelatedResult: | ||||
| 3459 | break; | ||||
| 3460 | } | ||||
| 3461 | |||||
| 3462 | return false; | ||||
| 3463 | } | ||||
| 3464 | |||||
| 3465 | unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const { | ||||
| 3466 | assert(getParent() != this)(static_cast <bool> (getParent() != this) ? void (0) : __assert_fail ("getParent() != this", "clang/lib/Sema/SemaInit.cpp", 3466, __extension__ __PRETTY_FUNCTION__)); | ||||
| 3467 | unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0; | ||||
| 3468 | for (unsigned I = 0; I != Depth; ++I) | ||||
| 3469 | OS << "`-"; | ||||
| 3470 | |||||
| 3471 | switch (getKind()) { | ||||
| 3472 | case EK_Variable: OS << "Variable"; break; | ||||
| 3473 | case EK_Parameter: OS << "Parameter"; break; | ||||
| 3474 | case EK_Parameter_CF_Audited: OS << "CF audited function Parameter"; | ||||
| 3475 | break; | ||||
| 3476 | case EK_TemplateParameter: OS << "TemplateParameter"; break; | ||||
| 3477 | case EK_Result: OS << "Result"; break; | ||||
| 3478 | case EK_StmtExprResult: OS << "StmtExprResult"; break; | ||||
| 3479 | case EK_Exception: OS << "Exception"; break; | ||||
| 3480 | case EK_Member: | ||||
| 3481 | case EK_ParenAggInitMember: | ||||
| 3482 | OS << "Member"; | ||||
| 3483 | break; | ||||
| 3484 | case EK_Binding: OS << "Binding"; break; | ||||
| 3485 | case EK_New: OS << "New"; break; | ||||
| 3486 | case EK_Temporary: OS << "Temporary"; break; | ||||
| 3487 | case EK_CompoundLiteralInit: OS << "CompoundLiteral";break; | ||||
| 3488 | case EK_RelatedResult: OS << "RelatedResult"; break; | ||||
| 3489 | case EK_Base: OS << "Base"; break; | ||||
| 3490 | case EK_Delegating: OS << "Delegating"; break; | ||||
| 3491 | case EK_ArrayElement: OS << "ArrayElement " << Index; break; | ||||
| 3492 | case EK_VectorElement: OS << "VectorElement " << Index; break; | ||||
| 3493 | case EK_ComplexElement: OS << "ComplexElement " << Index; break; | ||||
| 3494 | case EK_BlockElement: OS << "Block"; break; | ||||
| 3495 | case EK_LambdaToBlockConversionBlockElement: | ||||
| 3496 | OS << "Block (lambda)"; | ||||
| 3497 | break; | ||||
| 3498 | case EK_LambdaCapture: | ||||
| 3499 | OS << "LambdaCapture "; | ||||
| 3500 | OS << DeclarationName(Capture.VarID); | ||||
| 3501 | break; | ||||
| 3502 | } | ||||
| 3503 | |||||
| 3504 | if (auto *D = getDecl()) { | ||||
| 3505 | OS << " "; | ||||
| 3506 | D->printQualifiedName(OS); | ||||
| 3507 | } | ||||
| 3508 | |||||
| 3509 | OS << " '" << getType() << "'\n"; | ||||
| 3510 | |||||
| 3511 | return Depth + 1; | ||||
| 3512 | } | ||||
| 3513 | |||||
| 3514 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void InitializedEntity::dump() const { | ||||
| 3515 | dumpImpl(llvm::errs()); | ||||
| 3516 | } | ||||
| 3517 | |||||
| 3518 | //===----------------------------------------------------------------------===// | ||||
| 3519 | // Initialization sequence | ||||
| 3520 | //===----------------------------------------------------------------------===// | ||||
| 3521 | |||||
| 3522 | void InitializationSequence::Step::Destroy() { | ||||
| 3523 | switch (Kind) { | ||||
| 3524 | case SK_ResolveAddressOfOverloadedFunction: | ||||
| 3525 | case SK_CastDerivedToBasePRValue: | ||||
| 3526 | case SK_CastDerivedToBaseXValue: | ||||
| 3527 | case SK_CastDerivedToBaseLValue: | ||||
| 3528 | case SK_BindReference: | ||||
| 3529 | case SK_BindReferenceToTemporary: | ||||
| 3530 | case SK_FinalCopy: | ||||
| 3531 | case SK_ExtraneousCopyToTemporary: | ||||
| 3532 | case SK_UserConversion: | ||||
| 3533 | case SK_QualificationConversionPRValue: | ||||
| 3534 | case SK_QualificationConversionXValue: | ||||
| 3535 | case SK_QualificationConversionLValue: | ||||
| 3536 | case SK_FunctionReferenceConversion: | ||||
| 3537 | case SK_AtomicConversion: | ||||
| 3538 | case SK_ListInitialization: | ||||
| 3539 | case SK_UnwrapInitList: | ||||
| 3540 | case SK_RewrapInitList: | ||||
| 3541 | case SK_ConstructorInitialization: | ||||
| 3542 | case SK_ConstructorInitializationFromList: | ||||
| 3543 | case SK_ZeroInitialization: | ||||
| 3544 | case SK_CAssignment: | ||||
| 3545 | case SK_StringInit: | ||||
| 3546 | case SK_ObjCObjectConversion: | ||||
| 3547 | case SK_ArrayLoopIndex: | ||||
| 3548 | case SK_ArrayLoopInit: | ||||
| 3549 | case SK_ArrayInit: | ||||
| 3550 | case SK_GNUArrayInit: | ||||
| 3551 | case SK_ParenthesizedArrayInit: | ||||
| 3552 | case SK_PassByIndirectCopyRestore: | ||||
| 3553 | case SK_PassByIndirectRestore: | ||||
| 3554 | case SK_ProduceObjCObject: | ||||
| 3555 | case SK_StdInitializerList: | ||||
| 3556 | case SK_StdInitializerListConstructorCall: | ||||
| 3557 | case SK_OCLSamplerInit: | ||||
| 3558 | case SK_OCLZeroOpaqueType: | ||||
| 3559 | case SK_ParenthesizedListInit: | ||||
| 3560 | break; | ||||
| 3561 | |||||
| 3562 | case SK_ConversionSequence: | ||||
| 3563 | case SK_ConversionSequenceNoNarrowing: | ||||
| 3564 | delete ICS; | ||||
| 3565 | } | ||||
| 3566 | } | ||||
| 3567 | |||||
| 3568 | bool InitializationSequence::isDirectReferenceBinding() const { | ||||
| 3569 | // There can be some lvalue adjustments after the SK_BindReference step. | ||||
| 3570 | for (const Step &S : llvm::reverse(Steps)) { | ||||
| 3571 | if (S.Kind == SK_BindReference) | ||||
| 3572 | return true; | ||||
| 3573 | if (S.Kind == SK_BindReferenceToTemporary) | ||||
| 3574 | return false; | ||||
| 3575 | } | ||||
| 3576 | return false; | ||||
| 3577 | } | ||||
| 3578 | |||||
| 3579 | bool InitializationSequence::isAmbiguous() const { | ||||
| 3580 | if (!Failed()) | ||||
| 3581 | return false; | ||||
| 3582 | |||||
| 3583 | switch (getFailureKind()) { | ||||
| 3584 | case FK_TooManyInitsForReference: | ||||
| 3585 | case FK_ParenthesizedListInitForReference: | ||||
| 3586 | case FK_ArrayNeedsInitList: | ||||
| 3587 | case FK_ArrayNeedsInitListOrStringLiteral: | ||||
| 3588 | case FK_ArrayNeedsInitListOrWideStringLiteral: | ||||
| 3589 | case FK_NarrowStringIntoWideCharArray: | ||||
| 3590 | case FK_WideStringIntoCharArray: | ||||
| 3591 | case FK_IncompatWideStringIntoWideChar: | ||||
| 3592 | case FK_PlainStringIntoUTF8Char: | ||||
| 3593 | case FK_UTF8StringIntoPlainChar: | ||||
| 3594 | case FK_AddressOfOverloadFailed: // FIXME: Could do better | ||||
| 3595 | case FK_NonConstLValueReferenceBindingToTemporary: | ||||
| 3596 | case FK_NonConstLValueReferenceBindingToBitfield: | ||||
| 3597 | case FK_NonConstLValueReferenceBindingToVectorElement: | ||||
| 3598 | case FK_NonConstLValueReferenceBindingToMatrixElement: | ||||
| 3599 | case FK_NonConstLValueReferenceBindingToUnrelated: | ||||
| 3600 | case FK_RValueReferenceBindingToLValue: | ||||
| 3601 | case FK_ReferenceAddrspaceMismatchTemporary: | ||||
| 3602 | case FK_ReferenceInitDropsQualifiers: | ||||
| 3603 | case FK_ReferenceInitFailed: | ||||
| 3604 | case FK_ConversionFailed: | ||||
| 3605 | case FK_ConversionFromPropertyFailed: | ||||
| 3606 | case FK_TooManyInitsForScalar: | ||||
| 3607 | case FK_ParenthesizedListInitForScalar: | ||||
| 3608 | case FK_ReferenceBindingToInitList: | ||||
| 3609 | case FK_InitListBadDestinationType: | ||||
| 3610 | case FK_DefaultInitOfConst: | ||||
| 3611 | case FK_Incomplete: | ||||
| 3612 | case FK_ArrayTypeMismatch: | ||||
| 3613 | case FK_NonConstantArrayInit: | ||||
| 3614 | case FK_ListInitializationFailed: | ||||
| 3615 | case FK_VariableLengthArrayHasInitializer: | ||||
| 3616 | case FK_PlaceholderType: | ||||
| 3617 | case FK_ExplicitConstructor: | ||||
| 3618 | case FK_AddressOfUnaddressableFunction: | ||||
| 3619 | case FK_ParenthesizedListInitFailed: | ||||
| 3620 | case FK_DesignatedInitForNonAggregate: | ||||
| 3621 | return false; | ||||
| 3622 | |||||
| 3623 | case FK_ReferenceInitOverloadFailed: | ||||
| 3624 | case FK_UserConversionOverloadFailed: | ||||
| 3625 | case FK_ConstructorOverloadFailed: | ||||
| 3626 | case FK_ListConstructorOverloadFailed: | ||||
| 3627 | return FailedOverloadResult == OR_Ambiguous; | ||||
| 3628 | } | ||||
| 3629 | |||||
| 3630 | llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp" , 3630); | ||||
| 3631 | } | ||||
| 3632 | |||||
| 3633 | bool InitializationSequence::isConstructorInitialization() const { | ||||
| 3634 | return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; | ||||
| 3635 | } | ||||
| 3636 | |||||
| 3637 | void | ||||
| 3638 | InitializationSequence | ||||
| 3639 | ::AddAddressOverloadResolutionStep(FunctionDecl *Function, | ||||
| 3640 | DeclAccessPair Found, | ||||
| 3641 | bool HadMultipleCandidates) { | ||||
| 3642 | Step S; | ||||
| 3643 | S.Kind = SK_ResolveAddressOfOverloadedFunction; | ||||
| 3644 | S.Type = Function->getType(); | ||||
| 3645 | S.Function.HadMultipleCandidates = HadMultipleCandidates; | ||||
| 3646 | S.Function.Function = Function; | ||||
| 3647 | S.Function.FoundDecl = Found; | ||||
| 3648 | Steps.push_back(S); | ||||
| 3649 | } | ||||
| 3650 | |||||
| 3651 | void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, | ||||
| 3652 | ExprValueKind VK) { | ||||
| 3653 | Step S; | ||||
| 3654 | switch (VK) { | ||||
| 3655 | case VK_PRValue: | ||||
| 3656 | S.Kind = SK_CastDerivedToBasePRValue; | ||||
| 3657 | break; | ||||
| 3658 | case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; | ||||
| 3659 | case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; | ||||
| 3660 | } | ||||
| 3661 | S.Type = BaseType; | ||||
| 3662 | Steps.push_back(S); | ||||
| 3663 | } | ||||
| 3664 | |||||
| 3665 | void InitializationSequence::AddReferenceBindingStep(QualType T, | ||||
| 3666 | bool BindingTemporary) { | ||||
| 3667 | Step S; | ||||
| 3668 | S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; | ||||
| 3669 | S.Type = T; | ||||
| 3670 | Steps.push_back(S); | ||||
| 3671 | } | ||||
| 3672 | |||||
| 3673 | void InitializationSequence::AddFinalCopy(QualType T) { | ||||
| 3674 | Step S; | ||||
| 3675 | S.Kind = SK_FinalCopy; | ||||
| 3676 | S.Type = T; | ||||
| 3677 | Steps.push_back(S); | ||||
| 3678 | } | ||||
| 3679 | |||||
| 3680 | void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) { | ||||
| 3681 | Step S; | ||||
| 3682 | S.Kind = SK_ExtraneousCopyToTemporary; | ||||
| 3683 | S.Type = T; | ||||
| 3684 | Steps.push_back(S); | ||||
| 3685 | } | ||||
| 3686 | |||||
| 3687 | void | ||||
| 3688 | InitializationSequence::AddUserConversionStep(FunctionDecl *Function, | ||||
| 3689 | DeclAccessPair FoundDecl, | ||||
| 3690 | QualType T, | ||||
| 3691 | bool HadMultipleCandidates) { | ||||
| 3692 | Step S; | ||||
| 3693 | S.Kind = SK_UserConversion; | ||||
| 3694 | S.Type = T; | ||||
| 3695 | S.Function.HadMultipleCandidates = HadMultipleCandidates; | ||||
| 3696 | S.Function.Function = Function; | ||||
| 3697 | S.Function.FoundDecl = FoundDecl; | ||||
| 3698 | Steps.push_back(S); | ||||
| 3699 | } | ||||
| 3700 | |||||
| 3701 | void InitializationSequence::AddQualificationConversionStep(QualType Ty, | ||||
| 3702 | ExprValueKind VK) { | ||||
| 3703 | Step S; | ||||
| 3704 | S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning | ||||
| 3705 | switch (VK) { | ||||
| 3706 | case VK_PRValue: | ||||
| 3707 | S.Kind = SK_QualificationConversionPRValue; | ||||
| 3708 | break; | ||||
| 3709 | case VK_XValue: | ||||
| 3710 | S.Kind = SK_QualificationConversionXValue; | ||||
| 3711 | break; | ||||
| 3712 | case VK_LValue: | ||||
| 3713 | S.Kind = SK_QualificationConversionLValue; | ||||
| 3714 | break; | ||||
| 3715 | } | ||||
| 3716 | S.Type = Ty; | ||||
| 3717 | Steps.push_back(S); | ||||
| 3718 | } | ||||
| 3719 | |||||
| 3720 | void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) { | ||||
| 3721 | Step S; | ||||
| 3722 | S.Kind = SK_FunctionReferenceConversion; | ||||
| 3723 | S.Type = Ty; | ||||
| 3724 | Steps.push_back(S); | ||||
| 3725 | } | ||||
| 3726 | |||||
| 3727 | void InitializationSequence::AddAtomicConversionStep(QualType Ty) { | ||||
| 3728 | Step S; | ||||
| 3729 | S.Kind = SK_AtomicConversion; | ||||
| 3730 | S.Type = Ty; | ||||
| 3731 | Steps.push_back(S); | ||||
| 3732 | } | ||||
| 3733 | |||||
| 3734 | void InitializationSequence::AddConversionSequenceStep( | ||||
| 3735 | const ImplicitConversionSequence &ICS, QualType T, | ||||
| 3736 | bool TopLevelOfInitList) { | ||||
| 3737 | Step S; | ||||
| 3738 | S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing | ||||
| 3739 | : SK_ConversionSequence; | ||||
| 3740 | S.Type = T; | ||||
| 3741 | S.ICS = new ImplicitConversionSequence(ICS); | ||||
| 3742 | Steps.push_back(S); | ||||
| 3743 | } | ||||
| 3744 | |||||
| 3745 | void InitializationSequence::AddListInitializationStep(QualType T) { | ||||
| 3746 | Step S; | ||||
| 3747 | S.Kind = SK_ListInitialization; | ||||
| 3748 | S.Type = T; | ||||
| 3749 | Steps.push_back(S); | ||||
| 3750 | } | ||||
| 3751 | |||||
| 3752 | void InitializationSequence::AddConstructorInitializationStep( | ||||
| 3753 | DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, | ||||
| 3754 | bool HadMultipleCandidates, bool FromInitList, bool AsInitList) { | ||||
| 3755 | Step S; | ||||
| 3756 | S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall | ||||
| 3757 | : SK_ConstructorInitializationFromList | ||||
| 3758 | : SK_ConstructorInitialization; | ||||
| 3759 | S.Type = T; | ||||
| 3760 | S.Function.HadMultipleCandidates = HadMultipleCandidates; | ||||
| 3761 | S.Function.Function = Constructor; | ||||
| 3762 | S.Function.FoundDecl = FoundDecl; | ||||
| 3763 | Steps.push_back(S); | ||||
| 3764 | } | ||||
| 3765 | |||||
| 3766 | void InitializationSequence::AddZeroInitializationStep(QualType T) { | ||||
| 3767 | Step S; | ||||
| 3768 | S.Kind = SK_ZeroInitialization; | ||||
| 3769 | S.Type = T; | ||||
| 3770 | Steps.push_back(S); | ||||
| 3771 | } | ||||
| 3772 | |||||
| 3773 | void InitializationSequence::AddCAssignmentStep(QualType T) { | ||||
| 3774 | Step S; | ||||
| 3775 | S.Kind = SK_CAssignment; | ||||
| 3776 | S.Type = T; | ||||
| 3777 | Steps.push_back(S); | ||||
| 3778 | } | ||||
| 3779 | |||||
| 3780 | void InitializationSequence::AddStringInitStep(QualType T) { | ||||
| 3781 | Step S; | ||||
| 3782 | S.Kind = SK_StringInit; | ||||
| 3783 | S.Type = T; | ||||
| 3784 | Steps.push_back(S); | ||||
| 3785 | } | ||||
| 3786 | |||||
| 3787 | void InitializationSequence::AddObjCObjectConversionStep(QualType T) { | ||||
| 3788 | Step S; | ||||
| 3789 | S.Kind = SK_ObjCObjectConversion; | ||||
| 3790 | S.Type = T; | ||||
| 3791 | Steps.push_back(S); | ||||
| 3792 | } | ||||
| 3793 | |||||
| 3794 | void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) { | ||||
| 3795 | Step S; | ||||
| 3796 | S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit; | ||||
| 3797 | S.Type = T; | ||||
| 3798 | Steps.push_back(S); | ||||
| 3799 | } | ||||
| 3800 | |||||
| 3801 | void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) { | ||||
| 3802 | Step S; | ||||
| 3803 | S.Kind = SK_ArrayLoopIndex; | ||||
| 3804 | S.Type = EltT; | ||||
| 3805 | Steps.insert(Steps.begin(), S); | ||||
| 3806 | |||||
| 3807 | S.Kind = SK_ArrayLoopInit; | ||||
| 3808 | S.Type = T; | ||||
| 3809 | Steps.push_back(S); | ||||
| 3810 | } | ||||
| 3811 | |||||
| 3812 | void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) { | ||||
| 3813 | Step S; | ||||
| 3814 | S.Kind = SK_ParenthesizedArrayInit; | ||||
| 3815 | S.Type = T; | ||||
| 3816 | Steps.push_back(S); | ||||
| 3817 | } | ||||
| 3818 | |||||
| 3819 | void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, | ||||
| 3820 | bool shouldCopy) { | ||||
| 3821 | Step s; | ||||
| 3822 | s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore | ||||
| 3823 | : SK_PassByIndirectRestore); | ||||
| 3824 | s.Type = type; | ||||
| 3825 | Steps.push_back(s); | ||||
| 3826 | } | ||||
| 3827 | |||||
| 3828 | void InitializationSequence::AddProduceObjCObjectStep(QualType T) { | ||||
| 3829 | Step S; | ||||
| 3830 | S.Kind = SK_ProduceObjCObject; | ||||
| 3831 | S.Type = T; | ||||
| 3832 | Steps.push_back(S); | ||||
| 3833 | } | ||||
| 3834 | |||||
| 3835 | void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) { | ||||
| 3836 | Step S; | ||||
| 3837 | S.Kind = SK_StdInitializerList; | ||||
| 3838 | S.Type = T; | ||||
| 3839 | Steps.push_back(S); | ||||
| 3840 | } | ||||
| 3841 | |||||
| 3842 | void InitializationSequence::AddOCLSamplerInitStep(QualType T) { | ||||
| 3843 | Step S; | ||||
| 3844 | S.Kind = SK_OCLSamplerInit; | ||||
| 3845 | S.Type = T; | ||||
| 3846 | Steps.push_back(S); | ||||
| 3847 | } | ||||
| 3848 | |||||
| 3849 | void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) { | ||||
| 3850 | Step S; | ||||
| 3851 | S.Kind = SK_OCLZeroOpaqueType; | ||||
| 3852 | S.Type = T; | ||||
| 3853 | Steps.push_back(S); | ||||
| 3854 | } | ||||
| 3855 | |||||
| 3856 | void InitializationSequence::AddParenthesizedListInitStep(QualType T) { | ||||
| 3857 | Step S; | ||||
| 3858 | S.Kind = SK_ParenthesizedListInit; | ||||
| 3859 | S.Type = T; | ||||
| 3860 | Steps.push_back(S); | ||||
| 3861 | } | ||||
| 3862 | |||||
| 3863 | void InitializationSequence::RewrapReferenceInitList(QualType T, | ||||
| 3864 | InitListExpr *Syntactic) { | ||||
| 3865 | 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", 3866, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 3866 | "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", 3866, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 3867 | Step S; | ||||
| 3868 | S.Kind = SK_UnwrapInitList; | ||||
| 3869 | S.Type = Syntactic->getInit(0)->getType(); | ||||
| 3870 | Steps.insert(Steps.begin(), S); | ||||
| 3871 | |||||
| 3872 | S.Kind = SK_RewrapInitList; | ||||
| 3873 | S.Type = T; | ||||
| 3874 | S.WrappingSyntacticList = Syntactic; | ||||
| 3875 | Steps.push_back(S); | ||||
| 3876 | } | ||||
| 3877 | |||||
| 3878 | void InitializationSequence::SetOverloadFailure(FailureKind Failure, | ||||
| 3879 | OverloadingResult Result) { | ||||
| 3880 | setSequenceKind(FailedSequence); | ||||
| 3881 | this->Failure = Failure; | ||||
| 3882 | this->FailedOverloadResult = Result; | ||||
| 3883 | } | ||||
| 3884 | |||||
| 3885 | //===----------------------------------------------------------------------===// | ||||
| 3886 | // Attempt initialization | ||||
| 3887 | //===----------------------------------------------------------------------===// | ||||
| 3888 | |||||
| 3889 | /// Tries to add a zero initializer. Returns true if that worked. | ||||
| 3890 | static bool | ||||
| 3891 | maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, | ||||
| 3892 | const InitializedEntity &Entity) { | ||||
| 3893 | if (Entity.getKind() != InitializedEntity::EK_Variable) | ||||
| 3894 | return false; | ||||
| 3895 | |||||
| 3896 | VarDecl *VD = cast<VarDecl>(Entity.getDecl()); | ||||
| 3897 | if (VD->getInit() || VD->getEndLoc().isMacroID()) | ||||
| 3898 | return false; | ||||
| 3899 | |||||
| 3900 | QualType VariableTy = VD->getType().getCanonicalType(); | ||||
| 3901 | SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc()); | ||||
| 3902 | std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc); | ||||
| 3903 | if (!Init.empty()) { | ||||
| 3904 | Sequence.AddZeroInitializationStep(Entity.getType()); | ||||
| 3905 | Sequence.SetZeroInitializationFixit(Init, Loc); | ||||
| 3906 | return true; | ||||
| 3907 | } | ||||
| 3908 | return false; | ||||
| 3909 | } | ||||
| 3910 | |||||
| 3911 | static void MaybeProduceObjCObject(Sema &S, | ||||
| 3912 | InitializationSequence &Sequence, | ||||
| 3913 | const InitializedEntity &Entity) { | ||||
| 3914 | if (!S.getLangOpts().ObjCAutoRefCount) return; | ||||
| 3915 | |||||
| 3916 | /// When initializing a parameter, produce the value if it's marked | ||||
| 3917 | /// __attribute__((ns_consumed)). | ||||
| 3918 | if (Entity.isParameterKind()) { | ||||
| 3919 | if (!Entity.isParameterConsumed()) | ||||
| 3920 | return; | ||||
| 3921 | |||||
| 3922 | 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", 3923, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 3923 | "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", 3923, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 3924 | Sequence.AddProduceObjCObjectStep(Entity.getType()); | ||||
| 3925 | |||||
| 3926 | /// When initializing a return value, if the return type is a | ||||
| 3927 | /// retainable type, then returns need to immediately retain the | ||||
| 3928 | /// object. If an autorelease is required, it will be done at the | ||||
| 3929 | /// last instant. | ||||
| 3930 | } else if (Entity.getKind() == InitializedEntity::EK_Result || | ||||
| 3931 | Entity.getKind() == InitializedEntity::EK_StmtExprResult) { | ||||
| 3932 | if (!Entity.getType()->isObjCRetainableType()) | ||||
| 3933 | return; | ||||
| 3934 | |||||
| 3935 | Sequence.AddProduceObjCObjectStep(Entity.getType()); | ||||
| 3936 | } | ||||
| 3937 | } | ||||
| 3938 | |||||
| 3939 | static void TryListInitialization(Sema &S, | ||||
| 3940 | const InitializedEntity &Entity, | ||||
| 3941 | const InitializationKind &Kind, | ||||
| 3942 | InitListExpr *InitList, | ||||
| 3943 | InitializationSequence &Sequence, | ||||
| 3944 | bool TreatUnavailableAsInvalid); | ||||
| 3945 | |||||
| 3946 | /// When initializing from init list via constructor, handle | ||||
| 3947 | /// initialization of an object of type std::initializer_list<T>. | ||||
| 3948 | /// | ||||
| 3949 | /// \return true if we have handled initialization of an object of type | ||||
| 3950 | /// std::initializer_list<T>, false otherwise. | ||||
| 3951 | static bool TryInitializerListConstruction(Sema &S, | ||||
| 3952 | InitListExpr *List, | ||||
| 3953 | QualType DestType, | ||||
| 3954 | InitializationSequence &Sequence, | ||||
| 3955 | bool TreatUnavailableAsInvalid) { | ||||
| 3956 | QualType E; | ||||
| 3957 | if (!S.isStdInitializerList(DestType, &E)) | ||||
| 3958 | return false; | ||||
| 3959 | |||||
| 3960 | if (!S.isCompleteType(List->getExprLoc(), E)) { | ||||
| 3961 | Sequence.setIncompleteTypeFailure(E); | ||||
| 3962 | return true; | ||||
| 3963 | } | ||||
| 3964 | |||||
| 3965 | // Try initializing a temporary array from the init list. | ||||
| 3966 | QualType ArrayType = S.Context.getConstantArrayType( | ||||
| 3967 | E.withConst(), | ||||
| 3968 | llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), | ||||
| 3969 | List->getNumInits()), | ||||
| 3970 | nullptr, clang::ArrayType::Normal, 0); | ||||
| 3971 | InitializedEntity HiddenArray = | ||||
| 3972 | InitializedEntity::InitializeTemporary(ArrayType); | ||||
| 3973 | InitializationKind Kind = InitializationKind::CreateDirectList( | ||||
| 3974 | List->getExprLoc(), List->getBeginLoc(), List->getEndLoc()); | ||||
| 3975 | TryListInitialization(S, HiddenArray, Kind, List, Sequence, | ||||
| 3976 | TreatUnavailableAsInvalid); | ||||
| 3977 | if (Sequence) | ||||
| 3978 | Sequence.AddStdInitializerListConstructionStep(DestType); | ||||
| 3979 | return true; | ||||
| 3980 | } | ||||
| 3981 | |||||
| 3982 | /// Determine if the constructor has the signature of a copy or move | ||||
| 3983 | /// constructor for the type T of the class in which it was found. That is, | ||||
| 3984 | /// determine if its first parameter is of type T or reference to (possibly | ||||
| 3985 | /// cv-qualified) T. | ||||
| 3986 | static bool hasCopyOrMoveCtorParam(ASTContext &Ctx, | ||||
| 3987 | const ConstructorInfo &Info) { | ||||
| 3988 | if (Info.Constructor->getNumParams() == 0) | ||||
| 3989 | return false; | ||||
| 3990 | |||||
| 3991 | QualType ParmT = | ||||
| 3992 | Info.Constructor->getParamDecl(0)->getType().getNonReferenceType(); | ||||
| 3993 | QualType ClassT = | ||||
| 3994 | Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext())); | ||||
| 3995 | |||||
| 3996 | return Ctx.hasSameUnqualifiedType(ParmT, ClassT); | ||||
| 3997 | } | ||||
| 3998 | |||||
| 3999 | static OverloadingResult | ||||
| 4000 | ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, | ||||
| 4001 | MultiExprArg Args, | ||||
| 4002 | OverloadCandidateSet &CandidateSet, | ||||
| 4003 | QualType DestType, | ||||
| 4004 | DeclContext::lookup_result Ctors, | ||||
| 4005 | OverloadCandidateSet::iterator &Best, | ||||
| 4006 | bool CopyInitializing, bool AllowExplicit, | ||||
| 4007 | bool OnlyListConstructors, bool IsListInit, | ||||
| 4008 | bool SecondStepOfCopyInit = false) { | ||||
| 4009 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor); | ||||
| 4010 | CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); | ||||
| 4011 | |||||
| 4012 | for (NamedDecl *D : Ctors) { | ||||
| 4013 | auto Info = getConstructorInfo(D); | ||||
| 4014 | if (!Info.Constructor || Info.Constructor->isInvalidDecl()) | ||||
| 4015 | continue; | ||||
| 4016 | |||||
| 4017 | if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor)) | ||||
| 4018 | continue; | ||||
| 4019 | |||||
| 4020 | // C++11 [over.best.ics]p4: | ||||
| 4021 | // ... and the constructor or user-defined conversion function is a | ||||
| 4022 | // candidate by | ||||
| 4023 | // - 13.3.1.3, when the argument is the temporary in the second step | ||||
| 4024 | // of a class copy-initialization, or | ||||
| 4025 | // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here] | ||||
| 4026 | // - the second phase of 13.3.1.7 when the initializer list has exactly | ||||
| 4027 | // one element that is itself an initializer list, and the target is | ||||
| 4028 | // the first parameter of a constructor of class X, and the conversion | ||||
| 4029 | // is to X or reference to (possibly cv-qualified X), | ||||
| 4030 | // user-defined conversion sequences are not considered. | ||||
| 4031 | bool SuppressUserConversions = | ||||
| 4032 | SecondStepOfCopyInit || | ||||
| 4033 | (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) && | ||||
| 4034 | hasCopyOrMoveCtorParam(S.Context, Info)); | ||||
| 4035 | |||||
| 4036 | if (Info.ConstructorTmpl) | ||||
| 4037 | S.AddTemplateOverloadCandidate( | ||||
| 4038 | Info.ConstructorTmpl, Info.FoundDecl, | ||||
| 4039 | /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions, | ||||
| 4040 | /*PartialOverloading=*/false, AllowExplicit); | ||||
| 4041 | else { | ||||
| 4042 | // C++ [over.match.copy]p1: | ||||
| 4043 | // - When initializing a temporary to be bound to the first parameter | ||||
| 4044 | // of a constructor [for type T] that takes a reference to possibly | ||||
| 4045 | // cv-qualified T as its first argument, called with a single | ||||
| 4046 | // argument in the context of direct-initialization, explicit | ||||
| 4047 | // conversion functions are also considered. | ||||
| 4048 | // FIXME: What if a constructor template instantiates to such a signature? | ||||
| 4049 | bool AllowExplicitConv = AllowExplicit && !CopyInitializing && | ||||
| 4050 | Args.size() == 1 && | ||||
| 4051 | hasCopyOrMoveCtorParam(S.Context, Info); | ||||
| 4052 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args, | ||||
| 4053 | CandidateSet, SuppressUserConversions, | ||||
| 4054 | /*PartialOverloading=*/false, AllowExplicit, | ||||
| 4055 | AllowExplicitConv); | ||||
| 4056 | } | ||||
| 4057 | } | ||||
| 4058 | |||||
| 4059 | // FIXME: Work around a bug in C++17 guaranteed copy elision. | ||||
| 4060 | // | ||||
| 4061 | // When initializing an object of class type T by constructor | ||||
| 4062 | // ([over.match.ctor]) or by list-initialization ([over.match.list]) | ||||
| 4063 | // from a single expression of class type U, conversion functions of | ||||
| 4064 | // U that convert to the non-reference type cv T are candidates. | ||||
| 4065 | // Explicit conversion functions are only candidates during | ||||
| 4066 | // direct-initialization. | ||||
| 4067 | // | ||||
| 4068 | // Note: SecondStepOfCopyInit is only ever true in this case when | ||||
| 4069 | // evaluating whether to produce a C++98 compatibility warning. | ||||
| 4070 | if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 && | ||||
| 4071 | !SecondStepOfCopyInit) { | ||||
| 4072 | Expr *Initializer = Args[0]; | ||||
| 4073 | auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl(); | ||||
| 4074 | if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) { | ||||
| 4075 | const auto &Conversions = SourceRD->getVisibleConversionFunctions(); | ||||
| 4076 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | ||||
| 4077 | NamedDecl *D = *I; | ||||
| 4078 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); | ||||
| 4079 | D = D->getUnderlyingDecl(); | ||||
| 4080 | |||||
| 4081 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); | ||||
| 4082 | CXXConversionDecl *Conv; | ||||
| 4083 | if (ConvTemplate) | ||||
| 4084 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | ||||
| 4085 | else | ||||
| 4086 | Conv = cast<CXXConversionDecl>(D); | ||||
| 4087 | |||||
| 4088 | if (ConvTemplate) | ||||
| 4089 | S.AddTemplateConversionCandidate( | ||||
| 4090 | ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, | ||||
| 4091 | CandidateSet, AllowExplicit, AllowExplicit, | ||||
| 4092 | /*AllowResultConversion*/ false); | ||||
| 4093 | else | ||||
| 4094 | S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, | ||||
| 4095 | DestType, CandidateSet, AllowExplicit, | ||||
| 4096 | AllowExplicit, | ||||
| 4097 | /*AllowResultConversion*/ false); | ||||
| 4098 | } | ||||
| 4099 | } | ||||
| 4100 | } | ||||
| 4101 | |||||
| 4102 | // Perform overload resolution and return the result. | ||||
| 4103 | return CandidateSet.BestViableFunction(S, DeclLoc, Best); | ||||
| 4104 | } | ||||
| 4105 | |||||
| 4106 | /// Attempt initialization by constructor (C++ [dcl.init]), which | ||||
| 4107 | /// enumerates the constructors of the initialized entity and performs overload | ||||
| 4108 | /// resolution to select the best. | ||||
| 4109 | /// \param DestType The destination class type. | ||||
| 4110 | /// \param DestArrayType The destination type, which is either DestType or | ||||
| 4111 | /// a (possibly multidimensional) array of DestType. | ||||
| 4112 | /// \param IsListInit Is this list-initialization? | ||||
| 4113 | /// \param IsInitListCopy Is this non-list-initialization resulting from a | ||||
| 4114 | /// list-initialization from {x} where x is the same | ||||
| 4115 | /// type as the entity? | ||||
| 4116 | static void TryConstructorInitialization(Sema &S, | ||||
| 4117 | const InitializedEntity &Entity, | ||||
| 4118 | const InitializationKind &Kind, | ||||
| 4119 | MultiExprArg Args, QualType DestType, | ||||
| 4120 | QualType DestArrayType, | ||||
| 4121 | InitializationSequence &Sequence, | ||||
| 4122 | bool IsListInit = false, | ||||
| 4123 | bool IsInitListCopy = false) { | ||||
| 4124 | 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", 4127, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 4125 | (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", 4127, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 4126 | "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", 4127, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 4127 | "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", 4127, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 4128 | InitListExpr *ILE = | ||||
| 4129 | (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr; | ||||
| 4130 | MultiExprArg UnwrappedArgs = | ||||
| 4131 | ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args; | ||||
| 4132 | |||||
| 4133 | // The type we're constructing needs to be complete. | ||||
| 4134 | if (!S.isCompleteType(Kind.getLocation(), DestType)) { | ||||
| 4135 | Sequence.setIncompleteTypeFailure(DestType); | ||||
| 4136 | return; | ||||
| 4137 | } | ||||
| 4138 | |||||
| 4139 | // C++17 [dcl.init]p17: | ||||
| 4140 | // - If the initializer expression is a prvalue and the cv-unqualified | ||||
| 4141 | // version of the source type is the same class as the class of the | ||||
| 4142 | // destination, the initializer expression is used to initialize the | ||||
| 4143 | // destination object. | ||||
| 4144 | // Per DR (no number yet), this does not apply when initializing a base | ||||
| 4145 | // class or delegating to another constructor from a mem-initializer. | ||||
| 4146 | // ObjC++: Lambda captured by the block in the lambda to block conversion | ||||
| 4147 | // should avoid copy elision. | ||||
| 4148 | if (S.getLangOpts().CPlusPlus17 && | ||||
| 4149 | Entity.getKind() != InitializedEntity::EK_Base && | ||||
| 4150 | Entity.getKind() != InitializedEntity::EK_Delegating && | ||||
| 4151 | Entity.getKind() != | ||||
| 4152 | InitializedEntity::EK_LambdaToBlockConversionBlockElement && | ||||
| 4153 | UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() && | ||||
| 4154 | S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) { | ||||
| 4155 | // Convert qualifications if necessary. | ||||
| 4156 | Sequence.AddQualificationConversionStep(DestType, VK_PRValue); | ||||
| 4157 | if (ILE) | ||||
| 4158 | Sequence.RewrapReferenceInitList(DestType, ILE); | ||||
| 4159 | return; | ||||
| 4160 | } | ||||
| 4161 | |||||
| 4162 | const RecordType *DestRecordType = DestType->getAs<RecordType>(); | ||||
| 4163 | 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", 4163, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 4164 | CXXRecordDecl *DestRecordDecl | ||||
| 4165 | = cast<CXXRecordDecl>(DestRecordType->getDecl()); | ||||
| 4166 | |||||
| 4167 | // Build the candidate set directly in the initialization sequence | ||||
| 4168 | // structure, so that it will persist if we fail. | ||||
| 4169 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); | ||||
| 4170 | |||||
| 4171 | // Determine whether we are allowed to call explicit constructors or | ||||
| 4172 | // explicit conversion operators. | ||||
| 4173 | bool AllowExplicit = Kind.AllowExplicit() || IsListInit; | ||||
| 4174 | bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy; | ||||
| 4175 | |||||
| 4176 | // - Otherwise, if T is a class type, constructors are considered. The | ||||
| 4177 | // applicable constructors are enumerated, and the best one is chosen | ||||
| 4178 | // through overload resolution. | ||||
| 4179 | DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl); | ||||
| 4180 | |||||
| 4181 | OverloadingResult Result = OR_No_Viable_Function; | ||||
| 4182 | OverloadCandidateSet::iterator Best; | ||||
| 4183 | bool AsInitializerList = false; | ||||
| 4184 | |||||
| 4185 | // C++11 [over.match.list]p1, per DR1467: | ||||
| 4186 | // When objects of non-aggregate type T are list-initialized, such that | ||||
| 4187 | // 8.5.4 [dcl.init.list] specifies that overload resolution is performed | ||||
| 4188 | // according to the rules in this section, overload resolution selects | ||||
| 4189 | // the constructor in two phases: | ||||
| 4190 | // | ||||
| 4191 | // - Initially, the candidate functions are the initializer-list | ||||
| 4192 | // constructors of the class T and the argument list consists of the | ||||
| 4193 | // initializer list as a single argument. | ||||
| 4194 | if (IsListInit) { | ||||
| 4195 | AsInitializerList = true; | ||||
| 4196 | |||||
| 4197 | // If the initializer list has no elements and T has a default constructor, | ||||
| 4198 | // the first phase is omitted. | ||||
| 4199 | if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl))) | ||||
| 4200 | Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, | ||||
| 4201 | CandidateSet, DestType, Ctors, Best, | ||||
| 4202 | CopyInitialization, AllowExplicit, | ||||
| 4203 | /*OnlyListConstructors=*/true, | ||||
| 4204 | IsListInit); | ||||
| 4205 | } | ||||
| 4206 | |||||
| 4207 | // C++11 [over.match.list]p1: | ||||
| 4208 | // - If no viable initializer-list constructor is found, overload resolution | ||||
| 4209 | // is performed again, where the candidate functions are all the | ||||
| 4210 | // constructors of the class T and the argument list consists of the | ||||
| 4211 | // elements of the initializer list. | ||||
| 4212 | if (Result == OR_No_Viable_Function) { | ||||
| 4213 | AsInitializerList = false; | ||||
| 4214 | Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs, | ||||
| 4215 | CandidateSet, DestType, Ctors, Best, | ||||
| 4216 | CopyInitialization, AllowExplicit, | ||||
| 4217 | /*OnlyListConstructors=*/false, | ||||
| 4218 | IsListInit); | ||||
| 4219 | } | ||||
| 4220 | if (Result) { | ||||
| 4221 | Sequence.SetOverloadFailure( | ||||
| 4222 | IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed | ||||
| 4223 | : InitializationSequence::FK_ConstructorOverloadFailed, | ||||
| 4224 | Result); | ||||
| 4225 | |||||
| 4226 | if (Result != OR_Deleted) | ||||
| 4227 | return; | ||||
| 4228 | } | ||||
| 4229 | |||||
| 4230 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | ||||
| 4231 | |||||
| 4232 | // In C++17, ResolveConstructorOverload can select a conversion function | ||||
| 4233 | // instead of a constructor. | ||||
| 4234 | if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) { | ||||
| 4235 | // Add the user-defined conversion step that calls the conversion function. | ||||
| 4236 | QualType ConvType = CD->getConversionType(); | ||||
| 4237 | 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", 4238, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 4238 | "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", 4238, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 4239 | Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType, | ||||
| 4240 | HadMultipleCandidates); | ||||
| 4241 | if (!S.Context.hasSameType(ConvType, DestType)) | ||||
| 4242 | Sequence.AddQualificationConversionStep(DestType, VK_PRValue); | ||||
| 4243 | if (IsListInit) | ||||
| 4244 | Sequence.RewrapReferenceInitList(Entity.getType(), ILE); | ||||
| 4245 | return; | ||||
| 4246 | } | ||||
| 4247 | |||||
| 4248 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); | ||||
| 4249 | if (Result != OR_Deleted) { | ||||
| 4250 | // C++11 [dcl.init]p6: | ||||
| 4251 | // If a program calls for the default initialization of an object | ||||
| 4252 | // of a const-qualified type T, T shall be a class type with a | ||||
| 4253 | // user-provided default constructor. | ||||
| 4254 | // C++ core issue 253 proposal: | ||||
| 4255 | // If the implicit default constructor initializes all subobjects, no | ||||
| 4256 | // initializer should be required. | ||||
| 4257 | // The 253 proposal is for example needed to process libstdc++ headers | ||||
| 4258 | // in 5.x. | ||||
| 4259 | if (Kind.getKind() == InitializationKind::IK_Default && | ||||
| 4260 | Entity.getType().isConstQualified()) { | ||||
| 4261 | if (!CtorDecl->getParent()->allowConstDefaultInit()) { | ||||
| 4262 | if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) | ||||
| 4263 | Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); | ||||
| 4264 | return; | ||||
| 4265 | } | ||||
| 4266 | } | ||||
| 4267 | |||||
| 4268 | // C++11 [over.match.list]p1: | ||||
| 4269 | // In copy-list-initialization, if an explicit constructor is chosen, the | ||||
| 4270 | // initializer is ill-formed. | ||||
| 4271 | if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) { | ||||
| 4272 | Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor); | ||||
| 4273 | return; | ||||
| 4274 | } | ||||
| 4275 | } | ||||
| 4276 | |||||
| 4277 | // [class.copy.elision]p3: | ||||
| 4278 | // In some copy-initialization contexts, a two-stage overload resolution | ||||
| 4279 | // is performed. | ||||
| 4280 | // If the first overload resolution selects a deleted function, we also | ||||
| 4281 | // need the initialization sequence to decide whether to perform the second | ||||
| 4282 | // overload resolution. | ||||
| 4283 | // For deleted functions in other contexts, there is no need to get the | ||||
| 4284 | // initialization sequence. | ||||
| 4285 | if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy) | ||||
| 4286 | return; | ||||
| 4287 | |||||
| 4288 | // Add the constructor initialization step. Any cv-qualification conversion is | ||||
| 4289 | // subsumed by the initialization. | ||||
| 4290 | Sequence.AddConstructorInitializationStep( | ||||
| 4291 | Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates, | ||||
| 4292 | IsListInit | IsInitListCopy, AsInitializerList); | ||||
| 4293 | } | ||||
| 4294 | |||||
| 4295 | static bool | ||||
| 4296 | ResolveOverloadedFunctionForReferenceBinding(Sema &S, | ||||
| 4297 | Expr *Initializer, | ||||
| 4298 | QualType &SourceType, | ||||
| 4299 | QualType &UnqualifiedSourceType, | ||||
| 4300 | QualType UnqualifiedTargetType, | ||||
| 4301 | InitializationSequence &Sequence) { | ||||
| 4302 | if (S.Context.getCanonicalType(UnqualifiedSourceType) == | ||||
| 4303 | S.Context.OverloadTy) { | ||||
| 4304 | DeclAccessPair Found; | ||||
| 4305 | bool HadMultipleCandidates = false; | ||||
| 4306 | if (FunctionDecl *Fn | ||||
| 4307 | = S.ResolveAddressOfOverloadedFunction(Initializer, | ||||
| 4308 | UnqualifiedTargetType, | ||||
| 4309 | false, Found, | ||||
| 4310 | &HadMultipleCandidates)) { | ||||
| 4311 | Sequence.AddAddressOverloadResolutionStep(Fn, Found, | ||||
| 4312 | HadMultipleCandidates); | ||||
| 4313 | SourceType = Fn->getType(); | ||||
| 4314 | UnqualifiedSourceType = SourceType.getUnqualifiedType(); | ||||
| 4315 | } else if (!UnqualifiedTargetType->isRecordType()) { | ||||
| 4316 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); | ||||
| 4317 | return true; | ||||
| 4318 | } | ||||
| 4319 | } | ||||
| 4320 | return false; | ||||
| 4321 | } | ||||
| 4322 | |||||
| 4323 | static void TryReferenceInitializationCore(Sema &S, | ||||
| 4324 | const InitializedEntity &Entity, | ||||
| 4325 | const InitializationKind &Kind, | ||||
| 4326 | Expr *Initializer, | ||||
| 4327 | QualType cv1T1, QualType T1, | ||||
| 4328 | Qualifiers T1Quals, | ||||
| 4329 | QualType cv2T2, QualType T2, | ||||
| 4330 | Qualifiers T2Quals, | ||||
| 4331 | InitializationSequence &Sequence); | ||||
| 4332 | |||||
| 4333 | static void TryValueInitialization(Sema &S, | ||||
| 4334 | const InitializedEntity &Entity, | ||||
| 4335 | const InitializationKind &Kind, | ||||
| 4336 | InitializationSequence &Sequence, | ||||
| 4337 | InitListExpr *InitList = nullptr); | ||||
| 4338 | |||||
| 4339 | /// Attempt list initialization of a reference. | ||||
| 4340 | static void TryReferenceListInitialization(Sema &S, | ||||
| 4341 | const InitializedEntity &Entity, | ||||
| 4342 | const InitializationKind &Kind, | ||||
| 4343 | InitListExpr *InitList, | ||||
| 4344 | InitializationSequence &Sequence, | ||||
| 4345 | bool TreatUnavailableAsInvalid) { | ||||
| 4346 | // First, catch C++03 where this isn't possible. | ||||
| 4347 | if (!S.getLangOpts().CPlusPlus11) { | ||||
| 4348 | Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); | ||||
| 4349 | return; | ||||
| 4350 | } | ||||
| 4351 | // Can't reference initialize a compound literal. | ||||
| 4352 | if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) { | ||||
| 4353 | Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); | ||||
| 4354 | return; | ||||
| 4355 | } | ||||
| 4356 | |||||
| 4357 | QualType DestType = Entity.getType(); | ||||
| 4358 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); | ||||
| 4359 | Qualifiers T1Quals; | ||||
| 4360 | QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); | ||||
| 4361 | |||||
| 4362 | // Reference initialization via an initializer list works thus: | ||||
| 4363 | // If the initializer list consists of a single element that is | ||||
| 4364 | // reference-related to the referenced type, bind directly to that element | ||||
| 4365 | // (possibly creating temporaries). | ||||
| 4366 | // Otherwise, initialize a temporary with the initializer list and | ||||
| 4367 | // bind to that. | ||||
| 4368 | if (InitList->getNumInits() == 1) { | ||||
| 4369 | Expr *Initializer = InitList->getInit(0); | ||||
| 4370 | QualType cv2T2 = S.getCompletedType(Initializer); | ||||
| 4371 | Qualifiers T2Quals; | ||||
| 4372 | QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); | ||||
| 4373 | |||||
| 4374 | // If this fails, creating a temporary wouldn't work either. | ||||
| 4375 | if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, | ||||
| 4376 | T1, Sequence)) | ||||
| 4377 | return; | ||||
| 4378 | |||||
| 4379 | SourceLocation DeclLoc = Initializer->getBeginLoc(); | ||||
| 4380 | Sema::ReferenceCompareResult RefRelationship | ||||
| 4381 | = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2); | ||||
| 4382 | if (RefRelationship >= Sema::Ref_Related) { | ||||
| 4383 | // Try to bind the reference here. | ||||
| 4384 | TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, | ||||
| 4385 | T1Quals, cv2T2, T2, T2Quals, Sequence); | ||||
| 4386 | if (Sequence) | ||||
| 4387 | Sequence.RewrapReferenceInitList(cv1T1, InitList); | ||||
| 4388 | return; | ||||
| 4389 | } | ||||
| 4390 | |||||
| 4391 | // Update the initializer if we've resolved an overloaded function. | ||||
| 4392 | if (Sequence.step_begin() != Sequence.step_end()) | ||||
| 4393 | Sequence.RewrapReferenceInitList(cv1T1, InitList); | ||||
| 4394 | } | ||||
| 4395 | // Perform address space compatibility check. | ||||
| 4396 | QualType cv1T1IgnoreAS = cv1T1; | ||||
| 4397 | if (T1Quals.hasAddressSpace()) { | ||||
| 4398 | Qualifiers T2Quals; | ||||
| 4399 | (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals); | ||||
| 4400 | if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) { | ||||
| 4401 | Sequence.SetFailed( | ||||
| 4402 | InitializationSequence::FK_ReferenceInitDropsQualifiers); | ||||
| 4403 | return; | ||||
| 4404 | } | ||||
| 4405 | // Ignore address space of reference type at this point and perform address | ||||
| 4406 | // space conversion after the reference binding step. | ||||
| 4407 | cv1T1IgnoreAS = | ||||
| 4408 | S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace()); | ||||
| 4409 | } | ||||
| 4410 | // Not reference-related. Create a temporary and bind to that. | ||||
| 4411 | InitializedEntity TempEntity = | ||||
| 4412 | InitializedEntity::InitializeTemporary(cv1T1IgnoreAS); | ||||
| 4413 | |||||
| 4414 | TryListInitialization(S, TempEntity, Kind, InitList, Sequence, | ||||
| 4415 | TreatUnavailableAsInvalid); | ||||
| 4416 | if (Sequence) { | ||||
| 4417 | if (DestType->isRValueReferenceType() || | ||||
| 4418 | (T1Quals.hasConst() && !T1Quals.hasVolatile())) { | ||||
| 4419 | Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, | ||||
| 4420 | /*BindingTemporary=*/true); | ||||
| 4421 | if (T1Quals.hasAddressSpace()) | ||||
| 4422 | Sequence.AddQualificationConversionStep( | ||||
| 4423 | cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue); | ||||
| 4424 | } else | ||||
| 4425 | Sequence.SetFailed( | ||||
| 4426 | InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); | ||||
| 4427 | } | ||||
| 4428 | } | ||||
| 4429 | |||||
| 4430 | /// Attempt list initialization (C++0x [dcl.init.list]) | ||||
| 4431 | static void TryListInitialization(Sema &S, | ||||
| 4432 | const InitializedEntity &Entity, | ||||
| 4433 | const InitializationKind &Kind, | ||||
| 4434 | InitListExpr *InitList, | ||||
| 4435 | InitializationSequence &Sequence, | ||||
| 4436 | bool TreatUnavailableAsInvalid) { | ||||
| 4437 | QualType DestType = Entity.getType(); | ||||
| 4438 | |||||
| 4439 | // C++ doesn't allow scalar initialization with more than one argument. | ||||
| 4440 | // But C99 complex numbers are scalars and it makes sense there. | ||||
| 4441 | if (S.getLangOpts().CPlusPlus && DestType->isScalarType() && | ||||
| 4442 | !DestType->isAnyComplexType() && InitList->getNumInits() > 1) { | ||||
| 4443 | Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); | ||||
| 4444 | return; | ||||
| 4445 | } | ||||
| 4446 | if (DestType->isReferenceType()) { | ||||
| 4447 | TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence, | ||||
| 4448 | TreatUnavailableAsInvalid); | ||||
| 4449 | return; | ||||
| 4450 | } | ||||
| 4451 | |||||
| 4452 | if (DestType->isRecordType() && | ||||
| 4453 | !S.isCompleteType(InitList->getBeginLoc(), DestType)) { | ||||
| 4454 | Sequence.setIncompleteTypeFailure(DestType); | ||||
| 4455 | return; | ||||
| 4456 | } | ||||
| 4457 | |||||
| 4458 | // C++20 [dcl.init.list]p3: | ||||
| 4459 | // - If the braced-init-list contains a designated-initializer-list, T shall | ||||
| 4460 | // be an aggregate class. [...] Aggregate initialization is performed. | ||||
| 4461 | // | ||||
| 4462 | // We allow arrays here too in order to support array designators. | ||||
| 4463 | // | ||||
| 4464 | // FIXME: This check should precede the handling of reference initialization. | ||||
| 4465 | // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};' | ||||
| 4466 | // as a tentative DR resolution. | ||||
| 4467 | bool IsDesignatedInit = InitList->hasDesignatedInit(); | ||||
| 4468 | if (!DestType->isAggregateType() && IsDesignatedInit) { | ||||
| 4469 | Sequence.SetFailed( | ||||
| 4470 | InitializationSequence::FK_DesignatedInitForNonAggregate); | ||||
| 4471 | return; | ||||
| 4472 | } | ||||
| 4473 | |||||
| 4474 | // C++11 [dcl.init.list]p3, per DR1467: | ||||
| 4475 | // - If T is a class type and the initializer list has a single element of | ||||
| 4476 | // type cv U, where U is T or a class derived from T, the object is | ||||
| 4477 | // initialized from that element (by copy-initialization for | ||||
| 4478 | // copy-list-initialization, or by direct-initialization for | ||||
| 4479 | // direct-list-initialization). | ||||
| 4480 | // - Otherwise, if T is a character array and the initializer list has a | ||||
| 4481 | // single element that is an appropriately-typed string literal | ||||
| 4482 | // (8.5.2 [dcl.init.string]), initialization is performed as described | ||||
| 4483 | // in that section. | ||||
| 4484 | // - Otherwise, if T is an aggregate, [...] (continue below). | ||||
| 4485 | if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 && | ||||
| 4486 | !IsDesignatedInit) { | ||||
| 4487 | if (DestType->isRecordType()) { | ||||
| 4488 | QualType InitType = InitList->getInit(0)->getType(); | ||||
| 4489 | if (S.Context.hasSameUnqualifiedType(InitType, DestType) || | ||||
| 4490 | S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) { | ||||
| 4491 | Expr *InitListAsExpr = InitList; | ||||
| 4492 | TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, | ||||
| 4493 | DestType, Sequence, | ||||
| 4494 | /*InitListSyntax*/false, | ||||
| 4495 | /*IsInitListCopy*/true); | ||||
| 4496 | return; | ||||
| 4497 | } | ||||
| 4498 | } | ||||
| 4499 | if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) { | ||||
| 4500 | Expr *SubInit[1] = {InitList->getInit(0)}; | ||||
| 4501 | if (!isa<VariableArrayType>(DestAT) && | ||||
| 4502 | IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) { | ||||
| 4503 | InitializationKind SubKind = | ||||
| 4504 | Kind.getKind() == InitializationKind::IK_DirectList | ||||
| 4505 | ? InitializationKind::CreateDirect(Kind.getLocation(), | ||||
| 4506 | InitList->getLBraceLoc(), | ||||
| 4507 | InitList->getRBraceLoc()) | ||||
| 4508 | : Kind; | ||||
| 4509 | Sequence.InitializeFrom(S, Entity, SubKind, SubInit, | ||||
| 4510 | /*TopLevelOfInitList*/ true, | ||||
| 4511 | TreatUnavailableAsInvalid); | ||||
| 4512 | |||||
| 4513 | // TryStringLiteralInitialization() (in InitializeFrom()) will fail if | ||||
| 4514 | // the element is not an appropriately-typed string literal, in which | ||||
| 4515 | // case we should proceed as in C++11 (below). | ||||
| 4516 | if (Sequence) { | ||||
| 4517 | Sequence.RewrapReferenceInitList(Entity.getType(), InitList); | ||||
| 4518 | return; | ||||
| 4519 | } | ||||
| 4520 | } | ||||
| 4521 | } | ||||
| 4522 | } | ||||
| 4523 | |||||
| 4524 | // C++11 [dcl.init.list]p3: | ||||
| 4525 | // - If T is an aggregate, aggregate initialization is performed. | ||||
| 4526 | if ((DestType->isRecordType() && !DestType->isAggregateType()) || | ||||
| 4527 | (S.getLangOpts().CPlusPlus11 && | ||||
| 4528 | S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) { | ||||
| 4529 | if (S.getLangOpts().CPlusPlus11) { | ||||
| 4530 | // - Otherwise, if the initializer list has no elements and T is a | ||||
| 4531 | // class type with a default constructor, the object is | ||||
| 4532 | // value-initialized. | ||||
| 4533 | if (InitList->getNumInits() == 0) { | ||||
| 4534 | CXXRecordDecl *RD = DestType->getAsCXXRecordDecl(); | ||||
| 4535 | if (S.LookupDefaultConstructor(RD)) { | ||||
| 4536 | TryValueInitialization(S, Entity, Kind, Sequence, InitList); | ||||
| 4537 | return; | ||||
| 4538 | } | ||||
| 4539 | } | ||||
| 4540 | |||||
| 4541 | // - Otherwise, if T is a specialization of std::initializer_list<E>, | ||||
| 4542 | // an initializer_list object constructed [...] | ||||
| 4543 | if (TryInitializerListConstruction(S, InitList, DestType, Sequence, | ||||
| 4544 | TreatUnavailableAsInvalid)) | ||||
| 4545 | return; | ||||
| 4546 | |||||
| 4547 | // - Otherwise, if T is a class type, constructors are considered. | ||||
| 4548 | Expr *InitListAsExpr = InitList; | ||||
| 4549 | TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, | ||||
| 4550 | DestType, Sequence, /*InitListSyntax*/true); | ||||
| 4551 | } else | ||||
| 4552 | Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); | ||||
| 4553 | return; | ||||
| 4554 | } | ||||
| 4555 | |||||
| 4556 | if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() && | ||||
| 4557 | InitList->getNumInits() == 1) { | ||||
| 4558 | Expr *E = InitList->getInit(0); | ||||
| 4559 | |||||
| 4560 | // - Otherwise, if T is an enumeration with a fixed underlying type, | ||||
| 4561 | // the initializer-list has a single element v, and the initialization | ||||
| 4562 | // is direct-list-initialization, the object is initialized with the | ||||
| 4563 | // value T(v); if a narrowing conversion is required to convert v to | ||||
| 4564 | // the underlying type of T, the program is ill-formed. | ||||
| 4565 | auto *ET = DestType->getAs<EnumType>(); | ||||
| 4566 | if (S.getLangOpts().CPlusPlus17 && | ||||
| 4567 | Kind.getKind() == InitializationKind::IK_DirectList && | ||||
| 4568 | ET && ET->getDecl()->isFixed() && | ||||
| 4569 | !S.Context.hasSameUnqualifiedType(E->getType(), DestType) && | ||||
| 4570 | (E->getType()->isIntegralOrUnscopedEnumerationType() || | ||||
| 4571 | E->getType()->isFloatingType())) { | ||||
| 4572 | // There are two ways that T(v) can work when T is an enumeration type. | ||||
| 4573 | // If there is either an implicit conversion sequence from v to T or | ||||
| 4574 | // a conversion function that can convert from v to T, then we use that. | ||||
| 4575 | // Otherwise, if v is of integral, unscoped enumeration, or floating-point | ||||
| 4576 | // type, it is converted to the enumeration type via its underlying type. | ||||
| 4577 | // There is no overlap possible between these two cases (except when the | ||||
| 4578 | // source value is already of the destination type), and the first | ||||
| 4579 | // case is handled by the general case for single-element lists below. | ||||
| 4580 | ImplicitConversionSequence ICS; | ||||
| 4581 | ICS.setStandard(); | ||||
| 4582 | ICS.Standard.setAsIdentityConversion(); | ||||
| 4583 | if (!E->isPRValue()) | ||||
| 4584 | ICS.Standard.First = ICK_Lvalue_To_Rvalue; | ||||
| 4585 | // If E is of a floating-point type, then the conversion is ill-formed | ||||
| 4586 | // due to narrowing, but go through the motions in order to produce the | ||||
| 4587 | // right diagnostic. | ||||
| 4588 | ICS.Standard.Second = E->getType()->isFloatingType() | ||||
| 4589 | ? ICK_Floating_Integral | ||||
| 4590 | : ICK_Integral_Conversion; | ||||
| 4591 | ICS.Standard.setFromType(E->getType()); | ||||
| 4592 | ICS.Standard.setToType(0, E->getType()); | ||||
| 4593 | ICS.Standard.setToType(1, DestType); | ||||
| 4594 | ICS.Standard.setToType(2, DestType); | ||||
| 4595 | Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2), | ||||
| 4596 | /*TopLevelOfInitList*/true); | ||||
| 4597 | Sequence.RewrapReferenceInitList(Entity.getType(), InitList); | ||||
| 4598 | return; | ||||
| 4599 | } | ||||
| 4600 | |||||
| 4601 | // - Otherwise, if the initializer list has a single element of type E | ||||
| 4602 | // [...references are handled above...], the object or reference is | ||||
| 4603 | // initialized from that element (by copy-initialization for | ||||
| 4604 | // copy-list-initialization, or by direct-initialization for | ||||
| 4605 | // direct-list-initialization); if a narrowing conversion is required | ||||
| 4606 | // to convert the element to T, the program is ill-formed. | ||||
| 4607 | // | ||||
| 4608 | // Per core-24034, this is direct-initialization if we were performing | ||||
| 4609 | // direct-list-initialization and copy-initialization otherwise. | ||||
| 4610 | // We can't use InitListChecker for this, because it always performs | ||||
| 4611 | // copy-initialization. This only matters if we might use an 'explicit' | ||||
| 4612 | // conversion operator, or for the special case conversion of nullptr_t to | ||||
| 4613 | // bool, so we only need to handle those cases. | ||||
| 4614 | // | ||||
| 4615 | // FIXME: Why not do this in all cases? | ||||
| 4616 | Expr *Init = InitList->getInit(0); | ||||
| 4617 | if (Init->getType()->isRecordType() || | ||||
| 4618 | (Init->getType()->isNullPtrType() && DestType->isBooleanType())) { | ||||
| 4619 | InitializationKind SubKind = | ||||
| 4620 | Kind.getKind() == InitializationKind::IK_DirectList | ||||
| 4621 | ? InitializationKind::CreateDirect(Kind.getLocation(), | ||||
| 4622 | InitList->getLBraceLoc(), | ||||
| 4623 | InitList->getRBraceLoc()) | ||||
| 4624 | : Kind; | ||||
| 4625 | Expr *SubInit[1] = { Init }; | ||||
| 4626 | Sequence.InitializeFrom(S, Entity, SubKind, SubInit, | ||||
| 4627 | /*TopLevelOfInitList*/true, | ||||
| 4628 | TreatUnavailableAsInvalid); | ||||
| 4629 | if (Sequence) | ||||
| 4630 | Sequence.RewrapReferenceInitList(Entity.getType(), InitList); | ||||
| 4631 | return; | ||||
| 4632 | } | ||||
| 4633 | } | ||||
| 4634 | |||||
| 4635 | InitListChecker CheckInitList(S, Entity, InitList, | ||||
| 4636 | DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid); | ||||
| 4637 | if (CheckInitList.HadError()) { | ||||
| 4638 | Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed); | ||||
| 4639 | return; | ||||
| 4640 | } | ||||
| 4641 | |||||
| 4642 | // Add the list initialization step with the built init list. | ||||
| 4643 | Sequence.AddListInitializationStep(DestType); | ||||
| 4644 | } | ||||
| 4645 | |||||
| 4646 | /// Try a reference initialization that involves calling a conversion | ||||
| 4647 | /// function. | ||||
| 4648 | static OverloadingResult TryRefInitWithConversionFunction( | ||||
| 4649 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, | ||||
| 4650 | Expr *Initializer, bool AllowRValues, bool IsLValueRef, | ||||
| 4651 | InitializationSequence &Sequence) { | ||||
| 4652 | QualType DestType = Entity.getType(); | ||||
| 4653 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); | ||||
| 4654 | QualType T1 = cv1T1.getUnqualifiedType(); | ||||
| 4655 | QualType cv2T2 = Initializer->getType(); | ||||
| 4656 | QualType T2 = cv2T2.getUnqualifiedType(); | ||||
| 4657 | |||||
| 4658 | 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", 4659, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 4659 | "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", 4659, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 4660 | |||||
| 4661 | // Build the candidate set directly in the initialization sequence | ||||
| 4662 | // structure, so that it will persist if we fail. | ||||
| 4663 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); | ||||
| 4664 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); | ||||
| 4665 | |||||
| 4666 | // Determine whether we are allowed to call explicit conversion operators. | ||||
| 4667 | // Note that none of [over.match.copy], [over.match.conv], nor | ||||
| 4668 | // [over.match.ref] permit an explicit constructor to be chosen when | ||||
| 4669 | // initializing a reference, not even for direct-initialization. | ||||
| 4670 | bool AllowExplicitCtors = false; | ||||
| 4671 | bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding(); | ||||
| 4672 | |||||
| 4673 | const RecordType *T1RecordType = nullptr; | ||||
| 4674 | if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) && | ||||
| 4675 | S.isCompleteType(Kind.getLocation(), T1)) { | ||||
| 4676 | // The type we're converting to is a class type. Enumerate its constructors | ||||
| 4677 | // to see if there is a suitable conversion. | ||||
| 4678 | CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); | ||||
| 4679 | |||||
| 4680 | for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) { | ||||
| 4681 | auto Info = getConstructorInfo(D); | ||||
| 4682 | if (!Info.Constructor) | ||||
| 4683 | continue; | ||||
| 4684 | |||||
| 4685 | if (!Info.Constructor->isInvalidDecl() && | ||||
| 4686 | Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { | ||||
| 4687 | if (Info.ConstructorTmpl) | ||||
| 4688 | S.AddTemplateOverloadCandidate( | ||||
| 4689 | Info.ConstructorTmpl, Info.FoundDecl, | ||||
| 4690 | /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, | ||||
| 4691 | /*SuppressUserConversions=*/true, | ||||
| 4692 | /*PartialOverloading*/ false, AllowExplicitCtors); | ||||
| 4693 | else | ||||
| 4694 | S.AddOverloadCandidate( | ||||
| 4695 | Info.Constructor, Info.FoundDecl, Initializer, CandidateSet, | ||||
| 4696 | /*SuppressUserConversions=*/true, | ||||
| 4697 | /*PartialOverloading*/ false, AllowExplicitCtors); | ||||
| 4698 | } | ||||
| 4699 | } | ||||
| 4700 | } | ||||
| 4701 | if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) | ||||
| 4702 | return OR_No_Viable_Function; | ||||
| 4703 | |||||
| 4704 | const RecordType *T2RecordType = nullptr; | ||||
| 4705 | if ((T2RecordType = T2->getAs<RecordType>()) && | ||||
| 4706 | S.isCompleteType(Kind.getLocation(), T2)) { | ||||
| 4707 | // The type we're converting from is a class type, enumerate its conversion | ||||
| 4708 | // functions. | ||||
| 4709 | CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); | ||||
| 4710 | |||||
| 4711 | const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); | ||||
| 4712 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | ||||
| 4713 | NamedDecl *D = *I; | ||||
| 4714 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); | ||||
| 4715 | if (isa<UsingShadowDecl>(D)) | ||||
| 4716 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | ||||
| 4717 | |||||
| 4718 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); | ||||
| 4719 | CXXConversionDecl *Conv; | ||||
| 4720 | if (ConvTemplate) | ||||
| 4721 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | ||||
| 4722 | else | ||||
| 4723 | Conv = cast<CXXConversionDecl>(D); | ||||
| 4724 | |||||
| 4725 | // If the conversion function doesn't return a reference type, | ||||
| 4726 | // it can't be considered for this conversion unless we're allowed to | ||||
| 4727 | // consider rvalues. | ||||
| 4728 | // FIXME: Do we need to make sure that we only consider conversion | ||||
| 4729 | // candidates with reference-compatible results? That might be needed to | ||||
| 4730 | // break recursion. | ||||
| 4731 | if ((AllowRValues || | ||||
| 4732 | Conv->getConversionType()->isLValueReferenceType())) { | ||||
| 4733 | if (ConvTemplate) | ||||
| 4734 | S.AddTemplateConversionCandidate( | ||||
| 4735 | ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, | ||||
| 4736 | CandidateSet, | ||||
| 4737 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs); | ||||
| 4738 | else | ||||
| 4739 | S.AddConversionCandidate( | ||||
| 4740 | Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet, | ||||
| 4741 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs); | ||||
| 4742 | } | ||||
| 4743 | } | ||||
| 4744 | } | ||||
| 4745 | if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) | ||||
| 4746 | return OR_No_Viable_Function; | ||||
| 4747 | |||||
| 4748 | SourceLocation DeclLoc = Initializer->getBeginLoc(); | ||||
| 4749 | |||||
| 4750 | // Perform overload resolution. If it fails, return the failed result. | ||||
| 4751 | OverloadCandidateSet::iterator Best; | ||||
| 4752 | if (OverloadingResult Result | ||||
| 4753 | = CandidateSet.BestViableFunction(S, DeclLoc, Best)) | ||||
| 4754 | return Result; | ||||
| 4755 | |||||
| 4756 | FunctionDecl *Function = Best->Function; | ||||
| 4757 | // This is the overload that will be used for this initialization step if we | ||||
| 4758 | // use this initialization. Mark it as referenced. | ||||
| 4759 | Function->setReferenced(); | ||||
| 4760 | |||||
| 4761 | // Compute the returned type and value kind of the conversion. | ||||
| 4762 | QualType cv3T3; | ||||
| 4763 | if (isa<CXXConversionDecl>(Function)) | ||||
| 4764 | cv3T3 = Function->getReturnType(); | ||||
| 4765 | else | ||||
| 4766 | cv3T3 = T1; | ||||
| 4767 | |||||
| 4768 | ExprValueKind VK = VK_PRValue; | ||||
| 4769 | if (cv3T3->isLValueReferenceType()) | ||||
| 4770 | VK = VK_LValue; | ||||
| 4771 | else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>()) | ||||
| 4772 | VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; | ||||
| 4773 | cv3T3 = cv3T3.getNonLValueExprType(S.Context); | ||||
| 4774 | |||||
| 4775 | // Add the user-defined conversion step. | ||||
| 4776 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | ||||
| 4777 | Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3, | ||||
| 4778 | HadMultipleCandidates); | ||||
| 4779 | |||||
| 4780 | // Determine whether we'll need to perform derived-to-base adjustments or | ||||
| 4781 | // other conversions. | ||||
| 4782 | Sema::ReferenceConversions RefConv; | ||||
| 4783 | Sema::ReferenceCompareResult NewRefRelationship = | ||||
| 4784 | S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv); | ||||
| 4785 | |||||
| 4786 | // Add the final conversion sequence, if necessary. | ||||
| 4787 | if (NewRefRelationship == Sema::Ref_Incompatible) { | ||||
| 4788 | 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", 4789, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 4789 | "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", 4789, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 4790 | |||||
| 4791 | ImplicitConversionSequence ICS; | ||||
| 4792 | ICS.setStandard(); | ||||
| 4793 | ICS.Standard = Best->FinalConversion; | ||||
| 4794 | Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2)); | ||||
| 4795 | |||||
| 4796 | // Every implicit conversion results in a prvalue, except for a glvalue | ||||
| 4797 | // derived-to-base conversion, which we handle below. | ||||
| 4798 | cv3T3 = ICS.Standard.getToType(2); | ||||
| 4799 | VK = VK_PRValue; | ||||
| 4800 | } | ||||
| 4801 | |||||
| 4802 | // If the converted initializer is a prvalue, its type T4 is adjusted to | ||||
| 4803 | // type "cv1 T4" and the temporary materialization conversion is applied. | ||||
| 4804 | // | ||||
| 4805 | // We adjust the cv-qualifications to match the reference regardless of | ||||
| 4806 | // whether we have a prvalue so that the AST records the change. In this | ||||
| 4807 | // case, T4 is "cv3 T3". | ||||
| 4808 | QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers()); | ||||
| 4809 | if (cv1T4.getQualifiers() != cv3T3.getQualifiers()) | ||||
| 4810 | Sequence.AddQualificationConversionStep(cv1T4, VK); | ||||
| 4811 | Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue); | ||||
| 4812 | VK = IsLValueRef ? VK_LValue : VK_XValue; | ||||
| 4813 | |||||
| 4814 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) | ||||
| 4815 | Sequence.AddDerivedToBaseCastStep(cv1T1, VK); | ||||
| 4816 | else if (RefConv & Sema::ReferenceConversions::ObjC) | ||||
| 4817 | Sequence.AddObjCObjectConversionStep(cv1T1); | ||||
| 4818 | else if (RefConv & Sema::ReferenceConversions::Function) | ||||
| 4819 | Sequence.AddFunctionReferenceConversionStep(cv1T1); | ||||
| 4820 | else if (RefConv & Sema::ReferenceConversions::Qualification) { | ||||
| 4821 | if (!S.Context.hasSameType(cv1T4, cv1T1)) | ||||
| 4822 | Sequence.AddQualificationConversionStep(cv1T1, VK); | ||||
| 4823 | } | ||||
| 4824 | |||||
| 4825 | return OR_Success; | ||||
| 4826 | } | ||||
| 4827 | |||||
| 4828 | static void CheckCXX98CompatAccessibleCopy(Sema &S, | ||||
| 4829 | const InitializedEntity &Entity, | ||||
| 4830 | Expr *CurInitExpr); | ||||
| 4831 | |||||
| 4832 | /// Attempt reference initialization (C++0x [dcl.init.ref]) | ||||
| 4833 | static void TryReferenceInitialization(Sema &S, | ||||
| 4834 | const InitializedEntity &Entity, | ||||
| 4835 | const InitializationKind &Kind, | ||||
| 4836 | Expr *Initializer, | ||||
| 4837 | InitializationSequence &Sequence) { | ||||
| 4838 | QualType DestType = Entity.getType(); | ||||
| 4839 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); | ||||
| 4840 | Qualifiers T1Quals; | ||||
| 4841 | QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); | ||||
| 4842 | QualType cv2T2 = S.getCompletedType(Initializer); | ||||
| 4843 | Qualifiers T2Quals; | ||||
| 4844 | QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); | ||||
| 4845 | |||||
| 4846 | // If the initializer is the address of an overloaded function, try | ||||
| 4847 | // to resolve the overloaded function. If all goes well, T2 is the | ||||
| 4848 | // type of the resulting function. | ||||
| 4849 | if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, | ||||
| 4850 | T1, Sequence)) | ||||
| 4851 | return; | ||||
| 4852 | |||||
| 4853 | // Delegate everything else to a subfunction. | ||||
| 4854 | TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, | ||||
| 4855 | T1Quals, cv2T2, T2, T2Quals, Sequence); | ||||
| 4856 | } | ||||
| 4857 | |||||
| 4858 | /// Determine whether an expression is a non-referenceable glvalue (one to | ||||
| 4859 | /// which a reference can never bind). Attempting to bind a reference to | ||||
| 4860 | /// such a glvalue will always create a temporary. | ||||
| 4861 | static bool isNonReferenceableGLValue(Expr *E) { | ||||
| 4862 | return E->refersToBitField() || E->refersToVectorElement() || | ||||
| 4863 | E->refersToMatrixElement(); | ||||
| 4864 | } | ||||
| 4865 | |||||
| 4866 | /// Reference initialization without resolving overloaded functions. | ||||
| 4867 | /// | ||||
| 4868 | /// We also can get here in C if we call a builtin which is declared as | ||||
| 4869 | /// a function with a parameter of reference type (such as __builtin_va_end()). | ||||
| 4870 | static void TryReferenceInitializationCore(Sema &S, | ||||
| 4871 | const InitializedEntity &Entity, | ||||
| 4872 | const InitializationKind &Kind, | ||||
| 4873 | Expr *Initializer, | ||||
| 4874 | QualType cv1T1, QualType T1, | ||||
| 4875 | Qualifiers T1Quals, | ||||
| 4876 | QualType cv2T2, QualType T2, | ||||
| 4877 | Qualifiers T2Quals, | ||||
| 4878 | InitializationSequence &Sequence) { | ||||
| 4879 | QualType DestType = Entity.getType(); | ||||
| 4880 | SourceLocation DeclLoc = Initializer->getBeginLoc(); | ||||
| 4881 | |||||
| 4882 | // Compute some basic properties of the types and the initializer. | ||||
| 4883 | bool isLValueRef = DestType->isLValueReferenceType(); | ||||
| 4884 | bool isRValueRef = !isLValueRef; | ||||
| 4885 | Expr::Classification InitCategory = Initializer->Classify(S.Context); | ||||
| 4886 | |||||
| 4887 | Sema::ReferenceConversions RefConv; | ||||
| 4888 | Sema::ReferenceCompareResult RefRelationship = | ||||
| 4889 | S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv); | ||||
| 4890 | |||||
| 4891 | // C++0x [dcl.init.ref]p5: | ||||
| 4892 | // A reference to type "cv1 T1" is initialized by an expression of type | ||||
| 4893 | // "cv2 T2" as follows: | ||||
| 4894 | // | ||||
| 4895 | // - If the reference is an lvalue reference and the initializer | ||||
| 4896 | // expression | ||||
| 4897 | // Note the analogous bullet points for rvalue refs to functions. Because | ||||
| 4898 | // there are no function rvalues in C++, rvalue refs to functions are treated | ||||
| 4899 | // like lvalue refs. | ||||
| 4900 | OverloadingResult ConvOvlResult = OR_Success; | ||||
| 4901 | bool T1Function = T1->isFunctionType(); | ||||
| 4902 | if (isLValueRef || T1Function) { | ||||
| 4903 | if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) && | ||||
| 4904 | (RefRelationship == Sema::Ref_Compatible || | ||||
| 4905 | (Kind.isCStyleOrFunctionalCast() && | ||||
| 4906 | RefRelationship == Sema::Ref_Related))) { | ||||
| 4907 | // - is an lvalue (but is not a bit-field), and "cv1 T1" is | ||||
| 4908 | // reference-compatible with "cv2 T2," or | ||||
| 4909 | if (RefConv & (Sema::ReferenceConversions::DerivedToBase | | ||||
| 4910 | Sema::ReferenceConversions::ObjC)) { | ||||
| 4911 | // If we're converting the pointee, add any qualifiers first; | ||||
| 4912 | // these qualifiers must all be top-level, so just convert to "cv1 T2". | ||||
| 4913 | if (RefConv & (Sema::ReferenceConversions::Qualification)) | ||||
| 4914 | Sequence.AddQualificationConversionStep( | ||||
| 4915 | S.Context.getQualifiedType(T2, T1Quals), | ||||
| 4916 | Initializer->getValueKind()); | ||||
| 4917 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) | ||||
| 4918 | Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue); | ||||
| 4919 | else | ||||
| 4920 | Sequence.AddObjCObjectConversionStep(cv1T1); | ||||
| 4921 | } else if (RefConv & Sema::ReferenceConversions::Qualification) { | ||||
| 4922 | // Perform a (possibly multi-level) qualification conversion. | ||||
| 4923 | Sequence.AddQualificationConversionStep(cv1T1, | ||||
| 4924 | Initializer->getValueKind()); | ||||
| 4925 | } else if (RefConv & Sema::ReferenceConversions::Function) { | ||||
| 4926 | Sequence.AddFunctionReferenceConversionStep(cv1T1); | ||||
| 4927 | } | ||||
| 4928 | |||||
| 4929 | // We only create a temporary here when binding a reference to a | ||||
| 4930 | // bit-field or vector element. Those cases are't supposed to be | ||||
| 4931 | // handled by this bullet, but the outcome is the same either way. | ||||
| 4932 | Sequence.AddReferenceBindingStep(cv1T1, false); | ||||
| 4933 | return; | ||||
| 4934 | } | ||||
| 4935 | |||||
| 4936 | // - has a class type (i.e., T2 is a class type), where T1 is not | ||||
| 4937 | // reference-related to T2, and can be implicitly converted to an | ||||
| 4938 | // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible | ||||
| 4939 | // with "cv3 T3" (this conversion is selected by enumerating the | ||||
| 4940 | // applicable conversion functions (13.3.1.6) and choosing the best | ||||
| 4941 | // one through overload resolution (13.3)), | ||||
| 4942 | // If we have an rvalue ref to function type here, the rhs must be | ||||
| 4943 | // an rvalue. DR1287 removed the "implicitly" here. | ||||
| 4944 | if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && | ||||
| 4945 | (isLValueRef || InitCategory.isRValue())) { | ||||
| 4946 | if (S.getLangOpts().CPlusPlus) { | ||||
| 4947 | // Try conversion functions only for C++. | ||||
| 4948 | ConvOvlResult = TryRefInitWithConversionFunction( | ||||
| 4949 | S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef, | ||||
| 4950 | /*IsLValueRef*/ isLValueRef, Sequence); | ||||
| 4951 | if (ConvOvlResult == OR_Success) | ||||
| 4952 | return; | ||||
| 4953 | if (ConvOvlResult != OR_No_Viable_Function) | ||||
| 4954 | Sequence.SetOverloadFailure( | ||||
| 4955 | InitializationSequence::FK_ReferenceInitOverloadFailed, | ||||
| 4956 | ConvOvlResult); | ||||
| 4957 | } else { | ||||
| 4958 | ConvOvlResult = OR_No_Viable_Function; | ||||
| 4959 | } | ||||
| 4960 | } | ||||
| 4961 | } | ||||
| 4962 | |||||
| 4963 | // - Otherwise, the reference shall be an lvalue reference to a | ||||
| 4964 | // non-volatile const type (i.e., cv1 shall be const), or the reference | ||||
| 4965 | // shall be an rvalue reference. | ||||
| 4966 | // For address spaces, we interpret this to mean that an addr space | ||||
| 4967 | // of a reference "cv1 T1" is a superset of addr space of "cv2 T2". | ||||
| 4968 | if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() && | ||||
| 4969 | T1Quals.isAddressSpaceSupersetOf(T2Quals))) { | ||||
| 4970 | if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) | ||||
| 4971 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); | ||||
| 4972 | else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) | ||||
| 4973 | Sequence.SetOverloadFailure( | ||||
| 4974 | InitializationSequence::FK_ReferenceInitOverloadFailed, | ||||
| 4975 | ConvOvlResult); | ||||
| 4976 | else if (!InitCategory.isLValue()) | ||||
| 4977 | Sequence.SetFailed( | ||||
| 4978 | T1Quals.isAddressSpaceSupersetOf(T2Quals) | ||||
| 4979 | ? InitializationSequence:: | ||||
| 4980 | FK_NonConstLValueReferenceBindingToTemporary | ||||
| 4981 | : InitializationSequence::FK_ReferenceInitDropsQualifiers); | ||||
| 4982 | else { | ||||
| 4983 | InitializationSequence::FailureKind FK; | ||||
| 4984 | switch (RefRelationship) { | ||||
| 4985 | case Sema::Ref_Compatible: | ||||
| 4986 | if (Initializer->refersToBitField()) | ||||
| 4987 | FK = InitializationSequence:: | ||||
| 4988 | FK_NonConstLValueReferenceBindingToBitfield; | ||||
| 4989 | else if (Initializer->refersToVectorElement()) | ||||
| 4990 | FK = InitializationSequence:: | ||||
| 4991 | FK_NonConstLValueReferenceBindingToVectorElement; | ||||
| 4992 | else if (Initializer->refersToMatrixElement()) | ||||
| 4993 | FK = InitializationSequence:: | ||||
| 4994 | FK_NonConstLValueReferenceBindingToMatrixElement; | ||||
| 4995 | else | ||||
| 4996 | llvm_unreachable("unexpected kind of compatible initializer")::llvm::llvm_unreachable_internal("unexpected kind of compatible initializer" , "clang/lib/Sema/SemaInit.cpp", 4996); | ||||
| 4997 | break; | ||||
| 4998 | case Sema::Ref_Related: | ||||
| 4999 | FK = InitializationSequence::FK_ReferenceInitDropsQualifiers; | ||||
| 5000 | break; | ||||
| 5001 | case Sema::Ref_Incompatible: | ||||
| 5002 | FK = InitializationSequence:: | ||||
| 5003 | FK_NonConstLValueReferenceBindingToUnrelated; | ||||
| 5004 | break; | ||||
| 5005 | } | ||||
| 5006 | Sequence.SetFailed(FK); | ||||
| 5007 | } | ||||
| 5008 | return; | ||||
| 5009 | } | ||||
| 5010 | |||||
| 5011 | // - If the initializer expression | ||||
| 5012 | // - is an | ||||
| 5013 | // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or | ||||
| 5014 | // [1z] rvalue (but not a bit-field) or | ||||
| 5015 | // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2" | ||||
| 5016 | // | ||||
| 5017 | // Note: functions are handled above and below rather than here... | ||||
| 5018 | if (!T1Function && | ||||
| 5019 | (RefRelationship == Sema::Ref_Compatible || | ||||
| 5020 | (Kind.isCStyleOrFunctionalCast() && | ||||
| 5021 | RefRelationship == Sema::Ref_Related)) && | ||||
| 5022 | ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) || | ||||
| 5023 | (InitCategory.isPRValue() && | ||||
| 5024 | (S.getLangOpts().CPlusPlus17 || T2->isRecordType() || | ||||
| 5025 | T2->isArrayType())))) { | ||||
| 5026 | ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue; | ||||
| 5027 | if (InitCategory.isPRValue() && T2->isRecordType()) { | ||||
| 5028 | // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the | ||||
| 5029 | // compiler the freedom to perform a copy here or bind to the | ||||
| 5030 | // object, while C++0x requires that we bind directly to the | ||||
| 5031 | // object. Hence, we always bind to the object without making an | ||||
| 5032 | // extra copy. However, in C++03 requires that we check for the | ||||
| 5033 | // presence of a suitable copy constructor: | ||||
| 5034 | // | ||||
| 5035 | // The constructor that would be used to make the copy shall | ||||
| 5036 | // be callable whether or not the copy is actually done. | ||||
| 5037 | if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt) | ||||
| 5038 | Sequence.AddExtraneousCopyToTemporary(cv2T2); | ||||
| 5039 | else if (S.getLangOpts().CPlusPlus11) | ||||
| 5040 | CheckCXX98CompatAccessibleCopy(S, Entity, Initializer); | ||||
| 5041 | } | ||||
| 5042 | |||||
| 5043 | // C++1z [dcl.init.ref]/5.2.1.2: | ||||
| 5044 | // If the converted initializer is a prvalue, its type T4 is adjusted | ||||
| 5045 | // to type "cv1 T4" and the temporary materialization conversion is | ||||
| 5046 | // applied. | ||||
| 5047 | // Postpone address space conversions to after the temporary materialization | ||||
| 5048 | // conversion to allow creating temporaries in the alloca address space. | ||||
| 5049 | auto T1QualsIgnoreAS = T1Quals; | ||||
| 5050 | auto T2QualsIgnoreAS = T2Quals; | ||||
| 5051 | if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { | ||||
| 5052 | T1QualsIgnoreAS.removeAddressSpace(); | ||||
| 5053 | T2QualsIgnoreAS.removeAddressSpace(); | ||||
| 5054 | } | ||||
| 5055 | QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS); | ||||
| 5056 | if (T1QualsIgnoreAS != T2QualsIgnoreAS) | ||||
| 5057 | Sequence.AddQualificationConversionStep(cv1T4, ValueKind); | ||||
| 5058 | Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue); | ||||
| 5059 | ValueKind = isLValueRef ? VK_LValue : VK_XValue; | ||||
| 5060 | // Add addr space conversion if required. | ||||
| 5061 | if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { | ||||
| 5062 | auto T4Quals = cv1T4.getQualifiers(); | ||||
| 5063 | T4Quals.addAddressSpace(T1Quals.getAddressSpace()); | ||||
| 5064 | QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals); | ||||
| 5065 | Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind); | ||||
| 5066 | cv1T4 = cv1T4WithAS; | ||||
| 5067 | } | ||||
| 5068 | |||||
| 5069 | // In any case, the reference is bound to the resulting glvalue (or to | ||||
| 5070 | // an appropriate base class subobject). | ||||
| 5071 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) | ||||
| 5072 | Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind); | ||||
| 5073 | else if (RefConv & Sema::ReferenceConversions::ObjC) | ||||
| 5074 | Sequence.AddObjCObjectConversionStep(cv1T1); | ||||
| 5075 | else if (RefConv & Sema::ReferenceConversions::Qualification) { | ||||
| 5076 | if (!S.Context.hasSameType(cv1T4, cv1T1)) | ||||
| 5077 | Sequence.AddQualificationConversionStep(cv1T1, ValueKind); | ||||
| 5078 | } | ||||
| 5079 | return; | ||||
| 5080 | } | ||||
| 5081 | |||||
| 5082 | // - has a class type (i.e., T2 is a class type), where T1 is not | ||||
| 5083 | // reference-related to T2, and can be implicitly converted to an | ||||
| 5084 | // xvalue, class prvalue, or function lvalue of type "cv3 T3", | ||||
| 5085 | // where "cv1 T1" is reference-compatible with "cv3 T3", | ||||
| 5086 | // | ||||
| 5087 | // DR1287 removes the "implicitly" here. | ||||
| 5088 | if (T2->isRecordType()) { | ||||
| 5089 | if (RefRelationship == Sema::Ref_Incompatible) { | ||||
| 5090 | ConvOvlResult = TryRefInitWithConversionFunction( | ||||
| 5091 | S, Entity, Kind, Initializer, /*AllowRValues*/ true, | ||||
| 5092 | /*IsLValueRef*/ isLValueRef, Sequence); | ||||
| 5093 | if (ConvOvlResult) | ||||
| 5094 | Sequence.SetOverloadFailure( | ||||
| 5095 | InitializationSequence::FK_ReferenceInitOverloadFailed, | ||||
| 5096 | ConvOvlResult); | ||||
| 5097 | |||||
| 5098 | return; | ||||
| 5099 | } | ||||
| 5100 | |||||
| 5101 | if (RefRelationship == Sema::Ref_Compatible && | ||||
| 5102 | isRValueRef && InitCategory.isLValue()) { | ||||
| 5103 | Sequence.SetFailed( | ||||
| 5104 | InitializationSequence::FK_RValueReferenceBindingToLValue); | ||||
| 5105 | return; | ||||
| 5106 | } | ||||
| 5107 | |||||
| 5108 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); | ||||
| 5109 | return; | ||||
| 5110 | } | ||||
| 5111 | |||||
| 5112 | // - Otherwise, a temporary of type "cv1 T1" is created and initialized | ||||
| 5113 | // from the initializer expression using the rules for a non-reference | ||||
| 5114 | // copy-initialization (8.5). The reference is then bound to the | ||||
| 5115 | // temporary. [...] | ||||
| 5116 | |||||
| 5117 | // Ignore address space of reference type at this point and perform address | ||||
| 5118 | // space conversion after the reference binding step. | ||||
| 5119 | QualType cv1T1IgnoreAS = | ||||
| 5120 | T1Quals.hasAddressSpace() | ||||
| 5121 | ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace()) | ||||
| 5122 | : cv1T1; | ||||
| 5123 | |||||
| 5124 | InitializedEntity TempEntity = | ||||
| 5125 | InitializedEntity::InitializeTemporary(cv1T1IgnoreAS); | ||||
| 5126 | |||||
| 5127 | // FIXME: Why do we use an implicit conversion here rather than trying | ||||
| 5128 | // copy-initialization? | ||||
| 5129 | ImplicitConversionSequence ICS | ||||
| 5130 | = S.TryImplicitConversion(Initializer, TempEntity.getType(), | ||||
| 5131 | /*SuppressUserConversions=*/false, | ||||
| 5132 | Sema::AllowedExplicit::None, | ||||
| 5133 | /*FIXME:InOverloadResolution=*/false, | ||||
| 5134 | /*CStyle=*/Kind.isCStyleOrFunctionalCast(), | ||||
| 5135 | /*AllowObjCWritebackConversion=*/false); | ||||
| 5136 | |||||
| 5137 | if (ICS.isBad()) { | ||||
| 5138 | // FIXME: Use the conversion function set stored in ICS to turn | ||||
| 5139 | // this into an overloading ambiguity diagnostic. However, we need | ||||
| 5140 | // to keep that set as an OverloadCandidateSet rather than as some | ||||
| 5141 | // other kind of set. | ||||
| 5142 | if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) | ||||
| 5143 | Sequence.SetOverloadFailure( | ||||
| 5144 | InitializationSequence::FK_ReferenceInitOverloadFailed, | ||||
| 5145 | ConvOvlResult); | ||||
| 5146 | else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) | ||||
| 5147 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); | ||||
| 5148 | else | ||||
| 5149 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); | ||||
| 5150 | return; | ||||
| 5151 | } else { | ||||
| 5152 | Sequence.AddConversionSequenceStep(ICS, TempEntity.getType()); | ||||
| 5153 | } | ||||
| 5154 | |||||
| 5155 | // [...] If T1 is reference-related to T2, cv1 must be the | ||||
| 5156 | // same cv-qualification as, or greater cv-qualification | ||||
| 5157 | // than, cv2; otherwise, the program is ill-formed. | ||||
| 5158 | unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); | ||||
| 5159 | unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); | ||||
| 5160 | if (RefRelationship == Sema::Ref_Related && | ||||
| 5161 | ((T1CVRQuals | T2CVRQuals) != T1CVRQuals || | ||||
| 5162 | !T1Quals.isAddressSpaceSupersetOf(T2Quals))) { | ||||
| 5163 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); | ||||
| 5164 | return; | ||||
| 5165 | } | ||||
| 5166 | |||||
| 5167 | // [...] If T1 is reference-related to T2 and the reference is an rvalue | ||||
| 5168 | // reference, the initializer expression shall not be an lvalue. | ||||
| 5169 | if (RefRelationship >= Sema::Ref_Related && !isLValueRef && | ||||
| 5170 | InitCategory.isLValue()) { | ||||
| 5171 | Sequence.SetFailed( | ||||
| 5172 | InitializationSequence::FK_RValueReferenceBindingToLValue); | ||||
| 5173 | return; | ||||
| 5174 | } | ||||
| 5175 | |||||
| 5176 | Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true); | ||||
| 5177 | |||||
| 5178 | if (T1Quals.hasAddressSpace()) { | ||||
| 5179 | if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(), | ||||
| 5180 | LangAS::Default)) { | ||||
| 5181 | Sequence.SetFailed( | ||||
| 5182 | InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary); | ||||
| 5183 | return; | ||||
| 5184 | } | ||||
| 5185 | Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue | ||||
| 5186 | : VK_XValue); | ||||
| 5187 | } | ||||
| 5188 | } | ||||
| 5189 | |||||
| 5190 | /// Attempt character array initialization from a string literal | ||||
| 5191 | /// (C++ [dcl.init.string], C99 6.7.8). | ||||
| 5192 | static void TryStringLiteralInitialization(Sema &S, | ||||
| 5193 | const InitializedEntity &Entity, | ||||
| 5194 | const InitializationKind &Kind, | ||||
| 5195 | Expr *Initializer, | ||||
| 5196 | InitializationSequence &Sequence) { | ||||
| 5197 | Sequence.AddStringInitStep(Entity.getType()); | ||||
| 5198 | } | ||||
| 5199 | |||||
| 5200 | /// Attempt value initialization (C++ [dcl.init]p7). | ||||
| 5201 | static void TryValueInitialization(Sema &S, | ||||
| 5202 | const InitializedEntity &Entity, | ||||
| 5203 | const InitializationKind &Kind, | ||||
| 5204 | InitializationSequence &Sequence, | ||||
| 5205 | InitListExpr *InitList) { | ||||
| 5206 | 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", 5207, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 5207 | "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", 5207, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 5208 | |||||
| 5209 | // C++98 [dcl.init]p5, C++11 [dcl.init]p7: | ||||
| 5210 | // | ||||
| 5211 | // To value-initialize an object of type T means: | ||||
| 5212 | QualType T = Entity.getType(); | ||||
| 5213 | |||||
| 5214 | // -- if T is an array type, then each element is value-initialized; | ||||
| 5215 | T = S.Context.getBaseElementType(T); | ||||
| 5216 | |||||
| 5217 | if (const RecordType *RT = T->getAs<RecordType>()) { | ||||
| 5218 | if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { | ||||
| 5219 | bool NeedZeroInitialization = true; | ||||
| 5220 | // C++98: | ||||
| 5221 | // -- if T is a class type (clause 9) with a user-declared constructor | ||||
| 5222 | // (12.1), then the default constructor for T is called (and the | ||||
| 5223 | // initialization is ill-formed if T has no accessible default | ||||
| 5224 | // constructor); | ||||
| 5225 | // C++11: | ||||
| 5226 | // -- if T is a class type (clause 9) with either no default constructor | ||||
| 5227 | // (12.1 [class.ctor]) or a default constructor that is user-provided | ||||
| 5228 | // or deleted, then the object is default-initialized; | ||||
| 5229 | // | ||||
| 5230 | // Note that the C++11 rule is the same as the C++98 rule if there are no | ||||
| 5231 | // defaulted or deleted constructors, so we just use it unconditionally. | ||||
| 5232 | CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl); | ||||
| 5233 | if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted()) | ||||
| 5234 | NeedZeroInitialization = false; | ||||
| 5235 | |||||
| 5236 | // -- if T is a (possibly cv-qualified) non-union class type without a | ||||
| 5237 | // user-provided or deleted default constructor, then the object is | ||||
| 5238 | // zero-initialized and, if T has a non-trivial default constructor, | ||||
| 5239 | // default-initialized; | ||||
| 5240 | // The 'non-union' here was removed by DR1502. The 'non-trivial default | ||||
| 5241 | // constructor' part was removed by DR1507. | ||||
| 5242 | if (NeedZeroInitialization) | ||||
| 5243 | Sequence.AddZeroInitializationStep(Entity.getType()); | ||||
| 5244 | |||||
| 5245 | // C++03: | ||||
| 5246 | // -- if T is a non-union class type without a user-declared constructor, | ||||
| 5247 | // then every non-static data member and base class component of T is | ||||
| 5248 | // value-initialized; | ||||
| 5249 | // [...] A program that calls for [...] value-initialization of an | ||||
| 5250 | // entity of reference type is ill-formed. | ||||
| 5251 | // | ||||
| 5252 | // C++11 doesn't need this handling, because value-initialization does not | ||||
| 5253 | // occur recursively there, and the implicit default constructor is | ||||
| 5254 | // defined as deleted in the problematic cases. | ||||
| 5255 | if (!S.getLangOpts().CPlusPlus11 && | ||||
| 5256 | ClassDecl->hasUninitializedReferenceMember()) { | ||||
| 5257 | Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference); | ||||
| 5258 | return; | ||||
| 5259 | } | ||||
| 5260 | |||||
| 5261 | // If this is list-value-initialization, pass the empty init list on when | ||||
| 5262 | // building the constructor call. This affects the semantics of a few | ||||
| 5263 | // things (such as whether an explicit default constructor can be called). | ||||
| 5264 | Expr *InitListAsExpr = InitList; | ||||
| 5265 | MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0); | ||||
| 5266 | bool InitListSyntax = InitList; | ||||
| 5267 | |||||
| 5268 | // FIXME: Instead of creating a CXXConstructExpr of array type here, | ||||
| 5269 | // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr. | ||||
| 5270 | return TryConstructorInitialization( | ||||
| 5271 | S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax); | ||||
| 5272 | } | ||||
| 5273 | } | ||||
| 5274 | |||||
| 5275 | Sequence.AddZeroInitializationStep(Entity.getType()); | ||||
| 5276 | } | ||||
| 5277 | |||||
| 5278 | /// Attempt default initialization (C++ [dcl.init]p6). | ||||
| 5279 | static void TryDefaultInitialization(Sema &S, | ||||
| 5280 | const InitializedEntity &Entity, | ||||
| 5281 | const InitializationKind &Kind, | ||||
| 5282 | InitializationSequence &Sequence) { | ||||
| 5283 | 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", 5283, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 5284 | |||||
| 5285 | // C++ [dcl.init]p6: | ||||
| 5286 | // To default-initialize an object of type T means: | ||||
| 5287 | // - if T is an array type, each element is default-initialized; | ||||
| 5288 | QualType DestType = S.Context.getBaseElementType(Entity.getType()); | ||||
| 5289 | |||||
| 5290 | // - if T is a (possibly cv-qualified) class type (Clause 9), the default | ||||
| 5291 | // constructor for T is called (and the initialization is ill-formed if | ||||
| 5292 | // T has no accessible default constructor); | ||||
| 5293 | if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) { | ||||
| 5294 | TryConstructorInitialization(S, Entity, Kind, std::nullopt, DestType, | ||||
| 5295 | Entity.getType(), Sequence); | ||||
| 5296 | return; | ||||
| 5297 | } | ||||
| 5298 | |||||
| 5299 | // - otherwise, no initialization is performed. | ||||
| 5300 | |||||
| 5301 | // If a program calls for the default initialization of an object of | ||||
| 5302 | // a const-qualified type T, T shall be a class type with a user-provided | ||||
| 5303 | // default constructor. | ||||
| 5304 | if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) { | ||||
| 5305 | if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) | ||||
| 5306 | Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); | ||||
| 5307 | return; | ||||
| 5308 | } | ||||
| 5309 | |||||
| 5310 | // If the destination type has a lifetime property, zero-initialize it. | ||||
| 5311 | if (DestType.getQualifiers().hasObjCLifetime()) { | ||||
| 5312 | Sequence.AddZeroInitializationStep(Entity.getType()); | ||||
| 5313 | return; | ||||
| 5314 | } | ||||
| 5315 | } | ||||
| 5316 | |||||
| 5317 | static void TryOrBuildParenListInitialization( | ||||
| 5318 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, | ||||
| 5319 | ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly, | ||||
| 5320 | ExprResult *Result = nullptr) { | ||||
| 5321 | unsigned EntityIndexToProcess = 0; | ||||
| 5322 | SmallVector<Expr *, 4> InitExprs; | ||||
| 5323 | QualType ResultType; | ||||
| 5324 | Expr *ArrayFiller = nullptr; | ||||
| 5325 | FieldDecl *InitializedFieldInUnion = nullptr; | ||||
| 5326 | |||||
| 5327 | auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity, | ||||
| 5328 | const InitializationKind &SubKind, | ||||
| 5329 | Expr *Arg, Expr **InitExpr = nullptr) { | ||||
| 5330 | InitializationSequence IS = [&]() { | ||||
| 5331 | if (Arg) | ||||
| 5332 | return InitializationSequence(S, SubEntity, SubKind, Arg); | ||||
| 5333 | return InitializationSequence(S, SubEntity, SubKind, std::nullopt); | ||||
| 5334 | }(); | ||||
| 5335 | |||||
| 5336 | if (IS.Failed()) { | ||||
| 5337 | if (!VerifyOnly) { | ||||
| 5338 | if (Arg) | ||||
| 5339 | IS.Diagnose(S, SubEntity, SubKind, Arg); | ||||
| 5340 | else | ||||
| 5341 | IS.Diagnose(S, SubEntity, SubKind, std::nullopt); | ||||
| 5342 | } else { | ||||
| 5343 | Sequence.SetFailed( | ||||
| 5344 | InitializationSequence::FK_ParenthesizedListInitFailed); | ||||
| 5345 | } | ||||
| 5346 | |||||
| 5347 | return false; | ||||
| 5348 | } | ||||
| 5349 | if (!VerifyOnly) { | ||||
| 5350 | ExprResult ER; | ||||
| 5351 | if (Arg) | ||||
| 5352 | ER = IS.Perform(S, SubEntity, SubKind, Arg); | ||||
| 5353 | else | ||||
| 5354 | ER = IS.Perform(S, SubEntity, SubKind, std::nullopt); | ||||
| 5355 | if (InitExpr) | ||||
| 5356 | *InitExpr = ER.get(); | ||||
| 5357 | else | ||||
| 5358 | InitExprs.push_back(ER.get()); | ||||
| 5359 | } | ||||
| 5360 | return true; | ||||
| 5361 | }; | ||||
| 5362 | |||||
| 5363 | if (const ArrayType *AT = | ||||
| 5364 | S.getASTContext().getAsArrayType(Entity.getType())) { | ||||
| 5365 | SmallVector<InitializedEntity, 4> ElementEntities; | ||||
| 5366 | uint64_t ArrayLength; | ||||
| 5367 | // C++ [dcl.init]p16.5 | ||||
| 5368 | // if the destination type is an array, the object is initialized as | ||||
| 5369 | // follows. Let x1, . . . , xk be the elements of the expression-list. If | ||||
| 5370 | // the destination type is an array of unknown bound, it is defined as | ||||
| 5371 | // having k elements. | ||||
| 5372 | if (const ConstantArrayType *CAT = | ||||
| 5373 | S.getASTContext().getAsConstantArrayType(Entity.getType())) { | ||||
| 5374 | ArrayLength = CAT->getSize().getZExtValue(); | ||||
| 5375 | ResultType = Entity.getType(); | ||||
| 5376 | } else if (const VariableArrayType *VAT = | ||||
| 5377 | S.getASTContext().getAsVariableArrayType(Entity.getType())) { | ||||
| 5378 | // Braced-initialization of variable array types is not allowed, even if | ||||
| 5379 | // the size is greater than or equal to the number of args, so we don't | ||||
| 5380 | // allow them to be initialized via parenthesized aggregate initialization | ||||
| 5381 | // either. | ||||
| 5382 | const Expr *SE = VAT->getSizeExpr(); | ||||
| 5383 | S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init) | ||||
| 5384 | << SE->getSourceRange(); | ||||
| 5385 | return; | ||||
| 5386 | } else { | ||||
| 5387 | assert(isa<IncompleteArrayType>(Entity.getType()))(static_cast <bool> (isa<IncompleteArrayType>(Entity .getType())) ? void (0) : __assert_fail ("isa<IncompleteArrayType>(Entity.getType())" , "clang/lib/Sema/SemaInit.cpp", 5387, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 5388 | ArrayLength = Args.size(); | ||||
| 5389 | } | ||||
| 5390 | EntityIndexToProcess = ArrayLength; | ||||
| 5391 | |||||
| 5392 | // ...the ith array element is copy-initialized with xi for each | ||||
| 5393 | // 1 <= i <= k | ||||
| 5394 | for (Expr *E : Args) { | ||||
| 5395 | InitializedEntity SubEntity = InitializedEntity::InitializeElement( | ||||
| 5396 | S.getASTContext(), EntityIndexToProcess, Entity); | ||||
| 5397 | InitializationKind SubKind = InitializationKind::CreateForInit( | ||||
| 5398 | E->getExprLoc(), /*isDirectInit=*/false, E); | ||||
| 5399 | if (!HandleInitializedEntity(SubEntity, SubKind, E)) | ||||
| 5400 | return; | ||||
| 5401 | } | ||||
| 5402 | // ...and value-initialized for each k < i <= n; | ||||
| 5403 | if (ArrayLength > Args.size()) { | ||||
| 5404 | InitializedEntity SubEntity = InitializedEntity::InitializeElement( | ||||
| 5405 | S.getASTContext(), Args.size(), Entity); | ||||
| 5406 | InitializationKind SubKind = InitializationKind::CreateValue( | ||||
| 5407 | Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true); | ||||
| 5408 | if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller)) | ||||
| 5409 | return; | ||||
| 5410 | } | ||||
| 5411 | |||||
| 5412 | if (ResultType.isNull()) { | ||||
| 5413 | ResultType = S.Context.getConstantArrayType( | ||||
| 5414 | AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength), | ||||
| 5415 | /*SizeExpr=*/nullptr, ArrayType::Normal, 0); | ||||
| 5416 | } | ||||
| 5417 | } else if (auto *RT = Entity.getType()->getAs<RecordType>()) { | ||||
| 5418 | bool IsUnion = RT->isUnionType(); | ||||
| 5419 | const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); | ||||
| 5420 | |||||
| 5421 | if (!IsUnion) { | ||||
| 5422 | for (const CXXBaseSpecifier &Base : RD->bases()) { | ||||
| 5423 | InitializedEntity SubEntity = InitializedEntity::InitializeBase( | ||||
| 5424 | S.getASTContext(), &Base, false, &Entity); | ||||
| 5425 | if (EntityIndexToProcess < Args.size()) { | ||||
| 5426 | // C++ [dcl.init]p16.6.2.2. | ||||
| 5427 | // ...the object is initialized is follows. Let e1, ..., en be the | ||||
| 5428 | // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be | ||||
| 5429 | // the elements of the expression-list...The element ei is | ||||
| 5430 | // copy-initialized with xi for 1 <= i <= k. | ||||
| 5431 | Expr *E = Args[EntityIndexToProcess]; | ||||
| 5432 | InitializationKind SubKind = InitializationKind::CreateForInit( | ||||
| 5433 | E->getExprLoc(), /*isDirectInit=*/false, E); | ||||
| 5434 | if (!HandleInitializedEntity(SubEntity, SubKind, E)) | ||||
| 5435 | return; | ||||
| 5436 | } else { | ||||
| 5437 | // We've processed all of the args, but there are still base classes | ||||
| 5438 | // that have to be initialized. | ||||
| 5439 | // C++ [dcl.init]p17.6.2.2 | ||||
| 5440 | // The remaining elements...otherwise are value initialzed | ||||
| 5441 | InitializationKind SubKind = InitializationKind::CreateValue( | ||||
| 5442 | Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), | ||||
| 5443 | /*IsImplicit=*/true); | ||||
| 5444 | if (!HandleInitializedEntity(SubEntity, SubKind, nullptr)) | ||||
| 5445 | return; | ||||
| 5446 | } | ||||
| 5447 | EntityIndexToProcess++; | ||||
| 5448 | } | ||||
| 5449 | } | ||||
| 5450 | |||||
| 5451 | for (FieldDecl *FD : RD->fields()) { | ||||
| 5452 | // Unnamed bitfields should not be initialized at all, either with an arg | ||||
| 5453 | // or by default. | ||||
| 5454 | if (FD->isUnnamedBitfield()) | ||||
| 5455 | continue; | ||||
| 5456 | |||||
| 5457 | InitializedEntity SubEntity = | ||||
| 5458 | InitializedEntity::InitializeMemberFromParenAggInit(FD); | ||||
| 5459 | |||||
| 5460 | if (EntityIndexToProcess < Args.size()) { | ||||
| 5461 | // ...The element ei is copy-initialized with xi for 1 <= i <= k. | ||||
| 5462 | Expr *E = Args[EntityIndexToProcess]; | ||||
| 5463 | |||||
| 5464 | // Incomplete array types indicate flexible array members. Do not allow | ||||
| 5465 | // paren list initializations of structs with these members, as GCC | ||||
| 5466 | // doesn't either. | ||||
| 5467 | if (FD->getType()->isIncompleteArrayType()) { | ||||
| 5468 | if (!VerifyOnly) { | ||||
| 5469 | S.Diag(E->getBeginLoc(), diag::err_flexible_array_init) | ||||
| 5470 | << SourceRange(E->getBeginLoc(), E->getEndLoc()); | ||||
| 5471 | S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD; | ||||
| 5472 | } | ||||
| 5473 | Sequence.SetFailed( | ||||
| 5474 | InitializationSequence::FK_ParenthesizedListInitFailed); | ||||
| 5475 | return; | ||||
| 5476 | } | ||||
| 5477 | |||||
| 5478 | InitializationKind SubKind = InitializationKind::CreateForInit( | ||||
| 5479 | E->getExprLoc(), /*isDirectInit=*/false, E); | ||||
| 5480 | if (!HandleInitializedEntity(SubEntity, SubKind, E)) | ||||
| 5481 | return; | ||||
| 5482 | |||||
| 5483 | // Unions should have only one initializer expression, so we bail out | ||||
| 5484 | // after processing the first field. If there are more initializers then | ||||
| 5485 | // it will be caught when we later check whether EntityIndexToProcess is | ||||
| 5486 | // less than Args.size(); | ||||
| 5487 | if (IsUnion) { | ||||
| 5488 | InitializedFieldInUnion = FD; | ||||
| 5489 | EntityIndexToProcess = 1; | ||||
| 5490 | break; | ||||
| 5491 | } | ||||
| 5492 | } else { | ||||
| 5493 | // We've processed all of the args, but there are still members that | ||||
| 5494 | // have to be initialized. | ||||
| 5495 | if (FD->hasInClassInitializer()) { | ||||
| 5496 | if (!VerifyOnly) { | ||||
| 5497 | // C++ [dcl.init]p16.6.2.2 | ||||
| 5498 | // The remaining elements are initialized with their default | ||||
| 5499 | // member initializers, if any | ||||
| 5500 | ExprResult DIE = S.BuildCXXDefaultInitExpr(FD->getLocation(), FD); | ||||
| 5501 | if (DIE.isInvalid()) | ||||
| 5502 | return; | ||||
| 5503 | S.checkInitializerLifetime(SubEntity, DIE.get()); | ||||
| 5504 | InitExprs.push_back(DIE.get()); | ||||
| 5505 | } | ||||
| 5506 | } else { | ||||
| 5507 | // C++ [dcl.init]p17.6.2.2 | ||||
| 5508 | // The remaining elements...otherwise are value initialzed | ||||
| 5509 | if (FD->getType()->isReferenceType()) { | ||||
| 5510 | Sequence.SetFailed( | ||||
| 5511 | InitializationSequence::FK_ParenthesizedListInitFailed); | ||||
| 5512 | if (!VerifyOnly) { | ||||
| 5513 | SourceRange SR = Kind.getParenOrBraceRange(); | ||||
| 5514 | S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized) | ||||
| 5515 | << FD->getType() << SR; | ||||
| 5516 | S.Diag(FD->getLocation(), diag::note_uninit_reference_member); | ||||
| 5517 | } | ||||
| 5518 | return; | ||||
| 5519 | } | ||||
| 5520 | InitializationKind SubKind = InitializationKind::CreateValue( | ||||
| 5521 | Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true); | ||||
| 5522 | if (!HandleInitializedEntity(SubEntity, SubKind, nullptr)) | ||||
| 5523 | return; | ||||
| 5524 | } | ||||
| 5525 | } | ||||
| 5526 | EntityIndexToProcess++; | ||||
| 5527 | } | ||||
| 5528 | ResultType = Entity.getType(); | ||||
| 5529 | } | ||||
| 5530 | |||||
| 5531 | // Not all of the args have been processed, so there must've been more args | ||||
| 5532 | // than were required to initialize the element. | ||||
| 5533 | if (EntityIndexToProcess < Args.size()) { | ||||
| 5534 | Sequence.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed); | ||||
| 5535 | if (!VerifyOnly) { | ||||
| 5536 | QualType T = Entity.getType(); | ||||
| 5537 | int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4; | ||||
| 5538 | SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(), | ||||
| 5539 | Args.back()->getEndLoc()); | ||||
| 5540 | S.Diag(Kind.getLocation(), diag::err_excess_initializers) | ||||
| 5541 | << InitKind << ExcessInitSR; | ||||
| 5542 | } | ||||
| 5543 | return; | ||||
| 5544 | } | ||||
| 5545 | |||||
| 5546 | if (VerifyOnly) { | ||||
| 5547 | Sequence.setSequenceKind(InitializationSequence::NormalSequence); | ||||
| 5548 | Sequence.AddParenthesizedListInitStep(Entity.getType()); | ||||
| 5549 | } else if (Result) { | ||||
| 5550 | SourceRange SR = Kind.getParenOrBraceRange(); | ||||
| 5551 | auto *CPLIE = CXXParenListInitExpr::Create( | ||||
| 5552 | S.getASTContext(), InitExprs, ResultType, Args.size(), | ||||
| 5553 | Kind.getLocation(), SR.getBegin(), SR.getEnd()); | ||||
| 5554 | if (ArrayFiller) | ||||
| 5555 | CPLIE->setArrayFiller(ArrayFiller); | ||||
| 5556 | if (InitializedFieldInUnion) | ||||
| 5557 | CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion); | ||||
| 5558 | *Result = CPLIE; | ||||
| 5559 | S.Diag(Kind.getLocation(), | ||||
| 5560 | diag::warn_cxx17_compat_aggregate_init_paren_list) | ||||
| 5561 | << Kind.getLocation() << SR << ResultType; | ||||
| 5562 | } | ||||
| 5563 | |||||
| 5564 | return; | ||||
| 5565 | } | ||||
| 5566 | |||||
| 5567 | /// Attempt a user-defined conversion between two types (C++ [dcl.init]), | ||||
| 5568 | /// which enumerates all conversion functions and performs overload resolution | ||||
| 5569 | /// to select the best. | ||||
| 5570 | static void TryUserDefinedConversion(Sema &S, | ||||
| 5571 | QualType DestType, | ||||
| 5572 | const InitializationKind &Kind, | ||||
| 5573 | Expr *Initializer, | ||||
| 5574 | InitializationSequence &Sequence, | ||||
| 5575 | bool TopLevelOfInitList) { | ||||
| 5576 | 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", 5576, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 5577 | QualType SourceType = Initializer->getType(); | ||||
| 5578 | 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", 5579, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 5579 | "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", 5579, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 5580 | |||||
| 5581 | // Build the candidate set directly in the initialization sequence | ||||
| 5582 | // structure, so that it will persist if we fail. | ||||
| 5583 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); | ||||
| 5584 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); | ||||
| 5585 | CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); | ||||
| 5586 | |||||
| 5587 | // Determine whether we are allowed to call explicit constructors or | ||||
| 5588 | // explicit conversion operators. | ||||
| 5589 | bool AllowExplicit = Kind.AllowExplicit(); | ||||
| 5590 | |||||
| 5591 | if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { | ||||
| 5592 | // The type we're converting to is a class type. Enumerate its constructors | ||||
| 5593 | // to see if there is a suitable conversion. | ||||
| 5594 | CXXRecordDecl *DestRecordDecl | ||||
| 5595 | = cast<CXXRecordDecl>(DestRecordType->getDecl()); | ||||
| 5596 | |||||
| 5597 | // Try to complete the type we're converting to. | ||||
| 5598 | if (S.isCompleteType(Kind.getLocation(), DestType)) { | ||||
| 5599 | for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) { | ||||
| 5600 | auto Info = getConstructorInfo(D); | ||||
| 5601 | if (!Info.Constructor) | ||||
| 5602 | continue; | ||||
| 5603 | |||||
| 5604 | if (!Info.Constructor->isInvalidDecl() && | ||||
| 5605 | Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { | ||||
| 5606 | if (Info.ConstructorTmpl) | ||||
| 5607 | S.AddTemplateOverloadCandidate( | ||||
| 5608 | Info.ConstructorTmpl, Info.FoundDecl, | ||||
| 5609 | /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, | ||||
| 5610 | /*SuppressUserConversions=*/true, | ||||
| 5611 | /*PartialOverloading*/ false, AllowExplicit); | ||||
| 5612 | else | ||||
| 5613 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, | ||||
| 5614 | Initializer, CandidateSet, | ||||
| 5615 | /*SuppressUserConversions=*/true, | ||||
| 5616 | /*PartialOverloading*/ false, AllowExplicit); | ||||
| 5617 | } | ||||
| 5618 | } | ||||
| 5619 | } | ||||
| 5620 | } | ||||
| 5621 | |||||
| 5622 | SourceLocation DeclLoc = Initializer->getBeginLoc(); | ||||
| 5623 | |||||
| 5624 | if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { | ||||
| 5625 | // The type we're converting from is a class type, enumerate its conversion | ||||
| 5626 | // functions. | ||||
| 5627 | |||||
| 5628 | // We can only enumerate the conversion functions for a complete type; if | ||||
| 5629 | // the type isn't complete, simply skip this step. | ||||
| 5630 | if (S.isCompleteType(DeclLoc, SourceType)) { | ||||
| 5631 | CXXRecordDecl *SourceRecordDecl | ||||
| 5632 | = cast<CXXRecordDecl>(SourceRecordType->getDecl()); | ||||
| 5633 | |||||
| 5634 | const auto &Conversions = | ||||
| 5635 | SourceRecordDecl->getVisibleConversionFunctions(); | ||||
| 5636 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | ||||
| 5637 | NamedDecl *D = *I; | ||||
| 5638 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); | ||||
| 5639 | if (isa<UsingShadowDecl>(D)) | ||||
| 5640 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | ||||
| 5641 | |||||
| 5642 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); | ||||
| 5643 | CXXConversionDecl *Conv; | ||||
| 5644 | if (ConvTemplate) | ||||
| 5645 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | ||||
| 5646 | else | ||||
| 5647 | Conv = cast<CXXConversionDecl>(D); | ||||
| 5648 | |||||
| 5649 | if (ConvTemplate) | ||||
| 5650 | S.AddTemplateConversionCandidate( | ||||
| 5651 | ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, | ||||
| 5652 | CandidateSet, AllowExplicit, AllowExplicit); | ||||
| 5653 | else | ||||
| 5654 | S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, | ||||
| 5655 | DestType, CandidateSet, AllowExplicit, | ||||
| 5656 | AllowExplicit); | ||||
| 5657 | } | ||||
| 5658 | } | ||||
| 5659 | } | ||||
| 5660 | |||||
| 5661 | // Perform overload resolution. If it fails, return the failed result. | ||||
| 5662 | OverloadCandidateSet::iterator Best; | ||||
| 5663 | if (OverloadingResult Result | ||||
| 5664 | = CandidateSet.BestViableFunction(S, DeclLoc, Best)) { | ||||
| 5665 | Sequence.SetOverloadFailure( | ||||
| 5666 | InitializationSequence::FK_UserConversionOverloadFailed, Result); | ||||
| 5667 | |||||
| 5668 | // [class.copy.elision]p3: | ||||
| 5669 | // In some copy-initialization contexts, a two-stage overload resolution | ||||
| 5670 | // is performed. | ||||
| 5671 | // If the first overload resolution selects a deleted function, we also | ||||
| 5672 | // need the initialization sequence to decide whether to perform the second | ||||
| 5673 | // overload resolution. | ||||
| 5674 | if (!(Result == OR_Deleted && | ||||
| 5675 | Kind.getKind() == InitializationKind::IK_Copy)) | ||||
| 5676 | return; | ||||
| 5677 | } | ||||
| 5678 | |||||
| 5679 | FunctionDecl *Function = Best->Function; | ||||
| 5680 | Function->setReferenced(); | ||||
| 5681 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | ||||
| 5682 | |||||
| 5683 | if (isa<CXXConstructorDecl>(Function)) { | ||||
| 5684 | // Add the user-defined conversion step. Any cv-qualification conversion is | ||||
| 5685 | // subsumed by the initialization. Per DR5, the created temporary is of the | ||||
| 5686 | // cv-unqualified type of the destination. | ||||
| 5687 | Sequence.AddUserConversionStep(Function, Best->FoundDecl, | ||||
| 5688 | DestType.getUnqualifiedType(), | ||||
| 5689 | HadMultipleCandidates); | ||||
| 5690 | |||||
| 5691 | // C++14 and before: | ||||
| 5692 | // - if the function is a constructor, the call initializes a temporary | ||||
| 5693 | // of the cv-unqualified version of the destination type. The [...] | ||||
| 5694 | // temporary [...] is then used to direct-initialize, according to the | ||||
| 5695 | // rules above, the object that is the destination of the | ||||
| 5696 | // copy-initialization. | ||||
| 5697 | // Note that this just performs a simple object copy from the temporary. | ||||
| 5698 | // | ||||
| 5699 | // C++17: | ||||
| 5700 | // - if the function is a constructor, the call is a prvalue of the | ||||
| 5701 | // cv-unqualified version of the destination type whose return object | ||||
| 5702 | // is initialized by the constructor. The call is used to | ||||
| 5703 | // direct-initialize, according to the rules above, the object that | ||||
| 5704 | // is the destination of the copy-initialization. | ||||
| 5705 | // Therefore we need to do nothing further. | ||||
| 5706 | // | ||||
| 5707 | // FIXME: Mark this copy as extraneous. | ||||
| 5708 | if (!S.getLangOpts().CPlusPlus17) | ||||
| 5709 | Sequence.AddFinalCopy(DestType); | ||||
| 5710 | else if (DestType.hasQualifiers()) | ||||
| 5711 | Sequence.AddQualificationConversionStep(DestType, VK_PRValue); | ||||
| 5712 | return; | ||||
| 5713 | } | ||||
| 5714 | |||||
| 5715 | // Add the user-defined conversion step that calls the conversion function. | ||||
| 5716 | QualType ConvType = Function->getCallResultType(); | ||||
| 5717 | Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType, | ||||
| 5718 | HadMultipleCandidates); | ||||
| 5719 | |||||
| 5720 | if (ConvType->getAs<RecordType>()) { | ||||
| 5721 | // The call is used to direct-initialize [...] the object that is the | ||||
| 5722 | // destination of the copy-initialization. | ||||
| 5723 | // | ||||
| 5724 | // In C++17, this does not call a constructor if we enter /17.6.1: | ||||
| 5725 | // - If the initializer expression is a prvalue and the cv-unqualified | ||||
| 5726 | // version of the source type is the same as the class of the | ||||
| 5727 | // destination [... do not make an extra copy] | ||||
| 5728 | // | ||||
| 5729 | // FIXME: Mark this copy as extraneous. | ||||
| 5730 | if (!S.getLangOpts().CPlusPlus17 || | ||||
| 5731 | Function->getReturnType()->isReferenceType() || | ||||
| 5732 | !S.Context.hasSameUnqualifiedType(ConvType, DestType)) | ||||
| 5733 | Sequence.AddFinalCopy(DestType); | ||||
| 5734 | else if (!S.Context.hasSameType(ConvType, DestType)) | ||||
| 5735 | Sequence.AddQualificationConversionStep(DestType, VK_PRValue); | ||||
| 5736 | return; | ||||
| 5737 | } | ||||
| 5738 | |||||
| 5739 | // If the conversion following the call to the conversion function | ||||
| 5740 | // is interesting, add it as a separate step. | ||||
| 5741 | if (Best->FinalConversion.First || Best->FinalConversion.Second || | ||||
| 5742 | Best->FinalConversion.Third) { | ||||
| 5743 | ImplicitConversionSequence ICS; | ||||
| 5744 | ICS.setStandard(); | ||||
| 5745 | ICS.Standard = Best->FinalConversion; | ||||
| 5746 | Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); | ||||
| 5747 | } | ||||
| 5748 | } | ||||
| 5749 | |||||
| 5750 | /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>, | ||||
| 5751 | /// a function with a pointer return type contains a 'return false;' statement. | ||||
| 5752 | /// In C++11, 'false' is not a null pointer, so this breaks the build of any | ||||
| 5753 | /// code using that header. | ||||
| 5754 | /// | ||||
| 5755 | /// Work around this by treating 'return false;' as zero-initializing the result | ||||
| 5756 | /// if it's used in a pointer-returning function in a system header. | ||||
| 5757 | static bool isLibstdcxxPointerReturnFalseHack(Sema &S, | ||||
| 5758 | const InitializedEntity &Entity, | ||||
| 5759 | const Expr *Init) { | ||||
| 5760 | return S.getLangOpts().CPlusPlus11 && | ||||
| 5761 | Entity.getKind() == InitializedEntity::EK_Result && | ||||
| 5762 | Entity.getType()->isPointerType() && | ||||
| 5763 | isa<CXXBoolLiteralExpr>(Init) && | ||||
| 5764 | !cast<CXXBoolLiteralExpr>(Init)->getValue() && | ||||
| 5765 | S.getSourceManager().isInSystemHeader(Init->getExprLoc()); | ||||
| 5766 | } | ||||
| 5767 | |||||
| 5768 | /// The non-zero enum values here are indexes into diagnostic alternatives. | ||||
| 5769 | enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; | ||||
| 5770 | |||||
| 5771 | /// Determines whether this expression is an acceptable ICR source. | ||||
| 5772 | static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, | ||||
| 5773 | bool isAddressOf, bool &isWeakAccess) { | ||||
| 5774 | // Skip parens. | ||||
| 5775 | e = e->IgnoreParens(); | ||||
| 5776 | |||||
| 5777 | // Skip address-of nodes. | ||||
| 5778 | if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { | ||||
| 5779 | if (op->getOpcode() == UO_AddrOf) | ||||
| 5780 | return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true, | ||||
| 5781 | isWeakAccess); | ||||
| 5782 | |||||
| 5783 | // Skip certain casts. | ||||
| 5784 | } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) { | ||||
| 5785 | switch (ce->getCastKind()) { | ||||
| 5786 | case CK_Dependent: | ||||
| 5787 | case CK_BitCast: | ||||
| 5788 | case CK_LValueBitCast: | ||||
| 5789 | case CK_NoOp: | ||||
| 5790 | return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess); | ||||
| 5791 | |||||
| 5792 | case CK_ArrayToPointerDecay: | ||||
| 5793 | return IIK_nonscalar; | ||||
| 5794 | |||||
| 5795 | case CK_NullToPointer: | ||||
| 5796 | return IIK_okay; | ||||
| 5797 | |||||
| 5798 | default: | ||||
| 5799 | break; | ||||
| 5800 | } | ||||
| 5801 | |||||
| 5802 | // If we have a declaration reference, it had better be a local variable. | ||||
| 5803 | } else if (isa<DeclRefExpr>(e)) { | ||||
| 5804 | // set isWeakAccess to true, to mean that there will be an implicit | ||||
| 5805 | // load which requires a cleanup. | ||||
| 5806 | if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak) | ||||
| 5807 | isWeakAccess = true; | ||||
| 5808 | |||||
| 5809 | if (!isAddressOf) return IIK_nonlocal; | ||||
| 5810 | |||||
| 5811 | VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl()); | ||||
| 5812 | if (!var) return IIK_nonlocal; | ||||
| 5813 | |||||
| 5814 | return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); | ||||
| 5815 | |||||
| 5816 | // If we have a conditional operator, check both sides. | ||||
| 5817 | } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) { | ||||
| 5818 | if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf, | ||||
| 5819 | isWeakAccess)) | ||||
| 5820 | return iik; | ||||
| 5821 | |||||
| 5822 | return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess); | ||||
| 5823 | |||||
| 5824 | // These are never scalar. | ||||
| 5825 | } else if (isa<ArraySubscriptExpr>(e)) { | ||||
| 5826 | return IIK_nonscalar; | ||||
| 5827 | |||||
| 5828 | // Otherwise, it needs to be a null pointer constant. | ||||
| 5829 | } else { | ||||
| 5830 | return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull) | ||||
| 5831 | ? IIK_okay : IIK_nonlocal); | ||||
| 5832 | } | ||||
| 5833 | |||||
| 5834 | return IIK_nonlocal; | ||||
| 5835 | } | ||||
| 5836 | |||||
| 5837 | /// Check whether the given expression is a valid operand for an | ||||
| 5838 | /// indirect copy/restore. | ||||
| 5839 | static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { | ||||
| 5840 | assert(src->isPRValue())(static_cast <bool> (src->isPRValue()) ? void (0) : __assert_fail ("src->isPRValue()", "clang/lib/Sema/SemaInit.cpp", 5840, __extension__ __PRETTY_FUNCTION__)); | ||||
| 5841 | bool isWeakAccess = false; | ||||
| 5842 | InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess); | ||||
| 5843 | // If isWeakAccess to true, there will be an implicit | ||||
| 5844 | // load which requires a cleanup. | ||||
| 5845 | if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess) | ||||
| 5846 | S.Cleanup.setExprNeedsCleanups(true); | ||||
| 5847 | |||||
| 5848 | if (iik == IIK_okay) return; | ||||
| 5849 | |||||
| 5850 | S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback) | ||||
| 5851 | << ((unsigned) iik - 1) // shift index into diagnostic explanations | ||||
| 5852 | << src->getSourceRange(); | ||||
| 5853 | } | ||||
| 5854 | |||||
| 5855 | /// Determine whether we have compatible array types for the | ||||
| 5856 | /// purposes of GNU by-copy array initialization. | ||||
| 5857 | static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, | ||||
| 5858 | const ArrayType *Source) { | ||||
| 5859 | // If the source and destination array types are equivalent, we're | ||||
| 5860 | // done. | ||||
| 5861 | if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0))) | ||||
| 5862 | return true; | ||||
| 5863 | |||||
| 5864 | // Make sure that the element types are the same. | ||||
| 5865 | if (!Context.hasSameType(Dest->getElementType(), Source->getElementType())) | ||||
| 5866 | return false; | ||||
| 5867 | |||||
| 5868 | // The only mismatch we allow is when the destination is an | ||||
| 5869 | // incomplete array type and the source is a constant array type. | ||||
| 5870 | return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); | ||||
| 5871 | } | ||||
| 5872 | |||||
| 5873 | static bool tryObjCWritebackConversion(Sema &S, | ||||
| 5874 | InitializationSequence &Sequence, | ||||
| 5875 | const InitializedEntity &Entity, | ||||
| 5876 | Expr *Initializer) { | ||||
| 5877 | bool ArrayDecay = false; | ||||
| 5878 | QualType ArgType = Initializer->getType(); | ||||
| 5879 | QualType ArgPointee; | ||||
| 5880 | if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) { | ||||
| 5881 | ArrayDecay = true; | ||||
| 5882 | ArgPointee = ArgArrayType->getElementType(); | ||||
| 5883 | ArgType = S.Context.getPointerType(ArgPointee); | ||||
| 5884 | } | ||||
| 5885 | |||||
| 5886 | // Handle write-back conversion. | ||||
| 5887 | QualType ConvertedArgType; | ||||
| 5888 | if (!S.isObjCWritebackConversion(ArgType, Entity.getType(), | ||||
| 5889 | ConvertedArgType)) | ||||
| 5890 | return false; | ||||
| 5891 | |||||
| 5892 | // We should copy unless we're passing to an argument explicitly | ||||
| 5893 | // marked 'out'. | ||||
| 5894 | bool ShouldCopy = true; | ||||
| 5895 | if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl())) | ||||
| 5896 | ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); | ||||
| 5897 | |||||
| 5898 | // Do we need an lvalue conversion? | ||||
| 5899 | if (ArrayDecay || Initializer->isGLValue()) { | ||||
| 5900 | ImplicitConversionSequence ICS; | ||||
| 5901 | ICS.setStandard(); | ||||
| 5902 | ICS.Standard.setAsIdentityConversion(); | ||||
| 5903 | |||||
| 5904 | QualType ResultType; | ||||
| 5905 | if (ArrayDecay) { | ||||
| 5906 | ICS.Standard.First = ICK_Array_To_Pointer; | ||||
| 5907 | ResultType = S.Context.getPointerType(ArgPointee); | ||||
| 5908 | } else { | ||||
| 5909 | ICS.Standard.First = ICK_Lvalue_To_Rvalue; | ||||
| 5910 | ResultType = Initializer->getType().getNonLValueExprType(S.Context); | ||||
| 5911 | } | ||||
| 5912 | |||||
| 5913 | Sequence.AddConversionSequenceStep(ICS, ResultType); | ||||
| 5914 | } | ||||
| 5915 | |||||
| 5916 | Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); | ||||
| 5917 | return true; | ||||
| 5918 | } | ||||
| 5919 | |||||
| 5920 | static bool TryOCLSamplerInitialization(Sema &S, | ||||
| 5921 | InitializationSequence &Sequence, | ||||
| 5922 | QualType DestType, | ||||
| 5923 | Expr *Initializer) { | ||||
| 5924 | if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() || | ||||
| 5925 | (!Initializer->isIntegerConstantExpr(S.Context) && | ||||
| 5926 | !Initializer->getType()->isSamplerT())) | ||||
| 5927 | return false; | ||||
| 5928 | |||||
| 5929 | Sequence.AddOCLSamplerInitStep(DestType); | ||||
| 5930 | return true; | ||||
| 5931 | } | ||||
| 5932 | |||||
| 5933 | static bool IsZeroInitializer(Expr *Initializer, Sema &S) { | ||||
| 5934 | return Initializer->isIntegerConstantExpr(S.getASTContext()) && | ||||
| 5935 | (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0); | ||||
| 5936 | } | ||||
| 5937 | |||||
| 5938 | static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, | ||||
| 5939 | InitializationSequence &Sequence, | ||||
| 5940 | QualType DestType, | ||||
| 5941 | Expr *Initializer) { | ||||
| 5942 | if (!S.getLangOpts().OpenCL) | ||||
| 5943 | return false; | ||||
| 5944 | |||||
| 5945 | // | ||||
| 5946 | // OpenCL 1.2 spec, s6.12.10 | ||||
| 5947 | // | ||||
| 5948 | // The event argument can also be used to associate the | ||||
| 5949 | // async_work_group_copy with a previous async copy allowing | ||||
| 5950 | // an event to be shared by multiple async copies; otherwise | ||||
| 5951 | // event should be zero. | ||||
| 5952 | // | ||||
| 5953 | if (DestType->isEventT() || DestType->isQueueT()) { | ||||
| 5954 | if (!IsZeroInitializer(Initializer, S)) | ||||
| 5955 | return false; | ||||
| 5956 | |||||
| 5957 | Sequence.AddOCLZeroOpaqueTypeStep(DestType); | ||||
| 5958 | return true; | ||||
| 5959 | } | ||||
| 5960 | |||||
| 5961 | // We should allow zero initialization for all types defined in the | ||||
| 5962 | // cl_intel_device_side_avc_motion_estimation extension, except | ||||
| 5963 | // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t. | ||||
| 5964 | if (S.getOpenCLOptions().isAvailableOption( | ||||
| 5965 | "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) && | ||||
| 5966 | DestType->isOCLIntelSubgroupAVCType()) { | ||||
| 5967 | if (DestType->isOCLIntelSubgroupAVCMcePayloadType() || | ||||
| 5968 | DestType->isOCLIntelSubgroupAVCMceResultType()) | ||||
| 5969 | return false; | ||||
| 5970 | if (!IsZeroInitializer(Initializer, S)) | ||||
| 5971 | return false; | ||||
| 5972 | |||||
| 5973 | Sequence.AddOCLZeroOpaqueTypeStep(DestType); | ||||
| 5974 | return true; | ||||
| 5975 | } | ||||
| 5976 | |||||
| 5977 | return false; | ||||
| 5978 | } | ||||
| 5979 | |||||
| 5980 | InitializationSequence::InitializationSequence( | ||||
| 5981 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, | ||||
| 5982 | MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid) | ||||
| 5983 | : FailedOverloadResult(OR_Success), | ||||
| 5984 | FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) { | ||||
| 5985 | InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList, | ||||
| 5986 | TreatUnavailableAsInvalid); | ||||
| 5987 | } | ||||
| 5988 | |||||
| 5989 | /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the | ||||
| 5990 | /// address of that function, this returns true. Otherwise, it returns false. | ||||
| 5991 | static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) { | ||||
| 5992 | auto *DRE = dyn_cast<DeclRefExpr>(E); | ||||
| 5993 | if (!DRE || !isa<FunctionDecl>(DRE->getDecl())) | ||||
| 5994 | return false; | ||||
| 5995 | |||||
| 5996 | return !S.checkAddressOfFunctionIsAvailable( | ||||
| 5997 | cast<FunctionDecl>(DRE->getDecl())); | ||||
| 5998 | } | ||||
| 5999 | |||||
| 6000 | /// Determine whether we can perform an elementwise array copy for this kind | ||||
| 6001 | /// of entity. | ||||
| 6002 | static bool canPerformArrayCopy(const InitializedEntity &Entity) { | ||||
| 6003 | switch (Entity.getKind()) { | ||||
| 6004 | case InitializedEntity::EK_LambdaCapture: | ||||
| 6005 | // C++ [expr.prim.lambda]p24: | ||||
| 6006 | // For array members, the array elements are direct-initialized in | ||||
| 6007 | // increasing subscript order. | ||||
| 6008 | return true; | ||||
| 6009 | |||||
| 6010 | case InitializedEntity::EK_Variable: | ||||
| 6011 | // C++ [dcl.decomp]p1: | ||||
| 6012 | // [...] each element is copy-initialized or direct-initialized from the | ||||
| 6013 | // corresponding element of the assignment-expression [...] | ||||
| 6014 | return isa<DecompositionDecl>(Entity.getDecl()); | ||||
| 6015 | |||||
| 6016 | case InitializedEntity::EK_Member: | ||||
| 6017 | // C++ [class.copy.ctor]p14: | ||||
| 6018 | // - if the member is an array, each element is direct-initialized with | ||||
| 6019 | // the corresponding subobject of x | ||||
| 6020 | return Entity.isImplicitMemberInitializer(); | ||||
| 6021 | |||||
| 6022 | case InitializedEntity::EK_ArrayElement: | ||||
| 6023 | // All the above cases are intended to apply recursively, even though none | ||||
| 6024 | // of them actually say that. | ||||
| 6025 | if (auto *E = Entity.getParent()) | ||||
| 6026 | return canPerformArrayCopy(*E); | ||||
| 6027 | break; | ||||
| 6028 | |||||
| 6029 | default: | ||||
| 6030 | break; | ||||
| 6031 | } | ||||
| 6032 | |||||
| 6033 | return false; | ||||
| 6034 | } | ||||
| 6035 | |||||
| 6036 | void InitializationSequence::InitializeFrom(Sema &S, | ||||
| 6037 | const InitializedEntity &Entity, | ||||
| 6038 | const InitializationKind &Kind, | ||||
| 6039 | MultiExprArg Args, | ||||
| 6040 | bool TopLevelOfInitList, | ||||
| 6041 | bool TreatUnavailableAsInvalid) { | ||||
| 6042 | ASTContext &Context = S.Context; | ||||
| 6043 | |||||
| 6044 | // Eliminate non-overload placeholder types in the arguments. We | ||||
| 6045 | // need to do this before checking whether types are dependent | ||||
| 6046 | // because lowering a pseudo-object expression might well give us | ||||
| 6047 | // something of dependent type. | ||||
| 6048 | for (unsigned I = 0, E = Args.size(); I != E; ++I) | ||||
| 6049 | if (Args[I]->getType()->isNonOverloadPlaceholderType()) { | ||||
| 6050 | // FIXME: should we be doing this here? | ||||
| 6051 | ExprResult result = S.CheckPlaceholderExpr(Args[I]); | ||||
| 6052 | if (result.isInvalid()) { | ||||
| 6053 | SetFailed(FK_PlaceholderType); | ||||
| 6054 | return; | ||||
| 6055 | } | ||||
| 6056 | Args[I] = result.get(); | ||||
| 6057 | } | ||||
| 6058 | |||||
| 6059 | // C++0x [dcl.init]p16: | ||||
| 6060 | // The semantics of initializers are as follows. The destination type is | ||||
| 6061 | // the type of the object or reference being initialized and the source | ||||
| 6062 | // type is the type of the initializer expression. The source type is not | ||||
| 6063 | // defined when the initializer is a braced-init-list or when it is a | ||||
| 6064 | // parenthesized list of expressions. | ||||
| 6065 | QualType DestType = Entity.getType(); | ||||
| 6066 | |||||
| 6067 | if (DestType->isDependentType() || | ||||
| 6068 | Expr::hasAnyTypeDependentArguments(Args)) { | ||||
| 6069 | SequenceKind = DependentSequence; | ||||
| 6070 | return; | ||||
| 6071 | } | ||||
| 6072 | |||||
| 6073 | // Almost everything is a normal sequence. | ||||
| 6074 | setSequenceKind(NormalSequence); | ||||
| 6075 | |||||
| 6076 | QualType SourceType; | ||||
| 6077 | Expr *Initializer = nullptr; | ||||
| 6078 | if (Args.size() == 1) { | ||||
| 6079 | Initializer = Args[0]; | ||||
| 6080 | if (S.getLangOpts().ObjC) { | ||||
| 6081 | if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(), | ||||
| 6082 | DestType, Initializer->getType(), | ||||
| 6083 | Initializer) || | ||||
| 6084 | S.CheckConversionToObjCLiteral(DestType, Initializer)) | ||||
| 6085 | Args[0] = Initializer; | ||||
| 6086 | } | ||||
| 6087 | if (!isa<InitListExpr>(Initializer)) | ||||
| 6088 | SourceType = Initializer->getType(); | ||||
| 6089 | } | ||||
| 6090 | |||||
| 6091 | // - If the initializer is a (non-parenthesized) braced-init-list, the | ||||
| 6092 | // object is list-initialized (8.5.4). | ||||
| 6093 | if (Kind.getKind() != InitializationKind::IK_Direct) { | ||||
| 6094 | if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { | ||||
| 6095 | TryListInitialization(S, Entity, Kind, InitList, *this, | ||||
| 6096 | TreatUnavailableAsInvalid); | ||||
| 6097 | return; | ||||
| 6098 | } | ||||
| 6099 | } | ||||
| 6100 | |||||
| 6101 | // - If the destination type is a reference type, see 8.5.3. | ||||
| 6102 | if (DestType->isReferenceType()) { | ||||
| 6103 | // C++0x [dcl.init.ref]p1: | ||||
| 6104 | // A variable declared to be a T& or T&&, that is, "reference to type T" | ||||
| 6105 | // (8.3.2), shall be initialized by an object, or function, of type T or | ||||
| 6106 | // by an object that can be converted into a T. | ||||
| 6107 | // (Therefore, multiple arguments are not permitted.) | ||||
| 6108 | if (Args.size() != 1) | ||||
| 6109 | SetFailed(FK_TooManyInitsForReference); | ||||
| 6110 | // C++17 [dcl.init.ref]p5: | ||||
| 6111 | // A reference [...] is initialized by an expression [...] as follows: | ||||
| 6112 | // If the initializer is not an expression, presumably we should reject, | ||||
| 6113 | // but the standard fails to actually say so. | ||||
| 6114 | else if (isa<InitListExpr>(Args[0])) | ||||
| 6115 | SetFailed(FK_ParenthesizedListInitForReference); | ||||
| 6116 | else | ||||
| 6117 | TryReferenceInitialization(S, Entity, Kind, Args[0], *this); | ||||
| 6118 | return; | ||||
| 6119 | } | ||||
| 6120 | |||||
| 6121 | // - If the initializer is (), the object is value-initialized. | ||||
| 6122 | if (Kind.getKind() == InitializationKind::IK_Value || | ||||
| 6123 | (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) { | ||||
| 6124 | TryValueInitialization(S, Entity, Kind, *this); | ||||
| 6125 | return; | ||||
| 6126 | } | ||||
| 6127 | |||||
| 6128 | // Handle default initialization. | ||||
| 6129 | if (Kind.getKind() == InitializationKind::IK_Default) { | ||||
| 6130 | TryDefaultInitialization(S, Entity, Kind, *this); | ||||
| 6131 | return; | ||||
| 6132 | } | ||||
| 6133 | |||||
| 6134 | // - If the destination type is an array of characters, an array of | ||||
| 6135 | // char16_t, an array of char32_t, or an array of wchar_t, and the | ||||
| 6136 | // initializer is a string literal, see 8.5.2. | ||||
| 6137 | // - Otherwise, if the destination type is an array, the program is | ||||
| 6138 | // ill-formed. | ||||
| 6139 | if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) { | ||||
| 6140 | if (Initializer && isa<VariableArrayType>(DestAT)) { | ||||
| 6141 | SetFailed(FK_VariableLengthArrayHasInitializer); | ||||
| 6142 | return; | ||||
| 6143 | } | ||||
| 6144 | |||||
| 6145 | if (Initializer) { | ||||
| 6146 | switch (IsStringInit(Initializer, DestAT, Context)) { | ||||
| 6147 | case SIF_None: | ||||
| 6148 | TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); | ||||
| 6149 | return; | ||||
| 6150 | case SIF_NarrowStringIntoWideChar: | ||||
| 6151 | SetFailed(FK_NarrowStringIntoWideCharArray); | ||||
| 6152 | return; | ||||
| 6153 | case SIF_WideStringIntoChar: | ||||
| 6154 | SetFailed(FK_WideStringIntoCharArray); | ||||
| 6155 | return; | ||||
| 6156 | case SIF_IncompatWideStringIntoWideChar: | ||||
| 6157 | SetFailed(FK_IncompatWideStringIntoWideChar); | ||||
| 6158 | return; | ||||
| 6159 | case SIF_PlainStringIntoUTF8Char: | ||||
| 6160 | SetFailed(FK_PlainStringIntoUTF8Char); | ||||
| 6161 | return; | ||||
| 6162 | case SIF_UTF8StringIntoPlainChar: | ||||
| 6163 | SetFailed(FK_UTF8StringIntoPlainChar); | ||||
| 6164 | return; | ||||
| 6165 | case SIF_Other: | ||||
| 6166 | break; | ||||
| 6167 | } | ||||
| 6168 | } | ||||
| 6169 | |||||
| 6170 | // Some kinds of initialization permit an array to be initialized from | ||||
| 6171 | // another array of the same type, and perform elementwise initialization. | ||||
| 6172 | if (Initializer && isa<ConstantArrayType>(DestAT) && | ||||
| 6173 | S.Context.hasSameUnqualifiedType(Initializer->getType(), | ||||
| 6174 | Entity.getType()) && | ||||
| 6175 | canPerformArrayCopy(Entity)) { | ||||
| 6176 | // If source is a prvalue, use it directly. | ||||
| 6177 | if (Initializer->isPRValue()) { | ||||
| 6178 | AddArrayInitStep(DestType, /*IsGNUExtension*/false); | ||||
| 6179 | return; | ||||
| 6180 | } | ||||
| 6181 | |||||
| 6182 | // Emit element-at-a-time copy loop. | ||||
| 6183 | InitializedEntity Element = | ||||
| 6184 | InitializedEntity::InitializeElement(S.Context, 0, Entity); | ||||
| 6185 | QualType InitEltT = | ||||
| 6186 | Context.getAsArrayType(Initializer->getType())->getElementType(); | ||||
| 6187 | OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT, | ||||
| 6188 | Initializer->getValueKind(), | ||||
| 6189 | Initializer->getObjectKind()); | ||||
| 6190 | Expr *OVEAsExpr = &OVE; | ||||
| 6191 | InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList, | ||||
| 6192 | TreatUnavailableAsInvalid); | ||||
| 6193 | if (!Failed()) | ||||
| 6194 | AddArrayInitLoopStep(Entity.getType(), InitEltT); | ||||
| 6195 | return; | ||||
| 6196 | } | ||||
| 6197 | |||||
| 6198 | // Note: as an GNU C extension, we allow initialization of an | ||||
| 6199 | // array from a compound literal that creates an array of the same | ||||
| 6200 | // type, so long as the initializer has no side effects. | ||||
| 6201 | if (!S.getLangOpts().CPlusPlus && Initializer && | ||||
| 6202 | isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) && | ||||
| 6203 | Initializer->getType()->isArrayType()) { | ||||
| 6204 | const ArrayType *SourceAT | ||||
| 6205 | = Context.getAsArrayType(Initializer->getType()); | ||||
| 6206 | if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT)) | ||||
| 6207 | SetFailed(FK_ArrayTypeMismatch); | ||||
| 6208 | else if (Initializer->HasSideEffects(S.Context)) | ||||
| 6209 | SetFailed(FK_NonConstantArrayInit); | ||||
| 6210 | else { | ||||
| 6211 | AddArrayInitStep(DestType, /*IsGNUExtension*/true); | ||||
| 6212 | } | ||||
| 6213 | } | ||||
| 6214 | // Note: as a GNU C++ extension, we allow list-initialization of a | ||||
| 6215 | // class member of array type from a parenthesized initializer list. | ||||
| 6216 | else if (S.getLangOpts().CPlusPlus && | ||||
| 6217 | Entity.getKind() == InitializedEntity::EK_Member && | ||||
| 6218 | Initializer && isa<InitListExpr>(Initializer)) { | ||||
| 6219 | TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer), | ||||
| 6220 | *this, TreatUnavailableAsInvalid); | ||||
| 6221 | AddParenthesizedArrayInitStep(DestType); | ||||
| 6222 | } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList && | ||||
| 6223 | Kind.getKind() == InitializationKind::IK_Direct) | ||||
| 6224 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this, | ||||
| 6225 | /*VerifyOnly=*/true); | ||||
| 6226 | else if (DestAT->getElementType()->isCharType()) | ||||
| 6227 | SetFailed(FK_ArrayNeedsInitListOrStringLiteral); | ||||
| 6228 | else if (IsWideCharCompatible(DestAT->getElementType(), Context)) | ||||
| 6229 | SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral); | ||||
| 6230 | else | ||||
| 6231 | SetFailed(FK_ArrayNeedsInitList); | ||||
| 6232 | |||||
| 6233 | return; | ||||
| 6234 | } | ||||
| 6235 | |||||
| 6236 | // Determine whether we should consider writeback conversions for | ||||
| 6237 | // Objective-C ARC. | ||||
| 6238 | bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount && | ||||
| 6239 | Entity.isParameterKind(); | ||||
| 6240 | |||||
| 6241 | if (TryOCLSamplerInitialization(S, *this, DestType, Initializer)) | ||||
| 6242 | return; | ||||
| 6243 | |||||
| 6244 | // We're at the end of the line for C: it's either a write-back conversion | ||||
| 6245 | // or it's a C assignment. There's no need to check anything else. | ||||
| 6246 | if (!S.getLangOpts().CPlusPlus) { | ||||
| 6247 | // If allowed, check whether this is an Objective-C writeback conversion. | ||||
| 6248 | if (allowObjCWritebackConversion && | ||||
| 6249 | tryObjCWritebackConversion(S, *this, Entity, Initializer)) { | ||||
| 6250 | return; | ||||
| 6251 | } | ||||
| 6252 | |||||
| 6253 | if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer)) | ||||
| 6254 | return; | ||||
| 6255 | |||||
| 6256 | // Handle initialization in C | ||||
| 6257 | AddCAssignmentStep(DestType); | ||||
| 6258 | MaybeProduceObjCObject(S, *this, Entity); | ||||
| 6259 | return; | ||||
| 6260 | } | ||||
| 6261 | |||||
| 6262 | assert(S.getLangOpts().CPlusPlus)(static_cast <bool> (S.getLangOpts().CPlusPlus) ? void ( 0) : __assert_fail ("S.getLangOpts().CPlusPlus", "clang/lib/Sema/SemaInit.cpp" , 6262, __extension__ __PRETTY_FUNCTION__)); | ||||
| 6263 | |||||
| 6264 | // - If the destination type is a (possibly cv-qualified) class type: | ||||
| 6265 | if (DestType->isRecordType()) { | ||||
| 6266 | // - If the initialization is direct-initialization, or if it is | ||||
| 6267 | // copy-initialization where the cv-unqualified version of the | ||||
| 6268 | // source type is the same class as, or a derived class of, the | ||||
| 6269 | // class of the destination, constructors are considered. [...] | ||||
| 6270 | if (Kind.getKind() == InitializationKind::IK_Direct || | ||||
| 6271 | (Kind.getKind() == InitializationKind::IK_Copy && | ||||
| 6272 | (Context.hasSameUnqualifiedType(SourceType, DestType) || | ||||
| 6273 | S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType)))) { | ||||
| 6274 | TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType, | ||||
| 6275 | *this); | ||||
| 6276 | |||||
| 6277 | // We fall back to the "no matching constructor" path if the | ||||
| 6278 | // failed candidate set has functions other than the three default | ||||
| 6279 | // constructors. For example, conversion function. | ||||
| 6280 | if (const auto *RD = | ||||
| 6281 | dyn_cast<CXXRecordDecl>(DestType->getAs<RecordType>()->getDecl()); | ||||
| 6282 | // In general, we should call isCompleteType for RD to check its | ||||
| 6283 | // completeness, we don't call it here as it was already called in the | ||||
| 6284 | // above TryConstructorInitialization. | ||||
| 6285 | S.getLangOpts().CPlusPlus20 && RD && RD->hasDefinition() && | ||||
| 6286 | RD->isAggregate() && Failed() && | ||||
| 6287 | getFailureKind() == FK_ConstructorOverloadFailed) { | ||||
| 6288 | // Do not attempt paren list initialization if overload resolution | ||||
| 6289 | // resolves to a deleted function . | ||||
| 6290 | // | ||||
| 6291 | // We may reach this condition if we have a union wrapping a class with | ||||
| 6292 | // a non-trivial copy or move constructor and we call one of those two | ||||
| 6293 | // constructors. The union is an aggregate, but the matched constructor | ||||
| 6294 | // is implicitly deleted, so we need to prevent aggregate initialization | ||||
| 6295 | // (otherwise, it'll attempt aggregate initialization by initializing | ||||
| 6296 | // the first element with a reference to the union). | ||||
| 6297 | OverloadCandidateSet::iterator Best; | ||||
| 6298 | OverloadingResult OR = getFailedCandidateSet().BestViableFunction( | ||||
| 6299 | S, Kind.getLocation(), Best); | ||||
| 6300 | if (OR != OverloadingResult::OR_Deleted) { | ||||
| 6301 | // C++20 [dcl.init] 17.6.2.2: | ||||
| 6302 | // - Otherwise, if no constructor is viable, the destination type is | ||||
| 6303 | // an | ||||
| 6304 | // aggregate class, and the initializer is a parenthesized | ||||
| 6305 | // expression-list. | ||||
| 6306 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this, | ||||
| 6307 | /*VerifyOnly=*/true); | ||||
| 6308 | } | ||||
| 6309 | } | ||||
| 6310 | } else { | ||||
| 6311 | // - Otherwise (i.e., for the remaining copy-initialization cases), | ||||
| 6312 | // user-defined conversion sequences that can convert from the | ||||
| 6313 | // source type to the destination type or (when a conversion | ||||
| 6314 | // function is used) to a derived class thereof are enumerated as | ||||
| 6315 | // described in 13.3.1.4, and the best one is chosen through | ||||
| 6316 | // overload resolution (13.3). | ||||
| 6317 | TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, | ||||
| 6318 | TopLevelOfInitList); | ||||
| 6319 | } | ||||
| 6320 | return; | ||||
| 6321 | } | ||||
| 6322 | |||||
| 6323 | 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", 6323, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 6324 | |||||
| 6325 | // For HLSL ext vector types we allow list initialization behavior for C++ | ||||
| 6326 | // constructor syntax. This is accomplished by converting initialization | ||||
| 6327 | // arguments an InitListExpr late. | ||||
| 6328 | if (S.getLangOpts().HLSL && DestType->isExtVectorType() && | ||||
| 6329 | (SourceType.isNull() || | ||||
| 6330 | !Context.hasSameUnqualifiedType(SourceType, DestType))) { | ||||
| 6331 | |||||
| 6332 | llvm::SmallVector<Expr *> InitArgs; | ||||
| 6333 | for (auto *Arg : Args) { | ||||
| 6334 | if (Arg->getType()->isExtVectorType()) { | ||||
| 6335 | const auto *VTy = Arg->getType()->castAs<ExtVectorType>(); | ||||
| 6336 | unsigned Elm = VTy->getNumElements(); | ||||
| 6337 | for (unsigned Idx = 0; Idx < Elm; ++Idx) { | ||||
| 6338 | InitArgs.emplace_back(new (Context) ArraySubscriptExpr( | ||||
| 6339 | Arg, | ||||
| 6340 | IntegerLiteral::Create( | ||||
| 6341 | Context, llvm::APInt(Context.getIntWidth(Context.IntTy), Idx), | ||||
| 6342 | Context.IntTy, SourceLocation()), | ||||
| 6343 | VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(), | ||||
| 6344 | SourceLocation())); | ||||
| 6345 | } | ||||
| 6346 | } else | ||||
| 6347 | InitArgs.emplace_back(Arg); | ||||
| 6348 | } | ||||
| 6349 | InitListExpr *ILE = new (Context) InitListExpr( | ||||
| 6350 | S.getASTContext(), SourceLocation(), InitArgs, SourceLocation()); | ||||
| 6351 | Args[0] = ILE; | ||||
| 6352 | AddListInitializationStep(DestType); | ||||
| 6353 | return; | ||||
| 6354 | } | ||||
| 6355 | |||||
| 6356 | // The remaining cases all need a source type. | ||||
| 6357 | if (Args.size() > 1) { | ||||
| 6358 | SetFailed(FK_TooManyInitsForScalar); | ||||
| 6359 | return; | ||||
| 6360 | } else if (isa<InitListExpr>(Args[0])) { | ||||
| 6361 | SetFailed(FK_ParenthesizedListInitForScalar); | ||||
| 6362 | return; | ||||
| 6363 | } | ||||
| 6364 | |||||
| 6365 | // - Otherwise, if the source type is a (possibly cv-qualified) class | ||||
| 6366 | // type, conversion functions are considered. | ||||
| 6367 | if (!SourceType.isNull() && SourceType->isRecordType()) { | ||||
| 6368 | // For a conversion to _Atomic(T) from either T or a class type derived | ||||
| 6369 | // from T, initialize the T object then convert to _Atomic type. | ||||
| 6370 | bool NeedAtomicConversion = false; | ||||
| 6371 | if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) { | ||||
| 6372 | if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) || | ||||
| 6373 | S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, | ||||
| 6374 | Atomic->getValueType())) { | ||||
| 6375 | DestType = Atomic->getValueType(); | ||||
| 6376 | NeedAtomicConversion = true; | ||||
| 6377 | } | ||||
| 6378 | } | ||||
| 6379 | |||||
| 6380 | TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, | ||||
| 6381 | TopLevelOfInitList); | ||||
| 6382 | MaybeProduceObjCObject(S, *this, Entity); | ||||
| 6383 | if (!Failed() && NeedAtomicConversion) | ||||
| 6384 | AddAtomicConversionStep(Entity.getType()); | ||||
| 6385 | return; | ||||
| 6386 | } | ||||
| 6387 | |||||
| 6388 | // - Otherwise, if the initialization is direct-initialization, the source | ||||
| 6389 | // type is std::nullptr_t, and the destination type is bool, the initial | ||||
| 6390 | // value of the object being initialized is false. | ||||
| 6391 | if (!SourceType.isNull() && SourceType->isNullPtrType() && | ||||
| 6392 | DestType->isBooleanType() && | ||||
| 6393 | Kind.getKind() == InitializationKind::IK_Direct) { | ||||
| 6394 | AddConversionSequenceStep( | ||||
| 6395 | ImplicitConversionSequence::getNullptrToBool(SourceType, DestType, | ||||
| 6396 | Initializer->isGLValue()), | ||||
| 6397 | DestType); | ||||
| 6398 | return; | ||||
| 6399 | } | ||||
| 6400 | |||||
| 6401 | // - Otherwise, the initial value of the object being initialized is the | ||||
| 6402 | // (possibly converted) value of the initializer expression. Standard | ||||
| 6403 | // conversions (Clause 4) will be used, if necessary, to convert the | ||||
| 6404 | // initializer expression to the cv-unqualified version of the | ||||
| 6405 | // destination type; no user-defined conversions are considered. | ||||
| 6406 | |||||
| 6407 | ImplicitConversionSequence ICS | ||||
| 6408 | = S.TryImplicitConversion(Initializer, DestType, | ||||
| 6409 | /*SuppressUserConversions*/true, | ||||
| 6410 | Sema::AllowedExplicit::None, | ||||
| 6411 | /*InOverloadResolution*/ false, | ||||
| 6412 | /*CStyle=*/Kind.isCStyleOrFunctionalCast(), | ||||
| 6413 | allowObjCWritebackConversion); | ||||
| 6414 | |||||
| 6415 | if (ICS.isStandard() && | ||||
| 6416 | ICS.Standard.Second == ICK_Writeback_Conversion) { | ||||
| 6417 | // Objective-C ARC writeback conversion. | ||||
| 6418 | |||||
| 6419 | // We should copy unless we're passing to an argument explicitly | ||||
| 6420 | // marked 'out'. | ||||
| 6421 | bool ShouldCopy = true; | ||||
| 6422 | if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl())) | ||||
| 6423 | ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); | ||||
| 6424 | |||||
| 6425 | // If there was an lvalue adjustment, add it as a separate conversion. | ||||
| 6426 | if (ICS.Standard.First == ICK_Array_To_Pointer || | ||||
| 6427 | ICS.Standard.First == ICK_Lvalue_To_Rvalue) { | ||||
| 6428 | ImplicitConversionSequence LvalueICS; | ||||
| 6429 | LvalueICS.setStandard(); | ||||
| 6430 | LvalueICS.Standard.setAsIdentityConversion(); | ||||
| 6431 | LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0)); | ||||
| 6432 | LvalueICS.Standard.First = ICS.Standard.First; | ||||
| 6433 | AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); | ||||
| 6434 | } | ||||
| 6435 | |||||
| 6436 | AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy); | ||||
| 6437 | } else if (ICS.isBad()) { | ||||
| 6438 | DeclAccessPair dap; | ||||
| 6439 | if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) { | ||||
| 6440 | AddZeroInitializationStep(Entity.getType()); | ||||
| 6441 | } else if (Initializer->getType() == Context.OverloadTy && | ||||
| 6442 | !S.ResolveAddressOfOverloadedFunction(Initializer, DestType, | ||||
| 6443 | false, dap)) | ||||
| 6444 | SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); | ||||
| 6445 | else if (Initializer->getType()->isFunctionType() && | ||||
| 6446 | isExprAnUnaddressableFunction(S, Initializer)) | ||||
| 6447 | SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction); | ||||
| 6448 | else | ||||
| 6449 | SetFailed(InitializationSequence::FK_ConversionFailed); | ||||
| 6450 | } else { | ||||
| 6451 | AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); | ||||
| 6452 | |||||
| 6453 | MaybeProduceObjCObject(S, *this, Entity); | ||||
| 6454 | } | ||||
| 6455 | } | ||||
| 6456 | |||||
| 6457 | InitializationSequence::~InitializationSequence() { | ||||
| 6458 | for (auto &S : Steps) | ||||
| 6459 | S.Destroy(); | ||||
| 6460 | } | ||||
| 6461 | |||||
| 6462 | //===----------------------------------------------------------------------===// | ||||
| 6463 | // Perform initialization | ||||
| 6464 | //===----------------------------------------------------------------------===// | ||||
| 6465 | static Sema::AssignmentAction | ||||
| 6466 | getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) { | ||||
| 6467 | switch(Entity.getKind()) { | ||||
| 6468 | case InitializedEntity::EK_Variable: | ||||
| 6469 | case InitializedEntity::EK_New: | ||||
| 6470 | case InitializedEntity::EK_Exception: | ||||
| 6471 | case InitializedEntity::EK_Base: | ||||
| 6472 | case InitializedEntity::EK_Delegating: | ||||
| 6473 | return Sema::AA_Initializing; | ||||
| 6474 | |||||
| 6475 | case InitializedEntity::EK_Parameter: | ||||
| 6476 | if (Entity.getDecl() && | ||||
| 6477 | isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) | ||||
| 6478 | return Sema::AA_Sending; | ||||
| 6479 | |||||
| 6480 | return Sema::AA_Passing; | ||||
| 6481 | |||||
| 6482 | case InitializedEntity::EK_Parameter_CF_Audited: | ||||
| 6483 | if (Entity.getDecl() && | ||||
| 6484 | isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) | ||||
| 6485 | return Sema::AA_Sending; | ||||
| 6486 | |||||
| 6487 | return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited; | ||||
| 6488 | |||||
| 6489 | case InitializedEntity::EK_Result: | ||||
| 6490 | case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right. | ||||
| 6491 | return Sema::AA_Returning; | ||||
| 6492 | |||||
| 6493 | case InitializedEntity::EK_Temporary: | ||||
| 6494 | case InitializedEntity::EK_RelatedResult: | ||||
| 6495 | // FIXME: Can we tell apart casting vs. converting? | ||||
| 6496 | return Sema::AA_Casting; | ||||
| 6497 | |||||
| 6498 | case InitializedEntity::EK_TemplateParameter: | ||||
| 6499 | // This is really initialization, but refer to it as conversion for | ||||
| 6500 | // consistency with CheckConvertedConstantExpression. | ||||
| 6501 | return Sema::AA_Converting; | ||||
| 6502 | |||||
| 6503 | case InitializedEntity::EK_Member: | ||||
| 6504 | case InitializedEntity::EK_ParenAggInitMember: | ||||
| 6505 | case InitializedEntity::EK_Binding: | ||||
| 6506 | case InitializedEntity::EK_ArrayElement: | ||||
| 6507 | case InitializedEntity::EK_VectorElement: | ||||
| 6508 | case InitializedEntity::EK_ComplexElement: | ||||
| 6509 | case InitializedEntity::EK_BlockElement: | ||||
| 6510 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | ||||
| 6511 | case InitializedEntity::EK_LambdaCapture: | ||||
| 6512 | case InitializedEntity::EK_CompoundLiteralInit: | ||||
| 6513 | return Sema::AA_Initializing; | ||||
| 6514 | } | ||||
| 6515 | |||||
| 6516 | llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp" , 6516); | ||||
| 6517 | } | ||||
| 6518 | |||||
| 6519 | /// Whether we should bind a created object as a temporary when | ||||
| 6520 | /// initializing the given entity. | ||||
| 6521 | static bool shouldBindAsTemporary(const InitializedEntity &Entity) { | ||||
| 6522 | switch (Entity.getKind()) { | ||||
| 6523 | case InitializedEntity::EK_ArrayElement: | ||||
| 6524 | case InitializedEntity::EK_Member: | ||||
| 6525 | case InitializedEntity::EK_ParenAggInitMember: | ||||
| 6526 | case InitializedEntity::EK_Result: | ||||
| 6527 | case InitializedEntity::EK_StmtExprResult: | ||||
| 6528 | case InitializedEntity::EK_New: | ||||
| 6529 | case InitializedEntity::EK_Variable: | ||||
| 6530 | case InitializedEntity::EK_Base: | ||||
| 6531 | case InitializedEntity::EK_Delegating: | ||||
| 6532 | case InitializedEntity::EK_VectorElement: | ||||
| 6533 | case InitializedEntity::EK_ComplexElement: | ||||
| 6534 | case InitializedEntity::EK_Exception: | ||||
| 6535 | case InitializedEntity::EK_BlockElement: | ||||
| 6536 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | ||||
| 6537 | case InitializedEntity::EK_LambdaCapture: | ||||
| 6538 | case InitializedEntity::EK_CompoundLiteralInit: | ||||
| 6539 | case InitializedEntity::EK_TemplateParameter: | ||||
| 6540 | return false; | ||||
| 6541 | |||||
| 6542 | case InitializedEntity::EK_Parameter: | ||||
| 6543 | case InitializedEntity::EK_Parameter_CF_Audited: | ||||
| 6544 | case InitializedEntity::EK_Temporary: | ||||
| 6545 | case InitializedEntity::EK_RelatedResult: | ||||
| 6546 | case InitializedEntity::EK_Binding: | ||||
| 6547 | return true; | ||||
| 6548 | } | ||||
| 6549 | |||||
| 6550 | llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?" , "clang/lib/Sema/SemaInit.cpp", 6550); | ||||
| 6551 | } | ||||
| 6552 | |||||
| 6553 | /// Whether the given entity, when initialized with an object | ||||
| 6554 | /// created for that initialization, requires destruction. | ||||
| 6555 | static bool shouldDestroyEntity(const InitializedEntity &Entity) { | ||||
| 6556 | switch (Entity.getKind()) { | ||||
| 6557 | case InitializedEntity::EK_Result: | ||||
| 6558 | case InitializedEntity::EK_StmtExprResult: | ||||
| 6559 | case InitializedEntity::EK_New: | ||||
| 6560 | case InitializedEntity::EK_Base: | ||||
| 6561 | case InitializedEntity::EK_Delegating: | ||||
| 6562 | case InitializedEntity::EK_VectorElement: | ||||
| 6563 | case InitializedEntity::EK_ComplexElement: | ||||
| 6564 | case InitializedEntity::EK_BlockElement: | ||||
| 6565 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | ||||
| 6566 | case InitializedEntity::EK_LambdaCapture: | ||||
| 6567 | return false; | ||||
| 6568 | |||||
| 6569 | case InitializedEntity::EK_Member: | ||||
| 6570 | case InitializedEntity::EK_ParenAggInitMember: | ||||
| 6571 | case InitializedEntity::EK_Binding: | ||||
| 6572 | case InitializedEntity::EK_Variable: | ||||
| 6573 | case InitializedEntity::EK_Parameter: | ||||
| 6574 | case InitializedEntity::EK_Parameter_CF_Audited: | ||||
| 6575 | case InitializedEntity::EK_TemplateParameter: | ||||
| 6576 | case InitializedEntity::EK_Temporary: | ||||
| 6577 | case InitializedEntity::EK_ArrayElement: | ||||
| 6578 | case InitializedEntity::EK_Exception: | ||||
| 6579 | case InitializedEntity::EK_CompoundLiteralInit: | ||||
| 6580 | case InitializedEntity::EK_RelatedResult: | ||||
| 6581 | return true; | ||||
| 6582 | } | ||||
| 6583 | |||||
| 6584 | llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?" , "clang/lib/Sema/SemaInit.cpp", 6584); | ||||
| 6585 | } | ||||
| 6586 | |||||
| 6587 | /// Get the location at which initialization diagnostics should appear. | ||||
| 6588 | static SourceLocation getInitializationLoc(const InitializedEntity &Entity, | ||||
| 6589 | Expr *Initializer) { | ||||
| 6590 | switch (Entity.getKind()) { | ||||
| 6591 | case InitializedEntity::EK_Result: | ||||
| 6592 | case InitializedEntity::EK_StmtExprResult: | ||||
| 6593 | return Entity.getReturnLoc(); | ||||
| 6594 | |||||
| 6595 | case InitializedEntity::EK_Exception: | ||||
| 6596 | return Entity.getThrowLoc(); | ||||
| 6597 | |||||
| 6598 | case InitializedEntity::EK_Variable: | ||||
| 6599 | case InitializedEntity::EK_Binding: | ||||
| 6600 | return Entity.getDecl()->getLocation(); | ||||
| 6601 | |||||
| 6602 | case InitializedEntity::EK_LambdaCapture: | ||||
| 6603 | return Entity.getCaptureLoc(); | ||||
| 6604 | |||||
| 6605 | case InitializedEntity::EK_ArrayElement: | ||||
| 6606 | case InitializedEntity::EK_Member: | ||||
| 6607 | case InitializedEntity::EK_ParenAggInitMember: | ||||
| 6608 | case InitializedEntity::EK_Parameter: | ||||
| 6609 | case InitializedEntity::EK_Parameter_CF_Audited: | ||||
| 6610 | case InitializedEntity::EK_TemplateParameter: | ||||
| 6611 | case InitializedEntity::EK_Temporary: | ||||
| 6612 | case InitializedEntity::EK_New: | ||||
| 6613 | case InitializedEntity::EK_Base: | ||||
| 6614 | case InitializedEntity::EK_Delegating: | ||||
| 6615 | case InitializedEntity::EK_VectorElement: | ||||
| 6616 | case InitializedEntity::EK_ComplexElement: | ||||
| 6617 | case InitializedEntity::EK_BlockElement: | ||||
| 6618 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | ||||
| 6619 | case InitializedEntity::EK_CompoundLiteralInit: | ||||
| 6620 | case InitializedEntity::EK_RelatedResult: | ||||
| 6621 | return Initializer->getBeginLoc(); | ||||
| 6622 | } | ||||
| 6623 | llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?" , "clang/lib/Sema/SemaInit.cpp", 6623); | ||||
| 6624 | } | ||||
| 6625 | |||||
| 6626 | /// Make a (potentially elidable) temporary copy of the object | ||||
| 6627 | /// provided by the given initializer by calling the appropriate copy | ||||
| 6628 | /// constructor. | ||||
| 6629 | /// | ||||
| 6630 | /// \param S The Sema object used for type-checking. | ||||
| 6631 | /// | ||||
| 6632 | /// \param T The type of the temporary object, which must either be | ||||
| 6633 | /// the type of the initializer expression or a superclass thereof. | ||||
| 6634 | /// | ||||
| 6635 | /// \param Entity The entity being initialized. | ||||
| 6636 | /// | ||||
| 6637 | /// \param CurInit The initializer expression. | ||||
| 6638 | /// | ||||
| 6639 | /// \param IsExtraneousCopy Whether this is an "extraneous" copy that | ||||
| 6640 | /// is permitted in C++03 (but not C++0x) when binding a reference to | ||||
| 6641 | /// an rvalue. | ||||
| 6642 | /// | ||||
| 6643 | /// \returns An expression that copies the initializer expression into | ||||
| 6644 | /// a temporary object, or an error expression if a copy could not be | ||||
| 6645 | /// created. | ||||
| 6646 | static ExprResult CopyObject(Sema &S, | ||||
| 6647 | QualType T, | ||||
| 6648 | const InitializedEntity &Entity, | ||||
| 6649 | ExprResult CurInit, | ||||
| 6650 | bool IsExtraneousCopy) { | ||||
| 6651 | if (CurInit.isInvalid()) | ||||
| 6652 | return CurInit; | ||||
| 6653 | // Determine which class type we're copying to. | ||||
| 6654 | Expr *CurInitExpr = (Expr *)CurInit.get(); | ||||
| 6655 | CXXRecordDecl *Class = nullptr; | ||||
| 6656 | if (const RecordType *Record = T->getAs<RecordType>()) | ||||
| 6657 | Class = cast<CXXRecordDecl>(Record->getDecl()); | ||||
| 6658 | if (!Class) | ||||
| 6659 | return CurInit; | ||||
| 6660 | |||||
| 6661 | SourceLocation Loc = getInitializationLoc(Entity, CurInit.get()); | ||||
| 6662 | |||||
| 6663 | // Make sure that the type we are copying is complete. | ||||
| 6664 | if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete)) | ||||
| 6665 | return CurInit; | ||||
| 6666 | |||||
| 6667 | // Perform overload resolution using the class's constructors. Per | ||||
| 6668 | // C++11 [dcl.init]p16, second bullet for class types, this initialization | ||||
| 6669 | // is direct-initialization. | ||||
| 6670 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); | ||||
| 6671 | DeclContext::lookup_result Ctors = S.LookupConstructors(Class); | ||||
| 6672 | |||||
| 6673 | OverloadCandidateSet::iterator Best; | ||||
| 6674 | switch (ResolveConstructorOverload( | ||||
| 6675 | S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best, | ||||
| 6676 | /*CopyInitializing=*/false, /*AllowExplicit=*/true, | ||||
| 6677 | /*OnlyListConstructors=*/false, /*IsListInit=*/false, | ||||
| 6678 | /*SecondStepOfCopyInit=*/true)) { | ||||
| 6679 | case OR_Success: | ||||
| 6680 | break; | ||||
| 6681 | |||||
| 6682 | case OR_No_Viable_Function: | ||||
| 6683 | CandidateSet.NoteCandidates( | ||||
| 6684 | PartialDiagnosticAt( | ||||
| 6685 | Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext() | ||||
| 6686 | ? diag::ext_rvalue_to_reference_temp_copy_no_viable | ||||
| 6687 | : diag::err_temp_copy_no_viable) | ||||
| 6688 | << (int)Entity.getKind() << CurInitExpr->getType() | ||||
| 6689 | << CurInitExpr->getSourceRange()), | ||||
| 6690 | S, OCD_AllCandidates, CurInitExpr); | ||||
| 6691 | if (!IsExtraneousCopy || S.isSFINAEContext()) | ||||
| 6692 | return ExprError(); | ||||
| 6693 | return CurInit; | ||||
| 6694 | |||||
| 6695 | case OR_Ambiguous: | ||||
| 6696 | CandidateSet.NoteCandidates( | ||||
| 6697 | PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous) | ||||
| 6698 | << (int)Entity.getKind() | ||||
| 6699 | << CurInitExpr->getType() | ||||
| 6700 | << CurInitExpr->getSourceRange()), | ||||
| 6701 | S, OCD_AmbiguousCandidates, CurInitExpr); | ||||
| 6702 | return ExprError(); | ||||
| 6703 | |||||
| 6704 | case OR_Deleted: | ||||
| 6705 | S.Diag(Loc, diag::err_temp_copy_deleted) | ||||
| 6706 | << (int)Entity.getKind() << CurInitExpr->getType() | ||||
| 6707 | << CurInitExpr->getSourceRange(); | ||||
| 6708 | S.NoteDeletedFunction(Best->Function); | ||||
| 6709 | return ExprError(); | ||||
| 6710 | } | ||||
| 6711 | |||||
| 6712 | bool HadMultipleCandidates = CandidateSet.size() > 1; | ||||
| 6713 | |||||
| 6714 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); | ||||
| 6715 | SmallVector<Expr*, 8> ConstructorArgs; | ||||
| 6716 | CurInit.get(); // Ownership transferred into MultiExprArg, below. | ||||
| 6717 | |||||
| 6718 | S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity, | ||||
| 6719 | IsExtraneousCopy); | ||||
| 6720 | |||||
| 6721 | if (IsExtraneousCopy) { | ||||
| 6722 | // If this is a totally extraneous copy for C++03 reference | ||||
| 6723 | // binding purposes, just return the original initialization | ||||
| 6724 | // expression. We don't generate an (elided) copy operation here | ||||
| 6725 | // because doing so would require us to pass down a flag to avoid | ||||
| 6726 | // infinite recursion, where each step adds another extraneous, | ||||
| 6727 | // elidable copy. | ||||
| 6728 | |||||
| 6729 | // Instantiate the default arguments of any extra parameters in | ||||
| 6730 | // the selected copy constructor, as if we were going to create a | ||||
| 6731 | // proper call to the copy constructor. | ||||
| 6732 | for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { | ||||
| 6733 | ParmVarDecl *Parm = Constructor->getParamDecl(I); | ||||
| 6734 | if (S.RequireCompleteType(Loc, Parm->getType(), | ||||
| 6735 | diag::err_call_incomplete_argument)) | ||||
| 6736 | break; | ||||
| 6737 | |||||
| 6738 | // Build the default argument expression; we don't actually care | ||||
| 6739 | // if this succeeds or not, because this routine will complain | ||||
| 6740 | // if there was a problem. | ||||
| 6741 | S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); | ||||
| 6742 | } | ||||
| 6743 | |||||
| 6744 | return CurInitExpr; | ||||
| 6745 | } | ||||
| 6746 | |||||
| 6747 | // Determine the arguments required to actually perform the | ||||
| 6748 | // constructor call (we might have derived-to-base conversions, or | ||||
| 6749 | // the copy constructor may have default arguments). | ||||
| 6750 | if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc, | ||||
| 6751 | ConstructorArgs)) | ||||
| 6752 | return ExprError(); | ||||
| 6753 | |||||
| 6754 | // C++0x [class.copy]p32: | ||||
| 6755 | // When certain criteria are met, an implementation is allowed to | ||||
| 6756 | // omit the copy/move construction of a class object, even if the | ||||
| 6757 | // copy/move constructor and/or destructor for the object have | ||||
| 6758 | // side effects. [...] | ||||
| 6759 | // - when a temporary class object that has not been bound to a | ||||
| 6760 | // reference (12.2) would be copied/moved to a class object | ||||
| 6761 | // with the same cv-unqualified type, the copy/move operation | ||||
| 6762 | // can be omitted by constructing the temporary object | ||||
| 6763 | // directly into the target of the omitted copy/move | ||||
| 6764 | // | ||||
| 6765 | // Note that the other three bullets are handled elsewhere. Copy | ||||
| 6766 | // elision for return statements and throw expressions are handled as part | ||||
| 6767 | // of constructor initialization, while copy elision for exception handlers | ||||
| 6768 | // is handled by the run-time. | ||||
| 6769 | // | ||||
| 6770 | // FIXME: If the function parameter is not the same type as the temporary, we | ||||
| 6771 | // should still be able to elide the copy, but we don't have a way to | ||||
| 6772 | // represent in the AST how much should be elided in this case. | ||||
| 6773 | bool Elidable = | ||||
| 6774 | CurInitExpr->isTemporaryObject(S.Context, Class) && | ||||
| 6775 | S.Context.hasSameUnqualifiedType( | ||||
| 6776 | Best->Function->getParamDecl(0)->getType().getNonReferenceType(), | ||||
| 6777 | CurInitExpr->getType()); | ||||
| 6778 | |||||
| 6779 | // Actually perform the constructor call. | ||||
| 6780 | CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor, | ||||
| 6781 | Elidable, | ||||
| 6782 | ConstructorArgs, | ||||
| 6783 | HadMultipleCandidates, | ||||
| 6784 | /*ListInit*/ false, | ||||
| 6785 | /*StdInitListInit*/ false, | ||||
| 6786 | /*ZeroInit*/ false, | ||||
| 6787 | CXXConstructExpr::CK_Complete, | ||||
| 6788 | SourceRange()); | ||||
| 6789 | |||||
| 6790 | // If we're supposed to bind temporaries, do so. | ||||
| 6791 | if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) | ||||
| 6792 | CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); | ||||
| 6793 | return CurInit; | ||||
| 6794 | } | ||||
| 6795 | |||||
| 6796 | /// Check whether elidable copy construction for binding a reference to | ||||
| 6797 | /// a temporary would have succeeded if we were building in C++98 mode, for | ||||
| 6798 | /// -Wc++98-compat. | ||||
| 6799 | static void CheckCXX98CompatAccessibleCopy(Sema &S, | ||||
| 6800 | const InitializedEntity &Entity, | ||||
| 6801 | Expr *CurInitExpr) { | ||||
| 6802 | assert(S.getLangOpts().CPlusPlus11)(static_cast <bool> (S.getLangOpts().CPlusPlus11) ? void (0) : __assert_fail ("S.getLangOpts().CPlusPlus11", "clang/lib/Sema/SemaInit.cpp" , 6802, __extension__ __PRETTY_FUNCTION__)); | ||||
| 6803 | |||||
| 6804 | const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>(); | ||||
| 6805 | if (!Record) | ||||
| 6806 | return; | ||||
| 6807 | |||||
| 6808 | SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr); | ||||
| 6809 | if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc)) | ||||
| 6810 | return; | ||||
| 6811 | |||||
| 6812 | // Find constructors which would have been considered. | ||||
| 6813 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); | ||||
| 6814 | DeclContext::lookup_result Ctors = | ||||
| 6815 | S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl())); | ||||
| 6816 | |||||
| 6817 | // Perform overload resolution. | ||||
| 6818 | OverloadCandidateSet::iterator Best; | ||||
| 6819 | OverloadingResult OR = ResolveConstructorOverload( | ||||
| 6820 | S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best, | ||||
| 6821 | /*CopyInitializing=*/false, /*AllowExplicit=*/true, | ||||
| 6822 | /*OnlyListConstructors=*/false, /*IsListInit=*/false, | ||||
| 6823 | /*SecondStepOfCopyInit=*/true); | ||||
| 6824 | |||||
| 6825 | PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy) | ||||
| 6826 | << OR << (int)Entity.getKind() << CurInitExpr->getType() | ||||
| 6827 | << CurInitExpr->getSourceRange(); | ||||
| 6828 | |||||
| 6829 | switch (OR) { | ||||
| 6830 | case OR_Success: | ||||
| 6831 | S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function), | ||||
| 6832 | Best->FoundDecl, Entity, Diag); | ||||
| 6833 | // FIXME: Check default arguments as far as that's possible. | ||||
| 6834 | break; | ||||
| 6835 | |||||
| 6836 | case OR_No_Viable_Function: | ||||
| 6837 | CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, | ||||
| 6838 | OCD_AllCandidates, CurInitExpr); | ||||
| 6839 | break; | ||||
| 6840 | |||||
| 6841 | case OR_Ambiguous: | ||||
| 6842 | CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, | ||||
| 6843 | OCD_AmbiguousCandidates, CurInitExpr); | ||||
| 6844 | break; | ||||
| 6845 | |||||
| 6846 | case OR_Deleted: | ||||
| 6847 | S.Diag(Loc, Diag); | ||||
| 6848 | S.NoteDeletedFunction(Best->Function); | ||||
| 6849 | break; | ||||
| 6850 | } | ||||
| 6851 | } | ||||
| 6852 | |||||
| 6853 | void InitializationSequence::PrintInitLocationNote(Sema &S, | ||||
| 6854 | const InitializedEntity &Entity) { | ||||
| 6855 | if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) { | ||||
| 6856 | if (Entity.getDecl()->getLocation().isInvalid()) | ||||
| 6857 | return; | ||||
| 6858 | |||||
| 6859 | if (Entity.getDecl()->getDeclName()) | ||||
| 6860 | S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) | ||||
| 6861 | << Entity.getDecl()->getDeclName(); | ||||
| 6862 | else | ||||
| 6863 | S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); | ||||
| 6864 | } | ||||
| 6865 | else if (Entity.getKind() == InitializedEntity::EK_RelatedResult && | ||||
| 6866 | Entity.getMethodDecl()) | ||||
| 6867 | S.Diag(Entity.getMethodDecl()->getLocation(), | ||||
| 6868 | diag::note_method_return_type_change) | ||||
| 6869 | << Entity.getMethodDecl()->getDeclName(); | ||||
| 6870 | } | ||||
| 6871 | |||||
| 6872 | /// Returns true if the parameters describe a constructor initialization of | ||||
| 6873 | /// an explicit temporary object, e.g. "Point(x, y)". | ||||
| 6874 | static bool isExplicitTemporary(const InitializedEntity &Entity, | ||||
| 6875 | const InitializationKind &Kind, | ||||
| 6876 | unsigned NumArgs) { | ||||
| 6877 | switch (Entity.getKind()) { | ||||
| 6878 | case InitializedEntity::EK_Temporary: | ||||
| 6879 | case InitializedEntity::EK_CompoundLiteralInit: | ||||
| 6880 | case InitializedEntity::EK_RelatedResult: | ||||
| 6881 | break; | ||||
| 6882 | default: | ||||
| 6883 | return false; | ||||
| 6884 | } | ||||
| 6885 | |||||
| 6886 | switch (Kind.getKind()) { | ||||
| 6887 | case InitializationKind::IK_DirectList: | ||||
| 6888 | return true; | ||||
| 6889 | // FIXME: Hack to work around cast weirdness. | ||||
| 6890 | case InitializationKind::IK_Direct: | ||||
| 6891 | case InitializationKind::IK_Value: | ||||
| 6892 | return NumArgs != 1; | ||||
| 6893 | default: | ||||
| 6894 | return false; | ||||
| 6895 | } | ||||
| 6896 | } | ||||
| 6897 | |||||
| 6898 | static ExprResult | ||||
| 6899 | PerformConstructorInitialization(Sema &S, | ||||
| 6900 | const InitializedEntity &Entity, | ||||
| 6901 | const InitializationKind &Kind, | ||||
| 6902 | MultiExprArg Args, | ||||
| 6903 | const InitializationSequence::Step& Step, | ||||
| 6904 | bool &ConstructorInitRequiresZeroInit, | ||||
| 6905 | bool IsListInitialization, | ||||
| 6906 | bool IsStdInitListInitialization, | ||||
| 6907 | SourceLocation LBraceLoc, | ||||
| 6908 | SourceLocation RBraceLoc) { | ||||
| 6909 | unsigned NumArgs = Args.size(); | ||||
| 6910 | CXXConstructorDecl *Constructor | ||||
| 6911 | = cast<CXXConstructorDecl>(Step.Function.Function); | ||||
| 6912 | bool HadMultipleCandidates = Step.Function.HadMultipleCandidates; | ||||
| 6913 | |||||
| 6914 | // Build a call to the selected constructor. | ||||
| 6915 | SmallVector<Expr*, 8> ConstructorArgs; | ||||
| 6916 | SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) | ||||
| 6917 | ? Kind.getEqualLoc() | ||||
| 6918 | : Kind.getLocation(); | ||||
| 6919 | |||||
| 6920 | if (Kind.getKind() == InitializationKind::IK_Default) { | ||||
| 6921 | // Force even a trivial, implicit default constructor to be | ||||
| 6922 | // semantically checked. We do this explicitly because we don't build | ||||
| 6923 | // the definition for completely trivial constructors. | ||||
| 6924 | 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", 6924, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 6925 | if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && | ||||
| 6926 | Constructor->isTrivial() && !Constructor->isUsed(false)) { | ||||
| 6927 | S.runWithSufficientStackSpace(Loc, [&] { | ||||
| 6928 | S.DefineImplicitDefaultConstructor(Loc, Constructor); | ||||
| 6929 | }); | ||||
| 6930 | } | ||||
| 6931 | } | ||||
| 6932 | |||||
| 6933 | ExprResult CurInit((Expr *)nullptr); | ||||
| 6934 | |||||
| 6935 | // C++ [over.match.copy]p1: | ||||
| 6936 | // - When initializing a temporary to be bound to the first parameter | ||||
| 6937 | // of a constructor that takes a reference to possibly cv-qualified | ||||
| 6938 | // T as its first argument, called with a single argument in the | ||||
| 6939 | // context of direct-initialization, explicit conversion functions | ||||
| 6940 | // are also considered. | ||||
| 6941 | bool AllowExplicitConv = | ||||
| 6942 | Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 && | ||||
| 6943 | hasCopyOrMoveCtorParam(S.Context, | ||||
| 6944 | getConstructorInfo(Step.Function.FoundDecl)); | ||||
| 6945 | |||||
| 6946 | // Determine the arguments required to actually perform the constructor | ||||
| 6947 | // call. | ||||
| 6948 | if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc, | ||||
| 6949 | ConstructorArgs, AllowExplicitConv, | ||||
| 6950 | IsListInitialization)) | ||||
| 6951 | return ExprError(); | ||||
| 6952 | |||||
| 6953 | if (isExplicitTemporary(Entity, Kind, NumArgs)) { | ||||
| 6954 | // An explicitly-constructed temporary, e.g., X(1, 2). | ||||
| 6955 | if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc)) | ||||
| 6956 | return ExprError(); | ||||
| 6957 | |||||
| 6958 | TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); | ||||
| 6959 | if (!TSInfo) | ||||
| 6960 | TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc); | ||||
| 6961 | SourceRange ParenOrBraceRange = | ||||
| 6962 | (Kind.getKind() == InitializationKind::IK_DirectList) | ||||
| 6963 | ? SourceRange(LBraceLoc, RBraceLoc) | ||||
| 6964 | : Kind.getParenOrBraceRange(); | ||||
| 6965 | |||||
| 6966 | CXXConstructorDecl *CalleeDecl = Constructor; | ||||
| 6967 | if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>( | ||||
| 6968 | Step.Function.FoundDecl.getDecl())) { | ||||
| 6969 | CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow); | ||||
| 6970 | } | ||||
| 6971 | S.MarkFunctionReferenced(Loc, CalleeDecl); | ||||
| 6972 | |||||
| 6973 | CurInit = S.CheckForImmediateInvocation( | ||||
| 6974 | CXXTemporaryObjectExpr::Create( | ||||
| 6975 | S.Context, CalleeDecl, | ||||
| 6976 | Entity.getType().getNonLValueExprType(S.Context), TSInfo, | ||||
| 6977 | ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates, | ||||
| 6978 | IsListInitialization, IsStdInitListInitialization, | ||||
| 6979 | ConstructorInitRequiresZeroInit), | ||||
| 6980 | CalleeDecl); | ||||
| 6981 | } else { | ||||
| 6982 | CXXConstructExpr::ConstructionKind ConstructKind = | ||||
| 6983 | CXXConstructExpr::CK_Complete; | ||||
| 6984 | |||||
| 6985 | if (Entity.getKind() == InitializedEntity::EK_Base) { | ||||
| 6986 | ConstructKind = Entity.getBaseSpecifier()->isVirtual() ? | ||||
| 6987 | CXXConstructExpr::CK_VirtualBase : | ||||
| 6988 | CXXConstructExpr::CK_NonVirtualBase; | ||||
| 6989 | } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { | ||||
| 6990 | ConstructKind = CXXConstructExpr::CK_Delegating; | ||||
| 6991 | } | ||||
| 6992 | |||||
| 6993 | // Only get the parenthesis or brace range if it is a list initialization or | ||||
| 6994 | // direct construction. | ||||
| 6995 | SourceRange ParenOrBraceRange; | ||||
| 6996 | if (IsListInitialization) | ||||
| 6997 | ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc); | ||||
| 6998 | else if (Kind.getKind() == InitializationKind::IK_Direct) | ||||
| 6999 | ParenOrBraceRange = Kind.getParenOrBraceRange(); | ||||
| 7000 | |||||
| 7001 | // If the entity allows NRVO, mark the construction as elidable | ||||
| 7002 | // unconditionally. | ||||
| 7003 | if (Entity.allowsNRVO()) | ||||
| 7004 | CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, | ||||
| 7005 | Step.Function.FoundDecl, | ||||
| 7006 | Constructor, /*Elidable=*/true, | ||||
| 7007 | ConstructorArgs, | ||||
| 7008 | HadMultipleCandidates, | ||||
| 7009 | IsListInitialization, | ||||
| 7010 | IsStdInitListInitialization, | ||||
| 7011 | ConstructorInitRequiresZeroInit, | ||||
| 7012 | ConstructKind, | ||||
| 7013 | ParenOrBraceRange); | ||||
| 7014 | else | ||||
| 7015 | CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, | ||||
| 7016 | Step.Function.FoundDecl, | ||||
| 7017 | Constructor, | ||||
| 7018 | ConstructorArgs, | ||||
| 7019 | HadMultipleCandidates, | ||||
| 7020 | IsListInitialization, | ||||
| 7021 | IsStdInitListInitialization, | ||||
| 7022 | ConstructorInitRequiresZeroInit, | ||||
| 7023 | ConstructKind, | ||||
| 7024 | ParenOrBraceRange); | ||||
| 7025 | } | ||||
| 7026 | if (CurInit.isInvalid()) | ||||
| 7027 | return ExprError(); | ||||
| 7028 | |||||
| 7029 | // Only check access if all of that succeeded. | ||||
| 7030 | S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity); | ||||
| 7031 | if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc)) | ||||
| 7032 | return ExprError(); | ||||
| 7033 | |||||
| 7034 | if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType())) | ||||
| 7035 | if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S)) | ||||
| 7036 | return ExprError(); | ||||
| 7037 | |||||
| 7038 | if (shouldBindAsTemporary(Entity)) | ||||
| 7039 | CurInit = S.MaybeBindToTemporary(CurInit.get()); | ||||
| 7040 | |||||
| 7041 | return CurInit; | ||||
| 7042 | } | ||||
| 7043 | |||||
| 7044 | namespace { | ||||
| 7045 | enum LifetimeKind { | ||||
| 7046 | /// The lifetime of a temporary bound to this entity ends at the end of the | ||||
| 7047 | /// full-expression, and that's (probably) fine. | ||||
| 7048 | LK_FullExpression, | ||||
| 7049 | |||||
| 7050 | /// The lifetime of a temporary bound to this entity is extended to the | ||||
| 7051 | /// lifeitme of the entity itself. | ||||
| 7052 | LK_Extended, | ||||
| 7053 | |||||
| 7054 | /// The lifetime of a temporary bound to this entity probably ends too soon, | ||||
| 7055 | /// because the entity is allocated in a new-expression. | ||||
| 7056 | LK_New, | ||||
| 7057 | |||||
| 7058 | /// The lifetime of a temporary bound to this entity ends too soon, because | ||||
| 7059 | /// the entity is a return object. | ||||
| 7060 | LK_Return, | ||||
| 7061 | |||||
| 7062 | /// The lifetime of a temporary bound to this entity ends too soon, because | ||||
| 7063 | /// the entity is the result of a statement expression. | ||||
| 7064 | LK_StmtExprResult, | ||||
| 7065 | |||||
| 7066 | /// This is a mem-initializer: if it would extend a temporary (other than via | ||||
| 7067 | /// a default member initializer), the program is ill-formed. | ||||
| 7068 | LK_MemInitializer, | ||||
| 7069 | }; | ||||
| 7070 | using LifetimeResult = | ||||
| 7071 | llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>; | ||||
| 7072 | } | ||||
| 7073 | |||||
| 7074 | /// Determine the declaration which an initialized entity ultimately refers to, | ||||
| 7075 | /// for the purpose of lifetime-extending a temporary bound to a reference in | ||||
| 7076 | /// the initialization of \p Entity. | ||||
| 7077 | static LifetimeResult getEntityLifetime( | ||||
| 7078 | const InitializedEntity *Entity, | ||||
| 7079 | const InitializedEntity *InitField = nullptr) { | ||||
| 7080 | // C++11 [class.temporary]p5: | ||||
| 7081 | switch (Entity->getKind()) { | ||||
| 7082 | case InitializedEntity::EK_Variable: | ||||
| 7083 | // The temporary [...] persists for the lifetime of the reference | ||||
| 7084 | return {Entity, LK_Extended}; | ||||
| 7085 | |||||
| 7086 | case InitializedEntity::EK_Member: | ||||
| 7087 | // For subobjects, we look at the complete object. | ||||
| 7088 | if (Entity->getParent()) | ||||
| 7089 | return getEntityLifetime(Entity->getParent(), Entity); | ||||
| 7090 | |||||
| 7091 | // except: | ||||
| 7092 | // C++17 [class.base.init]p8: | ||||
| 7093 | // A temporary expression bound to a reference member in a | ||||
| 7094 | // mem-initializer is ill-formed. | ||||
| 7095 | // C++17 [class.base.init]p11: | ||||
| 7096 | // A temporary expression bound to a reference member from a | ||||
| 7097 | // default member initializer is ill-formed. | ||||
| 7098 | // | ||||
| 7099 | // The context of p11 and its example suggest that it's only the use of a | ||||
| 7100 | // default member initializer from a constructor that makes the program | ||||
| 7101 | // ill-formed, not its mere existence, and that it can even be used by | ||||
| 7102 | // aggregate initialization. | ||||
| 7103 | return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended | ||||
| 7104 | : LK_MemInitializer}; | ||||
| 7105 | |||||
| 7106 | case InitializedEntity::EK_Binding: | ||||
| 7107 | // Per [dcl.decomp]p3, the binding is treated as a variable of reference | ||||
| 7108 | // type. | ||||
| 7109 | return {Entity, LK_Extended}; | ||||
| 7110 | |||||
| 7111 | case InitializedEntity::EK_Parameter: | ||||
| 7112 | case InitializedEntity::EK_Parameter_CF_Audited: | ||||
| 7113 | // -- A temporary bound to a reference parameter in a function call | ||||
| 7114 | // persists until the completion of the full-expression containing | ||||
| 7115 | // the call. | ||||
| 7116 | return {nullptr, LK_FullExpression}; | ||||
| 7117 | |||||
| 7118 | case InitializedEntity::EK_TemplateParameter: | ||||
| 7119 | // FIXME: This will always be ill-formed; should we eagerly diagnose it here? | ||||
| 7120 | return {nullptr, LK_FullExpression}; | ||||
| 7121 | |||||
| 7122 | case InitializedEntity::EK_Result: | ||||
| 7123 | // -- The lifetime of a temporary bound to the returned value in a | ||||
| 7124 | // function return statement is not extended; the temporary is | ||||
| 7125 | // destroyed at the end of the full-expression in the return statement. | ||||
| 7126 | return {nullptr, LK_Return}; | ||||
| 7127 | |||||
| 7128 | case InitializedEntity::EK_StmtExprResult: | ||||
| 7129 | // FIXME: Should we lifetime-extend through the result of a statement | ||||
| 7130 | // expression? | ||||
| 7131 | return {nullptr, LK_StmtExprResult}; | ||||
| 7132 | |||||
| 7133 | case InitializedEntity::EK_New: | ||||
| 7134 | // -- A temporary bound to a reference in a new-initializer persists | ||||
| 7135 | // until the completion of the full-expression containing the | ||||
| 7136 | // new-initializer. | ||||
| 7137 | return {nullptr, LK_New}; | ||||
| 7138 | |||||
| 7139 | case InitializedEntity::EK_Temporary: | ||||
| 7140 | case InitializedEntity::EK_CompoundLiteralInit: | ||||
| 7141 | case InitializedEntity::EK_RelatedResult: | ||||
| 7142 | // We don't yet know the storage duration of the surrounding temporary. | ||||
| 7143 | // Assume it's got full-expression duration for now, it will patch up our | ||||
| 7144 | // storage duration if that's not correct. | ||||
| 7145 | return {nullptr, LK_FullExpression}; | ||||
| 7146 | |||||
| 7147 | case InitializedEntity::EK_ArrayElement: | ||||
| 7148 | // For subobjects, we look at the complete object. | ||||
| 7149 | return getEntityLifetime(Entity->getParent(), InitField); | ||||
| 7150 | |||||
| 7151 | case InitializedEntity::EK_Base: | ||||
| 7152 | // For subobjects, we look at the complete object. | ||||
| 7153 | if (Entity->getParent()) | ||||
| 7154 | return getEntityLifetime(Entity->getParent(), InitField); | ||||
| 7155 | return {InitField, LK_MemInitializer}; | ||||
| 7156 | |||||
| 7157 | case InitializedEntity::EK_Delegating: | ||||
| 7158 | // We can reach this case for aggregate initialization in a constructor: | ||||
| 7159 | // struct A { int &&r; }; | ||||
| 7160 | // struct B : A { B() : A{0} {} }; | ||||
| 7161 | // In this case, use the outermost field decl as the context. | ||||
| 7162 | return {InitField, LK_MemInitializer}; | ||||
| 7163 | |||||
| 7164 | case InitializedEntity::EK_BlockElement: | ||||
| 7165 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | ||||
| 7166 | case InitializedEntity::EK_LambdaCapture: | ||||
| 7167 | case InitializedEntity::EK_VectorElement: | ||||
| 7168 | case InitializedEntity::EK_ComplexElement: | ||||
| 7169 | return {nullptr, LK_FullExpression}; | ||||
| 7170 | |||||
| 7171 | case InitializedEntity::EK_Exception: | ||||
| 7172 | // FIXME: Can we diagnose lifetime problems with exceptions? | ||||
| 7173 | return {nullptr, LK_FullExpression}; | ||||
| 7174 | |||||
| 7175 | case InitializedEntity::EK_ParenAggInitMember: | ||||
| 7176 | // -- A temporary object bound to a reference element of an aggregate of | ||||
| 7177 | // class type initialized from a parenthesized expression-list | ||||
| 7178 | // [dcl.init, 9.3] persists until the completion of the full-expression | ||||
| 7179 | // containing the expression-list. | ||||
| 7180 | return {nullptr, LK_FullExpression}; | ||||
| 7181 | } | ||||
| 7182 | |||||
| 7183 | llvm_unreachable("unknown entity kind")::llvm::llvm_unreachable_internal("unknown entity kind", "clang/lib/Sema/SemaInit.cpp" , 7183); | ||||
| 7184 | } | ||||
| 7185 | |||||
| 7186 | namespace { | ||||
| 7187 | enum ReferenceKind { | ||||
| 7188 | /// Lifetime would be extended by a reference binding to a temporary. | ||||
| 7189 | RK_ReferenceBinding, | ||||
| 7190 | /// Lifetime would be extended by a std::initializer_list object binding to | ||||
| 7191 | /// its backing array. | ||||
| 7192 | RK_StdInitializerList, | ||||
| 7193 | }; | ||||
| 7194 | |||||
| 7195 | /// A temporary or local variable. This will be one of: | ||||
| 7196 | /// * A MaterializeTemporaryExpr. | ||||
| 7197 | /// * A DeclRefExpr whose declaration is a local. | ||||
| 7198 | /// * An AddrLabelExpr. | ||||
| 7199 | /// * A BlockExpr for a block with captures. | ||||
| 7200 | using Local = Expr*; | ||||
| 7201 | |||||
| 7202 | /// Expressions we stepped over when looking for the local state. Any steps | ||||
| 7203 | /// that would inhibit lifetime extension or take us out of subexpressions of | ||||
| 7204 | /// the initializer are included. | ||||
| 7205 | struct IndirectLocalPathEntry { | ||||
| 7206 | enum EntryKind { | ||||
| 7207 | DefaultInit, | ||||
| 7208 | AddressOf, | ||||
| 7209 | VarInit, | ||||
| 7210 | LValToRVal, | ||||
| 7211 | LifetimeBoundCall, | ||||
| 7212 | TemporaryCopy, | ||||
| 7213 | LambdaCaptureInit, | ||||
| 7214 | GslReferenceInit, | ||||
| 7215 | GslPointerInit | ||||
| 7216 | } Kind; | ||||
| 7217 | Expr *E; | ||||
| 7218 | union { | ||||
| 7219 | const Decl *D = nullptr; | ||||
| 7220 | const LambdaCapture *Capture; | ||||
| 7221 | }; | ||||
| 7222 | IndirectLocalPathEntry() {} | ||||
| 7223 | IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {} | ||||
| 7224 | IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D) | ||||
| 7225 | : Kind(K), E(E), D(D) {} | ||||
| 7226 | IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture) | ||||
| 7227 | : Kind(K), E(E), Capture(Capture) {} | ||||
| 7228 | }; | ||||
| 7229 | |||||
| 7230 | using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>; | ||||
| 7231 | |||||
| 7232 | struct RevertToOldSizeRAII { | ||||
| 7233 | IndirectLocalPath &Path; | ||||
| 7234 | unsigned OldSize = Path.size(); | ||||
| 7235 | RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {} | ||||
| 7236 | ~RevertToOldSizeRAII() { Path.resize(OldSize); } | ||||
| 7237 | }; | ||||
| 7238 | |||||
| 7239 | using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L, | ||||
| 7240 | ReferenceKind RK)>; | ||||
| 7241 | } | ||||
| 7242 | |||||
| 7243 | static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) { | ||||
| 7244 | for (auto E : Path) | ||||
| 7245 | if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD) | ||||
| 7246 | return true; | ||||
| 7247 | return false; | ||||
| 7248 | } | ||||
| 7249 | |||||
| 7250 | static bool pathContainsInit(IndirectLocalPath &Path) { | ||||
| 7251 | return llvm::any_of(Path, [=](IndirectLocalPathEntry E) { | ||||
| 7252 | return E.Kind == IndirectLocalPathEntry::DefaultInit || | ||||
| 7253 | E.Kind == IndirectLocalPathEntry::VarInit; | ||||
| 7254 | }); | ||||
| 7255 | } | ||||
| 7256 | |||||
| 7257 | static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, | ||||
| 7258 | Expr *Init, LocalVisitor Visit, | ||||
| 7259 | bool RevisitSubinits, | ||||
| 7260 | bool EnableLifetimeWarnings); | ||||
| 7261 | |||||
| 7262 | static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, | ||||
| 7263 | Expr *Init, ReferenceKind RK, | ||||
| 7264 | LocalVisitor Visit, | ||||
| 7265 | bool EnableLifetimeWarnings); | ||||
| 7266 | |||||
| 7267 | template <typename T> static bool isRecordWithAttr(QualType Type) { | ||||
| 7268 | if (auto *RD = Type->getAsCXXRecordDecl()) | ||||
| 7269 | return RD->hasAttr<T>(); | ||||
| 7270 | return false; | ||||
| 7271 | } | ||||
| 7272 | |||||
| 7273 | // Decl::isInStdNamespace will return false for iterators in some STL | ||||
| 7274 | // implementations due to them being defined in a namespace outside of the std | ||||
| 7275 | // namespace. | ||||
| 7276 | static bool isInStlNamespace(const Decl *D) { | ||||
| 7277 | const DeclContext *DC = D->getDeclContext(); | ||||
| 7278 | if (!DC) | ||||
| 7279 | return false; | ||||
| 7280 | if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) | ||||
| 7281 | if (const IdentifierInfo *II = ND->getIdentifier()) { | ||||
| 7282 | StringRef Name = II->getName(); | ||||
| 7283 | if (Name.size() >= 2 && Name.front() == '_' && | ||||
| 7284 | (Name[1] == '_' || isUppercase(Name[1]))) | ||||
| 7285 | return true; | ||||
| 7286 | } | ||||
| 7287 | |||||
| 7288 | return DC->isStdNamespace(); | ||||
| 7289 | } | ||||
| 7290 | |||||
| 7291 | static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) { | ||||
| 7292 | if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee)) | ||||
| 7293 | if (isRecordWithAttr<PointerAttr>(Conv->getConversionType())) | ||||
| 7294 | return true; | ||||
| 7295 | if (!isInStlNamespace(Callee->getParent())) | ||||
| 7296 | return false; | ||||
| 7297 | if (!isRecordWithAttr<PointerAttr>(Callee->getThisObjectType()) && | ||||
| 7298 | !isRecordWithAttr<OwnerAttr>(Callee->getThisObjectType())) | ||||
| 7299 | return false; | ||||
| 7300 | if (Callee->getReturnType()->isPointerType() || | ||||
| 7301 | isRecordWithAttr<PointerAttr>(Callee->getReturnType())) { | ||||
| 7302 | if (!Callee->getIdentifier()) | ||||
| 7303 | return false; | ||||
| 7304 | return llvm::StringSwitch<bool>(Callee->getName()) | ||||
| 7305 | .Cases("begin", "rbegin", "cbegin", "crbegin", true) | ||||
| 7306 | .Cases("end", "rend", "cend", "crend", true) | ||||
| 7307 | .Cases("c_str", "data", "get", true) | ||||
| 7308 | // Map and set types. | ||||
| 7309 | .Cases("find", "equal_range", "lower_bound", "upper_bound", true) | ||||
| 7310 | .Default(false); | ||||
| 7311 | } else if (Callee->getReturnType()->isReferenceType()) { | ||||
| 7312 | if (!Callee->getIdentifier()) { | ||||
| 7313 | auto OO = Callee->getOverloadedOperator(); | ||||
| 7314 | return OO == OverloadedOperatorKind::OO_Subscript || | ||||
| 7315 | OO == OverloadedOperatorKind::OO_Star; | ||||
| 7316 | } | ||||
| 7317 | return llvm::StringSwitch<bool>(Callee->getName()) | ||||
| 7318 | .Cases("front", "back", "at", "top", "value", true) | ||||
| 7319 | .Default(false); | ||||
| 7320 | } | ||||
| 7321 | return false; | ||||
| 7322 | } | ||||
| 7323 | |||||
| 7324 | static bool shouldTrackFirstArgument(const FunctionDecl *FD) { | ||||
| 7325 | if (!FD->getIdentifier() || FD->getNumParams() != 1) | ||||
| 7326 | return false; | ||||
| 7327 | const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl(); | ||||
| 7328 | if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace()) | ||||
| 7329 | return false; | ||||
| 7330 | if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) && | ||||
| 7331 | !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0))) | ||||
| 7332 | return false; | ||||
| 7333 | if (FD->getReturnType()->isPointerType() || | ||||
| 7334 | isRecordWithAttr<PointerAttr>(FD->getReturnType())) { | ||||
| 7335 | return llvm::StringSwitch<bool>(FD->getName()) | ||||
| 7336 | .Cases("begin", "rbegin", "cbegin", "crbegin", true) | ||||
| 7337 | .Cases("end", "rend", "cend", "crend", true) | ||||
| 7338 | .Case("data", true) | ||||
| 7339 | .Default(false); | ||||
| 7340 | } else if (FD->getReturnType()->isReferenceType()) { | ||||
| 7341 | return llvm::StringSwitch<bool>(FD->getName()) | ||||
| 7342 | .Cases("get", "any_cast", true) | ||||
| 7343 | .Default(false); | ||||
| 7344 | } | ||||
| 7345 | return false; | ||||
| 7346 | } | ||||
| 7347 | |||||
| 7348 | static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call, | ||||
| 7349 | LocalVisitor Visit) { | ||||
| 7350 | auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) { | ||||
| 7351 | // We are not interested in the temporary base objects of gsl Pointers: | ||||
| 7352 | // Temp().ptr; // Here ptr might not dangle. | ||||
| 7353 | if (isa<MemberExpr>(Arg->IgnoreImpCasts())) | ||||
| 7354 | return; | ||||
| 7355 | // Once we initialized a value with a reference, it can no longer dangle. | ||||
| 7356 | if (!Value) { | ||||
| 7357 | for (const IndirectLocalPathEntry &PE : llvm::reverse(Path)) { | ||||
| 7358 | if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit) | ||||
| 7359 | continue; | ||||
| 7360 | if (PE.Kind == IndirectLocalPathEntry::GslPointerInit) | ||||
| 7361 | return; | ||||
| 7362 | break; | ||||
| 7363 | } | ||||
| 7364 | } | ||||
| 7365 | Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit | ||||
| 7366 | : IndirectLocalPathEntry::GslReferenceInit, | ||||
| 7367 | Arg, D}); | ||||
| 7368 | if (Arg->isGLValue()) | ||||
| 7369 | visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, | ||||
| 7370 | Visit, | ||||
| 7371 | /*EnableLifetimeWarnings=*/true); | ||||
| 7372 | else | ||||
| 7373 | visitLocalsRetainedByInitializer(Path, Arg, Visit, true, | ||||
| 7374 | /*EnableLifetimeWarnings=*/true); | ||||
| 7375 | Path.pop_back(); | ||||
| 7376 | }; | ||||
| 7377 | |||||
| 7378 | if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { | ||||
| 7379 | const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee()); | ||||
| 7380 | if (MD && shouldTrackImplicitObjectArg(MD)) | ||||
| 7381 | VisitPointerArg(MD, MCE->getImplicitObjectArgument(), | ||||
| 7382 | !MD->getReturnType()->isReferenceType()); | ||||
| 7383 | return; | ||||
| 7384 | } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) { | ||||
| 7385 | FunctionDecl *Callee = OCE->getDirectCallee(); | ||||
| 7386 | if (Callee && Callee->isCXXInstanceMember() && | ||||
| 7387 | shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee))) | ||||
| 7388 | VisitPointerArg(Callee, OCE->getArg(0), | ||||
| 7389 | !Callee->getReturnType()->isReferenceType()); | ||||
| 7390 | return; | ||||
| 7391 | } else if (auto *CE = dyn_cast<CallExpr>(Call)) { | ||||
| 7392 | FunctionDecl *Callee = CE->getDirectCallee(); | ||||
| 7393 | if (Callee && shouldTrackFirstArgument(Callee)) | ||||
| 7394 | VisitPointerArg(Callee, CE->getArg(0), | ||||
| 7395 | !Callee->getReturnType()->isReferenceType()); | ||||
| 7396 | return; | ||||
| 7397 | } | ||||
| 7398 | |||||
| 7399 | if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) { | ||||
| 7400 | const auto *Ctor = CCE->getConstructor(); | ||||
| 7401 | const CXXRecordDecl *RD = Ctor->getParent(); | ||||
| 7402 | if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>()) | ||||
| 7403 | VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true); | ||||
| 7404 | } | ||||
| 7405 | } | ||||
| 7406 | |||||
| 7407 | static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) { | ||||
| 7408 | const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); | ||||
| 7409 | if (!TSI) | ||||
| 7410 | return false; | ||||
| 7411 | // Don't declare this variable in the second operand of the for-statement; | ||||
| 7412 | // GCC miscompiles that by ending its lifetime before evaluating the | ||||
| 7413 | // third operand. See gcc.gnu.org/PR86769. | ||||
| 7414 | AttributedTypeLoc ATL; | ||||
| 7415 | for (TypeLoc TL = TSI->getTypeLoc(); | ||||
| 7416 | (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); | ||||
| 7417 | TL = ATL.getModifiedLoc()) { | ||||
| 7418 | if (ATL.getAttrAs<LifetimeBoundAttr>()) | ||||
| 7419 | return true; | ||||
| 7420 | } | ||||
| 7421 | |||||
| 7422 | // Assume that all assignment operators with a "normal" return type return | ||||
| 7423 | // *this, that is, an lvalue reference that is the same type as the implicit | ||||
| 7424 | // object parameter (or the LHS for a non-member operator$=). | ||||
| 7425 | OverloadedOperatorKind OO = FD->getDeclName().getCXXOverloadedOperator(); | ||||
| 7426 | if (OO == OO_Equal || isCompoundAssignmentOperator(OO)) { | ||||
| 7427 | QualType RetT = FD->getReturnType(); | ||||
| 7428 | if (RetT->isLValueReferenceType()) { | ||||
| 7429 | ASTContext &Ctx = FD->getASTContext(); | ||||
| 7430 | QualType LHST; | ||||
| 7431 | auto *MD = dyn_cast<CXXMethodDecl>(FD); | ||||
| 7432 | if (MD
| ||||
| 7433 | LHST = Ctx.getLValueReferenceType(MD->getThisObjectType()); | ||||
| 7434 | else | ||||
| 7435 | LHST = MD->getParamDecl(0)->getType(); | ||||
| |||||
| 7436 | if (Ctx.hasSameType(RetT, LHST)) | ||||
| 7437 | return true; | ||||
| 7438 | } | ||||
| 7439 | } | ||||
| 7440 | |||||
| 7441 | return false; | ||||
| 7442 | } | ||||
| 7443 | |||||
| 7444 | static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call, | ||||
| 7445 | LocalVisitor Visit) { | ||||
| 7446 | const FunctionDecl *Callee; | ||||
| 7447 | ArrayRef<Expr*> Args; | ||||
| 7448 | |||||
| 7449 | if (auto *CE
| ||||
| 7450 | Callee = CE->getDirectCallee(); | ||||
| 7451 | Args = llvm::ArrayRef(CE->getArgs(), CE->getNumArgs()); | ||||
| 7452 | } else { | ||||
| 7453 | auto *CCE = cast<CXXConstructExpr>(Call); | ||||
| 7454 | Callee = CCE->getConstructor(); | ||||
| 7455 | Args = llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()); | ||||
| 7456 | } | ||||
| 7457 | if (!Callee
| ||||
| 7458 | return; | ||||
| 7459 | |||||
| 7460 | Expr *ObjectArg = nullptr; | ||||
| 7461 | if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) { | ||||
| 7462 | ObjectArg = Args[0]; | ||||
| 7463 | Args = Args.slice(1); | ||||
| 7464 | } else if (auto *MCE
| ||||
| 7465 | ObjectArg = MCE->getImplicitObjectArgument(); | ||||
| 7466 | } | ||||
| 7467 | |||||
| 7468 | auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) { | ||||
| 7469 | Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D}); | ||||
| 7470 | if (Arg->isGLValue()) | ||||
| 7471 | visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, | ||||
| 7472 | Visit, | ||||
| 7473 | /*EnableLifetimeWarnings=*/false); | ||||
| 7474 | else | ||||
| 7475 | visitLocalsRetainedByInitializer(Path, Arg, Visit, true, | ||||
| 7476 | /*EnableLifetimeWarnings=*/false); | ||||
| 7477 | Path.pop_back(); | ||||
| 7478 | }; | ||||
| 7479 | |||||
| 7480 | if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee)) | ||||
| 7481 | VisitLifetimeBoundArg(Callee, ObjectArg); | ||||
| 7482 | |||||
| 7483 | for (unsigned I = 0, | ||||
| 7484 | N = std::min<unsigned>(Callee->getNumParams(), Args.size()); | ||||
| 7485 | I != N; ++I) { | ||||
| 7486 | if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>()) | ||||
| 7487 | VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]); | ||||
| 7488 | } | ||||
| 7489 | } | ||||
| 7490 | |||||
| 7491 | /// Visit the locals that would be reachable through a reference bound to the | ||||
| 7492 | /// glvalue expression \c Init. | ||||
| 7493 | static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, | ||||
| 7494 | Expr *Init, ReferenceKind RK, | ||||
| 7495 | LocalVisitor Visit, | ||||
| 7496 | bool EnableLifetimeWarnings) { | ||||
| 7497 | RevertToOldSizeRAII RAII(Path); | ||||
| 7498 | |||||
| 7499 | // Walk past any constructs which we can lifetime-extend across. | ||||
| 7500 | Expr *Old; | ||||
| 7501 | do { | ||||
| 7502 | Old = Init; | ||||
| 7503 | |||||
| 7504 | if (auto *FE = dyn_cast<FullExpr>(Init)) | ||||
| 7505 | Init = FE->getSubExpr(); | ||||
| 7506 | |||||
| 7507 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { | ||||
| 7508 | // If this is just redundant braces around an initializer, step over it. | ||||
| 7509 | if (ILE->isTransparent()) | ||||
| 7510 | Init = ILE->getInit(0); | ||||
| 7511 | } | ||||
| 7512 | |||||
| 7513 | // Step over any subobject adjustments; we may have a materialized | ||||
| 7514 | // temporary inside them. | ||||
| 7515 | Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); | ||||
| 7516 | |||||
| 7517 | // Per current approach for DR1376, look through casts to reference type | ||||
| 7518 | // when performing lifetime extension. | ||||
| 7519 | if (CastExpr *CE = dyn_cast<CastExpr>(Init)) | ||||
| 7520 | if (CE->getSubExpr()->isGLValue()) | ||||
| 7521 | Init = CE->getSubExpr(); | ||||
| 7522 | |||||
| 7523 | // Per the current approach for DR1299, look through array element access | ||||
| 7524 | // on array glvalues when performing lifetime extension. | ||||
| 7525 | if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) { | ||||
| 7526 | Init = ASE->getBase(); | ||||
| 7527 | auto *ICE = dyn_cast<ImplicitCastExpr>(Init); | ||||
| 7528 | if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay) | ||||
| 7529 | Init = ICE->getSubExpr(); | ||||
| 7530 | else | ||||
| 7531 | // We can't lifetime extend through this but we might still find some | ||||
| 7532 | // retained temporaries. | ||||
| 7533 | return visitLocalsRetainedByInitializer(Path, Init, Visit, true, | ||||
| 7534 | EnableLifetimeWarnings); | ||||
| 7535 | } | ||||
| 7536 | |||||
| 7537 | // Step into CXXDefaultInitExprs so we can diagnose cases where a | ||||
| 7538 | // constructor inherits one as an implicit mem-initializer. | ||||
| 7539 | if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { | ||||
| 7540 | Path.push_back( | ||||
| 7541 | {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); | ||||
| 7542 | Init = DIE->getExpr(); | ||||
| 7543 | } | ||||
| 7544 | } while (Init != Old); | ||||
| 7545 | |||||
| 7546 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) { | ||||
| 7547 | if (Visit(Path, Local(MTE), RK)) | ||||
| 7548 | visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true, | ||||
| 7549 | EnableLifetimeWarnings); | ||||
| 7550 | } | ||||
| 7551 | |||||
| 7552 | if (isa<CallExpr>(Init)) { | ||||
| 7553 | if (EnableLifetimeWarnings) | ||||
| 7554 | handleGslAnnotatedTypes(Path, Init, Visit); | ||||
| 7555 | return visitLifetimeBoundArguments(Path, Init, Visit); | ||||
| 7556 | } | ||||
| 7557 | |||||
| 7558 | switch (Init->getStmtClass()) { | ||||
| 7559 | case Stmt::DeclRefExprClass: { | ||||
| 7560 | // If we find the name of a local non-reference parameter, we could have a | ||||
| 7561 | // lifetime problem. | ||||
| 7562 | auto *DRE = cast<DeclRefExpr>(Init); | ||||
| 7563 | auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); | ||||
| 7564 | if (VD && VD->hasLocalStorage() && | ||||
| 7565 | !DRE->refersToEnclosingVariableOrCapture()) { | ||||
| 7566 | if (!VD->getType()->isReferenceType()) { | ||||
| 7567 | Visit(Path, Local(DRE), RK); | ||||
| 7568 | } else if (isa<ParmVarDecl>(DRE->getDecl())) { | ||||
| 7569 | // The lifetime of a reference parameter is unknown; assume it's OK | ||||
| 7570 | // for now. | ||||
| 7571 | break; | ||||
| 7572 | } else if (VD->getInit() && !isVarOnPath(Path, VD)) { | ||||
| 7573 | Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); | ||||
| 7574 | visitLocalsRetainedByReferenceBinding(Path, VD->getInit(), | ||||
| 7575 | RK_ReferenceBinding, Visit, | ||||
| 7576 | EnableLifetimeWarnings); | ||||
| 7577 | } | ||||
| 7578 | } | ||||
| 7579 | break; | ||||
| 7580 | } | ||||
| 7581 | |||||
| 7582 | case Stmt::UnaryOperatorClass: { | ||||
| 7583 | // The only unary operator that make sense to handle here | ||||
| 7584 | // is Deref. All others don't resolve to a "name." This includes | ||||
| 7585 | // handling all sorts of rvalues passed to a unary operator. | ||||
| 7586 | const UnaryOperator *U = cast<UnaryOperator>(Init); | ||||
| 7587 | if (U->getOpcode() == UO_Deref) | ||||
| 7588 | visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true, | ||||
| 7589 | EnableLifetimeWarnings); | ||||
| 7590 | break; | ||||
| 7591 | } | ||||
| 7592 | |||||
| 7593 | case Stmt::OMPArraySectionExprClass: { | ||||
| 7594 | visitLocalsRetainedByInitializer(Path, | ||||
| 7595 | cast<OMPArraySectionExpr>(Init)->getBase(), | ||||
| 7596 | Visit, true, EnableLifetimeWarnings); | ||||
| 7597 | break; | ||||
| 7598 | } | ||||
| 7599 | |||||
| 7600 | case Stmt::ConditionalOperatorClass: | ||||
| 7601 | case Stmt::BinaryConditionalOperatorClass: { | ||||
| 7602 | auto *C = cast<AbstractConditionalOperator>(Init); | ||||
| 7603 | if (!C->getTrueExpr()->getType()->isVoidType()) | ||||
| 7604 | visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit, | ||||
| 7605 | EnableLifetimeWarnings); | ||||
| 7606 | if (!C->getFalseExpr()->getType()->isVoidType()) | ||||
| 7607 | visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit, | ||||
| 7608 | EnableLifetimeWarnings); | ||||
| 7609 | break; | ||||
| 7610 | } | ||||
| 7611 | |||||
| 7612 | // FIXME: Visit the left-hand side of an -> or ->*. | ||||
| 7613 | |||||
| 7614 | default: | ||||
| 7615 | break; | ||||
| 7616 | } | ||||
| 7617 | } | ||||
| 7618 | |||||
| 7619 | /// Visit the locals that would be reachable through an object initialized by | ||||
| 7620 | /// the prvalue expression \c Init. | ||||
| 7621 | static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, | ||||
| 7622 | Expr *Init, LocalVisitor Visit, | ||||
| 7623 | bool RevisitSubinits, | ||||
| 7624 | bool EnableLifetimeWarnings) { | ||||
| 7625 | RevertToOldSizeRAII RAII(Path); | ||||
| 7626 | |||||
| 7627 | Expr *Old; | ||||
| 7628 | do { | ||||
| 7629 | Old = Init; | ||||
| 7630 | |||||
| 7631 | // Step into CXXDefaultInitExprs so we can diagnose cases where a | ||||
| 7632 | // constructor inherits one as an implicit mem-initializer. | ||||
| 7633 | if (auto *DIE
| ||||
| |||||
| 7634 | Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); | ||||
| 7635 | Init = DIE->getExpr(); | ||||
| 7636 | } | ||||
| 7637 | |||||
| 7638 | if (auto *FE
| ||||
| 7639 | Init = FE->getSubExpr(); | ||||
| 7640 | |||||
| 7641 | // Dig out the expression which constructs the extended temporary. | ||||
| 7642 | Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); | ||||
| 7643 | |||||
| 7644 | if (CXXBindTemporaryExpr *BTE
| ||||
| 7645 | Init = BTE->getSubExpr(); | ||||
| 7646 | |||||
| 7647 | Init = Init->IgnoreParens(); | ||||
| 7648 | |||||
| 7649 | // Step over value-preserving rvalue casts. | ||||
| 7650 | if (auto *CE
| ||||
| 7651 | switch (CE->getCastKind()) { | ||||
| 7652 | case CK_LValueToRValue: | ||||
| 7653 | // If we can match the lvalue to a const object, we can look at its | ||||
| 7654 | // initializer. | ||||
| 7655 | Path.push_back({IndirectLocalPathEntry::LValToRVal, CE}); | ||||
| 7656 | return visitLocalsRetainedByReferenceBinding( | ||||
| 7657 | Path, Init, RK_ReferenceBinding, | ||||
| 7658 | [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool { | ||||
| 7659 | if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { | ||||
| 7660 | auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); | ||||
| 7661 | if (VD && VD->getType().isConstQualified() && VD->getInit() && | ||||
| 7662 | !isVarOnPath(Path, VD)) { | ||||
| 7663 | Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); | ||||
| 7664 | visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true, | ||||
| 7665 | EnableLifetimeWarnings); | ||||
| 7666 | } | ||||
| 7667 | } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) { | ||||
| 7668 | if (MTE->getType().isConstQualified()) | ||||
| 7669 | visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, | ||||
| 7670 | true, EnableLifetimeWarnings); | ||||
| 7671 | } | ||||
| 7672 | return false; | ||||
| 7673 | }, EnableLifetimeWarnings); | ||||
| 7674 | |||||
| 7675 | // We assume that objects can be retained by pointers cast to integers, | ||||
| 7676 | // but not if the integer is cast to floating-point type or to _Complex. | ||||
| 7677 | // We assume that casts to 'bool' do not preserve enough information to | ||||
| 7678 | // retain a local object. | ||||
| 7679 | case CK_NoOp: | ||||
| 7680 | case CK_BitCast: | ||||
| 7681 | case CK_BaseToDerived: | ||||
| 7682 | case CK_DerivedToBase: | ||||
| 7683 | case CK_UncheckedDerivedToBase: | ||||
| 7684 | case CK_Dynamic: | ||||
| 7685 | case CK_ToUnion: | ||||
| 7686 | case CK_UserDefinedConversion: | ||||
| 7687 | case CK_ConstructorConversion: | ||||
| 7688 | case CK_IntegralToPointer: | ||||
| 7689 | case CK_PointerToIntegral: | ||||
| 7690 | case CK_VectorSplat: | ||||
| 7691 | case CK_IntegralCast: | ||||
| 7692 | case CK_CPointerToObjCPointerCast: | ||||
| 7693 | case CK_BlockPointerToObjCPointerCast: | ||||
| 7694 | case CK_AnyPointerToBlockPointerCast: | ||||
| 7695 | case CK_AddressSpaceConversion: | ||||
| 7696 | break; | ||||
| 7697 | |||||
| 7698 | case CK_ArrayToPointerDecay: | ||||
| 7699 | // Model array-to-pointer decay as taking the address of the array | ||||
| 7700 | // lvalue. | ||||
| 7701 | Path.push_back({IndirectLocalPathEntry::AddressOf, CE}); | ||||
| 7702 | return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(), | ||||
| 7703 | RK_ReferenceBinding, Visit, | ||||
| 7704 | EnableLifetimeWarnings); | ||||
| 7705 | |||||
| 7706 | default: | ||||
| 7707 | return; | ||||
| 7708 | } | ||||
| 7709 | |||||
| 7710 | Init = CE->getSubExpr(); | ||||
| 7711 | } | ||||
| 7712 | } while (Old != Init); | ||||
| 7713 | |||||
| 7714 | // C++17 [dcl.init.list]p6: | ||||
| 7715 | // initializing an initializer_list object from the array extends the | ||||
| 7716 | // lifetime of the array exactly like binding a reference to a temporary. | ||||
| 7717 | if (auto *ILE
| ||||
| 7718 | return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(), | ||||
| 7719 | RK_StdInitializerList, Visit, | ||||
| 7720 | EnableLifetimeWarnings); | ||||
| 7721 | |||||
| 7722 | if (InitListExpr *ILE
| ||||
| 7723 | // We already visited the elements of this initializer list while | ||||
| 7724 | // performing the initialization. Don't visit them again unless we've | ||||
| 7725 | // changed the lifetime of the initialized entity. | ||||
| 7726 | if (!RevisitSubinits) | ||||
| 7727 | return; | ||||
| 7728 | |||||
| 7729 | if (ILE->isTransparent()) | ||||
| 7730 | return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit, | ||||
| 7731 | RevisitSubinits, | ||||
| 7732 | EnableLifetimeWarnings); | ||||
| 7733 | |||||
| 7734 | if (ILE->getType()->isArrayType()) { | ||||
| 7735 | for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I) | ||||
| 7736 | visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit, | ||||
| 7737 | RevisitSubinits, | ||||
| 7738 | EnableLifetimeWarnings); | ||||
| 7739 | return; | ||||
| 7740 | } | ||||
| 7741 | |||||
| 7742 | if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) { | ||||
| 7743 | 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", 7743, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 7744 | |||||
| 7745 | // If we lifetime-extend a braced initializer which is initializing an | ||||
| 7746 | // aggregate, and that aggregate contains reference members which are | ||||
| 7747 | // bound to temporaries, those temporaries are also lifetime-extended. | ||||
| 7748 | if (RD->isUnion() && ILE->getInitializedFieldInUnion() && | ||||
| 7749 | ILE->getInitializedFieldInUnion()->getType()->isReferenceType()) | ||||
| 7750 | visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0), | ||||
| 7751 | RK_ReferenceBinding, Visit, | ||||
| 7752 | EnableLifetimeWarnings); | ||||
| 7753 | else { | ||||
| 7754 | unsigned Index = 0; | ||||
| 7755 | for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index) | ||||
| 7756 | visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit, | ||||
| 7757 | RevisitSubinits, | ||||
| 7758 | EnableLifetimeWarnings); | ||||
| 7759 | for (const auto *I : RD->fields()) { | ||||
| 7760 | if (Index >= ILE->getNumInits()) | ||||
| 7761 | break; | ||||
| 7762 | if (I->isUnnamedBitfield()) | ||||
| 7763 | continue; | ||||
| 7764 | Expr *SubInit = ILE->getInit(Index); | ||||
| 7765 | if (I->getType()->isReferenceType()) | ||||
| 7766 | visitLocalsRetainedByReferenceBinding(Path, SubInit, | ||||
| 7767 | RK_ReferenceBinding, Visit, | ||||
| 7768 | EnableLifetimeWarnings); | ||||
| 7769 | else | ||||
| 7770 | // This might be either aggregate-initialization of a member or | ||||
| 7771 | // initialization of a std::initializer_list object. Regardless, | ||||
| 7772 | // we should recursively lifetime-extend that initializer. | ||||
| 7773 | visitLocalsRetainedByInitializer(Path, SubInit, Visit, | ||||
| 7774 | RevisitSubinits, | ||||
| 7775 | EnableLifetimeWarnings); | ||||
| 7776 | ++Index; | ||||
| 7777 | } | ||||
| 7778 | } | ||||
| 7779 | } | ||||
| 7780 | return; | ||||
| 7781 | } | ||||
| 7782 | |||||
| 7783 | // The lifetime of an init-capture is that of the closure object constructed | ||||
| 7784 | // by a lambda-expression. | ||||
| 7785 | if (auto *LE
| ||||
| 7786 | LambdaExpr::capture_iterator CapI = LE->capture_begin(); | ||||
| 7787 | for (Expr *E : LE->capture_inits()) { | ||||
| 7788 | 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" , 7788, __extension__ __PRETTY_FUNCTION__)); | ||||
| 7789 | const LambdaCapture &Cap = *CapI++; | ||||
| 7790 | if (!E) | ||||
| 7791 | continue; | ||||
| 7792 | if (Cap.capturesVariable()) | ||||
| 7793 | Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap}); | ||||
| 7794 | if (E->isGLValue()) | ||||
| 7795 | visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding, | ||||
| 7796 | Visit, EnableLifetimeWarnings); | ||||
| 7797 | else | ||||
| 7798 | visitLocalsRetainedByInitializer(Path, E, Visit, true, | ||||
| 7799 | EnableLifetimeWarnings); | ||||
| 7800 | if (Cap.capturesVariable()) | ||||
| 7801 | Path.pop_back(); | ||||
| 7802 | } | ||||
| 7803 | } | ||||
| 7804 | |||||
| 7805 | // Assume that a copy or move from a temporary references the same objects | ||||
| 7806 | // that the temporary does. | ||||
| 7807 | if (auto *CCE
| ||||
| 7808 | if (CCE->getConstructor()->isCopyOrMoveConstructor()) { | ||||
| 7809 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) { | ||||
| 7810 | Expr *Arg = MTE->getSubExpr(); | ||||
| 7811 | Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg, | ||||
| 7812 | CCE->getConstructor()}); | ||||
| 7813 | visitLocalsRetainedByInitializer(Path, Arg, Visit, true, | ||||
| 7814 | /*EnableLifetimeWarnings*/false); | ||||
| 7815 | Path.pop_back(); | ||||
| 7816 | } | ||||
| 7817 | } | ||||
| 7818 | } | ||||
| 7819 | |||||
| 7820 | if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) { | ||||
| 7821 | if (EnableLifetimeWarnings) | ||||
| 7822 | handleGslAnnotatedTypes(Path, Init, Visit); | ||||
| 7823 | return visitLifetimeBoundArguments(Path, Init, Visit); | ||||
| 7824 | } | ||||
| 7825 | |||||
| 7826 | switch (Init->getStmtClass()) { | ||||
| 7827 | case Stmt::UnaryOperatorClass: { | ||||
| 7828 | auto *UO = cast<UnaryOperator>(Init); | ||||
| 7829 | // If the initializer is the address of a local, we could have a lifetime | ||||
| 7830 | // problem. | ||||
| 7831 | if (UO->getOpcode() == UO_AddrOf) { | ||||
| 7832 | // If this is &rvalue, then it's ill-formed and we have already diagnosed | ||||
| 7833 | // it. Don't produce a redundant warning about the lifetime of the | ||||
| 7834 | // temporary. | ||||
| 7835 | if (isa<MaterializeTemporaryExpr>(UO->getSubExpr())) | ||||
| 7836 | return; | ||||
| 7837 | |||||
| 7838 | Path.push_back({IndirectLocalPathEntry::AddressOf, UO}); | ||||
| 7839 | visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(), | ||||
| 7840 | RK_ReferenceBinding, Visit, | ||||
| 7841 | EnableLifetimeWarnings); | ||||
| 7842 | } | ||||
| 7843 | break; | ||||
| 7844 | } | ||||
| 7845 | |||||
| 7846 | case Stmt::BinaryOperatorClass: { | ||||
| 7847 | // Handle pointer arithmetic. | ||||
| 7848 | auto *BO = cast<BinaryOperator>(Init); | ||||
| 7849 | BinaryOperatorKind BOK = BO->getOpcode(); | ||||
| 7850 | if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub)) | ||||
| 7851 | break; | ||||
| 7852 | |||||
| 7853 | if (BO->getLHS()->getType()->isPointerType()) | ||||
| 7854 | visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true, | ||||
| 7855 | EnableLifetimeWarnings); | ||||
| 7856 | else if (BO->getRHS()->getType()->isPointerType()) | ||||
| 7857 | visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true, | ||||
| 7858 | EnableLifetimeWarnings); | ||||
| 7859 | break; | ||||
| 7860 | } | ||||
| 7861 | |||||
| 7862 | case Stmt::ConditionalOperatorClass: | ||||
| 7863 | case Stmt::BinaryConditionalOperatorClass: { | ||||
| 7864 | auto *C = cast<AbstractConditionalOperator>(Init); | ||||
| 7865 | // In C++, we can have a throw-expression operand, which has 'void' type | ||||
| 7866 | // and isn't interesting from a lifetime perspective. | ||||
| 7867 | if (!C->getTrueExpr()->getType()->isVoidType()) | ||||
| 7868 | visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true, | ||||
| 7869 | EnableLifetimeWarnings); | ||||
| 7870 | if (!C->getFalseExpr()->getType()->isVoidType()) | ||||
| 7871 | visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true, | ||||
| 7872 | EnableLifetimeWarnings); | ||||
| 7873 | break; | ||||
| 7874 | } | ||||
| 7875 | |||||
| 7876 | case Stmt::BlockExprClass: | ||||
| 7877 | if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) { | ||||
| 7878 | // This is a local block, whose lifetime is that of the function. | ||||
| 7879 | Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding); | ||||
| 7880 | } | ||||
| 7881 | break; | ||||
| 7882 | |||||
| 7883 | case Stmt::AddrLabelExprClass: | ||||
| 7884 | // We want to warn if the address of a label would escape the function. | ||||
| 7885 | Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding); | ||||
| 7886 | break; | ||||
| 7887 | |||||
| 7888 | default: | ||||
| 7889 | break; | ||||
| 7890 | } | ||||
| 7891 | } | ||||
| 7892 | |||||
| 7893 | /// Whether a path to an object supports lifetime extension. | ||||
| 7894 | enum PathLifetimeKind { | ||||
| 7895 | /// Lifetime-extend along this path. | ||||
| 7896 | Extend, | ||||
| 7897 | /// We should lifetime-extend, but we don't because (due to technical | ||||
| 7898 | /// limitations) we can't. This happens for default member initializers, | ||||
| 7899 | /// which we don't clone for every use, so we don't have a unique | ||||
| 7900 | /// MaterializeTemporaryExpr to update. | ||||
| 7901 | ShouldExtend, | ||||
| 7902 | /// Do not lifetime extend along this path. | ||||
| 7903 | NoExtend | ||||
| 7904 | }; | ||||
| 7905 | |||||
| 7906 | /// Determine whether this is an indirect path to a temporary that we are | ||||
| 7907 | /// supposed to lifetime-extend along. | ||||
| 7908 | static PathLifetimeKind | ||||
| 7909 | shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) { | ||||
| 7910 | PathLifetimeKind Kind = PathLifetimeKind::Extend; | ||||
| 7911 | for (auto Elem : Path) { | ||||
| 7912 | if (Elem.Kind == IndirectLocalPathEntry::DefaultInit) | ||||
| 7913 | Kind = PathLifetimeKind::ShouldExtend; | ||||
| 7914 | else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit) | ||||
| 7915 | return PathLifetimeKind::NoExtend; | ||||
| 7916 | } | ||||
| 7917 | return Kind; | ||||
| 7918 | } | ||||
| 7919 | |||||
| 7920 | /// Find the range for the first interesting entry in the path at or after I. | ||||
| 7921 | static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I, | ||||
| 7922 | Expr *E) { | ||||
| 7923 | for (unsigned N = Path.size(); I != N; ++I) { | ||||
| 7924 | switch (Path[I].Kind) { | ||||
| 7925 | case IndirectLocalPathEntry::AddressOf: | ||||
| 7926 | case IndirectLocalPathEntry::LValToRVal: | ||||
| 7927 | case IndirectLocalPathEntry::LifetimeBoundCall: | ||||
| 7928 | case IndirectLocalPathEntry::TemporaryCopy: | ||||
| 7929 | case IndirectLocalPathEntry::GslReferenceInit: | ||||
| 7930 | case IndirectLocalPathEntry::GslPointerInit: | ||||
| 7931 | // These exist primarily to mark the path as not permitting or | ||||
| 7932 | // supporting lifetime extension. | ||||
| 7933 | break; | ||||
| 7934 | |||||
| 7935 | case IndirectLocalPathEntry::VarInit: | ||||
| 7936 | if (cast<VarDecl>(Path[I].D)->isImplicit()) | ||||
| 7937 | return SourceRange(); | ||||
| 7938 | [[fallthrough]]; | ||||
| 7939 | case IndirectLocalPathEntry::DefaultInit: | ||||
| 7940 | return Path[I].E->getSourceRange(); | ||||
| 7941 | |||||
| 7942 | case IndirectLocalPathEntry::LambdaCaptureInit: | ||||
| 7943 | if (!Path[I].Capture->capturesVariable()) | ||||
| 7944 | continue; | ||||
| 7945 | return Path[I].E->getSourceRange(); | ||||
| 7946 | } | ||||
| 7947 | } | ||||
| 7948 | return E->getSourceRange(); | ||||
| 7949 | } | ||||
| 7950 | |||||
| 7951 | static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) { | ||||
| 7952 | for (const auto &It : llvm::reverse(Path)) { | ||||
| 7953 | if (It.Kind == IndirectLocalPathEntry::VarInit) | ||||
| 7954 | continue; | ||||
| 7955 | if (It.Kind == IndirectLocalPathEntry::AddressOf) | ||||
| 7956 | continue; | ||||
| 7957 | if (It.Kind == IndirectLocalPathEntry::LifetimeBoundCall) | ||||
| 7958 | continue; | ||||
| 7959 | return It.Kind == IndirectLocalPathEntry::GslPointerInit || | ||||
| 7960 | It.Kind == IndirectLocalPathEntry::GslReferenceInit; | ||||
| 7961 | } | ||||
| 7962 | return false; | ||||
| 7963 | } | ||||
| 7964 | |||||
| 7965 | void Sema::checkInitializerLifetime(const InitializedEntity &Entity, | ||||
| 7966 | Expr *Init) { | ||||
| 7967 | LifetimeResult LR = getEntityLifetime(&Entity); | ||||
| 7968 | LifetimeKind LK = LR.getInt(); | ||||
| 7969 | const InitializedEntity *ExtendingEntity = LR.getPointer(); | ||||
| 7970 | |||||
| 7971 | // If this entity doesn't have an interesting lifetime, don't bother looking | ||||
| 7972 | // for temporaries within its initializer. | ||||
| 7973 | if (LK == LK_FullExpression) | ||||
| 7974 | return; | ||||
| 7975 | |||||
| 7976 | auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L, | ||||
| 7977 | ReferenceKind RK) -> bool { | ||||
| 7978 | SourceRange DiagRange = nextPathEntryRange(Path, 0, L); | ||||
| 7979 | SourceLocation DiagLoc = DiagRange.getBegin(); | ||||
| 7980 | |||||
| 7981 | auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L); | ||||
| 7982 | |||||
| 7983 | bool IsGslPtrInitWithGslTempOwner = false; | ||||
| 7984 | bool IsLocalGslOwner = false; | ||||
| 7985 | if (pathOnlyInitializesGslPointer(Path)) { | ||||
| 7986 | if (isa<DeclRefExpr>(L)) { | ||||
| 7987 | // We do not want to follow the references when returning a pointer originating | ||||
| 7988 | // from a local owner to avoid the following false positive: | ||||
| 7989 | // int &p = *localUniquePtr; | ||||
| 7990 | // someContainer.add(std::move(localUniquePtr)); | ||||
| 7991 | // return p; | ||||
| 7992 | IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType()); | ||||
| 7993 | if (pathContainsInit(Path) || !IsLocalGslOwner) | ||||
| 7994 | return false; | ||||
| 7995 | } else { | ||||
| 7996 | IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() && | ||||
| 7997 | isRecordWithAttr<OwnerAttr>(MTE->getType()); | ||||
| 7998 | // Skipping a chain of initializing gsl::Pointer annotated objects. | ||||
| 7999 | // We are looking only for the final source to find out if it was | ||||
| 8000 | // a local or temporary owner or the address of a local variable/param. | ||||
| 8001 | if (!IsGslPtrInitWithGslTempOwner) | ||||
| 8002 | return true; | ||||
| 8003 | } | ||||
| 8004 | } | ||||
| 8005 | |||||
| 8006 | switch (LK) { | ||||
| 8007 | case LK_FullExpression: | ||||
| 8008 | llvm_unreachable("already handled this")::llvm::llvm_unreachable_internal("already handled this", "clang/lib/Sema/SemaInit.cpp" , 8008); | ||||
| 8009 | |||||
| 8010 | case LK_Extended: { | ||||
| 8011 | if (!MTE) { | ||||
| 8012 | // The initialized entity has lifetime beyond the full-expression, | ||||
| 8013 | // and the local entity does too, so don't warn. | ||||
| 8014 | // | ||||
| 8015 | // FIXME: We should consider warning if a static / thread storage | ||||
| 8016 | // duration variable retains an automatic storage duration local. | ||||
| 8017 | return false; | ||||
| 8018 | } | ||||
| 8019 | |||||
| 8020 | if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) { | ||||
| 8021 | Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange; | ||||
| 8022 | return false; | ||||
| 8023 | } | ||||
| 8024 | |||||
| 8025 | switch (shouldLifetimeExtendThroughPath(Path)) { | ||||
| 8026 | case PathLifetimeKind::Extend: | ||||
| 8027 | // Update the storage duration of the materialized temporary. | ||||
| 8028 | // FIXME: Rebuild the expression instead of mutating it. | ||||
| 8029 | MTE->setExtendingDecl(ExtendingEntity->getDecl(), | ||||
| 8030 | ExtendingEntity->allocateManglingNumber()); | ||||
| 8031 | // Also visit the temporaries lifetime-extended by this initializer. | ||||
| 8032 | return true; | ||||
| 8033 | |||||
| 8034 | case PathLifetimeKind::ShouldExtend: | ||||
| 8035 | // We're supposed to lifetime-extend the temporary along this path (per | ||||
| 8036 | // the resolution of DR1815), but we don't support that yet. | ||||
| 8037 | // | ||||
| 8038 | // FIXME: Properly handle this situation. Perhaps the easiest approach | ||||
| 8039 | // would be to clone the initializer expression on each use that would | ||||
| 8040 | // lifetime extend its temporaries. | ||||
| 8041 | Diag(DiagLoc, diag::warn_unsupported_lifetime_extension) | ||||
| 8042 | << RK << DiagRange; | ||||
| 8043 | break; | ||||
| 8044 | |||||
| 8045 | case PathLifetimeKind::NoExtend: | ||||
| 8046 | // If the path goes through the initialization of a variable or field, | ||||
| 8047 | // it can't possibly reach a temporary created in this full-expression. | ||||
| 8048 | // We will have already diagnosed any problems with the initializer. | ||||
| 8049 | if (pathContainsInit(Path)) | ||||
| 8050 | return false; | ||||
| 8051 | |||||
| 8052 | Diag(DiagLoc, diag::warn_dangling_variable) | ||||
| 8053 | << RK << !Entity.getParent() | ||||
| 8054 | << ExtendingEntity->getDecl()->isImplicit() | ||||
| 8055 | << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange; | ||||
| 8056 | break; | ||||
| 8057 | } | ||||
| 8058 | break; | ||||
| 8059 | } | ||||
| 8060 | |||||
| 8061 | case LK_MemInitializer: { | ||||
| 8062 | if (isa<MaterializeTemporaryExpr>(L)) { | ||||
| 8063 | // Under C++ DR1696, if a mem-initializer (or a default member | ||||
| 8064 | // initializer used by the absence of one) would lifetime-extend a | ||||
| 8065 | // temporary, the program is ill-formed. | ||||
| 8066 | if (auto *ExtendingDecl = | ||||
| 8067 | ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { | ||||
| 8068 | if (IsGslPtrInitWithGslTempOwner) { | ||||
| 8069 | Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member) | ||||
| 8070 | << ExtendingDecl << DiagRange; | ||||
| 8071 | Diag(ExtendingDecl->getLocation(), | ||||
| 8072 | diag::note_ref_or_ptr_member_declared_here) | ||||
| 8073 | << true; | ||||
| 8074 | return false; | ||||
| 8075 | } | ||||
| 8076 | bool IsSubobjectMember = ExtendingEntity != &Entity; | ||||
| 8077 | Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) != | ||||
| 8078 | PathLifetimeKind::NoExtend | ||||
| 8079 | ? diag::err_dangling_member | ||||
| 8080 | : diag::warn_dangling_member) | ||||
| 8081 | << ExtendingDecl << IsSubobjectMember << RK << DiagRange; | ||||
| 8082 | // Don't bother adding a note pointing to the field if we're inside | ||||
| 8083 | // its default member initializer; our primary diagnostic points to | ||||
| 8084 | // the same place in that case. | ||||
| 8085 | if (Path.empty() || | ||||
| 8086 | Path.back().Kind != IndirectLocalPathEntry::DefaultInit) { | ||||
| 8087 | Diag(ExtendingDecl->getLocation(), | ||||
| 8088 | diag::note_lifetime_extending_member_declared_here) | ||||
| 8089 | << RK << IsSubobjectMember; | ||||
| 8090 | } | ||||
| 8091 | } else { | ||||
| 8092 | // We have a mem-initializer but no particular field within it; this | ||||
| 8093 | // is either a base class or a delegating initializer directly | ||||
| 8094 | // initializing the base-class from something that doesn't live long | ||||
| 8095 | // enough. | ||||
| 8096 | // | ||||
| 8097 | // FIXME: Warn on this. | ||||
| 8098 | return false; | ||||
| 8099 | } | ||||
| 8100 | } else { | ||||
| 8101 | // Paths via a default initializer can only occur during error recovery | ||||
| 8102 | // (there's no other way that a default initializer can refer to a | ||||
| 8103 | // local). Don't produce a bogus warning on those cases. | ||||
| 8104 | if (pathContainsInit(Path)) | ||||
| 8105 | return false; | ||||
| 8106 | |||||
| 8107 | // Suppress false positives for code like the one below: | ||||
| 8108 | // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {} | ||||
| 8109 | if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path)) | ||||
| 8110 | return false; | ||||
| 8111 | |||||
| 8112 | auto *DRE = dyn_cast<DeclRefExpr>(L); | ||||
| 8113 | auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr; | ||||
| 8114 | if (!VD) { | ||||
| 8115 | // A member was initialized to a local block. | ||||
| 8116 | // FIXME: Warn on this. | ||||
| 8117 | return false; | ||||
| 8118 | } | ||||
| 8119 | |||||
| 8120 | if (auto *Member = | ||||
| 8121 | ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { | ||||
| 8122 | bool IsPointer = !Member->getType()->isReferenceType(); | ||||
| 8123 | Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr | ||||
| 8124 | : diag::warn_bind_ref_member_to_parameter) | ||||
| 8125 | << Member << VD << isa<ParmVarDecl>(VD) << DiagRange; | ||||
| 8126 | Diag(Member->getLocation(), | ||||
| 8127 | diag::note_ref_or_ptr_member_declared_here) | ||||
| 8128 | << (unsigned)IsPointer; | ||||
| 8129 | } | ||||
| 8130 | } | ||||
| 8131 | break; | ||||
| 8132 | } | ||||
| 8133 | |||||
| 8134 | case LK_New: | ||||
| 8135 | if (isa<MaterializeTemporaryExpr>(L)) { | ||||
| 8136 | if (IsGslPtrInitWithGslTempOwner) | ||||
| 8137 | Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange; | ||||
| 8138 | else | ||||
| 8139 | Diag(DiagLoc, RK == RK_ReferenceBinding | ||||
| 8140 | ? diag::warn_new_dangling_reference | ||||
| 8141 | : diag::warn_new_dangling_initializer_list) | ||||
| 8142 | << !Entity.getParent() << DiagRange; | ||||
| 8143 | } else { | ||||
| 8144 | // We can't determine if the allocation outlives the local declaration. | ||||
| 8145 | return false; | ||||
| 8146 | } | ||||
| 8147 | break; | ||||
| 8148 | |||||
| 8149 | case LK_Return: | ||||
| 8150 | case LK_StmtExprResult: | ||||
| 8151 | if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { | ||||
| 8152 | // We can't determine if the local variable outlives the statement | ||||
| 8153 | // expression. | ||||
| 8154 | if (LK == LK_StmtExprResult) | ||||
| 8155 | return false; | ||||
| 8156 | Diag(DiagLoc, diag::warn_ret_stack_addr_ref) | ||||
| 8157 | << Entity.getType()->isReferenceType() << DRE->getDecl() | ||||
| 8158 | << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange; | ||||
| 8159 | } else if (isa<BlockExpr>(L)) { | ||||
| 8160 | Diag(DiagLoc, diag::err_ret_local_block) << DiagRange; | ||||
| 8161 | } else if (isa<AddrLabelExpr>(L)) { | ||||
| 8162 | // Don't warn when returning a label from a statement expression. | ||||
| 8163 | // Leaving the scope doesn't end its lifetime. | ||||
| 8164 | if (LK == LK_StmtExprResult) | ||||
| 8165 | return false; | ||||
| 8166 | Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange; | ||||
| 8167 | } else { | ||||
| 8168 | Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref) | ||||
| 8169 | << Entity.getType()->isReferenceType() << DiagRange; | ||||
| 8170 | } | ||||
| 8171 | break; | ||||
| 8172 | } | ||||
| 8173 | |||||
| 8174 | for (unsigned I = 0; I != Path.size(); ++I) { | ||||
| 8175 | auto Elem = Path[I]; | ||||
| 8176 | |||||
| 8177 | switch (Elem.Kind) { | ||||
| 8178 | case IndirectLocalPathEntry::AddressOf: | ||||
| 8179 | case IndirectLocalPathEntry::LValToRVal: | ||||
| 8180 | // These exist primarily to mark the path as not permitting or | ||||
| 8181 | // supporting lifetime extension. | ||||
| 8182 | break; | ||||
| 8183 | |||||
| 8184 | case IndirectLocalPathEntry::LifetimeBoundCall: | ||||
| 8185 | case IndirectLocalPathEntry::TemporaryCopy: | ||||
| 8186 | case IndirectLocalPathEntry::GslPointerInit: | ||||
| 8187 | case IndirectLocalPathEntry::GslReferenceInit: | ||||
| 8188 | // FIXME: Consider adding a note for these. | ||||
| 8189 | break; | ||||
| 8190 | |||||
| 8191 | case IndirectLocalPathEntry::DefaultInit: { | ||||
| 8192 | auto *FD = cast<FieldDecl>(Elem.D); | ||||
| 8193 | Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer) | ||||
| 8194 | << FD << nextPathEntryRange(Path, I + 1, L); | ||||
| 8195 | break; | ||||
| 8196 | } | ||||
| 8197 | |||||
| 8198 | case IndirectLocalPathEntry::VarInit: { | ||||
| 8199 | const VarDecl *VD = cast<VarDecl>(Elem.D); | ||||
| 8200 | Diag(VD->getLocation(), diag::note_local_var_initializer) | ||||
| 8201 | << VD->getType()->isReferenceType() | ||||
| 8202 | << VD->isImplicit() << VD->getDeclName() | ||||
| 8203 | << nextPathEntryRange(Path, I + 1, L); | ||||
| 8204 | break; | ||||
| 8205 | } | ||||
| 8206 | |||||
| 8207 | case IndirectLocalPathEntry::LambdaCaptureInit: | ||||
| 8208 | if (!Elem.Capture->capturesVariable()) | ||||
| 8209 | break; | ||||
| 8210 | // FIXME: We can't easily tell apart an init-capture from a nested | ||||
| 8211 | // capture of an init-capture. | ||||
| 8212 | const ValueDecl *VD = Elem.Capture->getCapturedVar(); | ||||
| 8213 | Diag(Elem.Capture->getLocation(), diag::note_lambda_capture_initializer) | ||||
| 8214 | << VD << VD->isInitCapture() << Elem.Capture->isExplicit() | ||||
| 8215 | << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD | ||||
| 8216 | << nextPathEntryRange(Path, I + 1, L); | ||||
| 8217 | break; | ||||
| 8218 | } | ||||
| 8219 | } | ||||
| 8220 | |||||
| 8221 | // We didn't lifetime-extend, so don't go any further; we don't need more | ||||
| 8222 | // warnings or errors on inner temporaries within this one's initializer. | ||||
| 8223 | return false; | ||||
| 8224 | }; | ||||
| 8225 | |||||
| 8226 | bool EnableLifetimeWarnings = !getDiagnostics().isIgnored( | ||||
| 8227 | diag::warn_dangling_lifetime_pointer, SourceLocation()); | ||||
| 8228 | llvm::SmallVector<IndirectLocalPathEntry, 8> Path; | ||||
| 8229 | if (Init->isGLValue()) | ||||
| 8230 | visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding, | ||||
| 8231 | TemporaryVisitor, | ||||
| 8232 | EnableLifetimeWarnings); | ||||
| 8233 | else | ||||
| 8234 | visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false, | ||||
| 8235 | EnableLifetimeWarnings); | ||||
| 8236 | } | ||||
| 8237 | |||||
| 8238 | static void DiagnoseNarrowingInInitList(Sema &S, | ||||
| 8239 | const ImplicitConversionSequence &ICS, | ||||
| 8240 | QualType PreNarrowingType, | ||||
| 8241 | QualType EntityType, | ||||
| 8242 | const Expr *PostInit); | ||||
| 8243 | |||||
| 8244 | /// Provide warnings when std::move is used on construction. | ||||
| 8245 | static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, | ||||
| 8246 | bool IsReturnStmt) { | ||||
| 8247 | if (!InitExpr) | ||||
| 8248 | return; | ||||
| 8249 | |||||
| 8250 | if (S.inTemplateInstantiation()) | ||||
| 8251 | return; | ||||
| 8252 | |||||
| 8253 | QualType DestType = InitExpr->getType(); | ||||
| 8254 | if (!DestType->isRecordType()) | ||||
| 8255 | return; | ||||
| 8256 | |||||
| 8257 | unsigned DiagID = 0; | ||||
| 8258 | if (IsReturnStmt) { | ||||
| 8259 | const CXXConstructExpr *CCE = | ||||
| 8260 | dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens()); | ||||
| 8261 | if (!CCE || CCE->getNumArgs() != 1) | ||||
| 8262 | return; | ||||
| 8263 | |||||
| 8264 | if (!CCE->getConstructor()->isCopyOrMoveConstructor()) | ||||
| 8265 | return; | ||||
| 8266 | |||||
| 8267 | InitExpr = CCE->getArg(0)->IgnoreImpCasts(); | ||||
| 8268 | } | ||||
| 8269 | |||||
| 8270 | // Find the std::move call and get the argument. | ||||
| 8271 | const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens()); | ||||
| 8272 | if (!CE || !CE->isCallToStdMove()) | ||||
| 8273 | return; | ||||
| 8274 | |||||
| 8275 | const Expr *Arg = CE->getArg(0)->IgnoreImplicit(); | ||||
| 8276 | |||||
| 8277 | if (IsReturnStmt) { | ||||
| 8278 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts()); | ||||
| 8279 | if (!DRE || DRE->refersToEnclosingVariableOrCapture()) | ||||
| 8280 | return; | ||||
| 8281 | |||||
| 8282 | const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()); | ||||
| 8283 | if (!VD || !VD->hasLocalStorage()) | ||||
| 8284 | return; | ||||
| 8285 | |||||
| 8286 | // __block variables are not moved implicitly. | ||||
| 8287 | if (VD->hasAttr<BlocksAttr>()) | ||||
| 8288 | return; | ||||
| 8289 | |||||
| 8290 | QualType SourceType = VD->getType(); | ||||
| 8291 | if (!SourceType->isRecordType()) | ||||
| 8292 | return; | ||||
| 8293 | |||||
| 8294 | if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) { | ||||
| 8295 | return; | ||||
| 8296 | } | ||||
| 8297 | |||||
| 8298 | // If we're returning a function parameter, copy elision | ||||
| 8299 | // is not possible. | ||||
| 8300 | if (isa<ParmVarDecl>(VD)) | ||||
| 8301 | DiagID = diag::warn_redundant_move_on_return; | ||||
| 8302 | else | ||||
| 8303 | DiagID = diag::warn_pessimizing_move_on_return; | ||||
| 8304 | } else { | ||||
| 8305 | DiagID = diag::warn_pessimizing_move_on_initialization; | ||||
| 8306 | const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens(); | ||||
| 8307 | if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType()) | ||||
| 8308 | return; | ||||
| 8309 | } | ||||
| 8310 | |||||
| 8311 | S.Diag(CE->getBeginLoc(), DiagID); | ||||
| 8312 | |||||
| 8313 | // Get all the locations for a fix-it. Don't emit the fix-it if any location | ||||
| 8314 | // is within a macro. | ||||
| 8315 | SourceLocation CallBegin = CE->getCallee()->getBeginLoc(); | ||||
| 8316 | if (CallBegin.isMacroID()) | ||||
| 8317 | return; | ||||
| 8318 | SourceLocation RParen = CE->getRParenLoc(); | ||||
| 8319 | if (RParen.isMacroID()) | ||||
| 8320 | return; | ||||
| 8321 | SourceLocation LParen; | ||||
| 8322 | SourceLocation ArgLoc = Arg->getBeginLoc(); | ||||
| 8323 | |||||
| 8324 | // Special testing for the argument location. Since the fix-it needs the | ||||
| 8325 | // location right before the argument, the argument location can be in a | ||||
| 8326 | // macro only if it is at the beginning of the macro. | ||||
| 8327 | while (ArgLoc.isMacroID() && | ||||
| 8328 | S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) { | ||||
| 8329 | ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin(); | ||||
| 8330 | } | ||||
| 8331 | |||||
| 8332 | if (LParen.isMacroID()) | ||||
| 8333 | return; | ||||
| 8334 | |||||
| 8335 | LParen = ArgLoc.getLocWithOffset(-1); | ||||
| 8336 | |||||
| 8337 | S.Diag(CE->getBeginLoc(), diag::note_remove_move) | ||||
| 8338 | << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen)) | ||||
| 8339 | << FixItHint::CreateRemoval(SourceRange(RParen, RParen)); | ||||
| 8340 | } | ||||
| 8341 | |||||
| 8342 | static void CheckForNullPointerDereference(Sema &S, const Expr *E) { | ||||
| 8343 | // Check to see if we are dereferencing a null pointer. If so, this is | ||||
| 8344 | // undefined behavior, so warn about it. This only handles the pattern | ||||
| 8345 | // "*null", which is a very syntactic check. | ||||
| 8346 | if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) | ||||
| 8347 | if (UO->getOpcode() == UO_Deref && | ||||
| 8348 | UO->getSubExpr()->IgnoreParenCasts()-> | ||||
| 8349 | isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) { | ||||
| 8350 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||
| 8351 | S.PDiag(diag::warn_binding_null_to_reference) | ||||
| 8352 | << UO->getSubExpr()->getSourceRange()); | ||||
| 8353 | } | ||||
| 8354 | } | ||||
| 8355 | |||||
| 8356 | MaterializeTemporaryExpr * | ||||
| 8357 | Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, | ||||
| 8358 | bool BoundToLvalueReference) { | ||||
| 8359 | auto MTE = new (Context) | ||||
| 8360 | MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference); | ||||
| 8361 | |||||
| 8362 | // Order an ExprWithCleanups for lifetime marks. | ||||
| 8363 | // | ||||
| 8364 | // TODO: It'll be good to have a single place to check the access of the | ||||
| 8365 | // destructor and generate ExprWithCleanups for various uses. Currently these | ||||
| 8366 | // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary, | ||||
| 8367 | // but there may be a chance to merge them. | ||||
| 8368 | Cleanup.setExprNeedsCleanups(false); | ||||
| 8369 | return MTE; | ||||
| 8370 | } | ||||
| 8371 | |||||
| 8372 | ExprResult Sema::TemporaryMaterializationConversion(Expr *E) { | ||||
| 8373 | // In C++98, we don't want to implicitly create an xvalue. | ||||
| 8374 | // FIXME: This means that AST consumers need to deal with "prvalues" that | ||||
| 8375 | // denote materialized temporaries. Maybe we should add another ValueKind | ||||
| 8376 | // for "xvalue pretending to be a prvalue" for C++98 support. | ||||
| 8377 | if (!E->isPRValue() || !getLangOpts().CPlusPlus11) | ||||
| 8378 | return E; | ||||
| 8379 | |||||
| 8380 | // C++1z [conv.rval]/1: T shall be a complete type. | ||||
| 8381 | // FIXME: Does this ever matter (can we form a prvalue of incomplete type)? | ||||
| 8382 | // If so, we should check for a non-abstract class type here too. | ||||
| 8383 | QualType T = E->getType(); | ||||
| 8384 | if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type)) | ||||
| 8385 | return ExprError(); | ||||
| 8386 | |||||
| 8387 | return CreateMaterializeTemporaryExpr(E->getType(), E, false); | ||||
| 8388 | } | ||||
| 8389 | |||||
| 8390 | ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty, | ||||
| 8391 | ExprValueKind VK, | ||||
| 8392 | CheckedConversionKind CCK) { | ||||
| 8393 | |||||
| 8394 | CastKind CK = CK_NoOp; | ||||
| 8395 | |||||
| 8396 | if (VK == VK_PRValue) { | ||||
| 8397 | auto PointeeTy = Ty->getPointeeType(); | ||||
| 8398 | auto ExprPointeeTy = E->getType()->getPointeeType(); | ||||
| 8399 | if (!PointeeTy.isNull() && | ||||
| 8400 | PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace()) | ||||
| 8401 | CK = CK_AddressSpaceConversion; | ||||
| 8402 | } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) { | ||||
| 8403 | CK = CK_AddressSpaceConversion; | ||||
| 8404 | } | ||||
| 8405 | |||||
| 8406 | return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK); | ||||
| 8407 | } | ||||
| 8408 | |||||
| 8409 | ExprResult InitializationSequence::Perform(Sema &S, | ||||
| 8410 | const InitializedEntity &Entity, | ||||
| 8411 | const InitializationKind &Kind, | ||||
| 8412 | MultiExprArg Args, | ||||
| 8413 | QualType *ResultType) { | ||||
| 8414 | if (Failed()) { | ||||
| 8415 | Diagnose(S, Entity, Kind, Args); | ||||
| 8416 | return ExprError(); | ||||
| 8417 | } | ||||
| 8418 | if (!ZeroInitializationFixit.empty()) { | ||||
| 8419 | const Decl *D = Entity.getDecl(); | ||||
| 8420 | const auto *VD = dyn_cast_or_null<VarDecl>(D); | ||||
| 8421 | QualType DestType = Entity.getType(); | ||||
| 8422 | |||||
| 8423 | // The initialization would have succeeded with this fixit. Since the fixit | ||||
| 8424 | // is on the error, we need to build a valid AST in this case, so this isn't | ||||
| 8425 | // handled in the Failed() branch above. | ||||
| 8426 | if (!DestType->isRecordType() && VD && VD->isConstexpr()) { | ||||
| 8427 | // Use a more useful diagnostic for constexpr variables. | ||||
| 8428 | S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init) | ||||
| 8429 | << VD | ||||
| 8430 | << FixItHint::CreateInsertion(ZeroInitializationFixitLoc, | ||||
| 8431 | ZeroInitializationFixit); | ||||
| 8432 | } else { | ||||
| 8433 | unsigned DiagID = diag::err_default_init_const; | ||||
| 8434 | if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>()) | ||||
| 8435 | DiagID = diag::ext_default_init_const; | ||||
| 8436 | |||||
| 8437 | S.Diag(Kind.getLocation(), DiagID) | ||||
| 8438 | << DestType << (bool)DestType->getAs<RecordType>() | ||||
| 8439 | << FixItHint::CreateInsertion(ZeroInitializationFixitLoc, | ||||
| 8440 | ZeroInitializationFixit); | ||||
| 8441 | } | ||||
| 8442 | } | ||||
| 8443 | |||||
| 8444 | if (getKind() == DependentSequence) { | ||||
| 8445 | // If the declaration is a non-dependent, incomplete array type | ||||
| 8446 | // that has an initializer, then its type will be completed once | ||||
| 8447 | // the initializer is instantiated. | ||||
| 8448 | if (ResultType && !Entity.getType()->isDependentType() && | ||||
| 8449 | Args.size() == 1) { | ||||
| 8450 | QualType DeclType = Entity.getType(); | ||||
| 8451 | if (const IncompleteArrayType *ArrayT | ||||
| 8452 | = S.Context.getAsIncompleteArrayType(DeclType)) { | ||||
| 8453 | // FIXME: We don't currently have the ability to accurately | ||||
| 8454 | // compute the length of an initializer list without | ||||
| 8455 | // performing full type-checking of the initializer list | ||||
| 8456 | // (since we have to determine where braces are implicitly | ||||
| 8457 | // introduced and such). So, we fall back to making the array | ||||
| 8458 | // type a dependently-sized array type with no specified | ||||
| 8459 | // bound. | ||||
| 8460 | if (isa<InitListExpr>((Expr *)Args[0])) { | ||||
| 8461 | SourceRange Brackets; | ||||
| 8462 | |||||
| 8463 | // Scavange the location of the brackets from the entity, if we can. | ||||
| 8464 | if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) { | ||||
| 8465 | if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { | ||||
| 8466 | TypeLoc TL = TInfo->getTypeLoc(); | ||||
| 8467 | if (IncompleteArrayTypeLoc ArrayLoc = | ||||
| 8468 | TL.getAs<IncompleteArrayTypeLoc>()) | ||||
| 8469 | Brackets = ArrayLoc.getBracketsRange(); | ||||
| 8470 | } | ||||
| 8471 | } | ||||
| 8472 | |||||
| 8473 | *ResultType | ||||
| 8474 | = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), | ||||
| 8475 | /*NumElts=*/nullptr, | ||||
| 8476 | ArrayT->getSizeModifier(), | ||||
| 8477 | ArrayT->getIndexTypeCVRQualifiers(), | ||||
| 8478 | Brackets); | ||||
| 8479 | } | ||||
| 8480 | |||||
| 8481 | } | ||||
| 8482 | } | ||||
| 8483 | if (Kind.getKind() == InitializationKind::IK_Direct && | ||||
| 8484 | !Kind.isExplicitCast()) { | ||||
| 8485 | // Rebuild the ParenListExpr. | ||||
| 8486 | SourceRange ParenRange = Kind.getParenOrBraceRange(); | ||||
| 8487 | return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(), | ||||
| 8488 | Args); | ||||
| 8489 | } | ||||
| 8490 | 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", 8492, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 8491 | 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", 8492, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 8492 | 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", 8492, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 8493 | return ExprResult(Args[0]); | ||||
| 8494 | } | ||||
| 8495 | |||||
| 8496 | // No steps means no initialization. | ||||
| 8497 | if (Steps.empty()) | ||||
| 8498 | return ExprResult((Expr *)nullptr); | ||||
| 8499 | |||||
| 8500 | if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() && | ||||
| 8501 | Args.size() == 1 && isa<InitListExpr>(Args[0]) && | ||||
| 8502 | !Entity.isParamOrTemplateParamKind()) { | ||||
| 8503 | // Produce a C++98 compatibility warning if we are initializing a reference | ||||
| 8504 | // from an initializer list. For parameters, we produce a better warning | ||||
| 8505 | // elsewhere. | ||||
| 8506 | Expr *Init = Args[0]; | ||||
| 8507 | S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init) | ||||
| 8508 | << Init->getSourceRange(); | ||||
| 8509 | } | ||||
| 8510 | |||||
| 8511 | // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope | ||||
| 8512 | QualType ETy = Entity.getType(); | ||||
| 8513 | bool HasGlobalAS = ETy.hasAddressSpace() && | ||||
| 8514 | ETy.getAddressSpace() == LangAS::opencl_global; | ||||
| 8515 | |||||
| 8516 | if (S.getLangOpts().OpenCLVersion >= 200 && | ||||
| 8517 | ETy->isAtomicType() && !HasGlobalAS && | ||||
| 8518 | Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) { | ||||
| 8519 | S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init) | ||||
| 8520 | << 1 | ||||
| 8521 | << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc()); | ||||
| 8522 | return ExprError(); | ||||
| 8523 | } | ||||
| 8524 | |||||
| 8525 | QualType DestType = Entity.getType().getNonReferenceType(); | ||||
| 8526 | // FIXME: Ugly hack around the fact that Entity.getType() is not | ||||
| 8527 | // the same as Entity.getDecl()->getType() in cases involving type merging, | ||||
| 8528 | // and we want latter when it makes sense. | ||||
| 8529 | if (ResultType) | ||||
| 8530 | *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : | ||||
| 8531 | Entity.getType(); | ||||
| 8532 | |||||
| 8533 | ExprResult CurInit((Expr *)nullptr); | ||||
| 8534 | SmallVector<Expr*, 4> ArrayLoopCommonExprs; | ||||
| 8535 | |||||
| 8536 | // HLSL allows vector initialization to function like list initialization, but | ||||
| 8537 | // use the syntax of a C++-like constructor. | ||||
| 8538 | bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() && | ||||
| 8539 | isa<InitListExpr>(Args[0]); | ||||
| 8540 | (void)IsHLSLVectorInit; | ||||
| 8541 | |||||
| 8542 | // For initialization steps that start with a single initializer, | ||||
| 8543 | // grab the only argument out the Args and place it into the "current" | ||||
| 8544 | // initializer. | ||||
| 8545 | switch (Steps.front().Kind) { | ||||
| 8546 | case SK_ResolveAddressOfOverloadedFunction: | ||||
| 8547 | case SK_CastDerivedToBasePRValue: | ||||
| 8548 | case SK_CastDerivedToBaseXValue: | ||||
| 8549 | case SK_CastDerivedToBaseLValue: | ||||
| 8550 | case SK_BindReference: | ||||
| 8551 | case SK_BindReferenceToTemporary: | ||||
| 8552 | case SK_FinalCopy: | ||||
| 8553 | case SK_ExtraneousCopyToTemporary: | ||||
| 8554 | case SK_UserConversion: | ||||
| 8555 | case SK_QualificationConversionLValue: | ||||
| 8556 | case SK_QualificationConversionXValue: | ||||
| 8557 | case SK_QualificationConversionPRValue: | ||||
| 8558 | case SK_FunctionReferenceConversion: | ||||
| 8559 | case SK_AtomicConversion: | ||||
| 8560 | case SK_ConversionSequence: | ||||
| 8561 | case SK_ConversionSequenceNoNarrowing: | ||||
| 8562 | case SK_ListInitialization: | ||||
| 8563 | case SK_UnwrapInitList: | ||||
| 8564 | case SK_RewrapInitList: | ||||
| 8565 | case SK_CAssignment: | ||||
| 8566 | case SK_StringInit: | ||||
| 8567 | case SK_ObjCObjectConversion: | ||||
| 8568 | case SK_ArrayLoopIndex: | ||||
| 8569 | case SK_ArrayLoopInit: | ||||
| 8570 | case SK_ArrayInit: | ||||
| 8571 | case SK_GNUArrayInit: | ||||
| 8572 | case SK_ParenthesizedArrayInit: | ||||
| 8573 | case SK_PassByIndirectCopyRestore: | ||||
| 8574 | case SK_PassByIndirectRestore: | ||||
| 8575 | case SK_ProduceObjCObject: | ||||
| 8576 | case SK_StdInitializerList: | ||||
| 8577 | case SK_OCLSamplerInit: | ||||
| 8578 | case SK_OCLZeroOpaqueType: { | ||||
| 8579 | 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", 8579, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 8580 | CurInit = Args[0]; | ||||
| 8581 | if (!CurInit.get()) return ExprError(); | ||||
| 8582 | break; | ||||
| 8583 | } | ||||
| 8584 | |||||
| 8585 | case SK_ConstructorInitialization: | ||||
| 8586 | case SK_ConstructorInitializationFromList: | ||||
| 8587 | case SK_StdInitializerListConstructorCall: | ||||
| 8588 | case SK_ZeroInitialization: | ||||
| 8589 | case SK_ParenthesizedListInit: | ||||
| 8590 | break; | ||||
| 8591 | } | ||||
| 8592 | |||||
| 8593 | // Promote from an unevaluated context to an unevaluated list context in | ||||
| 8594 | // C++11 list-initialization; we need to instantiate entities usable in | ||||
| 8595 | // constant expressions here in order to perform narrowing checks =( | ||||
| 8596 | EnterExpressionEvaluationContext Evaluated( | ||||
| 8597 | S, EnterExpressionEvaluationContext::InitList, | ||||
| 8598 | CurInit.get() && isa<InitListExpr>(CurInit.get())); | ||||
| 8599 | |||||
| 8600 | // C++ [class.abstract]p2: | ||||
| 8601 | // no objects of an abstract class can be created except as subobjects | ||||
| 8602 | // of a class derived from it | ||||
| 8603 | auto checkAbstractType = [&](QualType T) -> bool { | ||||
| 8604 | if (Entity.getKind() == InitializedEntity::EK_Base || | ||||
| 8605 | Entity.getKind() == InitializedEntity::EK_Delegating) | ||||
| 8606 | return false; | ||||
| 8607 | return S.RequireNonAbstractType(Kind.getLocation(), T, | ||||
| 8608 | diag::err_allocation_of_abstract_type); | ||||
| 8609 | }; | ||||
| 8610 | |||||
| 8611 | // Walk through the computed steps for the initialization sequence, | ||||
| 8612 | // performing the specified conversions along the way. | ||||
| 8613 | bool ConstructorInitRequiresZeroInit = false; | ||||
| 8614 | for (step_iterator Step = step_begin(), StepEnd = step_end(); | ||||
| 8615 | Step != StepEnd; ++Step) { | ||||
| 8616 | if (CurInit.isInvalid()) | ||||
| 8617 | return ExprError(); | ||||
| 8618 | |||||
| 8619 | QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); | ||||
| 8620 | |||||
| 8621 | switch (Step->Kind) { | ||||
| 8622 | case SK_ResolveAddressOfOverloadedFunction: | ||||
| 8623 | // Overload resolution determined which function invoke; update the | ||||
| 8624 | // initializer to reflect that choice. | ||||
| 8625 | S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl); | ||||
| 8626 | if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation())) | ||||
| 8627 | return ExprError(); | ||||
| 8628 | CurInit = S.FixOverloadedFunctionReference(CurInit, | ||||
| 8629 | Step->Function.FoundDecl, | ||||
| 8630 | Step->Function.Function); | ||||
| 8631 | // We might get back another placeholder expression if we resolved to a | ||||
| 8632 | // builtin. | ||||
| 8633 | if (!CurInit.isInvalid()) | ||||
| 8634 | CurInit = S.CheckPlaceholderExpr(CurInit.get()); | ||||
| 8635 | break; | ||||
| 8636 | |||||
| 8637 | case SK_CastDerivedToBasePRValue: | ||||
| 8638 | case SK_CastDerivedToBaseXValue: | ||||
| 8639 | case SK_CastDerivedToBaseLValue: { | ||||
| 8640 | // We have a derived-to-base cast that produces either an rvalue or an | ||||
| 8641 | // lvalue. Perform that cast. | ||||
| 8642 | |||||
| 8643 | CXXCastPath BasePath; | ||||
| 8644 | |||||
| 8645 | // Casts to inaccessible base classes are allowed with C-style casts. | ||||
| 8646 | bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); | ||||
| 8647 | if (S.CheckDerivedToBaseConversion( | ||||
| 8648 | SourceType, Step->Type, CurInit.get()->getBeginLoc(), | ||||
| 8649 | CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess)) | ||||
| 8650 | return ExprError(); | ||||
| 8651 | |||||
| 8652 | ExprValueKind VK = | ||||
| 8653 | Step->Kind == SK_CastDerivedToBaseLValue | ||||
| 8654 | ? VK_LValue | ||||
| 8655 | : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue | ||||
| 8656 | : VK_PRValue); | ||||
| 8657 | CurInit = ImplicitCastExpr::Create(S.Context, Step->Type, | ||||
| 8658 | CK_DerivedToBase, CurInit.get(), | ||||
| 8659 | &BasePath, VK, FPOptionsOverride()); | ||||
| 8660 | break; | ||||
| 8661 | } | ||||
| 8662 | |||||
| 8663 | case SK_BindReference: | ||||
| 8664 | // Reference binding does not have any corresponding ASTs. | ||||
| 8665 | |||||
| 8666 | // Check exception specifications | ||||
| 8667 | if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) | ||||
| 8668 | return ExprError(); | ||||
| 8669 | |||||
| 8670 | // We don't check for e.g. function pointers here, since address | ||||
| 8671 | // availability checks should only occur when the function first decays | ||||
| 8672 | // into a pointer or reference. | ||||
| 8673 | if (CurInit.get()->getType()->isFunctionProtoType()) { | ||||
| 8674 | if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) { | ||||
| 8675 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { | ||||
| 8676 | if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | ||||
| 8677 | DRE->getBeginLoc())) | ||||
| 8678 | return ExprError(); | ||||
| 8679 | } | ||||
| 8680 | } | ||||
| 8681 | } | ||||
| 8682 | |||||
| 8683 | CheckForNullPointerDereference(S, CurInit.get()); | ||||
| 8684 | break; | ||||
| 8685 | |||||
| 8686 | case SK_BindReferenceToTemporary: { | ||||
| 8687 | // Make sure the "temporary" is actually an rvalue. | ||||
| 8688 | 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", 8688, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 8689 | |||||
| 8690 | // Check exception specifications | ||||
| 8691 | if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) | ||||
| 8692 | return ExprError(); | ||||
| 8693 | |||||
| 8694 | QualType MTETy = Step->Type; | ||||
| 8695 | |||||
| 8696 | // When this is an incomplete array type (such as when this is | ||||
| 8697 | // initializing an array of unknown bounds from an init list), use THAT | ||||
| 8698 | // type instead so that we propagate the array bounds. | ||||
| 8699 | if (MTETy->isIncompleteArrayType() && | ||||
| 8700 | !CurInit.get()->getType()->isIncompleteArrayType() && | ||||
| 8701 | S.Context.hasSameType( | ||||
| 8702 | MTETy->getPointeeOrArrayElementType(), | ||||
| 8703 | CurInit.get()->getType()->getPointeeOrArrayElementType())) | ||||
| 8704 | MTETy = CurInit.get()->getType(); | ||||
| 8705 | |||||
| 8706 | // Materialize the temporary into memory. | ||||
| 8707 | MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( | ||||
| 8708 | MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType()); | ||||
| 8709 | CurInit = MTE; | ||||
| 8710 | |||||
| 8711 | // If we're extending this temporary to automatic storage duration -- we | ||||
| 8712 | // need to register its cleanup during the full-expression's cleanups. | ||||
| 8713 | if (MTE->getStorageDuration() == SD_Automatic && | ||||
| 8714 | MTE->getType().isDestructedType()) | ||||
| 8715 | S.Cleanup.setExprNeedsCleanups(true); | ||||
| 8716 | break; | ||||
| 8717 | } | ||||
| 8718 | |||||
| 8719 | case SK_FinalCopy: | ||||
| 8720 | if (checkAbstractType(Step->Type)) | ||||
| 8721 | return ExprError(); | ||||
| 8722 | |||||
| 8723 | // If the overall initialization is initializing a temporary, we already | ||||
| 8724 | // bound our argument if it was necessary to do so. If not (if we're | ||||
| 8725 | // ultimately initializing a non-temporary), our argument needs to be | ||||
| 8726 | // bound since it's initializing a function parameter. | ||||
| 8727 | // FIXME: This is a mess. Rationalize temporary destruction. | ||||
| 8728 | if (!shouldBindAsTemporary(Entity)) | ||||
| 8729 | CurInit = S.MaybeBindToTemporary(CurInit.get()); | ||||
| 8730 | CurInit = CopyObject(S, Step->Type, Entity, CurInit, | ||||
| 8731 | /*IsExtraneousCopy=*/false); | ||||
| 8732 | break; | ||||
| 8733 | |||||
| 8734 | case SK_ExtraneousCopyToTemporary: | ||||
| 8735 | CurInit = CopyObject(S, Step->Type, Entity, CurInit, | ||||
| 8736 | /*IsExtraneousCopy=*/true); | ||||
| 8737 | break; | ||||
| 8738 | |||||
| 8739 | case SK_UserConversion: { | ||||
| 8740 | // We have a user-defined conversion that invokes either a constructor | ||||
| 8741 | // or a conversion function. | ||||
| 8742 | CastKind CastKind; | ||||
| 8743 | FunctionDecl *Fn = Step->Function.Function; | ||||
| 8744 | DeclAccessPair FoundFn = Step->Function.FoundDecl; | ||||
| 8745 | bool HadMultipleCandidates = Step->Function.HadMultipleCandidates; | ||||
| 8746 | bool CreatedObject = false; | ||||
| 8747 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) { | ||||
| 8748 | // Build a call to the selected constructor. | ||||
| 8749 | SmallVector<Expr*, 8> ConstructorArgs; | ||||
| 8750 | SourceLocation Loc = CurInit.get()->getBeginLoc(); | ||||
| 8751 | |||||
| 8752 | // Determine the arguments required to actually perform the constructor | ||||
| 8753 | // call. | ||||
| 8754 | Expr *Arg = CurInit.get(); | ||||
| 8755 | if (S.CompleteConstructorCall(Constructor, Step->Type, | ||||
| 8756 | MultiExprArg(&Arg, 1), Loc, | ||||
| 8757 | ConstructorArgs)) | ||||
| 8758 | return ExprError(); | ||||
| 8759 | |||||
| 8760 | // Build an expression that constructs a temporary. | ||||
| 8761 | CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, | ||||
| 8762 | FoundFn, Constructor, | ||||
| 8763 | ConstructorArgs, | ||||
| 8764 | HadMultipleCandidates, | ||||
| 8765 | /*ListInit*/ false, | ||||
| 8766 | /*StdInitListInit*/ false, | ||||
| 8767 | /*ZeroInit*/ false, | ||||
| 8768 | CXXConstructExpr::CK_Complete, | ||||
| 8769 | SourceRange()); | ||||
| 8770 | if (CurInit.isInvalid()) | ||||
| 8771 | return ExprError(); | ||||
| 8772 | |||||
| 8773 | S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn, | ||||
| 8774 | Entity); | ||||
| 8775 | if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) | ||||
| 8776 | return ExprError(); | ||||
| 8777 | |||||
| 8778 | CastKind = CK_ConstructorConversion; | ||||
| 8779 | CreatedObject = true; | ||||
| 8780 | } else { | ||||
| 8781 | // Build a call to the conversion function. | ||||
| 8782 | CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn); | ||||
| 8783 | S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr, | ||||
| 8784 | FoundFn); | ||||
| 8785 | if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) | ||||
| 8786 | return ExprError(); | ||||
| 8787 | |||||
| 8788 | CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion, | ||||
| 8789 | HadMultipleCandidates); | ||||
| 8790 | if (CurInit.isInvalid()) | ||||
| 8791 | return ExprError(); | ||||
| 8792 | |||||
| 8793 | CastKind = CK_UserDefinedConversion; | ||||
| 8794 | CreatedObject = Conversion->getReturnType()->isRecordType(); | ||||
| 8795 | } | ||||
| 8796 | |||||
| 8797 | if (CreatedObject && checkAbstractType(CurInit.get()->getType())) | ||||
| 8798 | return ExprError(); | ||||
| 8799 | |||||
| 8800 | CurInit = ImplicitCastExpr::Create( | ||||
| 8801 | S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr, | ||||
| 8802 | CurInit.get()->getValueKind(), S.CurFPFeatureOverrides()); | ||||
| 8803 | |||||
| 8804 | if (shouldBindAsTemporary(Entity)) | ||||
| 8805 | // The overall entity is temporary, so this expression should be | ||||
| 8806 | // destroyed at the end of its full-expression. | ||||
| 8807 | CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); | ||||
| 8808 | else if (CreatedObject && shouldDestroyEntity(Entity)) { | ||||
| 8809 | // The object outlasts the full-expression, but we need to prepare for | ||||
| 8810 | // a destructor being run on it. | ||||
| 8811 | // FIXME: It makes no sense to do this here. This should happen | ||||
| 8812 | // regardless of how we initialized the entity. | ||||
| 8813 | QualType T = CurInit.get()->getType(); | ||||
| 8814 | if (const RecordType *Record = T->getAs<RecordType>()) { | ||||
| 8815 | CXXDestructorDecl *Destructor | ||||
| 8816 | = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl())); | ||||
| 8817 | S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor, | ||||
| 8818 | S.PDiag(diag::err_access_dtor_temp) << T); | ||||
| 8819 | S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor); | ||||
| 8820 | if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc())) | ||||
| 8821 | return ExprError(); | ||||
| 8822 | } | ||||
| 8823 | } | ||||
| 8824 | break; | ||||
| 8825 | } | ||||
| 8826 | |||||
| 8827 | case SK_QualificationConversionLValue: | ||||
| 8828 | case SK_QualificationConversionXValue: | ||||
| 8829 | case SK_QualificationConversionPRValue: { | ||||
| 8830 | // Perform a qualification conversion; these can never go wrong. | ||||
| 8831 | ExprValueKind VK = | ||||
| 8832 | Step->Kind == SK_QualificationConversionLValue | ||||
| 8833 | ? VK_LValue | ||||
| 8834 | : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue | ||||
| 8835 | : VK_PRValue); | ||||
| 8836 | CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK); | ||||
| 8837 | break; | ||||
| 8838 | } | ||||
| 8839 | |||||
| 8840 | case SK_FunctionReferenceConversion: | ||||
| 8841 | 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", 8842, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 8842 | "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", 8842, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 8843 | CurInit = | ||||
| 8844 | S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue); | ||||
| 8845 | break; | ||||
| 8846 | |||||
| 8847 | case SK_AtomicConversion: { | ||||
| 8848 | 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", 8848, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 8849 | CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, | ||||
| 8850 | CK_NonAtomicToAtomic, VK_PRValue); | ||||
| 8851 | break; | ||||
| 8852 | } | ||||
| 8853 | |||||
| 8854 | case SK_ConversionSequence: | ||||
| 8855 | case SK_ConversionSequenceNoNarrowing: { | ||||
| 8856 | if (const auto *FromPtrType = | ||||
| 8857 | CurInit.get()->getType()->getAs<PointerType>()) { | ||||
| 8858 | if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) { | ||||
| 8859 | if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) && | ||||
| 8860 | !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { | ||||
| 8861 | // Do not check static casts here because they are checked earlier | ||||
| 8862 | // in Sema::ActOnCXXNamedCast() | ||||
| 8863 | if (!Kind.isStaticCast()) { | ||||
| 8864 | S.Diag(CurInit.get()->getExprLoc(), | ||||
| 8865 | diag::warn_noderef_to_dereferenceable_pointer) | ||||
| 8866 | << CurInit.get()->getSourceRange(); | ||||
| 8867 | } | ||||
| 8868 | } | ||||
| 8869 | } | ||||
| 8870 | } | ||||
| 8871 | |||||
| 8872 | Sema::CheckedConversionKind CCK | ||||
| 8873 | = Kind.isCStyleCast()? Sema::CCK_CStyleCast | ||||
| 8874 | : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast | ||||
| 8875 | : Kind.isExplicitCast()? Sema::CCK_OtherCast | ||||
| 8876 | : Sema::CCK_ImplicitConversion; | ||||
| 8877 | ExprResult CurInitExprRes = | ||||
| 8878 | S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS, | ||||
| 8879 | getAssignmentAction(Entity), CCK); | ||||
| 8880 | if (CurInitExprRes.isInvalid()) | ||||
| 8881 | return ExprError(); | ||||
| 8882 | |||||
| 8883 | S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get()); | ||||
| 8884 | |||||
| 8885 | CurInit = CurInitExprRes; | ||||
| 8886 | |||||
| 8887 | if (Step->Kind == SK_ConversionSequenceNoNarrowing && | ||||
| 8888 | S.getLangOpts().CPlusPlus) | ||||
| 8889 | DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(), | ||||
| 8890 | CurInit.get()); | ||||
| 8891 | |||||
| 8892 | break; | ||||
| 8893 | } | ||||
| 8894 | |||||
| 8895 | case SK_ListInitialization: { | ||||
| 8896 | if (checkAbstractType(Step->Type)) | ||||
| 8897 | return ExprError(); | ||||
| 8898 | |||||
| 8899 | InitListExpr *InitList = cast<InitListExpr>(CurInit.get()); | ||||
| 8900 | // If we're not initializing the top-level entity, we need to create an | ||||
| 8901 | // InitializeTemporary entity for our target type. | ||||
| 8902 | QualType Ty = Step->Type; | ||||
| 8903 | bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty); | ||||
| 8904 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty); | ||||
| 8905 | InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity; | ||||
| 8906 | InitListChecker PerformInitList(S, InitEntity, | ||||
| 8907 | InitList, Ty, /*VerifyOnly=*/false, | ||||
| 8908 | /*TreatUnavailableAsInvalid=*/false); | ||||
| 8909 | if (PerformInitList.HadError()) | ||||
| 8910 | return ExprError(); | ||||
| 8911 | |||||
| 8912 | // Hack: We must update *ResultType if available in order to set the | ||||
| 8913 | // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'. | ||||
| 8914 | // Worst case: 'const int (&arref)[] = {1, 2, 3};'. | ||||
| 8915 | if (ResultType && | ||||
| 8916 | ResultType->getNonReferenceType()->isIncompleteArrayType()) { | ||||
| 8917 | if ((*ResultType)->isRValueReferenceType()) | ||||
| 8918 | Ty = S.Context.getRValueReferenceType(Ty); | ||||
| 8919 | else if ((*ResultType)->isLValueReferenceType()) | ||||
| 8920 | Ty = S.Context.getLValueReferenceType(Ty, | ||||
| 8921 | (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue()); | ||||
| 8922 | *ResultType = Ty; | ||||
| 8923 | } | ||||
| 8924 | |||||
| 8925 | InitListExpr *StructuredInitList = | ||||
| 8926 | PerformInitList.getFullyStructuredList(); | ||||
| 8927 | CurInit.get(); | ||||
| 8928 | CurInit = shouldBindAsTemporary(InitEntity) | ||||
| 8929 | ? S.MaybeBindToTemporary(StructuredInitList) | ||||
| 8930 | : StructuredInitList; | ||||
| 8931 | break; | ||||
| 8932 | } | ||||
| 8933 | |||||
| 8934 | case SK_ConstructorInitializationFromList: { | ||||
| 8935 | if (checkAbstractType(Step->Type)) | ||||
| 8936 | return ExprError(); | ||||
| 8937 | |||||
| 8938 | // When an initializer list is passed for a parameter of type "reference | ||||
| 8939 | // to object", we don't get an EK_Temporary entity, but instead an | ||||
| 8940 | // EK_Parameter entity with reference type. | ||||
| 8941 | // FIXME: This is a hack. What we really should do is create a user | ||||
| 8942 | // conversion step for this case, but this makes it considerably more | ||||
| 8943 | // complicated. For now, this will do. | ||||
| 8944 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( | ||||
| 8945 | Entity.getType().getNonReferenceType()); | ||||
| 8946 | bool UseTemporary = Entity.getType()->isReferenceType(); | ||||
| 8947 | 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", 8947, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 8948 | InitListExpr *InitList = cast<InitListExpr>(Args[0]); | ||||
| 8949 | S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init) | ||||
| 8950 | << InitList->getSourceRange(); | ||||
| 8951 | MultiExprArg Arg(InitList->getInits(), InitList->getNumInits()); | ||||
| 8952 | CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity : | ||||
| 8953 | Entity, | ||||
| 8954 | Kind, Arg, *Step, | ||||
| 8955 | ConstructorInitRequiresZeroInit, | ||||
| 8956 | /*IsListInitialization*/true, | ||||
| 8957 | /*IsStdInitListInit*/false, | ||||
| 8958 | InitList->getLBraceLoc(), | ||||
| 8959 | InitList->getRBraceLoc()); | ||||
| 8960 | break; | ||||
| 8961 | } | ||||
| 8962 | |||||
| 8963 | case SK_UnwrapInitList: | ||||
| 8964 | CurInit = cast<InitListExpr>(CurInit.get())->getInit(0); | ||||
| 8965 | break; | ||||
| 8966 | |||||
| 8967 | case SK_RewrapInitList: { | ||||
| 8968 | Expr *E = CurInit.get(); | ||||
| 8969 | InitListExpr *Syntactic = Step->WrappingSyntacticList; | ||||
| 8970 | InitListExpr *ILE = new (S.Context) InitListExpr(S.Context, | ||||
| 8971 | Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc()); | ||||
| 8972 | ILE->setSyntacticForm(Syntactic); | ||||
| 8973 | ILE->setType(E->getType()); | ||||
| 8974 | ILE->setValueKind(E->getValueKind()); | ||||
| 8975 | CurInit = ILE; | ||||
| 8976 | break; | ||||
| 8977 | } | ||||
| 8978 | |||||
| 8979 | case SK_ConstructorInitialization: | ||||
| 8980 | case SK_StdInitializerListConstructorCall: { | ||||
| 8981 | if (checkAbstractType(Step->Type)) | ||||
| 8982 | return ExprError(); | ||||
| 8983 | |||||
| 8984 | // When an initializer list is passed for a parameter of type "reference | ||||
| 8985 | // to object", we don't get an EK_Temporary entity, but instead an | ||||
| 8986 | // EK_Parameter entity with reference type. | ||||
| 8987 | // FIXME: This is a hack. What we really should do is create a user | ||||
| 8988 | // conversion step for this case, but this makes it considerably more | ||||
| 8989 | // complicated. For now, this will do. | ||||
| 8990 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( | ||||
| 8991 | Entity.getType().getNonReferenceType()); | ||||
| 8992 | bool UseTemporary = Entity.getType()->isReferenceType(); | ||||
| 8993 | bool IsStdInitListInit = | ||||
| 8994 | Step->Kind == SK_StdInitializerListConstructorCall; | ||||
| 8995 | Expr *Source = CurInit.get(); | ||||
| 8996 | SourceRange Range = Kind.hasParenOrBraceRange() | ||||
| 8997 | ? Kind.getParenOrBraceRange() | ||||
| 8998 | : SourceRange(); | ||||
| 8999 | CurInit = PerformConstructorInitialization( | ||||
| 9000 | S, UseTemporary ? TempEntity : Entity, Kind, | ||||
| 9001 | Source ? MultiExprArg(Source) : Args, *Step, | ||||
| 9002 | ConstructorInitRequiresZeroInit, | ||||
| 9003 | /*IsListInitialization*/ IsStdInitListInit, | ||||
| 9004 | /*IsStdInitListInitialization*/ IsStdInitListInit, | ||||
| 9005 | /*LBraceLoc*/ Range.getBegin(), | ||||
| 9006 | /*RBraceLoc*/ Range.getEnd()); | ||||
| 9007 | break; | ||||
| 9008 | } | ||||
| 9009 | |||||
| 9010 | case SK_ZeroInitialization: { | ||||
| 9011 | step_iterator NextStep = Step; | ||||
| 9012 | ++NextStep; | ||||
| 9013 | if (NextStep != StepEnd && | ||||
| 9014 | (NextStep->Kind == SK_ConstructorInitialization || | ||||
| 9015 | NextStep->Kind == SK_ConstructorInitializationFromList)) { | ||||
| 9016 | // The need for zero-initialization is recorded directly into | ||||
| 9017 | // the call to the object's constructor within the next step. | ||||
| 9018 | ConstructorInitRequiresZeroInit = true; | ||||
| 9019 | } else if (Kind.getKind() == InitializationKind::IK_Value && | ||||
| 9020 | S.getLangOpts().CPlusPlus && | ||||
| 9021 | !Kind.isImplicitValueInit()) { | ||||
| 9022 | TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); | ||||
| 9023 | if (!TSInfo) | ||||
| 9024 | TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type, | ||||
| 9025 | Kind.getRange().getBegin()); | ||||
| 9026 | |||||
| 9027 | CurInit = new (S.Context) CXXScalarValueInitExpr( | ||||
| 9028 | Entity.getType().getNonLValueExprType(S.Context), TSInfo, | ||||
| 9029 | Kind.getRange().getEnd()); | ||||
| 9030 | } else { | ||||
| 9031 | CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type); | ||||
| 9032 | } | ||||
| 9033 | break; | ||||
| 9034 | } | ||||
| 9035 | |||||
| 9036 | case SK_CAssignment: { | ||||
| 9037 | QualType SourceType = CurInit.get()->getType(); | ||||
| 9038 | |||||
| 9039 | // Save off the initial CurInit in case we need to emit a diagnostic | ||||
| 9040 | ExprResult InitialCurInit = CurInit; | ||||
| 9041 | ExprResult Result = CurInit; | ||||
| 9042 | Sema::AssignConvertType ConvTy = | ||||
| 9043 | S.CheckSingleAssignmentConstraints(Step->Type, Result, true, | ||||
| 9044 | Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited); | ||||
| 9045 | if (Result.isInvalid()) | ||||
| 9046 | return ExprError(); | ||||
| 9047 | CurInit = Result; | ||||
| 9048 | |||||
| 9049 | // If this is a call, allow conversion to a transparent union. | ||||
| 9050 | ExprResult CurInitExprRes = CurInit; | ||||
| 9051 | if (ConvTy != Sema::Compatible && | ||||
| 9052 | Entity.isParameterKind() && | ||||
| 9053 | S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes) | ||||
| 9054 | == Sema::Compatible) | ||||
| 9055 | ConvTy = Sema::Compatible; | ||||
| 9056 | if (CurInitExprRes.isInvalid()) | ||||
| 9057 | return ExprError(); | ||||
| 9058 | CurInit = CurInitExprRes; | ||||
| 9059 | |||||
| 9060 | bool Complained; | ||||
| 9061 | if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), | ||||
| 9062 | Step->Type, SourceType, | ||||
| 9063 | InitialCurInit.get(), | ||||
| 9064 | getAssignmentAction(Entity, true), | ||||
| 9065 | &Complained)) { | ||||
| 9066 | PrintInitLocationNote(S, Entity); | ||||
| 9067 | return ExprError(); | ||||
| 9068 | } else if (Complained) | ||||
| 9069 | PrintInitLocationNote(S, Entity); | ||||
| 9070 | break; | ||||
| 9071 | } | ||||
| 9072 | |||||
| 9073 | case SK_StringInit: { | ||||
| 9074 | QualType Ty = Step->Type; | ||||
| 9075 | bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType(); | ||||
| 9076 | CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty, | ||||
| 9077 | S.Context.getAsArrayType(Ty), S); | ||||
| 9078 | break; | ||||
| 9079 | } | ||||
| 9080 | |||||
| 9081 | case SK_ObjCObjectConversion: | ||||
| 9082 | CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, | ||||
| 9083 | CK_ObjCObjectLValueCast, | ||||
| 9084 | CurInit.get()->getValueKind()); | ||||
| 9085 | break; | ||||
| 9086 | |||||
| 9087 | case SK_ArrayLoopIndex: { | ||||
| 9088 | Expr *Cur = CurInit.get(); | ||||
| 9089 | Expr *BaseExpr = new (S.Context) | ||||
| 9090 | OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(), | ||||
| 9091 | Cur->getValueKind(), Cur->getObjectKind(), Cur); | ||||
| 9092 | Expr *IndexExpr = | ||||
| 9093 | new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType()); | ||||
| 9094 | CurInit = S.CreateBuiltinArraySubscriptExpr( | ||||
| 9095 | BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation()); | ||||
| 9096 | ArrayLoopCommonExprs.push_back(BaseExpr); | ||||
| 9097 | break; | ||||
| 9098 | } | ||||
| 9099 | |||||
| 9100 | case SK_ArrayLoopInit: { | ||||
| 9101 | 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", 9102, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 9102 | "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", 9102, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 9103 | Expr *Common = ArrayLoopCommonExprs.pop_back_val(); | ||||
| 9104 | CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common, | ||||
| 9105 | CurInit.get()); | ||||
| 9106 | break; | ||||
| 9107 | } | ||||
| 9108 | |||||
| 9109 | case SK_GNUArrayInit: | ||||
| 9110 | // Okay: we checked everything before creating this step. Note that | ||||
| 9111 | // this is a GNU extension. | ||||
| 9112 | S.Diag(Kind.getLocation(), diag::ext_array_init_copy) | ||||
| 9113 | << Step->Type << CurInit.get()->getType() | ||||
| 9114 | << CurInit.get()->getSourceRange(); | ||||
| 9115 | updateGNUCompoundLiteralRValue(CurInit.get()); | ||||
| 9116 | [[fallthrough]]; | ||||
| 9117 | case SK_ArrayInit: | ||||
| 9118 | // If the destination type is an incomplete array type, update the | ||||
| 9119 | // type accordingly. | ||||
| 9120 | if (ResultType) { | ||||
| 9121 | if (const IncompleteArrayType *IncompleteDest | ||||
| 9122 | = S.Context.getAsIncompleteArrayType(Step->Type)) { | ||||
| 9123 | if (const ConstantArrayType *ConstantSource | ||||
| 9124 | = S.Context.getAsConstantArrayType(CurInit.get()->getType())) { | ||||
| 9125 | *ResultType = S.Context.getConstantArrayType( | ||||
| 9126 | IncompleteDest->getElementType(), | ||||
| 9127 | ConstantSource->getSize(), | ||||
| 9128 | ConstantSource->getSizeExpr(), | ||||
| 9129 | ArrayType::Normal, 0); | ||||
| 9130 | } | ||||
| 9131 | } | ||||
| 9132 | } | ||||
| 9133 | break; | ||||
| 9134 | |||||
| 9135 | case SK_ParenthesizedArrayInit: | ||||
| 9136 | // Okay: we checked everything before creating this step. Note that | ||||
| 9137 | // this is a GNU extension. | ||||
| 9138 | S.Diag(Kind.getLocation(), diag::ext_array_init_parens) | ||||
| 9139 | << CurInit.get()->getSourceRange(); | ||||
| 9140 | break; | ||||
| 9141 | |||||
| 9142 | case SK_PassByIndirectCopyRestore: | ||||
| 9143 | case SK_PassByIndirectRestore: | ||||
| 9144 | checkIndirectCopyRestoreSource(S, CurInit.get()); | ||||
| 9145 | CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr( | ||||
| 9146 | CurInit.get(), Step->Type, | ||||
| 9147 | Step->Kind == SK_PassByIndirectCopyRestore); | ||||
| 9148 | break; | ||||
| 9149 | |||||
| 9150 | case SK_ProduceObjCObject: | ||||
| 9151 | CurInit = ImplicitCastExpr::Create( | ||||
| 9152 | S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr, | ||||
| 9153 | VK_PRValue, FPOptionsOverride()); | ||||
| 9154 | break; | ||||
| 9155 | |||||
| 9156 | case SK_StdInitializerList: { | ||||
| 9157 | S.Diag(CurInit.get()->getExprLoc(), | ||||
| 9158 | diag::warn_cxx98_compat_initializer_list_init) | ||||
| 9159 | << CurInit.get()->getSourceRange(); | ||||
| 9160 | |||||
| 9161 | // Materialize the temporary into memory. | ||||
| 9162 | MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( | ||||
| 9163 | CurInit.get()->getType(), CurInit.get(), | ||||
| 9164 | /*BoundToLvalueReference=*/false); | ||||
| 9165 | |||||
| 9166 | // Wrap it in a construction of a std::initializer_list<T>. | ||||
| 9167 | CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE); | ||||
| 9168 | |||||
| 9169 | // Bind the result, in case the library has given initializer_list a | ||||
| 9170 | // non-trivial destructor. | ||||
| 9171 | if (shouldBindAsTemporary(Entity)) | ||||
| 9172 | CurInit = S.MaybeBindToTemporary(CurInit.get()); | ||||
| 9173 | break; | ||||
| 9174 | } | ||||
| 9175 | |||||
| 9176 | case SK_OCLSamplerInit: { | ||||
| 9177 | // Sampler initialization have 5 cases: | ||||
| 9178 | // 1. function argument passing | ||||
| 9179 | // 1a. argument is a file-scope variable | ||||
| 9180 | // 1b. argument is a function-scope variable | ||||
| 9181 | // 1c. argument is one of caller function's parameters | ||||
| 9182 | // 2. variable initialization | ||||
| 9183 | // 2a. initializing a file-scope variable | ||||
| 9184 | // 2b. initializing a function-scope variable | ||||
| 9185 | // | ||||
| 9186 | // For file-scope variables, since they cannot be initialized by function | ||||
| 9187 | // call of __translate_sampler_initializer in LLVM IR, their references | ||||
| 9188 | // need to be replaced by a cast from their literal initializers to | ||||
| 9189 | // sampler type. Since sampler variables can only be used in function | ||||
| 9190 | // calls as arguments, we only need to replace them when handling the | ||||
| 9191 | // argument passing. | ||||
| 9192 | 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", 9193, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 9193 | "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", 9193, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 9194 | Expr *Init = CurInit.get()->IgnoreParens(); | ||||
| 9195 | QualType SourceType = Init->getType(); | ||||
| 9196 | // Case 1 | ||||
| 9197 | if (Entity.isParameterKind()) { | ||||
| 9198 | if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) { | ||||
| 9199 | S.Diag(Kind.getLocation(), diag::err_sampler_argument_required) | ||||
| 9200 | << SourceType; | ||||
| 9201 | break; | ||||
| 9202 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) { | ||||
| 9203 | auto Var = cast<VarDecl>(DRE->getDecl()); | ||||
| 9204 | // Case 1b and 1c | ||||
| 9205 | // No cast from integer to sampler is needed. | ||||
| 9206 | if (!Var->hasGlobalStorage()) { | ||||
| 9207 | CurInit = ImplicitCastExpr::Create( | ||||
| 9208 | S.Context, Step->Type, CK_LValueToRValue, Init, | ||||
| 9209 | /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride()); | ||||
| 9210 | break; | ||||
| 9211 | } | ||||
| 9212 | // Case 1a | ||||
| 9213 | // For function call with a file-scope sampler variable as argument, | ||||
| 9214 | // get the integer literal. | ||||
| 9215 | // Do not diagnose if the file-scope variable does not have initializer | ||||
| 9216 | // since this has already been diagnosed when parsing the variable | ||||
| 9217 | // declaration. | ||||
| 9218 | if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit())) | ||||
| 9219 | break; | ||||
| 9220 | Init = cast<ImplicitCastExpr>(const_cast<Expr*>( | ||||
| 9221 | Var->getInit()))->getSubExpr(); | ||||
| 9222 | SourceType = Init->getType(); | ||||
| 9223 | } | ||||
| 9224 | } else { | ||||
| 9225 | // Case 2 | ||||
| 9226 | // Check initializer is 32 bit integer constant. | ||||
| 9227 | // If the initializer is taken from global variable, do not diagnose since | ||||
| 9228 | // this has already been done when parsing the variable declaration. | ||||
| 9229 | if (!Init->isConstantInitializer(S.Context, false)) | ||||
| 9230 | break; | ||||
| 9231 | |||||
| 9232 | if (!SourceType->isIntegerType() || | ||||
| 9233 | 32 != S.Context.getIntWidth(SourceType)) { | ||||
| 9234 | S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer) | ||||
| 9235 | << SourceType; | ||||
| 9236 | break; | ||||
| 9237 | } | ||||
| 9238 | |||||
| 9239 | Expr::EvalResult EVResult; | ||||
| 9240 | Init->EvaluateAsInt(EVResult, S.Context); | ||||
| 9241 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||
| 9242 | const uint64_t SamplerValue = Result.getLimitedValue(); | ||||
| 9243 | // 32-bit value of sampler's initializer is interpreted as | ||||
| 9244 | // bit-field with the following structure: | ||||
| 9245 | // |unspecified|Filter|Addressing Mode| Normalized Coords| | ||||
| 9246 | // |31 6|5 4|3 1| 0| | ||||
| 9247 | // This structure corresponds to enum values of sampler properties | ||||
| 9248 | // defined in SPIR spec v1.2 and also opencl-c.h | ||||
| 9249 | unsigned AddressingMode = (0x0E & SamplerValue) >> 1; | ||||
| 9250 | unsigned FilterMode = (0x30 & SamplerValue) >> 4; | ||||
| 9251 | if (FilterMode != 1 && FilterMode != 2 && | ||||
| 9252 | !S.getOpenCLOptions().isAvailableOption( | ||||
| 9253 | "cl_intel_device_side_avc_motion_estimation", S.getLangOpts())) | ||||
| 9254 | S.Diag(Kind.getLocation(), | ||||
| 9255 | diag::warn_sampler_initializer_invalid_bits) | ||||
| 9256 | << "Filter Mode"; | ||||
| 9257 | if (AddressingMode > 4) | ||||
| 9258 | S.Diag(Kind.getLocation(), | ||||
| 9259 | diag::warn_sampler_initializer_invalid_bits) | ||||
| 9260 | << "Addressing Mode"; | ||||
| 9261 | } | ||||
| 9262 | |||||
| 9263 | // Cases 1a, 2a and 2b | ||||
| 9264 | // Insert cast from integer to sampler. | ||||
| 9265 | CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy, | ||||
| 9266 | CK_IntToOCLSampler); | ||||
| 9267 | break; | ||||
| 9268 | } | ||||
| 9269 | case SK_OCLZeroOpaqueType: { | ||||
| 9270 | 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", 9272, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 9271 | 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", 9272, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 9272 | "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", 9272, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 9273 | |||||
| 9274 | CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, | ||||
| 9275 | CK_ZeroToOCLOpaqueType, | ||||
| 9276 | CurInit.get()->getValueKind()); | ||||
| 9277 | break; | ||||
| 9278 | } | ||||
| 9279 | case SK_ParenthesizedListInit: { | ||||
| 9280 | CurInit = nullptr; | ||||
| 9281 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this, | ||||
| 9282 | /*VerifyOnly=*/false, &CurInit); | ||||
| 9283 | if (CurInit.get() && ResultType) | ||||
| 9284 | *ResultType = CurInit.get()->getType(); | ||||
| 9285 | if (shouldBindAsTemporary(Entity)) | ||||
| 9286 | CurInit = S.MaybeBindToTemporary(CurInit.get()); | ||||
| 9287 | break; | ||||
| 9288 | } | ||||
| 9289 | } | ||||
| 9290 | } | ||||
| 9291 | |||||
| 9292 | // Check whether the initializer has a shorter lifetime than the initialized | ||||
| 9293 | // entity, and if not, either lifetime-extend or warn as appropriate. | ||||
| 9294 | if (auto *Init = CurInit.get()) | ||||
| 9295 | S.checkInitializerLifetime(Entity, Init); | ||||
| 9296 | |||||
| 9297 | // Diagnose non-fatal problems with the completed initialization. | ||||
| 9298 | if (InitializedEntity::EntityKind EK = Entity.getKind(); | ||||
| 9299 | (EK == InitializedEntity::EK_Member || | ||||
| 9300 | EK == InitializedEntity::EK_ParenAggInitMember) && | ||||
| 9301 | cast<FieldDecl>(Entity.getDecl())->isBitField()) | ||||
| 9302 | S.CheckBitFieldInitialization(Kind.getLocation(), | ||||
| 9303 | cast<FieldDecl>(Entity.getDecl()), | ||||
| 9304 | CurInit.get()); | ||||
| 9305 | |||||
| 9306 | // Check for std::move on construction. | ||||
| 9307 | if (const Expr *E = CurInit.get()) { | ||||
| 9308 | CheckMoveOnConstruction(S, E, | ||||
| 9309 | Entity.getKind() == InitializedEntity::EK_Result); | ||||
| 9310 | } | ||||
| 9311 | |||||
| 9312 | return CurInit; | ||||
| 9313 | } | ||||
| 9314 | |||||
| 9315 | /// Somewhere within T there is an uninitialized reference subobject. | ||||
| 9316 | /// Dig it out and diagnose it. | ||||
| 9317 | static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, | ||||
| 9318 | QualType T) { | ||||
| 9319 | if (T->isReferenceType()) { | ||||
| 9320 | S.Diag(Loc, diag::err_reference_without_init) | ||||
| 9321 | << T.getNonReferenceType(); | ||||
| 9322 | return true; | ||||
| 9323 | } | ||||
| 9324 | |||||
| 9325 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | ||||
| 9326 | if (!RD || !RD->hasUninitializedReferenceMember()) | ||||
| 9327 | return false; | ||||
| 9328 | |||||
| 9329 | for (const auto *FI : RD->fields()) { | ||||
| 9330 | if (FI->isUnnamedBitfield()) | ||||
| 9331 | continue; | ||||
| 9332 | |||||
| 9333 | if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) { | ||||
| 9334 | S.Diag(Loc, diag::note_value_initialization_here) << RD; | ||||
| 9335 | return true; | ||||
| 9336 | } | ||||
| 9337 | } | ||||
| 9338 | |||||
| 9339 | for (const auto &BI : RD->bases()) { | ||||
| 9340 | if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) { | ||||
| 9341 | S.Diag(Loc, diag::note_value_initialization_here) << RD; | ||||
| 9342 | return true; | ||||
| 9343 | } | ||||
| 9344 | } | ||||
| 9345 | |||||
| 9346 | return false; | ||||
| 9347 | } | ||||
| 9348 | |||||
| 9349 | |||||
| 9350 | //===----------------------------------------------------------------------===// | ||||
| 9351 | // Diagnose initialization failures | ||||
| 9352 | //===----------------------------------------------------------------------===// | ||||
| 9353 | |||||
| 9354 | /// Emit notes associated with an initialization that failed due to a | ||||
| 9355 | /// "simple" conversion failure. | ||||
| 9356 | static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, | ||||
| 9357 | Expr *op) { | ||||
| 9358 | QualType destType = entity.getType(); | ||||
| 9359 | if (destType.getNonReferenceType()->isObjCObjectPointerType() && | ||||
| 9360 | op->getType()->isObjCObjectPointerType()) { | ||||
| 9361 | |||||
| 9362 | // Emit a possible note about the conversion failing because the | ||||
| 9363 | // operand is a message send with a related result type. | ||||
| 9364 | S.EmitRelatedResultTypeNote(op); | ||||
| 9365 | |||||
| 9366 | // Emit a possible note about a return failing because we're | ||||
| 9367 | // expecting a related result type. | ||||
| 9368 | if (entity.getKind() == InitializedEntity::EK_Result) | ||||
| 9369 | S.EmitRelatedResultTypeNoteForReturn(destType); | ||||
| 9370 | } | ||||
| 9371 | QualType fromType = op->getType(); | ||||
| 9372 | QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType(); | ||||
| 9373 | QualType destPointeeType = destType.getCanonicalType()->getPointeeType(); | ||||
| 9374 | auto *fromDecl = fromType->getPointeeCXXRecordDecl(); | ||||
| 9375 | auto *destDecl = destType->getPointeeCXXRecordDecl(); | ||||
| 9376 | if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord && | ||||
| 9377 | destDecl->getDeclKind() == Decl::CXXRecord && | ||||
| 9378 | !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() && | ||||
| 9379 | !fromDecl->hasDefinition() && | ||||
| 9380 | destPointeeType.getQualifiers().compatiblyIncludes( | ||||
| 9381 | fromPointeeType.getQualifiers())) | ||||
| 9382 | S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion) | ||||
| 9383 | << S.getASTContext().getTagDeclType(fromDecl) | ||||
| 9384 | << S.getASTContext().getTagDeclType(destDecl); | ||||
| 9385 | } | ||||
| 9386 | |||||
| 9387 | static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, | ||||
| 9388 | InitListExpr *InitList) { | ||||
| 9389 | QualType DestType = Entity.getType(); | ||||
| 9390 | |||||
| 9391 | QualType E; | ||||
| 9392 | if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) { | ||||
| 9393 | QualType ArrayType = S.Context.getConstantArrayType( | ||||
| 9394 | E.withConst(), | ||||
| 9395 | llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), | ||||
| 9396 | InitList->getNumInits()), | ||||
| 9397 | nullptr, clang::ArrayType::Normal, 0); | ||||
| 9398 | InitializedEntity HiddenArray = | ||||
| 9399 | InitializedEntity::InitializeTemporary(ArrayType); | ||||
| 9400 | return diagnoseListInit(S, HiddenArray, InitList); | ||||
| 9401 | } | ||||
| 9402 | |||||
| 9403 | if (DestType->isReferenceType()) { | ||||
| 9404 | // A list-initialization failure for a reference means that we tried to | ||||
| 9405 | // create a temporary of the inner type (per [dcl.init.list]p3.6) and the | ||||
| 9406 | // inner initialization failed. | ||||
| 9407 | QualType T = DestType->castAs<ReferenceType>()->getPointeeType(); | ||||
| 9408 | diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList); | ||||
| 9409 | SourceLocation Loc = InitList->getBeginLoc(); | ||||
| 9410 | if (auto *D = Entity.getDecl()) | ||||
| 9411 | Loc = D->getLocation(); | ||||
| 9412 | S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T; | ||||
| 9413 | return; | ||||
| 9414 | } | ||||
| 9415 | |||||
| 9416 | InitListChecker DiagnoseInitList(S, Entity, InitList, DestType, | ||||
| 9417 | /*VerifyOnly=*/false, | ||||
| 9418 | /*TreatUnavailableAsInvalid=*/false); | ||||
| 9419 | 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", 9420, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 9420 | "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", 9420, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 9421 | } | ||||
| 9422 | |||||
| 9423 | bool InitializationSequence::Diagnose(Sema &S, | ||||
| 9424 | const InitializedEntity &Entity, | ||||
| 9425 | const InitializationKind &Kind, | ||||
| 9426 | ArrayRef<Expr *> Args) { | ||||
| 9427 | if (!Failed()) | ||||
| 9428 | return false; | ||||
| 9429 | |||||
| 9430 | // When we want to diagnose only one element of a braced-init-list, | ||||
| 9431 | // we need to factor it out. | ||||
| 9432 | Expr *OnlyArg; | ||||
| 9433 | if (Args.size() == 1) { | ||||
| 9434 | auto *List = dyn_cast<InitListExpr>(Args[0]); | ||||
| 9435 | if (List && List->getNumInits() == 1) | ||||
| 9436 | OnlyArg = List->getInit(0); | ||||
| 9437 | else | ||||
| 9438 | OnlyArg = Args[0]; | ||||
| 9439 | } | ||||
| 9440 | else | ||||
| 9441 | OnlyArg = nullptr; | ||||
| 9442 | |||||
| 9443 | QualType DestType = Entity.getType(); | ||||
| 9444 | switch (Failure) { | ||||
| 9445 | case FK_TooManyInitsForReference: | ||||
| 9446 | // FIXME: Customize for the initialized entity? | ||||
| 9447 | if (Args.empty()) { | ||||
| 9448 | // Dig out the reference subobject which is uninitialized and diagnose it. | ||||
| 9449 | // If this is value-initialization, this could be nested some way within | ||||
| 9450 | // the target type. | ||||
| 9451 | 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", 9452, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 9452 | 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", 9452, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 9453 | bool Diagnosed = | ||||
| 9454 | DiagnoseUninitializedReference(S, Kind.getLocation(), DestType); | ||||
| 9455 | 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", 9455, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 9456 | (void)Diagnosed; | ||||
| 9457 | } else // FIXME: diagnostic below could be better! | ||||
| 9458 | S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) | ||||
| 9459 | << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); | ||||
| 9460 | break; | ||||
| 9461 | case FK_ParenthesizedListInitForReference: | ||||
| 9462 | S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) | ||||
| 9463 | << 1 << Entity.getType() << Args[0]->getSourceRange(); | ||||
| 9464 | break; | ||||
| 9465 | |||||
| 9466 | case FK_ArrayNeedsInitList: | ||||
| 9467 | S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0; | ||||
| 9468 | break; | ||||
| 9469 | case FK_ArrayNeedsInitListOrStringLiteral: | ||||
| 9470 | S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1; | ||||
| 9471 | break; | ||||
| 9472 | case FK_ArrayNeedsInitListOrWideStringLiteral: | ||||
| 9473 | S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2; | ||||
| 9474 | break; | ||||
| 9475 | case FK_NarrowStringIntoWideCharArray: | ||||
| 9476 | S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar); | ||||
| 9477 | break; | ||||
| 9478 | case FK_WideStringIntoCharArray: | ||||
| 9479 | S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char); | ||||
| 9480 | break; | ||||
| 9481 | case FK_IncompatWideStringIntoWideChar: | ||||
| 9482 | S.Diag(Kind.getLocation(), | ||||
| 9483 | diag::err_array_init_incompat_wide_string_into_wchar); | ||||
| 9484 | break; | ||||
| 9485 | case FK_PlainStringIntoUTF8Char: | ||||
| 9486 | S.Diag(Kind.getLocation(), | ||||
| 9487 | diag::err_array_init_plain_string_into_char8_t); | ||||
| 9488 | S.Diag(Args.front()->getBeginLoc(), | ||||
| 9489 | diag::note_array_init_plain_string_into_char8_t) | ||||
| 9490 | << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8"); | ||||
| 9491 | break; | ||||
| 9492 | case FK_UTF8StringIntoPlainChar: | ||||
| 9493 | S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char) | ||||
| 9494 | << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20; | ||||
| 9495 | break; | ||||
| 9496 | case FK_ArrayTypeMismatch: | ||||
| 9497 | case FK_NonConstantArrayInit: | ||||
| 9498 | S.Diag(Kind.getLocation(), | ||||
| 9499 | (Failure == FK_ArrayTypeMismatch | ||||
| 9500 | ? diag::err_array_init_different_type | ||||
| 9501 | : diag::err_array_init_non_constant_array)) | ||||
| 9502 | << DestType.getNonReferenceType() | ||||
| 9503 | << OnlyArg->getType() | ||||
| 9504 | << Args[0]->getSourceRange(); | ||||
| 9505 | break; | ||||
| 9506 | |||||
| 9507 | case FK_VariableLengthArrayHasInitializer: | ||||
| 9508 | S.Diag(Kind.getLocation(), diag::err_variable_object_no_init) | ||||
| 9509 | << Args[0]->getSourceRange(); | ||||
| 9510 | break; | ||||
| 9511 | |||||
| 9512 | case FK_AddressOfOverloadFailed: { | ||||
| 9513 | DeclAccessPair Found; | ||||
| 9514 | S.ResolveAddressOfOverloadedFunction(OnlyArg, | ||||
| 9515 | DestType.getNonReferenceType(), | ||||
| 9516 | true, | ||||
| 9517 | Found); | ||||
| 9518 | break; | ||||
| 9519 | } | ||||
| 9520 | |||||
| 9521 | case FK_AddressOfUnaddressableFunction: { | ||||
| 9522 | auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl()); | ||||
| 9523 | S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | ||||
| 9524 | OnlyArg->getBeginLoc()); | ||||
| 9525 | break; | ||||
| 9526 | } | ||||
| 9527 | |||||
| 9528 | case FK_ReferenceInitOverloadFailed: | ||||
| 9529 | case FK_UserConversionOverloadFailed: | ||||
| 9530 | switch (FailedOverloadResult) { | ||||
| 9531 | case OR_Ambiguous: | ||||
| 9532 | |||||
| 9533 | FailedCandidateSet.NoteCandidates( | ||||
| 9534 | PartialDiagnosticAt( | ||||
| 9535 | Kind.getLocation(), | ||||
| 9536 | Failure == FK_UserConversionOverloadFailed | ||||
| 9537 | ? (S.PDiag(diag::err_typecheck_ambiguous_condition) | ||||
| 9538 | << OnlyArg->getType() << DestType | ||||
| 9539 | << Args[0]->getSourceRange()) | ||||
| 9540 | : (S.PDiag(diag::err_ref_init_ambiguous) | ||||
| 9541 | << DestType << OnlyArg->getType() | ||||
| 9542 | << Args[0]->getSourceRange())), | ||||
| 9543 | S, OCD_AmbiguousCandidates, Args); | ||||
| 9544 | break; | ||||
| 9545 | |||||
| 9546 | case OR_No_Viable_Function: { | ||||
| 9547 | auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args); | ||||
| 9548 | if (!S.RequireCompleteType(Kind.getLocation(), | ||||
| 9549 | DestType.getNonReferenceType(), | ||||
| 9550 | diag::err_typecheck_nonviable_condition_incomplete, | ||||
| 9551 | OnlyArg->getType(), Args[0]->getSourceRange())) | ||||
| 9552 | S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) | ||||
| 9553 | << (Entity.getKind() == InitializedEntity::EK_Result) | ||||
| 9554 | << OnlyArg->getType() << Args[0]->getSourceRange() | ||||
| 9555 | << DestType.getNonReferenceType(); | ||||
| 9556 | |||||
| 9557 | FailedCandidateSet.NoteCandidates(S, Args, Cands); | ||||
| 9558 | break; | ||||
| 9559 | } | ||||
| 9560 | case OR_Deleted: { | ||||
| 9561 | S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) | ||||
| 9562 | << OnlyArg->getType() << DestType.getNonReferenceType() | ||||
| 9563 | << Args[0]->getSourceRange(); | ||||
| 9564 | OverloadCandidateSet::iterator Best; | ||||
| 9565 | OverloadingResult Ovl | ||||
| 9566 | = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); | ||||
| 9567 | if (Ovl == OR_Deleted) { | ||||
| 9568 | S.NoteDeletedFunction(Best->Function); | ||||
| 9569 | } else { | ||||
| 9570 | llvm_unreachable("Inconsistent overload resolution?")::llvm::llvm_unreachable_internal("Inconsistent overload resolution?" , "clang/lib/Sema/SemaInit.cpp", 9570); | ||||
| 9571 | } | ||||
| 9572 | break; | ||||
| 9573 | } | ||||
| 9574 | |||||
| 9575 | case OR_Success: | ||||
| 9576 | llvm_unreachable("Conversion did not fail!")::llvm::llvm_unreachable_internal("Conversion did not fail!", "clang/lib/Sema/SemaInit.cpp", 9576); | ||||
| 9577 | } | ||||
| 9578 | break; | ||||
| 9579 | |||||
| 9580 | case FK_NonConstLValueReferenceBindingToTemporary: | ||||
| 9581 | if (isa<InitListExpr>(Args[0])) { | ||||
| 9582 | S.Diag(Kind.getLocation(), | ||||
| 9583 | diag::err_lvalue_reference_bind_to_initlist) | ||||
| 9584 | << DestType.getNonReferenceType().isVolatileQualified() | ||||
| 9585 | << DestType.getNonReferenceType() | ||||
| 9586 | << Args[0]->getSourceRange(); | ||||
| 9587 | break; | ||||
| 9588 | } | ||||
| 9589 | [[fallthrough]]; | ||||
| 9590 | |||||
| 9591 | case FK_NonConstLValueReferenceBindingToUnrelated: | ||||
| 9592 | S.Diag(Kind.getLocation(), | ||||
| 9593 | Failure == FK_NonConstLValueReferenceBindingToTemporary | ||||
| 9594 | ? diag::err_lvalue_reference_bind_to_temporary | ||||
| 9595 | : diag::err_lvalue_reference_bind_to_unrelated) | ||||
| 9596 | << DestType.getNonReferenceType().isVolatileQualified() | ||||
| 9597 | << DestType.getNonReferenceType() | ||||
| 9598 | << OnlyArg->getType() | ||||
| 9599 | << Args[0]->getSourceRange(); | ||||
| 9600 | break; | ||||
| 9601 | |||||
| 9602 | case FK_NonConstLValueReferenceBindingToBitfield: { | ||||
| 9603 | // We don't necessarily have an unambiguous source bit-field. | ||||
| 9604 | FieldDecl *BitField = Args[0]->getSourceBitField(); | ||||
| 9605 | S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) | ||||
| 9606 | << DestType.isVolatileQualified() | ||||
| 9607 | << (BitField ? BitField->getDeclName() : DeclarationName()) | ||||
| 9608 | << (BitField != nullptr) | ||||
| 9609 | << Args[0]->getSourceRange(); | ||||
| 9610 | if (BitField) | ||||
| 9611 | S.Diag(BitField->getLocation(), diag::note_bitfield_decl); | ||||
| 9612 | break; | ||||
| 9613 | } | ||||
| 9614 | |||||
| 9615 | case FK_NonConstLValueReferenceBindingToVectorElement: | ||||
| 9616 | S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element) | ||||
| 9617 | << DestType.isVolatileQualified() | ||||
| 9618 | << Args[0]->getSourceRange(); | ||||
| 9619 | break; | ||||
| 9620 | |||||
| 9621 | case FK_NonConstLValueReferenceBindingToMatrixElement: | ||||
| 9622 | S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element) | ||||
| 9623 | << DestType.isVolatileQualified() << Args[0]->getSourceRange(); | ||||
| 9624 | break; | ||||
| 9625 | |||||
| 9626 | case FK_RValueReferenceBindingToLValue: | ||||
| 9627 | S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) | ||||
| 9628 | << DestType.getNonReferenceType() << OnlyArg->getType() | ||||
| 9629 | << Args[0]->getSourceRange(); | ||||
| 9630 | break; | ||||
| 9631 | |||||
| 9632 | case FK_ReferenceAddrspaceMismatchTemporary: | ||||
| 9633 | S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace) | ||||
| 9634 | << DestType << Args[0]->getSourceRange(); | ||||
| 9635 | break; | ||||
| 9636 | |||||
| 9637 | case FK_ReferenceInitDropsQualifiers: { | ||||
| 9638 | QualType SourceType = OnlyArg->getType(); | ||||
| 9639 | QualType NonRefType = DestType.getNonReferenceType(); | ||||
| 9640 | Qualifiers DroppedQualifiers = | ||||
| 9641 | SourceType.getQualifiers() - NonRefType.getQualifiers(); | ||||
| 9642 | |||||
| 9643 | if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf( | ||||
| 9644 | SourceType.getQualifiers())) | ||||
| 9645 | S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) | ||||
| 9646 | << NonRefType << SourceType << 1 /*addr space*/ | ||||
| 9647 | << Args[0]->getSourceRange(); | ||||
| 9648 | else if (DroppedQualifiers.hasQualifiers()) | ||||
| 9649 | S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) | ||||
| 9650 | << NonRefType << SourceType << 0 /*cv quals*/ | ||||
| 9651 | << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers()) | ||||
| 9652 | << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange(); | ||||
| 9653 | else | ||||
| 9654 | // FIXME: Consider decomposing the type and explaining which qualifiers | ||||
| 9655 | // were dropped where, or on which level a 'const' is missing, etc. | ||||
| 9656 | S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) | ||||
| 9657 | << NonRefType << SourceType << 2 /*incompatible quals*/ | ||||
| 9658 | << Args[0]->getSourceRange(); | ||||
| 9659 | break; | ||||
| 9660 | } | ||||
| 9661 | |||||
| 9662 | case FK_ReferenceInitFailed: | ||||
| 9663 | S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) | ||||
| 9664 | << DestType.getNonReferenceType() | ||||
| 9665 | << DestType.getNonReferenceType()->isIncompleteType() | ||||
| 9666 | << OnlyArg->isLValue() | ||||
| 9667 | << OnlyArg->getType() | ||||
| 9668 | << Args[0]->getSourceRange(); | ||||
| 9669 | emitBadConversionNotes(S, Entity, Args[0]); | ||||
| 9670 | break; | ||||
| 9671 | |||||
| 9672 | case FK_ConversionFailed: { | ||||
| 9673 | QualType FromType = OnlyArg->getType(); | ||||
| 9674 | PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed) | ||||
| 9675 | << (int)Entity.getKind() | ||||
| 9676 | << DestType | ||||
| 9677 | << OnlyArg->isLValue() | ||||
| 9678 | << FromType | ||||
| 9679 | << Args[0]->getSourceRange(); | ||||
| 9680 | S.HandleFunctionTypeMismatch(PDiag, FromType, DestType); | ||||
| 9681 | S.Diag(Kind.getLocation(), PDiag); | ||||
| 9682 | emitBadConversionNotes(S, Entity, Args[0]); | ||||
| 9683 | break; | ||||
| 9684 | } | ||||
| 9685 | |||||
| 9686 | case FK_ConversionFromPropertyFailed: | ||||
| 9687 | // No-op. This error has already been reported. | ||||
| 9688 | break; | ||||
| 9689 | |||||
| 9690 | case FK_TooManyInitsForScalar: { | ||||
| 9691 | SourceRange R; | ||||
| 9692 | |||||
| 9693 | auto *InitList = dyn_cast<InitListExpr>(Args[0]); | ||||
| 9694 | if (InitList && InitList->getNumInits() >= 1) { | ||||
| 9695 | R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc()); | ||||
| 9696 | } else { | ||||
| 9697 | 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", 9697, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 9698 | R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc()); | ||||
| 9699 | } | ||||
| 9700 | |||||
| 9701 | R.setBegin(S.getLocForEndOfToken(R.getBegin())); | ||||
| 9702 | if (Kind.isCStyleOrFunctionalCast()) | ||||
| 9703 | S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg) | ||||
| 9704 | << R; | ||||
| 9705 | else | ||||
| 9706 | S.Diag(Kind.getLocation(), diag::err_excess_initializers) | ||||
| 9707 | << /*scalar=*/2 << R; | ||||
| 9708 | break; | ||||
| 9709 | } | ||||
| 9710 | |||||
| 9711 | case FK_ParenthesizedListInitForScalar: | ||||
| 9712 | S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) | ||||
| 9713 | << 0 << Entity.getType() << Args[0]->getSourceRange(); | ||||
| 9714 | break; | ||||
| 9715 | |||||
| 9716 | case FK_ReferenceBindingToInitList: | ||||
| 9717 | S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) | ||||
| 9718 | << DestType.getNonReferenceType() << Args[0]->getSourceRange(); | ||||
| 9719 | break; | ||||
| 9720 | |||||
| 9721 | case FK_InitListBadDestinationType: | ||||
| 9722 | S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) | ||||
| 9723 | << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); | ||||
| 9724 | break; | ||||
| 9725 | |||||
| 9726 | case FK_ListConstructorOverloadFailed: | ||||
| 9727 | case FK_ConstructorOverloadFailed: { | ||||
| 9728 | SourceRange ArgsRange; | ||||
| 9729 | if (Args.size()) | ||||
| 9730 | ArgsRange = | ||||
| 9731 | SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); | ||||
| 9732 | |||||
| 9733 | if (Failure == FK_ListConstructorOverloadFailed) { | ||||
| 9734 | 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", 9735, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 9735 | "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", 9735, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 9736 | InitListExpr *InitList = cast<InitListExpr>(Args[0]); | ||||
| 9737 | Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); | ||||
| 9738 | } | ||||
| 9739 | |||||
| 9740 | // FIXME: Using "DestType" for the entity we're printing is probably | ||||
| 9741 | // bad. | ||||
| 9742 | switch (FailedOverloadResult) { | ||||
| 9743 | case OR_Ambiguous: | ||||
| 9744 | FailedCandidateSet.NoteCandidates( | ||||
| 9745 | PartialDiagnosticAt(Kind.getLocation(), | ||||
| 9746 | S.PDiag(diag::err_ovl_ambiguous_init) | ||||
| 9747 | << DestType << ArgsRange), | ||||
| 9748 | S, OCD_AmbiguousCandidates, Args); | ||||
| 9749 | break; | ||||
| 9750 | |||||
| 9751 | case OR_No_Viable_Function: | ||||
| 9752 | if (Kind.getKind() == InitializationKind::IK_Default && | ||||
| 9753 | (Entity.getKind() == InitializedEntity::EK_Base || | ||||
| 9754 | Entity.getKind() == InitializedEntity::EK_Member || | ||||
| 9755 | Entity.getKind() == InitializedEntity::EK_ParenAggInitMember) && | ||||
| 9756 | isa<CXXConstructorDecl>(S.CurContext)) { | ||||
| 9757 | // This is implicit default initialization of a member or | ||||
| 9758 | // base within a constructor. If no viable function was | ||||
| 9759 | // found, notify the user that they need to explicitly | ||||
| 9760 | // initialize this base/member. | ||||
| 9761 | CXXConstructorDecl *Constructor | ||||
| 9762 | = cast<CXXConstructorDecl>(S.CurContext); | ||||
| 9763 | const CXXRecordDecl *InheritedFrom = nullptr; | ||||
| 9764 | if (auto Inherited = Constructor->getInheritedConstructor()) | ||||
| 9765 | InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass(); | ||||
| 9766 | if (Entity.getKind() == InitializedEntity::EK_Base) { | ||||
| 9767 | S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) | ||||
| 9768 | << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) | ||||
| 9769 | << S.Context.getTypeDeclType(Constructor->getParent()) | ||||
| 9770 | << /*base=*/0 | ||||
| 9771 | << Entity.getType() | ||||
| 9772 | << InheritedFrom; | ||||
| 9773 | |||||
| 9774 | RecordDecl *BaseDecl | ||||
| 9775 | = Entity.getBaseSpecifier()->getType()->castAs<RecordType>() | ||||
| 9776 | ->getDecl(); | ||||
| 9777 | S.Diag(BaseDecl->getLocation(), diag::note_previous_decl) | ||||
| 9778 | << S.Context.getTagDeclType(BaseDecl); | ||||
| 9779 | } else { | ||||
| 9780 | S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) | ||||
| 9781 | << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) | ||||
| 9782 | << S.Context.getTypeDeclType(Constructor->getParent()) | ||||
| 9783 | << /*member=*/1 | ||||
| 9784 | << Entity.getName() | ||||
| 9785 | << InheritedFrom; | ||||
| 9786 | S.Diag(Entity.getDecl()->getLocation(), | ||||
| 9787 | diag::note_member_declared_at); | ||||
| 9788 | |||||
| 9789 | if (const RecordType *Record | ||||
| 9790 | = Entity.getType()->getAs<RecordType>()) | ||||
| 9791 | S.Diag(Record->getDecl()->getLocation(), | ||||
| 9792 | diag::note_previous_decl) | ||||
| 9793 | << S.Context.getTagDeclType(Record->getDecl()); | ||||
| 9794 | } | ||||
| 9795 | break; | ||||
| 9796 | } | ||||
| 9797 | |||||
| 9798 | FailedCandidateSet.NoteCandidates( | ||||
| 9799 | PartialDiagnosticAt( | ||||
| 9800 | Kind.getLocation(), | ||||
| 9801 | S.PDiag(diag::err_ovl_no_viable_function_in_init) | ||||
| 9802 | << DestType << ArgsRange), | ||||
| 9803 | S, OCD_AllCandidates, Args); | ||||
| 9804 | break; | ||||
| 9805 | |||||
| 9806 | case OR_Deleted: { | ||||
| 9807 | OverloadCandidateSet::iterator Best; | ||||
| 9808 | OverloadingResult Ovl | ||||
| 9809 | = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); | ||||
| 9810 | if (Ovl != OR_Deleted) { | ||||
| 9811 | S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) | ||||
| 9812 | << DestType << ArgsRange; | ||||
| 9813 | llvm_unreachable("Inconsistent overload resolution?")::llvm::llvm_unreachable_internal("Inconsistent overload resolution?" , "clang/lib/Sema/SemaInit.cpp", 9813); | ||||
| 9814 | break; | ||||
| 9815 | } | ||||
| 9816 | |||||
| 9817 | // If this is a defaulted or implicitly-declared function, then | ||||
| 9818 | // it was implicitly deleted. Make it clear that the deletion was | ||||
| 9819 | // implicit. | ||||
| 9820 | if (S.isImplicitlyDeleted(Best->Function)) | ||||
| 9821 | S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init) | ||||
| 9822 | << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)) | ||||
| 9823 | << DestType << ArgsRange; | ||||
| 9824 | else | ||||
| 9825 | S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) | ||||
| 9826 | << DestType << ArgsRange; | ||||
| 9827 | |||||
| 9828 | S.NoteDeletedFunction(Best->Function); | ||||
| 9829 | break; | ||||
| 9830 | } | ||||
| 9831 | |||||
| 9832 | case OR_Success: | ||||
| 9833 | llvm_unreachable("Conversion did not fail!")::llvm::llvm_unreachable_internal("Conversion did not fail!", "clang/lib/Sema/SemaInit.cpp", 9833); | ||||
| 9834 | } | ||||
| 9835 | } | ||||
| 9836 | break; | ||||
| 9837 | |||||
| 9838 | case FK_DefaultInitOfConst: | ||||
| 9839 | if (Entity.getKind() == InitializedEntity::EK_Member && | ||||
| 9840 | isa<CXXConstructorDecl>(S.CurContext)) { | ||||
| 9841 | // This is implicit default-initialization of a const member in | ||||
| 9842 | // a constructor. Complain that it needs to be explicitly | ||||
| 9843 | // initialized. | ||||
| 9844 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext); | ||||
| 9845 | S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor) | ||||
| 9846 | << (Constructor->getInheritedConstructor() ? 2 : | ||||
| 9847 | Constructor->isImplicit() ? 1 : 0) | ||||
| 9848 | << S.Context.getTypeDeclType(Constructor->getParent()) | ||||
| 9849 | << /*const=*/1 | ||||
| 9850 | << Entity.getName(); | ||||
| 9851 | S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl) | ||||
| 9852 | << Entity.getName(); | ||||
| 9853 | } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl()); | ||||
| 9854 | VD && VD->isConstexpr()) { | ||||
| 9855 | S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init) | ||||
| 9856 | << VD; | ||||
| 9857 | } else { | ||||
| 9858 | S.Diag(Kind.getLocation(), diag::err_default_init_const) | ||||
| 9859 | << DestType << (bool)DestType->getAs<RecordType>(); | ||||
| 9860 | } | ||||
| 9861 | break; | ||||
| 9862 | |||||
| 9863 | case FK_Incomplete: | ||||
| 9864 | S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType, | ||||
| 9865 | diag::err_init_incomplete_type); | ||||
| 9866 | break; | ||||
| 9867 | |||||
| 9868 | case FK_ListInitializationFailed: { | ||||
| 9869 | // Run the init list checker again to emit diagnostics. | ||||
| 9870 | InitListExpr *InitList = cast<InitListExpr>(Args[0]); | ||||
| 9871 | diagnoseListInit(S, Entity, InitList); | ||||
| 9872 | break; | ||||
| 9873 | } | ||||
| 9874 | |||||
| 9875 | case FK_PlaceholderType: { | ||||
| 9876 | // FIXME: Already diagnosed! | ||||
| 9877 | break; | ||||
| 9878 | } | ||||
| 9879 | |||||
| 9880 | case FK_ExplicitConstructor: { | ||||
| 9881 | S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor) | ||||
| 9882 | << Args[0]->getSourceRange(); | ||||
| 9883 | OverloadCandidateSet::iterator Best; | ||||
| 9884 | OverloadingResult Ovl | ||||
| 9885 | = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); | ||||
| 9886 | (void)Ovl; | ||||
| 9887 | 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", 9887, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 9888 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); | ||||
| 9889 | S.Diag(CtorDecl->getLocation(), | ||||
| 9890 | diag::note_explicit_ctor_deduction_guide_here) << false; | ||||
| 9891 | break; | ||||
| 9892 | } | ||||
| 9893 | |||||
| 9894 | case FK_ParenthesizedListInitFailed: | ||||
| 9895 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this, | ||||
| 9896 | /*VerifyOnly=*/false); | ||||
| 9897 | break; | ||||
| 9898 | |||||
| 9899 | case FK_DesignatedInitForNonAggregate: | ||||
| 9900 | InitListExpr *InitList = cast<InitListExpr>(Args[0]); | ||||
| 9901 | S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate) | ||||
| 9902 | << Entity.getType() << InitList->getSourceRange(); | ||||
| 9903 | break; | ||||
| 9904 | } | ||||
| 9905 | |||||
| 9906 | PrintInitLocationNote(S, Entity); | ||||
| 9907 | return true; | ||||
| 9908 | } | ||||
| 9909 | |||||
| 9910 | void InitializationSequence::dump(raw_ostream &OS) const { | ||||
| 9911 | switch (SequenceKind) { | ||||
| 9912 | case FailedSequence: { | ||||
| 9913 | OS << "Failed sequence: "; | ||||
| 9914 | switch (Failure) { | ||||
| 9915 | case FK_TooManyInitsForReference: | ||||
| 9916 | OS << "too many initializers for reference"; | ||||
| 9917 | break; | ||||
| 9918 | |||||
| 9919 | case FK_ParenthesizedListInitForReference: | ||||
| 9920 | OS << "parenthesized list init for reference"; | ||||
| 9921 | break; | ||||
| 9922 | |||||
| 9923 | case FK_ArrayNeedsInitList: | ||||
| 9924 | OS << "array requires initializer list"; | ||||
| 9925 | break; | ||||
| 9926 | |||||
| 9927 | case FK_AddressOfUnaddressableFunction: | ||||
| 9928 | OS << "address of unaddressable function was taken"; | ||||
| 9929 | break; | ||||
| 9930 | |||||
| 9931 | case FK_ArrayNeedsInitListOrStringLiteral: | ||||
| 9932 | OS << "array requires initializer list or string literal"; | ||||
| 9933 | break; | ||||
| 9934 | |||||
| 9935 | case FK_ArrayNeedsInitListOrWideStringLiteral: | ||||
| 9936 | OS << "array requires initializer list or wide string literal"; | ||||
| 9937 | break; | ||||
| 9938 | |||||
| 9939 | case FK_NarrowStringIntoWideCharArray: | ||||
| 9940 | OS << "narrow string into wide char array"; | ||||
| 9941 | break; | ||||
| 9942 | |||||
| 9943 | case FK_WideStringIntoCharArray: | ||||
| 9944 | OS << "wide string into char array"; | ||||
| 9945 | break; | ||||
| 9946 | |||||
| 9947 | case FK_IncompatWideStringIntoWideChar: | ||||
| 9948 | OS << "incompatible wide string into wide char array"; | ||||
| 9949 | break; | ||||
| 9950 | |||||
| 9951 | case FK_PlainStringIntoUTF8Char: | ||||
| 9952 | OS << "plain string literal into char8_t array"; | ||||
| 9953 | break; | ||||
| 9954 | |||||
| 9955 | case FK_UTF8StringIntoPlainChar: | ||||
| 9956 | OS << "u8 string literal into char array"; | ||||
| 9957 | break; | ||||
| 9958 | |||||
| 9959 | case FK_ArrayTypeMismatch: | ||||
| 9960 | OS << "array type mismatch"; | ||||
| 9961 | break; | ||||
| 9962 | |||||
| 9963 | case FK_NonConstantArrayInit: | ||||
| 9964 | OS << "non-constant array initializer"; | ||||
| 9965 | break; | ||||
| 9966 | |||||
| 9967 | case FK_AddressOfOverloadFailed: | ||||
| 9968 | OS << "address of overloaded function failed"; | ||||
| 9969 | break; | ||||
| 9970 | |||||
| 9971 | case FK_ReferenceInitOverloadFailed: | ||||
| 9972 | OS << "overload resolution for reference initialization failed"; | ||||
| 9973 | break; | ||||
| 9974 | |||||
| 9975 | case FK_NonConstLValueReferenceBindingToTemporary: | ||||
| 9976 | OS << "non-const lvalue reference bound to temporary"; | ||||
| 9977 | break; | ||||
| 9978 | |||||
| 9979 | case FK_NonConstLValueReferenceBindingToBitfield: | ||||
| 9980 | OS << "non-const lvalue reference bound to bit-field"; | ||||
| 9981 | break; | ||||
| 9982 | |||||
| 9983 | case FK_NonConstLValueReferenceBindingToVectorElement: | ||||
| 9984 | OS << "non-const lvalue reference bound to vector element"; | ||||
| 9985 | break; | ||||
| 9986 | |||||
| 9987 | case FK_NonConstLValueReferenceBindingToMatrixElement: | ||||
| 9988 | OS << "non-const lvalue reference bound to matrix element"; | ||||
| 9989 | break; | ||||
| 9990 | |||||
| 9991 | case FK_NonConstLValueReferenceBindingToUnrelated: | ||||
| 9992 | OS << "non-const lvalue reference bound to unrelated type"; | ||||
| 9993 | break; | ||||
| 9994 | |||||
| 9995 | case FK_RValueReferenceBindingToLValue: | ||||
| 9996 | OS << "rvalue reference bound to an lvalue"; | ||||
| 9997 | break; | ||||
| 9998 | |||||
| 9999 | case FK_ReferenceInitDropsQualifiers: | ||||
| 10000 | OS << "reference initialization drops qualifiers"; | ||||
| 10001 | break; | ||||
| 10002 | |||||
| 10003 | case FK_ReferenceAddrspaceMismatchTemporary: | ||||
| 10004 | OS << "reference with mismatching address space bound to temporary"; | ||||
| 10005 | break; | ||||
| 10006 | |||||
| 10007 | case FK_ReferenceInitFailed: | ||||
| 10008 | OS << "reference initialization failed"; | ||||
| 10009 | break; | ||||
| 10010 | |||||
| 10011 | case FK_ConversionFailed: | ||||
| 10012 | OS << "conversion failed"; | ||||
| 10013 | break; | ||||
| 10014 | |||||
| 10015 | case FK_ConversionFromPropertyFailed: | ||||
| 10016 | OS << "conversion from property failed"; | ||||
| 10017 | break; | ||||
| 10018 | |||||
| 10019 | case FK_TooManyInitsForScalar: | ||||
| 10020 | OS << "too many initializers for scalar"; | ||||
| 10021 | break; | ||||
| 10022 | |||||
| 10023 | case FK_ParenthesizedListInitForScalar: | ||||
| 10024 | OS << "parenthesized list init for reference"; | ||||
| 10025 | break; | ||||
| 10026 | |||||
| 10027 | case FK_ReferenceBindingToInitList: | ||||
| 10028 | OS << "referencing binding to initializer list"; | ||||
| 10029 | break; | ||||
| 10030 | |||||
| 10031 | case FK_InitListBadDestinationType: | ||||
| 10032 | OS << "initializer list for non-aggregate, non-scalar type"; | ||||
| 10033 | break; | ||||
| 10034 | |||||
| 10035 | case FK_UserConversionOverloadFailed: | ||||
| 10036 | OS << "overloading failed for user-defined conversion"; | ||||
| 10037 | break; | ||||
| 10038 | |||||
| 10039 | case FK_ConstructorOverloadFailed: | ||||
| 10040 | OS << "constructor overloading failed"; | ||||
| 10041 | break; | ||||
| 10042 | |||||
| 10043 | case FK_DefaultInitOfConst: | ||||
| 10044 | OS << "default initialization of a const variable"; | ||||
| 10045 | break; | ||||
| 10046 | |||||
| 10047 | case FK_Incomplete: | ||||
| 10048 | OS << "initialization of incomplete type"; | ||||
| 10049 | break; | ||||
| 10050 | |||||
| 10051 | case FK_ListInitializationFailed: | ||||
| 10052 | OS << "list initialization checker failure"; | ||||
| 10053 | break; | ||||
| 10054 | |||||
| 10055 | case FK_VariableLengthArrayHasInitializer: | ||||
| 10056 | OS << "variable length array has an initializer"; | ||||
| 10057 | break; | ||||
| 10058 | |||||
| 10059 | case FK_PlaceholderType: | ||||
| 10060 | OS << "initializer expression isn't contextually valid"; | ||||
| 10061 | break; | ||||
| 10062 | |||||
| 10063 | case FK_ListConstructorOverloadFailed: | ||||
| 10064 | OS << "list constructor overloading failed"; | ||||
| 10065 | break; | ||||
| 10066 | |||||
| 10067 | case FK_ExplicitConstructor: | ||||
| 10068 | OS << "list copy initialization chose explicit constructor"; | ||||
| 10069 | break; | ||||
| 10070 | |||||
| 10071 | case FK_ParenthesizedListInitFailed: | ||||
| 10072 | OS << "parenthesized list initialization failed"; | ||||
| 10073 | break; | ||||
| 10074 | |||||
| 10075 | case FK_DesignatedInitForNonAggregate: | ||||
| 10076 | OS << "designated initializer for non-aggregate type"; | ||||
| 10077 | break; | ||||
| 10078 | } | ||||
| 10079 | OS << '\n'; | ||||
| 10080 | return; | ||||
| 10081 | } | ||||
| 10082 | |||||
| 10083 | case DependentSequence: | ||||
| 10084 | OS << "Dependent sequence\n"; | ||||
| 10085 | return; | ||||
| 10086 | |||||
| 10087 | case NormalSequence: | ||||
| 10088 | OS << "Normal sequence: "; | ||||
| 10089 | break; | ||||
| 10090 | } | ||||
| 10091 | |||||
| 10092 | for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { | ||||
| 10093 | if (S != step_begin()) { | ||||
| 10094 | OS << " -> "; | ||||
| 10095 | } | ||||
| 10096 | |||||
| 10097 | switch (S->Kind) { | ||||
| 10098 | case SK_ResolveAddressOfOverloadedFunction: | ||||
| 10099 | OS << "resolve address of overloaded function"; | ||||
| 10100 | break; | ||||
| 10101 | |||||
| 10102 | case SK_CastDerivedToBasePRValue: | ||||
| 10103 | OS << "derived-to-base (prvalue)"; | ||||
| 10104 | break; | ||||
| 10105 | |||||
| 10106 | case SK_CastDerivedToBaseXValue: | ||||
| 10107 | OS << "derived-to-base (xvalue)"; | ||||
| 10108 | break; | ||||
| 10109 | |||||
| 10110 | case SK_CastDerivedToBaseLValue: | ||||
| 10111 | OS << "derived-to-base (lvalue)"; | ||||
| 10112 | break; | ||||
| 10113 | |||||
| 10114 | case SK_BindReference: | ||||
| 10115 | OS << "bind reference to lvalue"; | ||||
| 10116 | break; | ||||
| 10117 | |||||
| 10118 | case SK_BindReferenceToTemporary: | ||||
| 10119 | OS << "bind reference to a temporary"; | ||||
| 10120 | break; | ||||
| 10121 | |||||
| 10122 | case SK_FinalCopy: | ||||
| 10123 | OS << "final copy in class direct-initialization"; | ||||
| 10124 | break; | ||||
| 10125 | |||||
| 10126 | case SK_ExtraneousCopyToTemporary: | ||||
| 10127 | OS << "extraneous C++03 copy to temporary"; | ||||
| 10128 | break; | ||||
| 10129 | |||||
| 10130 | case SK_UserConversion: | ||||
| 10131 | OS << "user-defined conversion via " << *S->Function.Function; | ||||
| 10132 | break; | ||||
| 10133 | |||||
| 10134 | case SK_QualificationConversionPRValue: | ||||
| 10135 | OS << "qualification conversion (prvalue)"; | ||||
| 10136 | break; | ||||
| 10137 | |||||
| 10138 | case SK_QualificationConversionXValue: | ||||
| 10139 | OS << "qualification conversion (xvalue)"; | ||||
| 10140 | break; | ||||
| 10141 | |||||
| 10142 | case SK_QualificationConversionLValue: | ||||
| 10143 | OS << "qualification conversion (lvalue)"; | ||||
| 10144 | break; | ||||
| 10145 | |||||
| 10146 | case SK_FunctionReferenceConversion: | ||||
| 10147 | OS << "function reference conversion"; | ||||
| 10148 | break; | ||||
| 10149 | |||||
| 10150 | case SK_AtomicConversion: | ||||
| 10151 | OS << "non-atomic-to-atomic conversion"; | ||||
| 10152 | break; | ||||
| 10153 | |||||
| 10154 | case SK_ConversionSequence: | ||||
| 10155 | OS << "implicit conversion sequence ("; | ||||
| 10156 | S->ICS->dump(); // FIXME: use OS | ||||
| 10157 | OS << ")"; | ||||
| 10158 | break; | ||||
| 10159 | |||||
| 10160 | case SK_ConversionSequenceNoNarrowing: | ||||
| 10161 | OS << "implicit conversion sequence with narrowing prohibited ("; | ||||
| 10162 | S->ICS->dump(); // FIXME: use OS | ||||
| 10163 | OS << ")"; | ||||
| 10164 | break; | ||||
| 10165 | |||||
| 10166 | case SK_ListInitialization: | ||||
| 10167 | OS << "list aggregate initialization"; | ||||
| 10168 | break; | ||||
| 10169 | |||||
| 10170 | case SK_UnwrapInitList: | ||||
| 10171 | OS << "unwrap reference initializer list"; | ||||
| 10172 | break; | ||||
| 10173 | |||||
| 10174 | case SK_RewrapInitList: | ||||
| 10175 | OS << "rewrap reference initializer list"; | ||||
| 10176 | break; | ||||
| 10177 | |||||
| 10178 | case SK_ConstructorInitialization: | ||||
| 10179 | OS << "constructor initialization"; | ||||
| 10180 | break; | ||||
| 10181 | |||||
| 10182 | case SK_ConstructorInitializationFromList: | ||||
| 10183 | OS << "list initialization via constructor"; | ||||
| 10184 | break; | ||||
| 10185 | |||||
| 10186 | case SK_ZeroInitialization: | ||||
| 10187 | OS << "zero initialization"; | ||||
| 10188 | break; | ||||
| 10189 | |||||
| 10190 | case SK_CAssignment: | ||||
| 10191 | OS << "C assignment"; | ||||
| 10192 | break; | ||||
| 10193 | |||||
| 10194 | case SK_StringInit: | ||||
| 10195 | OS << "string initialization"; | ||||
| 10196 | break; | ||||
| 10197 | |||||
| 10198 | case SK_ObjCObjectConversion: | ||||
| 10199 | OS << "Objective-C object conversion"; | ||||
| 10200 | break; | ||||
| 10201 | |||||
| 10202 | case SK_ArrayLoopIndex: | ||||
| 10203 | OS << "indexing for array initialization loop"; | ||||
| 10204 | break; | ||||
| 10205 | |||||
| 10206 | case SK_ArrayLoopInit: | ||||
| 10207 | OS << "array initialization loop"; | ||||
| 10208 | break; | ||||
| 10209 | |||||
| 10210 | case SK_ArrayInit: | ||||
| 10211 | OS << "array initialization"; | ||||
| 10212 | break; | ||||
| 10213 | |||||
| 10214 | case SK_GNUArrayInit: | ||||
| 10215 | OS << "array initialization (GNU extension)"; | ||||
| 10216 | break; | ||||
| 10217 | |||||
| 10218 | case SK_ParenthesizedArrayInit: | ||||
| 10219 | OS << "parenthesized array initialization"; | ||||
| 10220 | break; | ||||
| 10221 | |||||
| 10222 | case SK_PassByIndirectCopyRestore: | ||||
| 10223 | OS << "pass by indirect copy and restore"; | ||||
| 10224 | break; | ||||
| 10225 | |||||
| 10226 | case SK_PassByIndirectRestore: | ||||
| 10227 | OS << "pass by indirect restore"; | ||||
| 10228 | break; | ||||
| 10229 | |||||
| 10230 | case SK_ProduceObjCObject: | ||||
| 10231 | OS << "Objective-C object retension"; | ||||
| 10232 | break; | ||||
| 10233 | |||||
| 10234 | case SK_StdInitializerList: | ||||
| 10235 | OS << "std::initializer_list from initializer list"; | ||||
| 10236 | break; | ||||
| 10237 | |||||
| 10238 | case SK_StdInitializerListConstructorCall: | ||||
| 10239 | OS << "list initialization from std::initializer_list"; | ||||
| 10240 | break; | ||||
| 10241 | |||||
| 10242 | case SK_OCLSamplerInit: | ||||
| 10243 | OS << "OpenCL sampler_t from integer constant"; | ||||
| 10244 | break; | ||||
| 10245 | |||||
| 10246 | case SK_OCLZeroOpaqueType: | ||||
| 10247 | OS << "OpenCL opaque type from zero"; | ||||
| 10248 | break; | ||||
| 10249 | case SK_ParenthesizedListInit: | ||||
| 10250 | OS << "initialization from a parenthesized list of values"; | ||||
| 10251 | break; | ||||
| 10252 | } | ||||
| 10253 | |||||
| 10254 | OS << " [" << S->Type << ']'; | ||||
| 10255 | } | ||||
| 10256 | |||||
| 10257 | OS << '\n'; | ||||
| 10258 | } | ||||
| 10259 | |||||
| 10260 | void InitializationSequence::dump() const { | ||||
| 10261 | dump(llvm::errs()); | ||||
| 10262 | } | ||||
| 10263 | |||||
| 10264 | static bool NarrowingErrs(const LangOptions &L) { | ||||
| 10265 | return L.CPlusPlus11 && | ||||
| 10266 | (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)); | ||||
| 10267 | } | ||||
| 10268 | |||||
| 10269 | static void DiagnoseNarrowingInInitList(Sema &S, | ||||
| 10270 | const ImplicitConversionSequence &ICS, | ||||
| 10271 | QualType PreNarrowingType, | ||||
| 10272 | QualType EntityType, | ||||
| 10273 | const Expr *PostInit) { | ||||
| 10274 | const StandardConversionSequence *SCS = nullptr; | ||||
| 10275 | switch (ICS.getKind()) { | ||||
| 10276 | case ImplicitConversionSequence::StandardConversion: | ||||
| 10277 | SCS = &ICS.Standard; | ||||
| 10278 | break; | ||||
| 10279 | case ImplicitConversionSequence::UserDefinedConversion: | ||||
| 10280 | SCS = &ICS.UserDefined.After; | ||||
| 10281 | break; | ||||
| 10282 | case ImplicitConversionSequence::AmbiguousConversion: | ||||
| 10283 | case ImplicitConversionSequence::StaticObjectArgumentConversion: | ||||
| 10284 | case ImplicitConversionSequence::EllipsisConversion: | ||||
| 10285 | case ImplicitConversionSequence::BadConversion: | ||||
| 10286 | return; | ||||
| 10287 | } | ||||
| 10288 | |||||
| 10289 | // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion. | ||||
| 10290 | APValue ConstantValue; | ||||
| 10291 | QualType ConstantType; | ||||
| 10292 | switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue, | ||||
| 10293 | ConstantType)) { | ||||
| 10294 | case NK_Not_Narrowing: | ||||
| 10295 | case NK_Dependent_Narrowing: | ||||
| 10296 | // No narrowing occurred. | ||||
| 10297 | return; | ||||
| 10298 | |||||
| 10299 | case NK_Type_Narrowing: | ||||
| 10300 | // This was a floating-to-integer conversion, which is always considered a | ||||
| 10301 | // narrowing conversion even if the value is a constant and can be | ||||
| 10302 | // represented exactly as an integer. | ||||
| 10303 | S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts()) | ||||
| 10304 | ? diag::ext_init_list_type_narrowing | ||||
| 10305 | : diag::warn_init_list_type_narrowing) | ||||
| 10306 | << PostInit->getSourceRange() | ||||
| 10307 | << PreNarrowingType.getLocalUnqualifiedType() | ||||
| 10308 | << EntityType.getLocalUnqualifiedType(); | ||||
| 10309 | break; | ||||
| 10310 | |||||
| 10311 | case NK_Constant_Narrowing: | ||||
| 10312 | // A constant value was narrowed. | ||||
| 10313 | S.Diag(PostInit->getBeginLoc(), | ||||
| 10314 | NarrowingErrs(S.getLangOpts()) | ||||
| 10315 | ? diag::ext_init_list_constant_narrowing | ||||
| 10316 | : diag::warn_init_list_constant_narrowing) | ||||
| 10317 | << PostInit->getSourceRange() | ||||
| 10318 | << ConstantValue.getAsString(S.getASTContext(), ConstantType) | ||||
| 10319 | << EntityType.getLocalUnqualifiedType(); | ||||
| 10320 | break; | ||||
| 10321 | |||||
| 10322 | case NK_Variable_Narrowing: | ||||
| 10323 | // A variable's value may have been narrowed. | ||||
| 10324 | S.Diag(PostInit->getBeginLoc(), | ||||
| 10325 | NarrowingErrs(S.getLangOpts()) | ||||
| 10326 | ? diag::ext_init_list_variable_narrowing | ||||
| 10327 | : diag::warn_init_list_variable_narrowing) | ||||
| 10328 | << PostInit->getSourceRange() | ||||
| 10329 | << PreNarrowingType.getLocalUnqualifiedType() | ||||
| 10330 | << EntityType.getLocalUnqualifiedType(); | ||||
| 10331 | break; | ||||
| 10332 | } | ||||
| 10333 | |||||
| 10334 | SmallString<128> StaticCast; | ||||
| 10335 | llvm::raw_svector_ostream OS(StaticCast); | ||||
| 10336 | OS << "static_cast<"; | ||||
| 10337 | if (const TypedefType *TT = EntityType->getAs<TypedefType>()) { | ||||
| 10338 | // It's important to use the typedef's name if there is one so that the | ||||
| 10339 | // fixit doesn't break code using types like int64_t. | ||||
| 10340 | // | ||||
| 10341 | // FIXME: This will break if the typedef requires qualification. But | ||||
| 10342 | // getQualifiedNameAsString() includes non-machine-parsable components. | ||||
| 10343 | OS << *TT->getDecl(); | ||||
| 10344 | } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>()) | ||||
| 10345 | OS << BT->getName(S.getLangOpts()); | ||||
| 10346 | else { | ||||
| 10347 | // Oops, we didn't find the actual type of the variable. Don't emit a fixit | ||||
| 10348 | // with a broken cast. | ||||
| 10349 | return; | ||||
| 10350 | } | ||||
| 10351 | OS << ">("; | ||||
| 10352 | S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence) | ||||
| 10353 | << PostInit->getSourceRange() | ||||
| 10354 | << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str()) | ||||
| 10355 | << FixItHint::CreateInsertion( | ||||
| 10356 | S.getLocForEndOfToken(PostInit->getEndLoc()), ")"); | ||||
| 10357 | } | ||||
| 10358 | |||||
| 10359 | //===----------------------------------------------------------------------===// | ||||
| 10360 | // Initialization helper functions | ||||
| 10361 | //===----------------------------------------------------------------------===// | ||||
| 10362 | bool | ||||
| 10363 | Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, | ||||
| 10364 | ExprResult Init) { | ||||
| 10365 | if (Init.isInvalid()) | ||||
| 10366 | return false; | ||||
| 10367 | |||||
| 10368 | Expr *InitE = Init.get(); | ||||
| 10369 | 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", 10369, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 10370 | |||||
| 10371 | InitializationKind Kind = | ||||
| 10372 | InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation()); | ||||
| 10373 | InitializationSequence Seq(*this, Entity, Kind, InitE); | ||||
| 10374 | return !Seq.Failed(); | ||||
| 10375 | } | ||||
| 10376 | |||||
| 10377 | ExprResult | ||||
| 10378 | Sema::PerformCopyInitialization(const InitializedEntity &Entity, | ||||
| 10379 | SourceLocation EqualLoc, | ||||
| 10380 | ExprResult Init, | ||||
| 10381 | bool TopLevelOfInitList, | ||||
| 10382 | bool AllowExplicit) { | ||||
| 10383 | if (Init.isInvalid()) | ||||
| 10384 | return ExprError(); | ||||
| 10385 | |||||
| 10386 | Expr *InitE = Init.get(); | ||||
| 10387 | 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", 10387, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 10388 | |||||
| 10389 | if (EqualLoc.isInvalid()) | ||||
| 10390 | EqualLoc = InitE->getBeginLoc(); | ||||
| 10391 | |||||
| 10392 | InitializationKind Kind = InitializationKind::CreateCopy( | ||||
| 10393 | InitE->getBeginLoc(), EqualLoc, AllowExplicit); | ||||
| 10394 | InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList); | ||||
| 10395 | |||||
| 10396 | // Prevent infinite recursion when performing parameter copy-initialization. | ||||
| 10397 | const bool ShouldTrackCopy = | ||||
| 10398 | Entity.isParameterKind() && Seq.isConstructorInitialization(); | ||||
| 10399 | if (ShouldTrackCopy) { | ||||
| 10400 | if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) { | ||||
| 10401 | Seq.SetOverloadFailure( | ||||
| 10402 | InitializationSequence::FK_ConstructorOverloadFailed, | ||||
| 10403 | OR_No_Viable_Function); | ||||
| 10404 | |||||
| 10405 | // Try to give a meaningful diagnostic note for the problematic | ||||
| 10406 | // constructor. | ||||
| 10407 | const auto LastStep = Seq.step_end() - 1; | ||||
| 10408 | 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", 10409, __extension__ __PRETTY_FUNCTION__ )) | ||||
| 10409 | 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", 10409, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 10410 | const FunctionDecl *Function = LastStep->Function.Function; | ||||
| 10411 | auto Candidate = | ||||
| 10412 | llvm::find_if(Seq.getFailedCandidateSet(), | ||||
| 10413 | [Function](const OverloadCandidate &Candidate) -> bool { | ||||
| 10414 | return Candidate.Viable && | ||||
| 10415 | Candidate.Function == Function && | ||||
| 10416 | Candidate.Conversions.size() > 0; | ||||
| 10417 | }); | ||||
| 10418 | if (Candidate != Seq.getFailedCandidateSet().end() && | ||||
| 10419 | Function->getNumParams() > 0) { | ||||
| 10420 | Candidate->Viable = false; | ||||
| 10421 | Candidate->FailureKind = ovl_fail_bad_conversion; | ||||
| 10422 | Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion, | ||||
| 10423 | InitE, | ||||
| 10424 | Function->getParamDecl(0)->getType()); | ||||
| 10425 | } | ||||
| 10426 | } | ||||
| 10427 | CurrentParameterCopyTypes.push_back(Entity.getType()); | ||||
| 10428 | } | ||||
| 10429 | |||||
| 10430 | ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE); | ||||
| 10431 | |||||
| 10432 | if (ShouldTrackCopy) | ||||
| 10433 | CurrentParameterCopyTypes.pop_back(); | ||||
| 10434 | |||||
| 10435 | return Result; | ||||
| 10436 | } | ||||
| 10437 | |||||
| 10438 | /// Determine whether RD is, or is derived from, a specialization of CTD. | ||||
| 10439 | static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, | ||||
| 10440 | ClassTemplateDecl *CTD) { | ||||
| 10441 | auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) { | ||||
| 10442 | auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate); | ||||
| 10443 | return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD); | ||||
| 10444 | }; | ||||
| 10445 | return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization)); | ||||
| 10446 | } | ||||
| 10447 | |||||
| 10448 | QualType Sema::DeduceTemplateSpecializationFromInitializer( | ||||
| 10449 | TypeSourceInfo *TSInfo, const InitializedEntity &Entity, | ||||
| 10450 | const InitializationKind &Kind, MultiExprArg Inits) { | ||||
| 10451 | auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>( | ||||
| 10452 | TSInfo->getType()->getContainedDeducedType()); | ||||
| 10453 | 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", 10453, __extension__ __PRETTY_FUNCTION__ )); | ||||
| 10454 | |||||
| 10455 | auto TemplateName = DeducedTST->getTemplateName(); | ||||
| 10456 | if (TemplateName.isDependent()) | ||||
| 10457 | return SubstAutoTypeDependent(TSInfo->getType()); | ||||
| 10458 | |||||
| 10459 | // We can only perform deduction for class templates. | ||||
| 10460 | auto *Template = | ||||
| 10461 | dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl()); | ||||
| 10462 | if (!Template) { | ||||
| 10463 | Diag(Kind.getLocation(), | ||||
| 10464 | diag::err_deduced_non_class_template_specialization_type) | ||||
| 10465 | << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName; | ||||
| 10466 | if (auto *TD = TemplateName.getAsTemplateDecl()) | ||||
| 10467 | Diag(TD->getLocation(), diag::note_template_decl_here); | ||||
| 10468 | return QualType(); | ||||
| 10469 | } | ||||
| 10470 | |||||
| 10471 | // Can't deduce from dependent arguments. | ||||
| 10472 | if (Expr::hasAnyTypeDependentArguments(Inits)) { | ||||
| 10473 | Diag(TSInfo->getTypeLoc().getBeginLoc(), | ||||
| 10474 | diag::warn_cxx14_compat_class_template_argument_deduction) | ||||
| 10475 | << TSInfo->getTypeLoc().getSourceRange() << 0; | ||||
| 10476 | return SubstAutoTypeDependent(TSInfo->getType()); | ||||
| 10477 | } | ||||
| 10478 | |||||
| 10479 | // FIXME: Perform "exact type" matching first, per CWG discussion? | ||||
| 10480 | // Or implement this via an implied 'T(T) -> T' deduction guide? | ||||
| 10481 | |||||
| 10482 | // FIXME: Do we need/want a std::initializer_list<T> special case? | ||||
| 10483 | |||||
| 10484 | // Look up deduction guides, including those synthesized from constructors. | ||||
| 10485 | // | ||||
| 10486 | // C++1z [over.match.class.deduct]p1: | ||||
| 10487 | // A set of functions and function templates is formed comprising: | ||||
| 10488 | // - For each constructor of the class template designated by the | ||||
| 10489 | // template-name, a function template [...] | ||||
| 10490 | // - For each deduction-guide, a function or function template [...] | ||||
| 10491 | DeclarationNameInfo NameInfo( | ||||
| 10492 | Context.DeclarationNames.getCXXDeductionGuideName(Template), | ||||
| 10493 | TSInfo->getTypeLoc().getEndLoc()); | ||||
| 10494 | LookupResult Guides(*this, NameInfo, LookupOrdinaryName); | ||||
| 10495 | LookupQualifiedName(Guides, Template->getDeclContext()); | ||||
| 10496 | |||||
| 10497 | // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't | ||||
| 10498 | // clear on this, but they're not found by name so access does not apply. | ||||
| 10499 | Guides.suppressDiagnostics(); | ||||
| 10500 | |||||
| 10501 | // Figure out if this is list-initialization. | ||||
| 10502 | InitListExpr *ListInit = | ||||
| 10503 | (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct) | ||||
| 10504 | ? dyn_cast<InitListExpr>(Inits[0]) | ||||
| 10505 | : nullptr; | ||||
| 10506 | |||||
| 10507 | // C++1z [over.match.class.deduct]p1: | ||||
| 10508 | // Initialization and overload resolution are performed as described in | ||||
| 10509 | // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list] | ||||
| 10510 | // (as appropriate for the type of initialization performed) for an object | ||||
| 10511 | // of a hypothetical class type, where the selected functions and function | ||||
| 10512 | // templates are considered to be the constructors of that class type | ||||
| 10513 | // | ||||
| 10514 | // Since we know we're initializing a class type of a type unrelated to that | ||||
| 10515 | // of the initializer, this reduces to something fairly reasonable. | ||||
| 10516 | OverloadCandidateSet Candidates(Kind.getLocation(), | ||||
| 10517 | OverloadCandidateSet::CSK_Normal); | ||||
| 10518 | OverloadCandidateSet::iterator Best; | ||||
| 10519 | |||||
| 10520 | bool HasAnyDeductionGuide = false; | ||||
| 10521 | bool AllowExplicit = !Kind.isCopyInit() || ListInit; | ||||
| 10522 | |||||
| 10523 | auto tryToResolveOverload = | ||||
| 10524 | [&](bool OnlyListConstructors) -> OverloadingResult { | ||||
| 10525 | Candidates.clear(OverloadCandidateSet::CSK_Normal); | ||||
| 10526 | HasAnyDeductionGuide = false; | ||||
| 10527 | |||||
| 10528 | for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) { | ||||
| 10529 | NamedDecl *D = (*I)->getUnderlyingDecl(); | ||||
| 10530 | if (D->isInvalidDecl()) | ||||
| 10531 | continue; | ||||
| 10532 | |||||
| 10533 | auto *TD = dyn_cast<FunctionTemplateDecl>(D); | ||||
| 10534 | auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>( | ||||
| 10535 | TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D)); | ||||
| 10536 | if (!GD) | ||||
| 10537 | continue; | ||||
| 10538 | |||||
| 10539 | if (!GD->isImplicit()) | ||||
| 10540 | HasAnyDeductionGuide = true; | ||||
| 10541 | |||||
| 10542 | // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class) | ||||
| 10543 | // For copy-initialization, the candidate functions are all the | ||||
| 10544 | // converting constructors (12.3.1) of that class. | ||||
| 10545 | // C++ [over.match.copy]p1: (non-list copy-initialization from class) | ||||
| 10546 | // The converting constructors of T are candidate functions. | ||||
| 10547 | if (!AllowExplicit) { | ||||
| 10548 | // Overload resolution checks whether the deduction guide is declared | ||||
| 10549 | // explicit for us. | ||||
| 10550 | |||||
| 10551 | // When looking for a converting constructor, deduction guides that | ||||
| 10552 | // could never be called with one argument are not interesting to | ||||
| 10553 | // check or note. | ||||
| 10554 | if (GD->getMinRequiredArguments() > 1 || | ||||
| 10555 | (GD->getNumParams() == 0 && !GD->isVariadic())) | ||||
| 10556 | continue; | ||||
| 10557 | } | ||||
| 10558 | |||||
| 10559 | // C++ [over.match.list]p1.1: (first phase list initialization) | ||||
| 10560 | // Initially, the candidate functions are the initializer-list | ||||
| 10561 | // constructors of the class T | ||||
| 10562 | if (OnlyListConstructors && !isInitListConstructor(GD)) | ||||
| 10563 | continue; | ||||
| 10564 | |||||
| 10565 | // C++ [over.match.list]p1.2: (second phase list initialization) | ||||
| 10566 | // the candidate functions are all the constructors of the class T | ||||
| 10567 | // C++ [over.match.ctor]p1: (all other cases) | ||||
| 10568 | // the candidate functions are all the constructors of the class of | ||||
| 10569 | // the object being initialized | ||||
| 10570 | |||||
| 10571 | // C++ [over.best.ics]p4: | ||||
| 10572 | // When [...] the constructor [...] is a candidate by | ||||
| 10573 | // - [over.match.copy] (in all cases) | ||||
| 10574 | // FIXME: The "second phase of [over.match.list] case can also | ||||
| 10575 | // theoretically happen here, but it's not clear whether we can | ||||
| 10576 | // ever have a parameter of the right type. | ||||
| 10577 | bool SuppressUserConversions = Kind.isCopyInit(); | ||||
| 10578 | |||||
| 10579 | if (TD) | ||||
| 10580 | AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr, | ||||
| 10581 | Inits, Candidates, SuppressUserConversions, | ||||
| 10582 | /*PartialOverloading*/ false, | ||||
| 10583 | AllowExplicit); | ||||
| 10584 | else | ||||
| 10585 | AddOverloadCandidate(GD, I.getPair(), Inits, Candidates, | ||||
| 10586 | SuppressUserConversions, | ||||
| 10587 | /*PartialOverloading*/ false, AllowExplicit); | ||||
| 10588 | } | ||||
| 10589 | return Candidates.BestViableFunction(*this, Kind.getLocation(), Best); | ||||
| 10590 | }; | ||||
| 10591 | |||||
| 10592 | OverloadingResult Result = OR_No_Viable_Function; | ||||
| 10593 | |||||
| 10594 | // C++11 [over.match.list]p1, per DR1467: for list-initialization, first | ||||
| 10595 | // try initializer-list constructors. | ||||
| 10596 | if (ListInit) { | ||||
| 10597 | bool TryListConstructors = true; | ||||
| 10598 | |||||
| 10599 | // Try list constructors unless the list is empty and the class has one or | ||||
| 10600 | // more default constructors, in which case those constructors win. | ||||
| 10601 | if (!ListInit->getNumInits()) { | ||||
| 10602 | for (NamedDecl *D : Guides) { | ||||
| 10603 | auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl()); | ||||
| 10604 | if (FD && FD->getMinRequiredArguments() == 0) { | ||||
| 10605 | TryListConstructors = false; | ||||
| 10606 | break; | ||||
| 10607 | } | ||||
| 10608 | } | ||||
| 10609 | } else if (ListInit->getNumInits() == 1) { | ||||
| 10610 | // C++ [over.match.class.deduct]: | ||||
| 10611 | // As an exception, the first phase in [over.match.list] (considering | ||||
| 10612 | // initializer-list constructors) is omitted if the initializer list | ||||
| 10613 | // consists of a single expression of type cv U, where U is a | ||||
| 10614 | // specialization of C or a class derived from a specialization of C. | ||||
| 10615 | Expr *E = ListInit->getInit(0); | ||||
| 10616 | auto *RD = E->getType()->getAsCXXRecordDecl(); | ||||
| 10617 | if (!isa<InitListExpr>(E) && RD && | ||||
| 10618 | isCompleteType(Kind.getLocation(), E->getType()) && | ||||
| 10619 | isOrIsDerivedFromSpecializationOf(RD, Template)) | ||||
| 10620 | TryListConstructors = false; | ||||
| 10621 | } | ||||
| 10622 | |||||
| 10623 | if (TryListConstructors) | ||||
| 10624 | Result = tryToResolveOverload(/*OnlyListConstructor*/true); | ||||
| 10625 | // Then unwrap the initializer list and try again considering all | ||||
| 10626 | // constructors. | ||||
| 10627 | Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits()); | ||||
| 10628 | } | ||||
| 10629 | |||||
| 10630 | // If list-initialization fails, or if we're doing any other kind of | ||||
| 10631 | // initialization, we (eventually) consider constructors. | ||||
| 10632 | if (Result == OR_No_Viable_Function) | ||||
| 10633 | Result = tryToResolveOverload(/*OnlyListConstructor*/false); | ||||
| 10634 | |||||
| 10635 | switch (Result) { | ||||
| 10636 | case OR_Ambiguous: | ||||
| 10637 | // FIXME: For list-initialization candidates, it'd usually be better to | ||||
| 10638 | // list why they were not viable when given the initializer list itself as | ||||
| 10639 | // an argument. | ||||
| 10640 | Candidates.NoteCandidates( | ||||
| 10641 | PartialDiagnosticAt( | ||||
| 10642 | Kind.getLocation(), | ||||
| 10643 | PDiag(diag::err_deduced_class_template_ctor_ambiguous) | ||||
| 10644 | << TemplateName), | ||||
| 10645 | *this, OCD_AmbiguousCandidates, Inits); | ||||
| 10646 | return QualType(); | ||||
| 10647 | |||||
| 10648 | case OR_No_Viable_Function: { | ||||
| 10649 | CXXRecordDecl *Primary = | ||||
| 10650 | cast<ClassTemplateDecl>(Template)->getTemplatedDecl(); | ||||
| 10651 | bool Complete = | ||||
| 10652 | isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary)); | ||||
| 10653 | Candidates.NoteCandidates( | ||||
| 10654 | PartialDiagnosticAt( | ||||
| 10655 | Kind.getLocation(), | ||||
| 10656 | PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable | ||||
| 10657 | : diag::err_deduced_class_template_incomplete) | ||||
| 10658 | << TemplateName << !Guides.empty()), | ||||
| 10659 | *this, OCD_AllCandidates, Inits); | ||||
| 10660 | return QualType(); | ||||
| 10661 | } | ||||
| 10662 | |||||
| 10663 | case OR_Deleted: { | ||||
| 10664 | Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted) | ||||
| 10665 | << TemplateName; | ||||
| 10666 | NoteDeletedFunction(Best->Function); | ||||
| 10667 | return QualType(); | ||||
| 10668 | } | ||||
| 10669 | |||||
| 10670 | case OR_Success: | ||||
| 10671 | // C++ [over.match.list]p1: | ||||
| 10672 | // In copy-list-initialization, if an explicit constructor is chosen, the | ||||
| 10673 | // initialization is ill-formed. | ||||
| 10674 | if (Kind.isCopyInit() && ListInit && | ||||
| 10675 | cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) { | ||||
| 10676 | bool IsDeductionGuide = !Best->Function->isImplicit(); | ||||
| 10677 | Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit) | ||||
| 10678 | << TemplateName << IsDeductionGuide; | ||||
| 10679 | Diag(Best->Function->getLocation(), | ||||
| 10680 | diag::note_explicit_ctor_deduction_guide_here) | ||||
| 10681 | << IsDeductionGuide; | ||||
| 10682 | return QualType(); | ||||
| 10683 | } | ||||
| 10684 | |||||
| 10685 | // Make sure we didn't select an unusable deduction guide, and mark it | ||||
| 10686 | // as referenced. | ||||
| 10687 | DiagnoseUseOfDecl(Best->FoundDecl, Kind.getLocation()); | ||||
| 10688 | MarkFunctionReferenced(Kind.getLocation(), Best->Function); | ||||
| 10689 | break; | ||||
| 10690 | } | ||||
| 10691 | |||||
| 10692 | // C++ [dcl.type.class.deduct]p1: | ||||
| 10693 | // The placeholder is replaced by the return type of the function selected | ||||
| 10694 | // by overload resolution for class template deduction. | ||||
| 10695 | QualType DeducedType = | ||||
| 10696 | SubstAutoType(TSInfo->getType(), Best->Function->getReturnType()); | ||||
| 10697 | Diag(TSInfo->getTypeLoc().getBeginLoc(), | ||||
| 10698 | diag::warn_cxx14_compat_class_template_argument_deduction) | ||||
| 10699 | << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType; | ||||
| 10700 | |||||
| 10701 | // Warn if CTAD was used on a type that does not have any user-defined | ||||
| 10702 | // deduction guides. | ||||
| 10703 | if (!HasAnyDeductionGuide) { | ||||
| 10704 | Diag(TSInfo->getTypeLoc().getBeginLoc(), | ||||
| 10705 | diag::warn_ctad_maybe_unsupported) | ||||
| 10706 | << TemplateName; | ||||
| 10707 | Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported); | ||||
| 10708 | } | ||||
| 10709 | |||||
| 10710 | return DeducedType; | ||||
| 10711 | } |
| 1 | //===- Decl.h - Classes for representing declarations -----------*- C++ -*-===// |
| 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 defines the Decl subclasses. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #ifndef LLVM_CLANG_AST_DECL_H |
| 14 | #define LLVM_CLANG_AST_DECL_H |
| 15 | |
| 16 | #include "clang/AST/APValue.h" |
| 17 | #include "clang/AST/ASTContextAllocate.h" |
| 18 | #include "clang/AST/DeclAccessPair.h" |
| 19 | #include "clang/AST/DeclBase.h" |
| 20 | #include "clang/AST/DeclarationName.h" |
| 21 | #include "clang/AST/ExternalASTSource.h" |
| 22 | #include "clang/AST/NestedNameSpecifier.h" |
| 23 | #include "clang/AST/Redeclarable.h" |
| 24 | #include "clang/AST/Type.h" |
| 25 | #include "clang/Basic/AddressSpaces.h" |
| 26 | #include "clang/Basic/Diagnostic.h" |
| 27 | #include "clang/Basic/IdentifierTable.h" |
| 28 | #include "clang/Basic/LLVM.h" |
| 29 | #include "clang/Basic/Linkage.h" |
| 30 | #include "clang/Basic/OperatorKinds.h" |
| 31 | #include "clang/Basic/PartialDiagnostic.h" |
| 32 | #include "clang/Basic/PragmaKinds.h" |
| 33 | #include "clang/Basic/SourceLocation.h" |
| 34 | #include "clang/Basic/Specifiers.h" |
| 35 | #include "clang/Basic/Visibility.h" |
| 36 | #include "llvm/ADT/APSInt.h" |
| 37 | #include "llvm/ADT/ArrayRef.h" |
| 38 | #include "llvm/ADT/PointerIntPair.h" |
| 39 | #include "llvm/ADT/PointerUnion.h" |
| 40 | #include "llvm/ADT/StringRef.h" |
| 41 | #include "llvm/ADT/iterator_range.h" |
| 42 | #include "llvm/Support/Casting.h" |
| 43 | #include "llvm/Support/Compiler.h" |
| 44 | #include "llvm/Support/TrailingObjects.h" |
| 45 | #include <cassert> |
| 46 | #include <cstddef> |
| 47 | #include <cstdint> |
| 48 | #include <optional> |
| 49 | #include <string> |
| 50 | #include <utility> |
| 51 | |
| 52 | namespace clang { |
| 53 | |
| 54 | class ASTContext; |
| 55 | struct ASTTemplateArgumentListInfo; |
| 56 | class CompoundStmt; |
| 57 | class DependentFunctionTemplateSpecializationInfo; |
| 58 | class EnumDecl; |
| 59 | class Expr; |
| 60 | class FunctionTemplateDecl; |
| 61 | class FunctionTemplateSpecializationInfo; |
| 62 | class FunctionTypeLoc; |
| 63 | class LabelStmt; |
| 64 | class MemberSpecializationInfo; |
| 65 | class Module; |
| 66 | class NamespaceDecl; |
| 67 | class ParmVarDecl; |
| 68 | class RecordDecl; |
| 69 | class Stmt; |
| 70 | class StringLiteral; |
| 71 | class TagDecl; |
| 72 | class TemplateArgumentList; |
| 73 | class TemplateArgumentListInfo; |
| 74 | class TemplateParameterList; |
| 75 | class TypeAliasTemplateDecl; |
| 76 | class UnresolvedSetImpl; |
| 77 | class VarTemplateDecl; |
| 78 | |
| 79 | /// The top declaration context. |
| 80 | class TranslationUnitDecl : public Decl, |
| 81 | public DeclContext, |
| 82 | public Redeclarable<TranslationUnitDecl> { |
| 83 | using redeclarable_base = Redeclarable<TranslationUnitDecl>; |
| 84 | |
| 85 | TranslationUnitDecl *getNextRedeclarationImpl() override { |
| 86 | return getNextRedeclaration(); |
| 87 | } |
| 88 | |
| 89 | TranslationUnitDecl *getPreviousDeclImpl() override { |
| 90 | return getPreviousDecl(); |
| 91 | } |
| 92 | |
| 93 | TranslationUnitDecl *getMostRecentDeclImpl() override { |
| 94 | return getMostRecentDecl(); |
| 95 | } |
| 96 | |
| 97 | ASTContext &Ctx; |
| 98 | |
| 99 | /// The (most recently entered) anonymous namespace for this |
| 100 | /// translation unit, if one has been created. |
| 101 | NamespaceDecl *AnonymousNamespace = nullptr; |
| 102 | |
| 103 | explicit TranslationUnitDecl(ASTContext &ctx); |
| 104 | |
| 105 | virtual void anchor(); |
| 106 | |
| 107 | public: |
| 108 | using redecl_range = redeclarable_base::redecl_range; |
| 109 | using redecl_iterator = redeclarable_base::redecl_iterator; |
| 110 | |
| 111 | using redeclarable_base::getMostRecentDecl; |
| 112 | using redeclarable_base::getPreviousDecl; |
| 113 | using redeclarable_base::isFirstDecl; |
| 114 | using redeclarable_base::redecls; |
| 115 | using redeclarable_base::redecls_begin; |
| 116 | using redeclarable_base::redecls_end; |
| 117 | |
| 118 | ASTContext &getASTContext() const { return Ctx; } |
| 119 | |
| 120 | NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; } |
| 121 | void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; } |
| 122 | |
| 123 | static TranslationUnitDecl *Create(ASTContext &C); |
| 124 | |
| 125 | // Implement isa/cast/dyncast/etc. |
| 126 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 127 | static bool classofKind(Kind K) { return K == TranslationUnit; } |
| 128 | static DeclContext *castToDeclContext(const TranslationUnitDecl *D) { |
| 129 | return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D)); |
| 130 | } |
| 131 | static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) { |
| 132 | return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC)); |
| 133 | } |
| 134 | }; |
| 135 | |
| 136 | /// Represents a `#pragma comment` line. Always a child of |
| 137 | /// TranslationUnitDecl. |
| 138 | class PragmaCommentDecl final |
| 139 | : public Decl, |
| 140 | private llvm::TrailingObjects<PragmaCommentDecl, char> { |
| 141 | friend class ASTDeclReader; |
| 142 | friend class ASTDeclWriter; |
| 143 | friend TrailingObjects; |
| 144 | |
| 145 | PragmaMSCommentKind CommentKind; |
| 146 | |
| 147 | PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc, |
| 148 | PragmaMSCommentKind CommentKind) |
| 149 | : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {} |
| 150 | |
| 151 | virtual void anchor(); |
| 152 | |
| 153 | public: |
| 154 | static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC, |
| 155 | SourceLocation CommentLoc, |
| 156 | PragmaMSCommentKind CommentKind, |
| 157 | StringRef Arg); |
| 158 | static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
| 159 | unsigned ArgSize); |
| 160 | |
| 161 | PragmaMSCommentKind getCommentKind() const { return CommentKind; } |
| 162 | |
| 163 | StringRef getArg() const { return getTrailingObjects<char>(); } |
| 164 | |
| 165 | // Implement isa/cast/dyncast/etc. |
| 166 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 167 | static bool classofKind(Kind K) { return K == PragmaComment; } |
| 168 | }; |
| 169 | |
| 170 | /// Represents a `#pragma detect_mismatch` line. Always a child of |
| 171 | /// TranslationUnitDecl. |
| 172 | class PragmaDetectMismatchDecl final |
| 173 | : public Decl, |
| 174 | private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> { |
| 175 | friend class ASTDeclReader; |
| 176 | friend class ASTDeclWriter; |
| 177 | friend TrailingObjects; |
| 178 | |
| 179 | size_t ValueStart; |
| 180 | |
| 181 | PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc, |
| 182 | size_t ValueStart) |
| 183 | : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {} |
| 184 | |
| 185 | virtual void anchor(); |
| 186 | |
| 187 | public: |
| 188 | static PragmaDetectMismatchDecl *Create(const ASTContext &C, |
| 189 | TranslationUnitDecl *DC, |
| 190 | SourceLocation Loc, StringRef Name, |
| 191 | StringRef Value); |
| 192 | static PragmaDetectMismatchDecl * |
| 193 | CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize); |
| 194 | |
| 195 | StringRef getName() const { return getTrailingObjects<char>(); } |
| 196 | StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; } |
| 197 | |
| 198 | // Implement isa/cast/dyncast/etc. |
| 199 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 200 | static bool classofKind(Kind K) { return K == PragmaDetectMismatch; } |
| 201 | }; |
| 202 | |
| 203 | /// Declaration context for names declared as extern "C" in C++. This |
| 204 | /// is neither the semantic nor lexical context for such declarations, but is |
| 205 | /// used to check for conflicts with other extern "C" declarations. Example: |
| 206 | /// |
| 207 | /// \code |
| 208 | /// namespace N { extern "C" void f(); } // #1 |
| 209 | /// void N::f() {} // #2 |
| 210 | /// namespace M { extern "C" void f(); } // #3 |
| 211 | /// \endcode |
| 212 | /// |
| 213 | /// The semantic context of #1 is namespace N and its lexical context is the |
| 214 | /// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical |
| 215 | /// context is the TU. However, both declarations are also visible in the |
| 216 | /// extern "C" context. |
| 217 | /// |
| 218 | /// The declaration at #3 finds it is a redeclaration of \c N::f through |
| 219 | /// lookup in the extern "C" context. |
| 220 | class ExternCContextDecl : public Decl, public DeclContext { |
| 221 | explicit ExternCContextDecl(TranslationUnitDecl *TU) |
| 222 | : Decl(ExternCContext, TU, SourceLocation()), |
| 223 | DeclContext(ExternCContext) {} |
| 224 | |
| 225 | virtual void anchor(); |
| 226 | |
| 227 | public: |
| 228 | static ExternCContextDecl *Create(const ASTContext &C, |
| 229 | TranslationUnitDecl *TU); |
| 230 | |
| 231 | // Implement isa/cast/dyncast/etc. |
| 232 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 233 | static bool classofKind(Kind K) { return K == ExternCContext; } |
| 234 | static DeclContext *castToDeclContext(const ExternCContextDecl *D) { |
| 235 | return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D)); |
| 236 | } |
| 237 | static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) { |
| 238 | return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC)); |
| 239 | } |
| 240 | }; |
| 241 | |
| 242 | /// This represents a decl that may have a name. Many decls have names such |
| 243 | /// as ObjCMethodDecl, but not \@class, etc. |
| 244 | /// |
| 245 | /// Note that not every NamedDecl is actually named (e.g., a struct might |
| 246 | /// be anonymous), and not every name is an identifier. |
| 247 | class NamedDecl : public Decl { |
| 248 | /// The name of this declaration, which is typically a normal |
| 249 | /// identifier but may also be a special kind of name (C++ |
| 250 | /// constructor, Objective-C selector, etc.) |
| 251 | DeclarationName Name; |
| 252 | |
| 253 | virtual void anchor(); |
| 254 | |
| 255 | private: |
| 256 | NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__)); |
| 257 | |
| 258 | protected: |
| 259 | NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N) |
| 260 | : Decl(DK, DC, L), Name(N) {} |
| 261 | |
| 262 | public: |
| 263 | /// Get the identifier that names this declaration, if there is one. |
| 264 | /// |
| 265 | /// This will return NULL if this declaration has no name (e.g., for |
| 266 | /// an unnamed class) or if the name is a special name (C++ constructor, |
| 267 | /// Objective-C selector, etc.). |
| 268 | IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); } |
| 269 | |
| 270 | /// Get the name of identifier for this declaration as a StringRef. |
| 271 | /// |
| 272 | /// This requires that the declaration have a name and that it be a simple |
| 273 | /// identifier. |
| 274 | StringRef getName() const { |
| 275 | assert(Name.isIdentifier() && "Name is not a simple identifier")(static_cast <bool> (Name.isIdentifier() && "Name is not a simple identifier" ) ? void (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\"" , "clang/include/clang/AST/Decl.h", 275, __extension__ __PRETTY_FUNCTION__ )); |
| 276 | return getIdentifier() ? getIdentifier()->getName() : ""; |
| 277 | } |
| 278 | |
| 279 | /// Get a human-readable name for the declaration, even if it is one of the |
| 280 | /// special kinds of names (C++ constructor, Objective-C selector, etc). |
| 281 | /// |
| 282 | /// Creating this name requires expensive string manipulation, so it should |
| 283 | /// be called only when performance doesn't matter. For simple declarations, |
| 284 | /// getNameAsCString() should suffice. |
| 285 | // |
| 286 | // FIXME: This function should be renamed to indicate that it is not just an |
| 287 | // alternate form of getName(), and clients should move as appropriate. |
| 288 | // |
| 289 | // FIXME: Deprecated, move clients to getName(). |
| 290 | std::string getNameAsString() const { return Name.getAsString(); } |
| 291 | |
| 292 | /// Pretty-print the unqualified name of this declaration. Can be overloaded |
| 293 | /// by derived classes to provide a more user-friendly name when appropriate. |
| 294 | virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const; |
| 295 | /// Calls printName() with the ASTContext printing policy from the decl. |
| 296 | void printName(raw_ostream &OS) const; |
| 297 | |
| 298 | /// Get the actual, stored name of the declaration, which may be a special |
| 299 | /// name. |
| 300 | /// |
| 301 | /// Note that generally in diagnostics, the non-null \p NamedDecl* itself |
| 302 | /// should be sent into the diagnostic instead of using the result of |
| 303 | /// \p getDeclName(). |
| 304 | /// |
| 305 | /// A \p DeclarationName in a diagnostic will just be streamed to the output, |
| 306 | /// which will directly result in a call to \p DeclarationName::print. |
| 307 | /// |
| 308 | /// A \p NamedDecl* in a diagnostic will also ultimately result in a call to |
| 309 | /// \p DeclarationName::print, but with two customisation points along the |
| 310 | /// way (\p getNameForDiagnostic and \p printName). These are used to print |
| 311 | /// the template arguments if any, and to provide a user-friendly name for |
| 312 | /// some entities (such as unnamed variables and anonymous records). |
| 313 | DeclarationName getDeclName() const { return Name; } |
| 314 | |
| 315 | /// Set the name of this declaration. |
| 316 | void setDeclName(DeclarationName N) { Name = N; } |
| 317 | |
| 318 | /// Returns a human-readable qualified name for this declaration, like |
| 319 | /// A::B::i, for i being member of namespace A::B. |
| 320 | /// |
| 321 | /// If the declaration is not a member of context which can be named (record, |
| 322 | /// namespace), it will return the same result as printName(). |
| 323 | /// |
| 324 | /// Creating this name is expensive, so it should be called only when |
| 325 | /// performance doesn't matter. |
| 326 | void printQualifiedName(raw_ostream &OS) const; |
| 327 | void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const; |
| 328 | |
| 329 | /// Print only the nested name specifier part of a fully-qualified name, |
| 330 | /// including the '::' at the end. E.g. |
| 331 | /// when `printQualifiedName(D)` prints "A::B::i", |
| 332 | /// this function prints "A::B::". |
| 333 | void printNestedNameSpecifier(raw_ostream &OS) const; |
| 334 | void printNestedNameSpecifier(raw_ostream &OS, |
| 335 | const PrintingPolicy &Policy) const; |
| 336 | |
| 337 | // FIXME: Remove string version. |
| 338 | std::string getQualifiedNameAsString() const; |
| 339 | |
| 340 | /// Appends a human-readable name for this declaration into the given stream. |
| 341 | /// |
| 342 | /// This is the method invoked by Sema when displaying a NamedDecl |
| 343 | /// in a diagnostic. It does not necessarily produce the same |
| 344 | /// result as printName(); for example, class template |
| 345 | /// specializations are printed with their template arguments. |
| 346 | virtual void getNameForDiagnostic(raw_ostream &OS, |
| 347 | const PrintingPolicy &Policy, |
| 348 | bool Qualified) const; |
| 349 | |
| 350 | /// Determine whether this declaration, if known to be well-formed within |
| 351 | /// its context, will replace the declaration OldD if introduced into scope. |
| 352 | /// |
| 353 | /// A declaration will replace another declaration if, for example, it is |
| 354 | /// a redeclaration of the same variable or function, but not if it is a |
| 355 | /// declaration of a different kind (function vs. class) or an overloaded |
| 356 | /// function. |
| 357 | /// |
| 358 | /// \param IsKnownNewer \c true if this declaration is known to be newer |
| 359 | /// than \p OldD (for instance, if this declaration is newly-created). |
| 360 | bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const; |
| 361 | |
| 362 | /// Determine whether this declaration has linkage. |
| 363 | bool hasLinkage() const; |
| 364 | |
| 365 | using Decl::isModulePrivate; |
| 366 | using Decl::setModulePrivate; |
| 367 | |
| 368 | /// Determine whether this declaration is a C++ class member. |
| 369 | bool isCXXClassMember() const { |
| 370 | const DeclContext *DC = getDeclContext(); |
| 371 | |
| 372 | // C++0x [class.mem]p1: |
| 373 | // The enumerators of an unscoped enumeration defined in |
| 374 | // the class are members of the class. |
| 375 | if (isa<EnumDecl>(DC)) |
| 376 | DC = DC->getRedeclContext(); |
| 377 | |
| 378 | return DC->isRecord(); |
| 379 | } |
| 380 | |
| 381 | /// Determine whether the given declaration is an instance member of |
| 382 | /// a C++ class. |
| 383 | bool isCXXInstanceMember() const; |
| 384 | |
| 385 | /// Determine if the declaration obeys the reserved identifier rules of the |
| 386 | /// given language. |
| 387 | ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const; |
| 388 | |
| 389 | /// Determine what kind of linkage this entity has. |
| 390 | /// |
| 391 | /// This is not the linkage as defined by the standard or the codegen notion |
| 392 | /// of linkage. It is just an implementation detail that is used to compute |
| 393 | /// those. |
| 394 | Linkage getLinkageInternal() const; |
| 395 | |
| 396 | /// Get the linkage from a semantic point of view. Entities in |
| 397 | /// anonymous namespaces are external (in c++98). |
| 398 | Linkage getFormalLinkage() const; |
| 399 | |
| 400 | /// True if this decl has external linkage. |
| 401 | bool hasExternalFormalLinkage() const { |
| 402 | return isExternalFormalLinkage(getLinkageInternal()); |
| 403 | } |
| 404 | |
| 405 | bool isExternallyVisible() const { |
| 406 | return clang::isExternallyVisible(getLinkageInternal()); |
| 407 | } |
| 408 | |
| 409 | /// Determine whether this declaration can be redeclared in a |
| 410 | /// different translation unit. |
| 411 | bool isExternallyDeclarable() const { |
| 412 | return isExternallyVisible() && !getOwningModuleForLinkage(); |
| 413 | } |
| 414 | |
| 415 | /// Determines the visibility of this entity. |
| 416 | Visibility getVisibility() const { |
| 417 | return getLinkageAndVisibility().getVisibility(); |
| 418 | } |
| 419 | |
| 420 | /// Determines the linkage and visibility of this entity. |
| 421 | LinkageInfo getLinkageAndVisibility() const; |
| 422 | |
| 423 | /// Kinds of explicit visibility. |
| 424 | enum ExplicitVisibilityKind { |
| 425 | /// Do an LV computation for, ultimately, a type. |
| 426 | /// Visibility may be restricted by type visibility settings and |
| 427 | /// the visibility of template arguments. |
| 428 | VisibilityForType, |
| 429 | |
| 430 | /// Do an LV computation for, ultimately, a non-type declaration. |
| 431 | /// Visibility may be restricted by value visibility settings and |
| 432 | /// the visibility of template arguments. |
| 433 | VisibilityForValue |
| 434 | }; |
| 435 | |
| 436 | /// If visibility was explicitly specified for this |
| 437 | /// declaration, return that visibility. |
| 438 | std::optional<Visibility> |
| 439 | getExplicitVisibility(ExplicitVisibilityKind kind) const; |
| 440 | |
| 441 | /// True if the computed linkage is valid. Used for consistency |
| 442 | /// checking. Should always return true. |
| 443 | bool isLinkageValid() const; |
| 444 | |
| 445 | /// True if something has required us to compute the linkage |
| 446 | /// of this declaration. |
| 447 | /// |
| 448 | /// Language features which can retroactively change linkage (like a |
| 449 | /// typedef name for linkage purposes) may need to consider this, |
| 450 | /// but hopefully only in transitory ways during parsing. |
| 451 | bool hasLinkageBeenComputed() const { |
| 452 | return hasCachedLinkage(); |
| 453 | } |
| 454 | |
| 455 | /// Looks through UsingDecls and ObjCCompatibleAliasDecls for |
| 456 | /// the underlying named decl. |
| 457 | NamedDecl *getUnderlyingDecl() { |
| 458 | // Fast-path the common case. |
| 459 | if (this->getKind() != UsingShadow && |
| 460 | this->getKind() != ConstructorUsingShadow && |
| 461 | this->getKind() != ObjCCompatibleAlias && |
| 462 | this->getKind() != NamespaceAlias) |
| 463 | return this; |
| 464 | |
| 465 | return getUnderlyingDeclImpl(); |
| 466 | } |
| 467 | const NamedDecl *getUnderlyingDecl() const { |
| 468 | return const_cast<NamedDecl*>(this)->getUnderlyingDecl(); |
| 469 | } |
| 470 | |
| 471 | NamedDecl *getMostRecentDecl() { |
| 472 | return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl()); |
| 473 | } |
| 474 | const NamedDecl *getMostRecentDecl() const { |
| 475 | return const_cast<NamedDecl*>(this)->getMostRecentDecl(); |
| 476 | } |
| 477 | |
| 478 | ObjCStringFormatFamily getObjCFStringFormattingFamily() const; |
| 479 | |
| 480 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 481 | static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; } |
| 482 | }; |
| 483 | |
| 484 | inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) { |
| 485 | ND.printName(OS); |
| 486 | return OS; |
| 487 | } |
| 488 | |
| 489 | /// Represents the declaration of a label. Labels also have a |
| 490 | /// corresponding LabelStmt, which indicates the position that the label was |
| 491 | /// defined at. For normal labels, the location of the decl is the same as the |
| 492 | /// location of the statement. For GNU local labels (__label__), the decl |
| 493 | /// location is where the __label__ is. |
| 494 | class LabelDecl : public NamedDecl { |
| 495 | LabelStmt *TheStmt; |
| 496 | StringRef MSAsmName; |
| 497 | bool MSAsmNameResolved = false; |
| 498 | |
| 499 | /// For normal labels, this is the same as the main declaration |
| 500 | /// label, i.e., the location of the identifier; for GNU local labels, |
| 501 | /// this is the location of the __label__ keyword. |
| 502 | SourceLocation LocStart; |
| 503 | |
| 504 | LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II, |
| 505 | LabelStmt *S, SourceLocation StartL) |
| 506 | : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {} |
| 507 | |
| 508 | void anchor() override; |
| 509 | |
| 510 | public: |
| 511 | static LabelDecl *Create(ASTContext &C, DeclContext *DC, |
| 512 | SourceLocation IdentL, IdentifierInfo *II); |
| 513 | static LabelDecl *Create(ASTContext &C, DeclContext *DC, |
| 514 | SourceLocation IdentL, IdentifierInfo *II, |
| 515 | SourceLocation GnuLabelL); |
| 516 | static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 517 | |
| 518 | LabelStmt *getStmt() const { return TheStmt; } |
| 519 | void setStmt(LabelStmt *T) { TheStmt = T; } |
| 520 | |
| 521 | bool isGnuLocal() const { return LocStart != getLocation(); } |
| 522 | void setLocStart(SourceLocation L) { LocStart = L; } |
| 523 | |
| 524 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
| 525 | return SourceRange(LocStart, getLocation()); |
| 526 | } |
| 527 | |
| 528 | bool isMSAsmLabel() const { return !MSAsmName.empty(); } |
| 529 | bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; } |
| 530 | void setMSAsmLabel(StringRef Name); |
| 531 | StringRef getMSAsmLabel() const { return MSAsmName; } |
| 532 | void setMSAsmLabelResolved() { MSAsmNameResolved = true; } |
| 533 | |
| 534 | // Implement isa/cast/dyncast/etc. |
| 535 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 536 | static bool classofKind(Kind K) { return K == Label; } |
| 537 | }; |
| 538 | |
| 539 | /// Represent a C++ namespace. |
| 540 | class NamespaceDecl : public NamedDecl, public DeclContext, |
| 541 | public Redeclarable<NamespaceDecl> |
| 542 | { |
| 543 | |
| 544 | enum Flags : unsigned { F_Inline = 1 << 0, F_Nested = 1 << 1 }; |
| 545 | |
| 546 | /// The starting location of the source range, pointing |
| 547 | /// to either the namespace or the inline keyword. |
| 548 | SourceLocation LocStart; |
| 549 | |
| 550 | /// The ending location of the source range. |
| 551 | SourceLocation RBraceLoc; |
| 552 | |
| 553 | /// A pointer to either the anonymous namespace that lives just inside |
| 554 | /// this namespace or to the first namespace in the chain (the latter case |
| 555 | /// only when this is not the first in the chain), along with a |
| 556 | /// boolean value indicating whether this is an inline namespace. |
| 557 | llvm::PointerIntPair<NamespaceDecl *, 2, unsigned> |
| 558 | AnonOrFirstNamespaceAndFlags; |
| 559 | |
| 560 | NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline, |
| 561 | SourceLocation StartLoc, SourceLocation IdLoc, |
| 562 | IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested); |
| 563 | |
| 564 | using redeclarable_base = Redeclarable<NamespaceDecl>; |
| 565 | |
| 566 | NamespaceDecl *getNextRedeclarationImpl() override; |
| 567 | NamespaceDecl *getPreviousDeclImpl() override; |
| 568 | NamespaceDecl *getMostRecentDeclImpl() override; |
| 569 | |
| 570 | public: |
| 571 | friend class ASTDeclReader; |
| 572 | friend class ASTDeclWriter; |
| 573 | |
| 574 | static NamespaceDecl *Create(ASTContext &C, DeclContext *DC, bool Inline, |
| 575 | SourceLocation StartLoc, SourceLocation IdLoc, |
| 576 | IdentifierInfo *Id, NamespaceDecl *PrevDecl, |
| 577 | bool Nested); |
| 578 | |
| 579 | static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 580 | |
| 581 | using redecl_range = redeclarable_base::redecl_range; |
| 582 | using redecl_iterator = redeclarable_base::redecl_iterator; |
| 583 | |
| 584 | using redeclarable_base::redecls_begin; |
| 585 | using redeclarable_base::redecls_end; |
| 586 | using redeclarable_base::redecls; |
| 587 | using redeclarable_base::getPreviousDecl; |
| 588 | using redeclarable_base::getMostRecentDecl; |
| 589 | using redeclarable_base::isFirstDecl; |
| 590 | |
| 591 | /// Returns true if this is an anonymous namespace declaration. |
| 592 | /// |
| 593 | /// For example: |
| 594 | /// \code |
| 595 | /// namespace { |
| 596 | /// ... |
| 597 | /// }; |
| 598 | /// \endcode |
| 599 | /// q.v. C++ [namespace.unnamed] |
| 600 | bool isAnonymousNamespace() const { |
| 601 | return !getIdentifier(); |
| 602 | } |
| 603 | |
| 604 | /// Returns true if this is an inline namespace declaration. |
| 605 | bool isInline() const { |
| 606 | return AnonOrFirstNamespaceAndFlags.getInt() & F_Inline; |
| 607 | } |
| 608 | |
| 609 | /// Set whether this is an inline namespace declaration. |
| 610 | void setInline(bool Inline) { |
| 611 | unsigned F = AnonOrFirstNamespaceAndFlags.getInt(); |
| 612 | if (Inline) |
| 613 | AnonOrFirstNamespaceAndFlags.setInt(F | F_Inline); |
| 614 | else |
| 615 | AnonOrFirstNamespaceAndFlags.setInt(F & ~F_Inline); |
| 616 | } |
| 617 | |
| 618 | /// Returns true if this is a nested namespace declaration. |
| 619 | /// \code |
| 620 | /// namespace outer::nested { } |
| 621 | /// \endcode |
| 622 | bool isNested() const { |
| 623 | return AnonOrFirstNamespaceAndFlags.getInt() & F_Nested; |
| 624 | } |
| 625 | |
| 626 | /// Set whether this is a nested namespace declaration. |
| 627 | void setNested(bool Nested) { |
| 628 | unsigned F = AnonOrFirstNamespaceAndFlags.getInt(); |
| 629 | if (Nested) |
| 630 | AnonOrFirstNamespaceAndFlags.setInt(F | F_Nested); |
| 631 | else |
| 632 | AnonOrFirstNamespaceAndFlags.setInt(F & ~F_Nested); |
| 633 | } |
| 634 | |
| 635 | /// Returns true if the inline qualifier for \c Name is redundant. |
| 636 | bool isRedundantInlineQualifierFor(DeclarationName Name) const { |
| 637 | if (!isInline()) |
| 638 | return false; |
| 639 | auto X = lookup(Name); |
| 640 | // We should not perform a lookup within a transparent context, so find a |
| 641 | // non-transparent parent context. |
| 642 | auto Y = getParent()->getNonTransparentContext()->lookup(Name); |
| 643 | return std::distance(X.begin(), X.end()) == |
| 644 | std::distance(Y.begin(), Y.end()); |
| 645 | } |
| 646 | |
| 647 | /// Get the original (first) namespace declaration. |
| 648 | NamespaceDecl *getOriginalNamespace(); |
| 649 | |
| 650 | /// Get the original (first) namespace declaration. |
| 651 | const NamespaceDecl *getOriginalNamespace() const; |
| 652 | |
| 653 | /// Return true if this declaration is an original (first) declaration |
| 654 | /// of the namespace. This is false for non-original (subsequent) namespace |
| 655 | /// declarations and anonymous namespaces. |
| 656 | bool isOriginalNamespace() const; |
| 657 | |
| 658 | /// Retrieve the anonymous namespace nested inside this namespace, |
| 659 | /// if any. |
| 660 | NamespaceDecl *getAnonymousNamespace() const { |
| 661 | return getOriginalNamespace()->AnonOrFirstNamespaceAndFlags.getPointer(); |
| 662 | } |
| 663 | |
| 664 | void setAnonymousNamespace(NamespaceDecl *D) { |
| 665 | getOriginalNamespace()->AnonOrFirstNamespaceAndFlags.setPointer(D); |
| 666 | } |
| 667 | |
| 668 | /// Retrieves the canonical declaration of this namespace. |
| 669 | NamespaceDecl *getCanonicalDecl() override { |
| 670 | return getOriginalNamespace(); |
| 671 | } |
| 672 | const NamespaceDecl *getCanonicalDecl() const { |
| 673 | return getOriginalNamespace(); |
| 674 | } |
| 675 | |
| 676 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
| 677 | return SourceRange(LocStart, RBraceLoc); |
| 678 | } |
| 679 | |
| 680 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; } |
| 681 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
| 682 | void setLocStart(SourceLocation L) { LocStart = L; } |
| 683 | void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } |
| 684 | |
| 685 | // Implement isa/cast/dyncast/etc. |
| 686 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 687 | static bool classofKind(Kind K) { return K == Namespace; } |
| 688 | static DeclContext *castToDeclContext(const NamespaceDecl *D) { |
| 689 | return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D)); |
| 690 | } |
| 691 | static NamespaceDecl *castFromDeclContext(const DeclContext *DC) { |
| 692 | return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC)); |
| 693 | } |
| 694 | }; |
| 695 | |
| 696 | class VarDecl; |
| 697 | |
| 698 | /// Represent the declaration of a variable (in which case it is |
| 699 | /// an lvalue) a function (in which case it is a function designator) or |
| 700 | /// an enum constant. |
| 701 | class ValueDecl : public NamedDecl { |
| 702 | QualType DeclType; |
| 703 | |
| 704 | void anchor() override; |
| 705 | |
| 706 | protected: |
| 707 | ValueDecl(Kind DK, DeclContext *DC, SourceLocation L, |
| 708 | DeclarationName N, QualType T) |
| 709 | : NamedDecl(DK, DC, L, N), DeclType(T) {} |
| 710 | |
| 711 | public: |
| 712 | QualType getType() const { return DeclType; } |
| 713 | void setType(QualType newType) { DeclType = newType; } |
| 714 | |
| 715 | /// Determine whether this symbol is weakly-imported, |
| 716 | /// or declared with the weak or weak-ref attr. |
| 717 | bool isWeak() const; |
| 718 | |
| 719 | /// Whether this variable is the implicit variable for a lambda init-capture. |
| 720 | /// Only VarDecl can be init captures, but both VarDecl and BindingDecl |
| 721 | /// can be captured. |
| 722 | bool isInitCapture() const; |
| 723 | |
| 724 | // If this is a VarDecl, or a BindindDecl with an |
| 725 | // associated decomposed VarDecl, return that VarDecl. |
| 726 | VarDecl *getPotentiallyDecomposedVarDecl(); |
| 727 | const VarDecl *getPotentiallyDecomposedVarDecl() const { |
| 728 | return const_cast<ValueDecl *>(this)->getPotentiallyDecomposedVarDecl(); |
| 729 | } |
| 730 | |
| 731 | // Implement isa/cast/dyncast/etc. |
| 732 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 733 | static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; } |
| 734 | }; |
| 735 | |
| 736 | /// A struct with extended info about a syntactic |
| 737 | /// name qualifier, to be used for the case of out-of-line declarations. |
| 738 | struct QualifierInfo { |
| 739 | NestedNameSpecifierLoc QualifierLoc; |
| 740 | |
| 741 | /// The number of "outer" template parameter lists. |
| 742 | /// The count includes all of the template parameter lists that were matched |
| 743 | /// against the template-ids occurring into the NNS and possibly (in the |
| 744 | /// case of an explicit specialization) a final "template <>". |
| 745 | unsigned NumTemplParamLists = 0; |
| 746 | |
| 747 | /// A new-allocated array of size NumTemplParamLists, |
| 748 | /// containing pointers to the "outer" template parameter lists. |
| 749 | /// It includes all of the template parameter lists that were matched |
| 750 | /// against the template-ids occurring into the NNS and possibly (in the |
| 751 | /// case of an explicit specialization) a final "template <>". |
| 752 | TemplateParameterList** TemplParamLists = nullptr; |
| 753 | |
| 754 | QualifierInfo() = default; |
| 755 | QualifierInfo(const QualifierInfo &) = delete; |
| 756 | QualifierInfo& operator=(const QualifierInfo &) = delete; |
| 757 | |
| 758 | /// Sets info about "outer" template parameter lists. |
| 759 | void setTemplateParameterListsInfo(ASTContext &Context, |
| 760 | ArrayRef<TemplateParameterList *> TPLists); |
| 761 | }; |
| 762 | |
| 763 | /// Represents a ValueDecl that came out of a declarator. |
| 764 | /// Contains type source information through TypeSourceInfo. |
| 765 | class DeclaratorDecl : public ValueDecl { |
| 766 | // A struct representing a TInfo, a trailing requires-clause and a syntactic |
| 767 | // qualifier, to be used for the (uncommon) case of out-of-line declarations |
| 768 | // and constrained function decls. |
| 769 | struct ExtInfo : public QualifierInfo { |
| 770 | TypeSourceInfo *TInfo; |
| 771 | Expr *TrailingRequiresClause = nullptr; |
| 772 | }; |
| 773 | |
| 774 | llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo; |
| 775 | |
| 776 | /// The start of the source range for this declaration, |
| 777 | /// ignoring outer template declarations. |
| 778 | SourceLocation InnerLocStart; |
| 779 | |
| 780 | bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); } |
| 781 | ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); } |
| 782 | const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); } |
| 783 | |
| 784 | protected: |
| 785 | DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L, |
| 786 | DeclarationName N, QualType T, TypeSourceInfo *TInfo, |
| 787 | SourceLocation StartL) |
| 788 | : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {} |
| 789 | |
| 790 | public: |
| 791 | friend class ASTDeclReader; |
| 792 | friend class ASTDeclWriter; |
| 793 | |
| 794 | TypeSourceInfo *getTypeSourceInfo() const { |
| 795 | return hasExtInfo() |
| 796 | ? getExtInfo()->TInfo |
| 797 | : DeclInfo.get<TypeSourceInfo*>(); |
| 798 | } |
| 799 | |
| 800 | void setTypeSourceInfo(TypeSourceInfo *TI) { |
| 801 | if (hasExtInfo()) |
| 802 | getExtInfo()->TInfo = TI; |
| 803 | else |
| 804 | DeclInfo = TI; |
| 805 | } |
| 806 | |
| 807 | /// Return start of source range ignoring outer template declarations. |
| 808 | SourceLocation getInnerLocStart() const { return InnerLocStart; } |
| 809 | void setInnerLocStart(SourceLocation L) { InnerLocStart = L; } |
| 810 | |
| 811 | /// Return start of source range taking into account any outer template |
| 812 | /// declarations. |
| 813 | SourceLocation getOuterLocStart() const; |
| 814 | |
| 815 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
| 816 | |
| 817 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
| 818 | return getOuterLocStart(); |
| 819 | } |
| 820 | |
| 821 | /// Retrieve the nested-name-specifier that qualifies the name of this |
| 822 | /// declaration, if it was present in the source. |
| 823 | NestedNameSpecifier *getQualifier() const { |
| 824 | return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() |
| 825 | : nullptr; |
| 826 | } |
| 827 | |
| 828 | /// Retrieve the nested-name-specifier (with source-location |
| 829 | /// information) that qualifies the name of this declaration, if it was |
| 830 | /// present in the source. |
| 831 | NestedNameSpecifierLoc getQualifierLoc() const { |
| 832 | return hasExtInfo() ? getExtInfo()->QualifierLoc |
| 833 | : NestedNameSpecifierLoc(); |
| 834 | } |
| 835 | |
| 836 | void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); |
| 837 | |
| 838 | /// \brief Get the constraint-expression introduced by the trailing |
| 839 | /// requires-clause in the function/member declaration, or null if no |
| 840 | /// requires-clause was provided. |
| 841 | Expr *getTrailingRequiresClause() { |
| 842 | return hasExtInfo() ? getExtInfo()->TrailingRequiresClause |
| 843 | : nullptr; |
| 844 | } |
| 845 | |
| 846 | const Expr *getTrailingRequiresClause() const { |
| 847 | return hasExtInfo() ? getExtInfo()->TrailingRequiresClause |
| 848 | : nullptr; |
| 849 | } |
| 850 | |
| 851 | void setTrailingRequiresClause(Expr *TrailingRequiresClause); |
| 852 | |
| 853 | unsigned getNumTemplateParameterLists() const { |
| 854 | return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; |
| 855 | } |
| 856 | |
| 857 | TemplateParameterList *getTemplateParameterList(unsigned index) const { |
| 858 | assert(index < getNumTemplateParameterLists())(static_cast <bool> (index < getNumTemplateParameterLists ()) ? void (0) : __assert_fail ("index < getNumTemplateParameterLists()" , "clang/include/clang/AST/Decl.h", 858, __extension__ __PRETTY_FUNCTION__ )); |
| 859 | return getExtInfo()->TemplParamLists[index]; |
| 860 | } |
| 861 | |
| 862 | void setTemplateParameterListsInfo(ASTContext &Context, |
| 863 | ArrayRef<TemplateParameterList *> TPLists); |
| 864 | |
| 865 | SourceLocation getTypeSpecStartLoc() const; |
| 866 | SourceLocation getTypeSpecEndLoc() const; |
| 867 | |
| 868 | // Implement isa/cast/dyncast/etc. |
| 869 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 870 | static bool classofKind(Kind K) { |
| 871 | return K >= firstDeclarator && K <= lastDeclarator; |
| 872 | } |
| 873 | }; |
| 874 | |
| 875 | /// Structure used to store a statement, the constant value to |
| 876 | /// which it was evaluated (if any), and whether or not the statement |
| 877 | /// is an integral constant expression (if known). |
| 878 | struct EvaluatedStmt { |
| 879 | /// Whether this statement was already evaluated. |
| 880 | bool WasEvaluated : 1; |
| 881 | |
| 882 | /// Whether this statement is being evaluated. |
| 883 | bool IsEvaluating : 1; |
| 884 | |
| 885 | /// Whether this variable is known to have constant initialization. This is |
| 886 | /// currently only computed in C++, for static / thread storage duration |
| 887 | /// variables that might have constant initialization and for variables that |
| 888 | /// are usable in constant expressions. |
| 889 | bool HasConstantInitialization : 1; |
| 890 | |
| 891 | /// Whether this variable is known to have constant destruction. That is, |
| 892 | /// whether running the destructor on the initial value is a side-effect |
| 893 | /// (and doesn't inspect any state that might have changed during program |
| 894 | /// execution). This is currently only computed if the destructor is |
| 895 | /// non-trivial. |
| 896 | bool HasConstantDestruction : 1; |
| 897 | |
| 898 | /// In C++98, whether the initializer is an ICE. This affects whether the |
| 899 | /// variable is usable in constant expressions. |
| 900 | bool HasICEInit : 1; |
| 901 | bool CheckedForICEInit : 1; |
| 902 | |
| 903 | LazyDeclStmtPtr Value; |
| 904 | APValue Evaluated; |
| 905 | |
| 906 | EvaluatedStmt() |
| 907 | : WasEvaluated(false), IsEvaluating(false), |
| 908 | HasConstantInitialization(false), HasConstantDestruction(false), |
| 909 | HasICEInit(false), CheckedForICEInit(false) {} |
| 910 | }; |
| 911 | |
| 912 | /// Represents a variable declaration or definition. |
| 913 | class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> { |
| 914 | public: |
| 915 | /// Initialization styles. |
| 916 | enum InitializationStyle { |
| 917 | /// C-style initialization with assignment |
| 918 | CInit, |
| 919 | |
| 920 | /// Call-style initialization (C++98) |
| 921 | CallInit, |
| 922 | |
| 923 | /// Direct list-initialization (C++11) |
| 924 | ListInit, |
| 925 | |
| 926 | /// Parenthesized list-initialization (C++20) |
| 927 | ParenListInit |
| 928 | }; |
| 929 | |
| 930 | /// Kinds of thread-local storage. |
| 931 | enum TLSKind { |
| 932 | /// Not a TLS variable. |
| 933 | TLS_None, |
| 934 | |
| 935 | /// TLS with a known-constant initializer. |
| 936 | TLS_Static, |
| 937 | |
| 938 | /// TLS with a dynamic initializer. |
| 939 | TLS_Dynamic |
| 940 | }; |
| 941 | |
| 942 | /// Return the string used to specify the storage class \p SC. |
| 943 | /// |
| 944 | /// It is illegal to call this function with SC == None. |
| 945 | static const char *getStorageClassSpecifierString(StorageClass SC); |
| 946 | |
| 947 | protected: |
| 948 | // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we |
| 949 | // have allocated the auxiliary struct of information there. |
| 950 | // |
| 951 | // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for |
| 952 | // this as *many* VarDecls are ParmVarDecls that don't have default |
| 953 | // arguments. We could save some space by moving this pointer union to be |
| 954 | // allocated in trailing space when necessary. |
| 955 | using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>; |
| 956 | |
| 957 | /// The initializer for this variable or, for a ParmVarDecl, the |
| 958 | /// C++ default argument. |
| 959 | mutable InitType Init; |
| 960 | |
| 961 | private: |
| 962 | friend class ASTDeclReader; |
| 963 | friend class ASTNodeImporter; |
| 964 | friend class StmtIteratorBase; |
| 965 | |
| 966 | class VarDeclBitfields { |
| 967 | friend class ASTDeclReader; |
| 968 | friend class VarDecl; |
| 969 | |
| 970 | unsigned SClass : 3; |
| 971 | unsigned TSCSpec : 2; |
| 972 | unsigned InitStyle : 2; |
| 973 | |
| 974 | /// Whether this variable is an ARC pseudo-__strong variable; see |
| 975 | /// isARCPseudoStrong() for details. |
| 976 | unsigned ARCPseudoStrong : 1; |
| 977 | }; |
| 978 | enum { NumVarDeclBits = 8 }; |
| 979 | |
| 980 | protected: |
| 981 | enum { NumParameterIndexBits = 8 }; |
| 982 | |
| 983 | enum DefaultArgKind { |
| 984 | DAK_None, |
| 985 | DAK_Unparsed, |
| 986 | DAK_Uninstantiated, |
| 987 | DAK_Normal |
| 988 | }; |
| 989 | |
| 990 | enum { NumScopeDepthOrObjCQualsBits = 7 }; |
| 991 | |
| 992 | class ParmVarDeclBitfields { |
| 993 | friend class ASTDeclReader; |
| 994 | friend class ParmVarDecl; |
| 995 | |
| 996 | unsigned : NumVarDeclBits; |
| 997 | |
| 998 | /// Whether this parameter inherits a default argument from a |
| 999 | /// prior declaration. |
| 1000 | unsigned HasInheritedDefaultArg : 1; |
| 1001 | |
| 1002 | /// Describes the kind of default argument for this parameter. By default |
| 1003 | /// this is none. If this is normal, then the default argument is stored in |
| 1004 | /// the \c VarDecl initializer expression unless we were unable to parse |
| 1005 | /// (even an invalid) expression for the default argument. |
| 1006 | unsigned DefaultArgKind : 2; |
| 1007 | |
| 1008 | /// Whether this parameter undergoes K&R argument promotion. |
| 1009 | unsigned IsKNRPromoted : 1; |
| 1010 | |
| 1011 | /// Whether this parameter is an ObjC method parameter or not. |
| 1012 | unsigned IsObjCMethodParam : 1; |
| 1013 | |
| 1014 | /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier. |
| 1015 | /// Otherwise, the number of function parameter scopes enclosing |
| 1016 | /// the function parameter scope in which this parameter was |
| 1017 | /// declared. |
| 1018 | unsigned ScopeDepthOrObjCQuals : NumScopeDepthOrObjCQualsBits; |
| 1019 | |
| 1020 | /// The number of parameters preceding this parameter in the |
| 1021 | /// function parameter scope in which it was declared. |
| 1022 | unsigned ParameterIndex : NumParameterIndexBits; |
| 1023 | }; |
| 1024 | |
| 1025 | class NonParmVarDeclBitfields { |
| 1026 | friend class ASTDeclReader; |
| 1027 | friend class ImplicitParamDecl; |
| 1028 | friend class VarDecl; |
| 1029 | |
| 1030 | unsigned : NumVarDeclBits; |
| 1031 | |
| 1032 | // FIXME: We need something similar to CXXRecordDecl::DefinitionData. |
| 1033 | /// Whether this variable is a definition which was demoted due to |
| 1034 | /// module merge. |
| 1035 | unsigned IsThisDeclarationADemotedDefinition : 1; |
| 1036 | |
| 1037 | /// Whether this variable is the exception variable in a C++ catch |
| 1038 | /// or an Objective-C @catch statement. |
| 1039 | unsigned ExceptionVar : 1; |
| 1040 | |
| 1041 | /// Whether this local variable could be allocated in the return |
| 1042 | /// slot of its function, enabling the named return value optimization |
| 1043 | /// (NRVO). |
| 1044 | unsigned NRVOVariable : 1; |
| 1045 | |
| 1046 | /// Whether this variable is the for-range-declaration in a C++0x |
| 1047 | /// for-range statement. |
| 1048 | unsigned CXXForRangeDecl : 1; |
| 1049 | |
| 1050 | /// Whether this variable is the for-in loop declaration in Objective-C. |
| 1051 | unsigned ObjCForDecl : 1; |
| 1052 | |
| 1053 | /// Whether this variable is (C++1z) inline. |
| 1054 | unsigned IsInline : 1; |
| 1055 | |
| 1056 | /// Whether this variable has (C++1z) inline explicitly specified. |
| 1057 | unsigned IsInlineSpecified : 1; |
| 1058 | |
| 1059 | /// Whether this variable is (C++0x) constexpr. |
| 1060 | unsigned IsConstexpr : 1; |
| 1061 | |
| 1062 | /// Whether this variable is the implicit variable for a lambda |
| 1063 | /// init-capture. |
| 1064 | unsigned IsInitCapture : 1; |
| 1065 | |
| 1066 | /// Whether this local extern variable's previous declaration was |
| 1067 | /// declared in the same block scope. This controls whether we should merge |
| 1068 | /// the type of this declaration with its previous declaration. |
| 1069 | unsigned PreviousDeclInSameBlockScope : 1; |
| 1070 | |
| 1071 | /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or |
| 1072 | /// something else. |
| 1073 | unsigned ImplicitParamKind : 3; |
| 1074 | |
| 1075 | unsigned EscapingByref : 1; |
| 1076 | }; |
| 1077 | |
| 1078 | union { |
| 1079 | unsigned AllBits; |
| 1080 | VarDeclBitfields VarDeclBits; |
| 1081 | ParmVarDeclBitfields ParmVarDeclBits; |
| 1082 | NonParmVarDeclBitfields NonParmVarDeclBits; |
| 1083 | }; |
| 1084 | |
| 1085 | VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
| 1086 | SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, |
| 1087 | TypeSourceInfo *TInfo, StorageClass SC); |
| 1088 | |
| 1089 | using redeclarable_base = Redeclarable<VarDecl>; |
| 1090 | |
| 1091 | VarDecl *getNextRedeclarationImpl() override { |
| 1092 | return getNextRedeclaration(); |
| 1093 | } |
| 1094 | |
| 1095 | VarDecl *getPreviousDeclImpl() override { |
| 1096 | return getPreviousDecl(); |
| 1097 | } |
| 1098 | |
| 1099 | VarDecl *getMostRecentDeclImpl() override { |
| 1100 | return getMostRecentDecl(); |
| 1101 | } |
| 1102 | |
| 1103 | public: |
| 1104 | using redecl_range = redeclarable_base::redecl_range; |
| 1105 | using redecl_iterator = redeclarable_base::redecl_iterator; |
| 1106 | |
| 1107 | using redeclarable_base::redecls_begin; |
| 1108 | using redeclarable_base::redecls_end; |
| 1109 | using redeclarable_base::redecls; |
| 1110 | using redeclarable_base::getPreviousDecl; |
| 1111 | using redeclarable_base::getMostRecentDecl; |
| 1112 | using redeclarable_base::isFirstDecl; |
| 1113 | |
| 1114 | static VarDecl *Create(ASTContext &C, DeclContext *DC, |
| 1115 | SourceLocation StartLoc, SourceLocation IdLoc, |
| 1116 | const IdentifierInfo *Id, QualType T, |
| 1117 | TypeSourceInfo *TInfo, StorageClass S); |
| 1118 | |
| 1119 | static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 1120 | |
| 1121 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
| 1122 | |
| 1123 | /// Returns the storage class as written in the source. For the |
| 1124 | /// computed linkage of symbol, see getLinkage. |
| 1125 | StorageClass getStorageClass() const { |
| 1126 | return (StorageClass) VarDeclBits.SClass; |
| 1127 | } |
| 1128 | void setStorageClass(StorageClass SC); |
| 1129 | |
| 1130 | void setTSCSpec(ThreadStorageClassSpecifier TSC) { |
| 1131 | VarDeclBits.TSCSpec = TSC; |
| 1132 | assert(VarDeclBits.TSCSpec == TSC && "truncation")(static_cast <bool> (VarDeclBits.TSCSpec == TSC && "truncation") ? void (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\"" , "clang/include/clang/AST/Decl.h", 1132, __extension__ __PRETTY_FUNCTION__ )); |
| 1133 | } |
| 1134 | ThreadStorageClassSpecifier getTSCSpec() const { |
| 1135 | return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec); |
| 1136 | } |
| 1137 | TLSKind getTLSKind() const; |
| 1138 | |
| 1139 | /// Returns true if a variable with function scope is a non-static local |
| 1140 | /// variable. |
| 1141 | bool hasLocalStorage() const { |
| 1142 | if (getStorageClass() == SC_None) { |
| 1143 | // OpenCL v1.2 s6.5.3: The __constant or constant address space name is |
| 1144 | // used to describe variables allocated in global memory and which are |
| 1145 | // accessed inside a kernel(s) as read-only variables. As such, variables |
| 1146 | // in constant address space cannot have local storage. |
| 1147 | if (getType().getAddressSpace() == LangAS::opencl_constant) |
| 1148 | return false; |
| 1149 | // Second check is for C++11 [dcl.stc]p4. |
| 1150 | return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified; |
| 1151 | } |
| 1152 | |
| 1153 | // Global Named Register (GNU extension) |
| 1154 | if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm()) |
| 1155 | return false; |
| 1156 | |
| 1157 | // Return true for: Auto, Register. |
| 1158 | // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal. |
| 1159 | |
| 1160 | return getStorageClass() >= SC_Auto; |
| 1161 | } |
| 1162 | |
| 1163 | /// Returns true if a variable with function scope is a static local |
| 1164 | /// variable. |
| 1165 | bool isStaticLocal() const { |
| 1166 | return (getStorageClass() == SC_Static || |
| 1167 | // C++11 [dcl.stc]p4 |
| 1168 | (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local)) |
| 1169 | && !isFileVarDecl(); |
| 1170 | } |
| 1171 | |
| 1172 | /// Returns true if a variable has extern or __private_extern__ |
| 1173 | /// storage. |
| 1174 | bool hasExternalStorage() const { |
| 1175 | return getStorageClass() == SC_Extern || |
| 1176 | getStorageClass() == SC_PrivateExtern; |
| 1177 | } |
| 1178 | |
| 1179 | /// Returns true for all variables that do not have local storage. |
| 1180 | /// |
| 1181 | /// This includes all global variables as well as static variables declared |
| 1182 | /// within a function. |
| 1183 | bool hasGlobalStorage() const { return !hasLocalStorage(); } |
| 1184 | |
| 1185 | /// Get the storage duration of this variable, per C++ [basic.stc]. |
| 1186 | StorageDuration getStorageDuration() const { |
| 1187 | return hasLocalStorage() ? SD_Automatic : |
| 1188 | getTSCSpec() ? SD_Thread : SD_Static; |
| 1189 | } |
| 1190 | |
| 1191 | /// Compute the language linkage. |
| 1192 | LanguageLinkage getLanguageLinkage() const; |
| 1193 | |
| 1194 | /// Determines whether this variable is a variable with external, C linkage. |
| 1195 | bool isExternC() const; |
| 1196 | |
| 1197 | /// Determines whether this variable's context is, or is nested within, |
| 1198 | /// a C++ extern "C" linkage spec. |
| 1199 | bool isInExternCContext() const; |
| 1200 | |
| 1201 | /// Determines whether this variable's context is, or is nested within, |
| 1202 | /// a C++ extern "C++" linkage spec. |
| 1203 | bool isInExternCXXContext() const; |
| 1204 | |
| 1205 | /// Returns true for local variable declarations other than parameters. |
| 1206 | /// Note that this includes static variables inside of functions. It also |
| 1207 | /// includes variables inside blocks. |
| 1208 | /// |
| 1209 | /// void foo() { int x; static int y; extern int z; } |
| 1210 | bool isLocalVarDecl() const { |
| 1211 | if (getKind() != Decl::Var && getKind() != Decl::Decomposition) |
| 1212 | return false; |
| 1213 | if (const DeclContext *DC = getLexicalDeclContext()) |
| 1214 | return DC->getRedeclContext()->isFunctionOrMethod(); |
| 1215 | return false; |
| 1216 | } |
| 1217 | |
| 1218 | /// Similar to isLocalVarDecl but also includes parameters. |
| 1219 | bool isLocalVarDeclOrParm() const { |
| 1220 | return isLocalVarDecl() || getKind() == Decl::ParmVar; |
| 1221 | } |
| 1222 | |
| 1223 | /// Similar to isLocalVarDecl, but excludes variables declared in blocks. |
| 1224 | bool isFunctionOrMethodVarDecl() const { |
| 1225 | if (getKind() != Decl::Var && getKind() != Decl::Decomposition) |
| 1226 | return false; |
| 1227 | const DeclContext *DC = getLexicalDeclContext()->getRedeclContext(); |
| 1228 | return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block; |
| 1229 | } |
| 1230 | |
| 1231 | /// Determines whether this is a static data member. |
| 1232 | /// |
| 1233 | /// This will only be true in C++, and applies to, e.g., the |
| 1234 | /// variable 'x' in: |
| 1235 | /// \code |
| 1236 | /// struct S { |
| 1237 | /// static int x; |
| 1238 | /// }; |
| 1239 | /// \endcode |
| 1240 | bool isStaticDataMember() const { |
| 1241 | // If it wasn't static, it would be a FieldDecl. |
| 1242 | return getKind() != Decl::ParmVar && getDeclContext()->isRecord(); |
| 1243 | } |
| 1244 | |
| 1245 | VarDecl *getCanonicalDecl() override; |
| 1246 | const VarDecl *getCanonicalDecl() const { |
| 1247 | return const_cast<VarDecl*>(this)->getCanonicalDecl(); |
| 1248 | } |
| 1249 | |
| 1250 | enum DefinitionKind { |
| 1251 | /// This declaration is only a declaration. |
| 1252 | DeclarationOnly, |
| 1253 | |
| 1254 | /// This declaration is a tentative definition. |
| 1255 | TentativeDefinition, |
| 1256 | |
| 1257 | /// This declaration is definitely a definition. |
| 1258 | Definition |
| 1259 | }; |
| 1260 | |
| 1261 | /// Check whether this declaration is a definition. If this could be |
| 1262 | /// a tentative definition (in C), don't check whether there's an overriding |
| 1263 | /// definition. |
| 1264 | DefinitionKind isThisDeclarationADefinition(ASTContext &) const; |
| 1265 | DefinitionKind isThisDeclarationADefinition() const { |
| 1266 | return isThisDeclarationADefinition(getASTContext()); |
| 1267 | } |
| 1268 | |
| 1269 | /// Check whether this variable is defined in this translation unit. |
| 1270 | DefinitionKind hasDefinition(ASTContext &) const; |
| 1271 | DefinitionKind hasDefinition() const { |
| 1272 | return hasDefinition(getASTContext()); |
| 1273 | } |
| 1274 | |
| 1275 | /// Get the tentative definition that acts as the real definition in a TU. |
| 1276 | /// Returns null if there is a proper definition available. |
| 1277 | VarDecl *getActingDefinition(); |
| 1278 | const VarDecl *getActingDefinition() const { |
| 1279 | return const_cast<VarDecl*>(this)->getActingDefinition(); |
| 1280 | } |
| 1281 | |
| 1282 | /// Get the real (not just tentative) definition for this declaration. |
| 1283 | VarDecl *getDefinition(ASTContext &); |
| 1284 | const VarDecl *getDefinition(ASTContext &C) const { |
| 1285 | return const_cast<VarDecl*>(this)->getDefinition(C); |
| 1286 | } |
| 1287 | VarDecl *getDefinition() { |
| 1288 | return getDefinition(getASTContext()); |
| 1289 | } |
| 1290 | const VarDecl *getDefinition() const { |
| 1291 | return const_cast<VarDecl*>(this)->getDefinition(); |
| 1292 | } |
| 1293 | |
| 1294 | /// Determine whether this is or was instantiated from an out-of-line |
| 1295 | /// definition of a static data member. |
| 1296 | bool isOutOfLine() const override; |
| 1297 | |
| 1298 | /// Returns true for file scoped variable declaration. |
| 1299 | bool isFileVarDecl() const { |
| 1300 | Kind K = getKind(); |
| 1301 | if (K == ParmVar || K == ImplicitParam) |
| 1302 | return false; |
| 1303 | |
| 1304 | if (getLexicalDeclContext()->getRedeclContext()->isFileContext()) |
| 1305 | return true; |
| 1306 | |
| 1307 | if (isStaticDataMember()) |
| 1308 | return true; |
| 1309 | |
| 1310 | return false; |
| 1311 | } |
| 1312 | |
| 1313 | /// Get the initializer for this variable, no matter which |
| 1314 | /// declaration it is attached to. |
| 1315 | const Expr *getAnyInitializer() const { |
| 1316 | const VarDecl *D; |
| 1317 | return getAnyInitializer(D); |
| 1318 | } |
| 1319 | |
| 1320 | /// Get the initializer for this variable, no matter which |
| 1321 | /// declaration it is attached to. Also get that declaration. |
| 1322 | const Expr *getAnyInitializer(const VarDecl *&D) const; |
| 1323 | |
| 1324 | bool hasInit() const; |
| 1325 | const Expr *getInit() const { |
| 1326 | return const_cast<VarDecl *>(this)->getInit(); |
| 1327 | } |
| 1328 | Expr *getInit(); |
| 1329 | |
| 1330 | /// Retrieve the address of the initializer expression. |
| 1331 | Stmt **getInitAddress(); |
| 1332 | |
| 1333 | void setInit(Expr *I); |
| 1334 | |
| 1335 | /// Get the initializing declaration of this variable, if any. This is |
| 1336 | /// usually the definition, except that for a static data member it can be |
| 1337 | /// the in-class declaration. |
| 1338 | VarDecl *getInitializingDeclaration(); |
| 1339 | const VarDecl *getInitializingDeclaration() const { |
| 1340 | return const_cast<VarDecl *>(this)->getInitializingDeclaration(); |
| 1341 | } |
| 1342 | |
| 1343 | /// Determine whether this variable's value might be usable in a |
| 1344 | /// constant expression, according to the relevant language standard. |
| 1345 | /// This only checks properties of the declaration, and does not check |
| 1346 | /// whether the initializer is in fact a constant expression. |
| 1347 | /// |
| 1348 | /// This corresponds to C++20 [expr.const]p3's notion of a |
| 1349 | /// "potentially-constant" variable. |
| 1350 | bool mightBeUsableInConstantExpressions(const ASTContext &C) const; |
| 1351 | |
| 1352 | /// Determine whether this variable's value can be used in a |
| 1353 | /// constant expression, according to the relevant language standard, |
| 1354 | /// including checking whether it was initialized by a constant expression. |
| 1355 | bool isUsableInConstantExpressions(const ASTContext &C) const; |
| 1356 | |
| 1357 | EvaluatedStmt *ensureEvaluatedStmt() const; |
| 1358 | EvaluatedStmt *getEvaluatedStmt() const; |
| 1359 | |
| 1360 | /// Attempt to evaluate the value of the initializer attached to this |
| 1361 | /// declaration, and produce notes explaining why it cannot be evaluated. |
| 1362 | /// Returns a pointer to the value if evaluation succeeded, 0 otherwise. |
| 1363 | APValue *evaluateValue() const; |
| 1364 | |
| 1365 | private: |
| 1366 | APValue *evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes, |
| 1367 | bool IsConstantInitialization) const; |
| 1368 | |
| 1369 | public: |
| 1370 | /// Return the already-evaluated value of this variable's |
| 1371 | /// initializer, or NULL if the value is not yet known. Returns pointer |
| 1372 | /// to untyped APValue if the value could not be evaluated. |
| 1373 | APValue *getEvaluatedValue() const; |
| 1374 | |
| 1375 | /// Evaluate the destruction of this variable to determine if it constitutes |
| 1376 | /// constant destruction. |
| 1377 | /// |
| 1378 | /// \pre hasConstantInitialization() |
| 1379 | /// \return \c true if this variable has constant destruction, \c false if |
| 1380 | /// not. |
| 1381 | bool evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> &Notes) const; |
| 1382 | |
| 1383 | /// Determine whether this variable has constant initialization. |
| 1384 | /// |
| 1385 | /// This is only set in two cases: when the language semantics require |
| 1386 | /// constant initialization (globals in C and some globals in C++), and when |
| 1387 | /// the variable is usable in constant expressions (constexpr, const int, and |
| 1388 | /// reference variables in C++). |
| 1389 | bool hasConstantInitialization() const; |
| 1390 | |
| 1391 | /// Determine whether the initializer of this variable is an integer constant |
| 1392 | /// expression. For use in C++98, where this affects whether the variable is |
| 1393 | /// usable in constant expressions. |
| 1394 | bool hasICEInitializer(const ASTContext &Context) const; |
| 1395 | |
| 1396 | /// Evaluate the initializer of this variable to determine whether it's a |
| 1397 | /// constant initializer. Should only be called once, after completing the |
| 1398 | /// definition of the variable. |
| 1399 | bool checkForConstantInitialization( |
| 1400 | SmallVectorImpl<PartialDiagnosticAt> &Notes) const; |
| 1401 | |
| 1402 | void setInitStyle(InitializationStyle Style) { |
| 1403 | VarDeclBits.InitStyle = Style; |
| 1404 | } |
| 1405 | |
| 1406 | /// The style of initialization for this declaration. |
| 1407 | /// |
| 1408 | /// C-style initialization is "int x = 1;". Call-style initialization is |
| 1409 | /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be |
| 1410 | /// the expression inside the parens or a "ClassType(a,b,c)" class constructor |
| 1411 | /// expression for class types. List-style initialization is C++11 syntax, |
| 1412 | /// e.g. "int x{1};". Clients can distinguish between different forms of |
| 1413 | /// initialization by checking this value. In particular, "int x = {1};" is |
| 1414 | /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the |
| 1415 | /// Init expression in all three cases is an InitListExpr. |
| 1416 | InitializationStyle getInitStyle() const { |
| 1417 | return static_cast<InitializationStyle>(VarDeclBits.InitStyle); |
| 1418 | } |
| 1419 | |
| 1420 | /// Whether the initializer is a direct-initializer (list or call). |
| 1421 | bool isDirectInit() const { |
| 1422 | return getInitStyle() != CInit; |
| 1423 | } |
| 1424 | |
| 1425 | /// If this definition should pretend to be a declaration. |
| 1426 | bool isThisDeclarationADemotedDefinition() const { |
| 1427 | return isa<ParmVarDecl>(this) ? false : |
| 1428 | NonParmVarDeclBits.IsThisDeclarationADemotedDefinition; |
| 1429 | } |
| 1430 | |
| 1431 | /// This is a definition which should be demoted to a declaration. |
| 1432 | /// |
| 1433 | /// In some cases (mostly module merging) we can end up with two visible |
| 1434 | /// definitions one of which needs to be demoted to a declaration to keep |
| 1435 | /// the AST invariants. |
| 1436 | void demoteThisDefinitionToDeclaration() { |
| 1437 | assert(isThisDeclarationADefinition() && "Not a definition!")(static_cast <bool> (isThisDeclarationADefinition() && "Not a definition!") ? void (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\"" , "clang/include/clang/AST/Decl.h", 1437, __extension__ __PRETTY_FUNCTION__ )); |
| 1438 | assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")(static_cast <bool> (!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!") ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\"" , "clang/include/clang/AST/Decl.h", 1438, __extension__ __PRETTY_FUNCTION__ )); |
| 1439 | NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1; |
| 1440 | } |
| 1441 | |
| 1442 | /// Determine whether this variable is the exception variable in a |
| 1443 | /// C++ catch statememt or an Objective-C \@catch statement. |
| 1444 | bool isExceptionVariable() const { |
| 1445 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar; |
| 1446 | } |
| 1447 | void setExceptionVariable(bool EV) { |
| 1448 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "clang/include/clang/AST/Decl.h" , 1448, __extension__ __PRETTY_FUNCTION__)); |
| 1449 | NonParmVarDeclBits.ExceptionVar = EV; |
| 1450 | } |
| 1451 | |
| 1452 | /// Determine whether this local variable can be used with the named |
| 1453 | /// return value optimization (NRVO). |
| 1454 | /// |
| 1455 | /// The named return value optimization (NRVO) works by marking certain |
| 1456 | /// non-volatile local variables of class type as NRVO objects. These |
| 1457 | /// locals can be allocated within the return slot of their containing |
| 1458 | /// function, in which case there is no need to copy the object to the |
| 1459 | /// return slot when returning from the function. Within the function body, |
| 1460 | /// each return that returns the NRVO object will have this variable as its |
| 1461 | /// NRVO candidate. |
| 1462 | bool isNRVOVariable() const { |
| 1463 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable; |
| 1464 | } |
| 1465 | void setNRVOVariable(bool NRVO) { |
| 1466 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "clang/include/clang/AST/Decl.h" , 1466, __extension__ __PRETTY_FUNCTION__)); |
| 1467 | NonParmVarDeclBits.NRVOVariable = NRVO; |
| 1468 | } |
| 1469 | |
| 1470 | /// Determine whether this variable is the for-range-declaration in |
| 1471 | /// a C++0x for-range statement. |
| 1472 | bool isCXXForRangeDecl() const { |
| 1473 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl; |
| 1474 | } |
| 1475 | void setCXXForRangeDecl(bool FRD) { |
| 1476 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "clang/include/clang/AST/Decl.h" , 1476, __extension__ __PRETTY_FUNCTION__)); |
| 1477 | NonParmVarDeclBits.CXXForRangeDecl = FRD; |
| 1478 | } |
| 1479 | |
| 1480 | /// Determine whether this variable is a for-loop declaration for a |
| 1481 | /// for-in statement in Objective-C. |
| 1482 | bool isObjCForDecl() const { |
| 1483 | return NonParmVarDeclBits.ObjCForDecl; |
| 1484 | } |
| 1485 | |
| 1486 | void setObjCForDecl(bool FRD) { |
| 1487 | NonParmVarDeclBits.ObjCForDecl = FRD; |
| 1488 | } |
| 1489 | |
| 1490 | /// Determine whether this variable is an ARC pseudo-__strong variable. A |
| 1491 | /// pseudo-__strong variable has a __strong-qualified type but does not |
| 1492 | /// actually retain the object written into it. Generally such variables are |
| 1493 | /// also 'const' for safety. There are 3 cases where this will be set, 1) if |
| 1494 | /// the variable is annotated with the objc_externally_retained attribute, 2) |
| 1495 | /// if its 'self' in a non-init method, or 3) if its the variable in an for-in |
| 1496 | /// loop. |
| 1497 | bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; } |
| 1498 | void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; } |
| 1499 | |
| 1500 | /// Whether this variable is (C++1z) inline. |
| 1501 | bool isInline() const { |
| 1502 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline; |
| 1503 | } |
| 1504 | bool isInlineSpecified() const { |
| 1505 | return isa<ParmVarDecl>(this) ? false |
| 1506 | : NonParmVarDeclBits.IsInlineSpecified; |
| 1507 | } |
| 1508 | void setInlineSpecified() { |
| 1509 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "clang/include/clang/AST/Decl.h" , 1509, __extension__ __PRETTY_FUNCTION__)); |
| 1510 | NonParmVarDeclBits.IsInline = true; |
| 1511 | NonParmVarDeclBits.IsInlineSpecified = true; |
| 1512 | } |
| 1513 | void setImplicitlyInline() { |
| 1514 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "clang/include/clang/AST/Decl.h" , 1514, __extension__ __PRETTY_FUNCTION__)); |
| 1515 | NonParmVarDeclBits.IsInline = true; |
| 1516 | } |
| 1517 | |
| 1518 | /// Whether this variable is (C++11) constexpr. |
| 1519 | bool isConstexpr() const { |
| 1520 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr; |
| 1521 | } |
| 1522 | void setConstexpr(bool IC) { |
| 1523 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "clang/include/clang/AST/Decl.h" , 1523, __extension__ __PRETTY_FUNCTION__)); |
| 1524 | NonParmVarDeclBits.IsConstexpr = IC; |
| 1525 | } |
| 1526 | |
| 1527 | /// Whether this variable is the implicit variable for a lambda init-capture. |
| 1528 | bool isInitCapture() const { |
| 1529 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture; |
| 1530 | } |
| 1531 | void setInitCapture(bool IC) { |
| 1532 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "clang/include/clang/AST/Decl.h" , 1532, __extension__ __PRETTY_FUNCTION__)); |
| 1533 | NonParmVarDeclBits.IsInitCapture = IC; |
| 1534 | } |
| 1535 | |
| 1536 | /// Determine whether this variable is actually a function parameter pack or |
| 1537 | /// init-capture pack. |
| 1538 | bool isParameterPack() const; |
| 1539 | |
| 1540 | /// Whether this local extern variable declaration's previous declaration |
| 1541 | /// was declared in the same block scope. Only correct in C++. |
| 1542 | bool isPreviousDeclInSameBlockScope() const { |
| 1543 | return isa<ParmVarDecl>(this) |
| 1544 | ? false |
| 1545 | : NonParmVarDeclBits.PreviousDeclInSameBlockScope; |
| 1546 | } |
| 1547 | void setPreviousDeclInSameBlockScope(bool Same) { |
| 1548 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "clang/include/clang/AST/Decl.h" , 1548, __extension__ __PRETTY_FUNCTION__)); |
| 1549 | NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same; |
| 1550 | } |
| 1551 | |
| 1552 | /// Indicates the capture is a __block variable that is captured by a block |
| 1553 | /// that can potentially escape (a block for which BlockDecl::doesNotEscape |
| 1554 | /// returns false). |
| 1555 | bool isEscapingByref() const; |
| 1556 | |
| 1557 | /// Indicates the capture is a __block variable that is never captured by an |
| 1558 | /// escaping block. |
| 1559 | bool isNonEscapingByref() const; |
| 1560 | |
| 1561 | void setEscapingByref() { |
| 1562 | NonParmVarDeclBits.EscapingByref = true; |
| 1563 | } |
| 1564 | |
| 1565 | /// Determines if this variable's alignment is dependent. |
| 1566 | bool hasDependentAlignment() const; |
| 1567 | |
| 1568 | /// Retrieve the variable declaration from which this variable could |
| 1569 | /// be instantiated, if it is an instantiation (rather than a non-template). |
| 1570 | VarDecl *getTemplateInstantiationPattern() const; |
| 1571 | |
| 1572 | /// If this variable is an instantiated static data member of a |
| 1573 | /// class template specialization, returns the templated static data member |
| 1574 | /// from which it was instantiated. |
| 1575 | VarDecl *getInstantiatedFromStaticDataMember() const; |
| 1576 | |
| 1577 | /// If this variable is an instantiation of a variable template or a |
| 1578 | /// static data member of a class template, determine what kind of |
| 1579 | /// template specialization or instantiation this is. |
| 1580 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
| 1581 | |
| 1582 | /// Get the template specialization kind of this variable for the purposes of |
| 1583 | /// template instantiation. This differs from getTemplateSpecializationKind() |
| 1584 | /// for an instantiation of a class-scope explicit specialization. |
| 1585 | TemplateSpecializationKind |
| 1586 | getTemplateSpecializationKindForInstantiation() const; |
| 1587 | |
| 1588 | /// If this variable is an instantiation of a variable template or a |
| 1589 | /// static data member of a class template, determine its point of |
| 1590 | /// instantiation. |
| 1591 | SourceLocation getPointOfInstantiation() const; |
| 1592 | |
| 1593 | /// If this variable is an instantiation of a static data member of a |
| 1594 | /// class template specialization, retrieves the member specialization |
| 1595 | /// information. |
| 1596 | MemberSpecializationInfo *getMemberSpecializationInfo() const; |
| 1597 | |
| 1598 | /// For a static data member that was instantiated from a static |
| 1599 | /// data member of a class template, set the template specialiation kind. |
| 1600 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
| 1601 | SourceLocation PointOfInstantiation = SourceLocation()); |
| 1602 | |
| 1603 | /// Specify that this variable is an instantiation of the |
| 1604 | /// static data member VD. |
| 1605 | void setInstantiationOfStaticDataMember(VarDecl *VD, |
| 1606 | TemplateSpecializationKind TSK); |
| 1607 | |
| 1608 | /// Retrieves the variable template that is described by this |
| 1609 | /// variable declaration. |
| 1610 | /// |
| 1611 | /// Every variable template is represented as a VarTemplateDecl and a |
| 1612 | /// VarDecl. The former contains template properties (such as |
| 1613 | /// the template parameter lists) while the latter contains the |
| 1614 | /// actual description of the template's |
| 1615 | /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the |
| 1616 | /// VarDecl that from a VarTemplateDecl, while |
| 1617 | /// getDescribedVarTemplate() retrieves the VarTemplateDecl from |
| 1618 | /// a VarDecl. |
| 1619 | VarTemplateDecl *getDescribedVarTemplate() const; |
| 1620 | |
| 1621 | void setDescribedVarTemplate(VarTemplateDecl *Template); |
| 1622 | |
| 1623 | // Is this variable known to have a definition somewhere in the complete |
| 1624 | // program? This may be true even if the declaration has internal linkage and |
| 1625 | // has no definition within this source file. |
| 1626 | bool isKnownToBeDefined() const; |
| 1627 | |
| 1628 | /// Is destruction of this variable entirely suppressed? If so, the variable |
| 1629 | /// need not have a usable destructor at all. |
| 1630 | bool isNoDestroy(const ASTContext &) const; |
| 1631 | |
| 1632 | /// Would the destruction of this variable have any effect, and if so, what |
| 1633 | /// kind? |
| 1634 | QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const; |
| 1635 | |
| 1636 | /// Whether this variable has a flexible array member initialized with one |
| 1637 | /// or more elements. This can only be called for declarations where |
| 1638 | /// hasInit() is true. |
| 1639 | /// |
| 1640 | /// (The standard doesn't allow initializing flexible array members; this is |
| 1641 | /// a gcc/msvc extension.) |
| 1642 | bool hasFlexibleArrayInit(const ASTContext &Ctx) const; |
| 1643 | |
| 1644 | /// If hasFlexibleArrayInit is true, compute the number of additional bytes |
| 1645 | /// necessary to store those elements. Otherwise, returns zero. |
| 1646 | /// |
| 1647 | /// This can only be called for declarations where hasInit() is true. |
| 1648 | CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const; |
| 1649 | |
| 1650 | // Implement isa/cast/dyncast/etc. |
| 1651 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 1652 | static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; } |
| 1653 | }; |
| 1654 | |
| 1655 | class ImplicitParamDecl : public VarDecl { |
| 1656 | void anchor() override; |
| 1657 | |
| 1658 | public: |
| 1659 | /// Defines the kind of the implicit parameter: is this an implicit parameter |
| 1660 | /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured |
| 1661 | /// context or something else. |
| 1662 | enum ImplicitParamKind : unsigned { |
| 1663 | /// Parameter for Objective-C 'self' argument |
| 1664 | ObjCSelf, |
| 1665 | |
| 1666 | /// Parameter for Objective-C '_cmd' argument |
| 1667 | ObjCCmd, |
| 1668 | |
| 1669 | /// Parameter for C++ 'this' argument |
| 1670 | CXXThis, |
| 1671 | |
| 1672 | /// Parameter for C++ virtual table pointers |
| 1673 | CXXVTT, |
| 1674 | |
| 1675 | /// Parameter for captured context |
| 1676 | CapturedContext, |
| 1677 | |
| 1678 | /// Parameter for Thread private variable |
| 1679 | ThreadPrivateVar, |
| 1680 | |
| 1681 | /// Other implicit parameter |
| 1682 | Other, |
| 1683 | }; |
| 1684 | |
| 1685 | /// Create implicit parameter. |
| 1686 | static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC, |
| 1687 | SourceLocation IdLoc, IdentifierInfo *Id, |
| 1688 | QualType T, ImplicitParamKind ParamKind); |
| 1689 | static ImplicitParamDecl *Create(ASTContext &C, QualType T, |
| 1690 | ImplicitParamKind ParamKind); |
| 1691 | |
| 1692 | static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 1693 | |
| 1694 | ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, |
| 1695 | IdentifierInfo *Id, QualType Type, |
| 1696 | ImplicitParamKind ParamKind) |
| 1697 | : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type, |
| 1698 | /*TInfo=*/nullptr, SC_None) { |
| 1699 | NonParmVarDeclBits.ImplicitParamKind = ParamKind; |
| 1700 | setImplicit(); |
| 1701 | } |
| 1702 | |
| 1703 | ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind) |
| 1704 | : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(), |
| 1705 | SourceLocation(), /*Id=*/nullptr, Type, |
| 1706 | /*TInfo=*/nullptr, SC_None) { |
| 1707 | NonParmVarDeclBits.ImplicitParamKind = ParamKind; |
| 1708 | setImplicit(); |
| 1709 | } |
| 1710 | |
| 1711 | /// Returns the implicit parameter kind. |
| 1712 | ImplicitParamKind getParameterKind() const { |
| 1713 | return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind); |
| 1714 | } |
| 1715 | |
| 1716 | // Implement isa/cast/dyncast/etc. |
| 1717 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 1718 | static bool classofKind(Kind K) { return K == ImplicitParam; } |
| 1719 | }; |
| 1720 | |
| 1721 | /// Represents a parameter to a function. |
| 1722 | class ParmVarDecl : public VarDecl { |
| 1723 | public: |
| 1724 | enum { MaxFunctionScopeDepth = 255 }; |
| 1725 | enum { MaxFunctionScopeIndex = 255 }; |
| 1726 | |
| 1727 | protected: |
| 1728 | ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
| 1729 | SourceLocation IdLoc, IdentifierInfo *Id, QualType T, |
| 1730 | TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg) |
| 1731 | : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) { |
| 1732 | assert(ParmVarDeclBits.HasInheritedDefaultArg == false)(static_cast <bool> (ParmVarDeclBits.HasInheritedDefaultArg == false) ? void (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false" , "clang/include/clang/AST/Decl.h", 1732, __extension__ __PRETTY_FUNCTION__ )); |
| 1733 | assert(ParmVarDeclBits.DefaultArgKind == DAK_None)(static_cast <bool> (ParmVarDeclBits.DefaultArgKind == DAK_None ) ? void (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None" , "clang/include/clang/AST/Decl.h", 1733, __extension__ __PRETTY_FUNCTION__ )); |
| 1734 | assert(ParmVarDeclBits.IsKNRPromoted == false)(static_cast <bool> (ParmVarDeclBits.IsKNRPromoted == false ) ? void (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false" , "clang/include/clang/AST/Decl.h", 1734, __extension__ __PRETTY_FUNCTION__ )); |
| 1735 | assert(ParmVarDeclBits.IsObjCMethodParam == false)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam == false) ? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false" , "clang/include/clang/AST/Decl.h", 1735, __extension__ __PRETTY_FUNCTION__ )); |
| 1736 | setDefaultArg(DefArg); |
| 1737 | } |
| 1738 | |
| 1739 | public: |
| 1740 | static ParmVarDecl *Create(ASTContext &C, DeclContext *DC, |
| 1741 | SourceLocation StartLoc, |
| 1742 | SourceLocation IdLoc, IdentifierInfo *Id, |
| 1743 | QualType T, TypeSourceInfo *TInfo, |
| 1744 | StorageClass S, Expr *DefArg); |
| 1745 | |
| 1746 | static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 1747 | |
| 1748 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
| 1749 | |
| 1750 | void setObjCMethodScopeInfo(unsigned parameterIndex) { |
| 1751 | ParmVarDeclBits.IsObjCMethodParam = true; |
| 1752 | setParameterIndex(parameterIndex); |
| 1753 | } |
| 1754 | |
| 1755 | void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) { |
| 1756 | assert(!ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (!ParmVarDeclBits.IsObjCMethodParam ) ? void (0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam" , "clang/include/clang/AST/Decl.h", 1756, __extension__ __PRETTY_FUNCTION__ )); |
| 1757 | |
| 1758 | ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth; |
| 1759 | assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\"" , "clang/include/clang/AST/Decl.h", 1760, __extension__ __PRETTY_FUNCTION__ )) |
| 1760 | && "truncation!")(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\"" , "clang/include/clang/AST/Decl.h", 1760, __extension__ __PRETTY_FUNCTION__ )); |
| 1761 | |
| 1762 | setParameterIndex(parameterIndex); |
| 1763 | } |
| 1764 | |
| 1765 | bool isObjCMethodParameter() const { |
| 1766 | return ParmVarDeclBits.IsObjCMethodParam; |
| 1767 | } |
| 1768 | |
| 1769 | /// Determines whether this parameter is destroyed in the callee function. |
| 1770 | bool isDestroyedInCallee() const; |
| 1771 | |
| 1772 | unsigned getFunctionScopeDepth() const { |
| 1773 | if (ParmVarDeclBits.IsObjCMethodParam) return 0; |
| 1774 | return ParmVarDeclBits.ScopeDepthOrObjCQuals; |
| 1775 | } |
| 1776 | |
| 1777 | static constexpr unsigned getMaxFunctionScopeDepth() { |
| 1778 | return (1u << NumScopeDepthOrObjCQualsBits) - 1; |
| 1779 | } |
| 1780 | |
| 1781 | /// Returns the index of this parameter in its prototype or method scope. |
| 1782 | unsigned getFunctionScopeIndex() const { |
| 1783 | return getParameterIndex(); |
| 1784 | } |
| 1785 | |
| 1786 | ObjCDeclQualifier getObjCDeclQualifier() const { |
| 1787 | if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None; |
| 1788 | return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals); |
| 1789 | } |
| 1790 | void setObjCDeclQualifier(ObjCDeclQualifier QTVal) { |
| 1791 | assert(ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam) ? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam" , "clang/include/clang/AST/Decl.h", 1791, __extension__ __PRETTY_FUNCTION__ )); |
| 1792 | ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal; |
| 1793 | } |
| 1794 | |
| 1795 | /// True if the value passed to this parameter must undergo |
| 1796 | /// K&R-style default argument promotion: |
| 1797 | /// |
| 1798 | /// C99 6.5.2.2. |
| 1799 | /// If the expression that denotes the called function has a type |
| 1800 | /// that does not include a prototype, the integer promotions are |
| 1801 | /// performed on each argument, and arguments that have type float |
| 1802 | /// are promoted to double. |
| 1803 | bool isKNRPromoted() const { |
| 1804 | return ParmVarDeclBits.IsKNRPromoted; |
| 1805 | } |
| 1806 | void setKNRPromoted(bool promoted) { |
| 1807 | ParmVarDeclBits.IsKNRPromoted = promoted; |
| 1808 | } |
| 1809 | |
| 1810 | Expr *getDefaultArg(); |
| 1811 | const Expr *getDefaultArg() const { |
| 1812 | return const_cast<ParmVarDecl *>(this)->getDefaultArg(); |
| 1813 | } |
| 1814 | |
| 1815 | void setDefaultArg(Expr *defarg); |
| 1816 | |
| 1817 | /// Retrieve the source range that covers the entire default |
| 1818 | /// argument. |
| 1819 | SourceRange getDefaultArgRange() const; |
| 1820 | void setUninstantiatedDefaultArg(Expr *arg); |
| 1821 | Expr *getUninstantiatedDefaultArg(); |
| 1822 | const Expr *getUninstantiatedDefaultArg() const { |
| 1823 | return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg(); |
| 1824 | } |
| 1825 | |
| 1826 | /// Determines whether this parameter has a default argument, |
| 1827 | /// either parsed or not. |
| 1828 | bool hasDefaultArg() const; |
| 1829 | |
| 1830 | /// Determines whether this parameter has a default argument that has not |
| 1831 | /// yet been parsed. This will occur during the processing of a C++ class |
| 1832 | /// whose member functions have default arguments, e.g., |
| 1833 | /// @code |
| 1834 | /// class X { |
| 1835 | /// public: |
| 1836 | /// void f(int x = 17); // x has an unparsed default argument now |
| 1837 | /// }; // x has a regular default argument now |
| 1838 | /// @endcode |
| 1839 | bool hasUnparsedDefaultArg() const { |
| 1840 | return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed; |
| 1841 | } |
| 1842 | |
| 1843 | bool hasUninstantiatedDefaultArg() const { |
| 1844 | return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated; |
| 1845 | } |
| 1846 | |
| 1847 | /// Specify that this parameter has an unparsed default argument. |
| 1848 | /// The argument will be replaced with a real default argument via |
| 1849 | /// setDefaultArg when the class definition enclosing the function |
| 1850 | /// declaration that owns this default argument is completed. |
| 1851 | void setUnparsedDefaultArg() { |
| 1852 | ParmVarDeclBits.DefaultArgKind = DAK_Unparsed; |
| 1853 | } |
| 1854 | |
| 1855 | bool hasInheritedDefaultArg() const { |
| 1856 | return ParmVarDeclBits.HasInheritedDefaultArg; |
| 1857 | } |
| 1858 | |
| 1859 | void setHasInheritedDefaultArg(bool I = true) { |
| 1860 | ParmVarDeclBits.HasInheritedDefaultArg = I; |
| 1861 | } |
| 1862 | |
| 1863 | QualType getOriginalType() const; |
| 1864 | |
| 1865 | /// Sets the function declaration that owns this |
| 1866 | /// ParmVarDecl. Since ParmVarDecls are often created before the |
| 1867 | /// FunctionDecls that own them, this routine is required to update |
| 1868 | /// the DeclContext appropriately. |
| 1869 | void setOwningFunction(DeclContext *FD) { setDeclContext(FD); } |
| 1870 | |
| 1871 | // Implement isa/cast/dyncast/etc. |
| 1872 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 1873 | static bool classofKind(Kind K) { return K == ParmVar; } |
| 1874 | |
| 1875 | private: |
| 1876 | enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 }; |
| 1877 | |
| 1878 | void setParameterIndex(unsigned parameterIndex) { |
| 1879 | if (parameterIndex >= ParameterIndexSentinel) { |
| 1880 | setParameterIndexLarge(parameterIndex); |
| 1881 | return; |
| 1882 | } |
| 1883 | |
| 1884 | ParmVarDeclBits.ParameterIndex = parameterIndex; |
| 1885 | assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")(static_cast <bool> (ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\"" , "clang/include/clang/AST/Decl.h", 1885, __extension__ __PRETTY_FUNCTION__ )); |
| 1886 | } |
| 1887 | unsigned getParameterIndex() const { |
| 1888 | unsigned d = ParmVarDeclBits.ParameterIndex; |
| 1889 | return d == ParameterIndexSentinel ? getParameterIndexLarge() : d; |
| 1890 | } |
| 1891 | |
| 1892 | void setParameterIndexLarge(unsigned parameterIndex); |
| 1893 | unsigned getParameterIndexLarge() const; |
| 1894 | }; |
| 1895 | |
| 1896 | enum class MultiVersionKind { |
| 1897 | None, |
| 1898 | Target, |
| 1899 | CPUSpecific, |
| 1900 | CPUDispatch, |
| 1901 | TargetClones, |
| 1902 | TargetVersion |
| 1903 | }; |
| 1904 | |
| 1905 | /// Represents a function declaration or definition. |
| 1906 | /// |
| 1907 | /// Since a given function can be declared several times in a program, |
| 1908 | /// there may be several FunctionDecls that correspond to that |
| 1909 | /// function. Only one of those FunctionDecls will be found when |
| 1910 | /// traversing the list of declarations in the context of the |
| 1911 | /// FunctionDecl (e.g., the translation unit); this FunctionDecl |
| 1912 | /// contains all of the information known about the function. Other, |
| 1913 | /// previous declarations of the function are available via the |
| 1914 | /// getPreviousDecl() chain. |
| 1915 | class FunctionDecl : public DeclaratorDecl, |
| 1916 | public DeclContext, |
| 1917 | public Redeclarable<FunctionDecl> { |
| 1918 | // This class stores some data in DeclContext::FunctionDeclBits |
| 1919 | // to save some space. Use the provided accessors to access it. |
| 1920 | public: |
| 1921 | /// The kind of templated function a FunctionDecl can be. |
| 1922 | enum TemplatedKind { |
| 1923 | // Not templated. |
| 1924 | TK_NonTemplate, |
| 1925 | // The pattern in a function template declaration. |
| 1926 | TK_FunctionTemplate, |
| 1927 | // A non-template function that is an instantiation or explicit |
| 1928 | // specialization of a member of a templated class. |
| 1929 | TK_MemberSpecialization, |
| 1930 | // An instantiation or explicit specialization of a function template. |
| 1931 | // Note: this might have been instantiated from a templated class if it |
| 1932 | // is a class-scope explicit specialization. |
| 1933 | TK_FunctionTemplateSpecialization, |
| 1934 | // A function template specialization that hasn't yet been resolved to a |
| 1935 | // particular specialized function template. |
| 1936 | TK_DependentFunctionTemplateSpecialization, |
| 1937 | // A non-template function which is in a dependent scope. |
| 1938 | TK_DependentNonTemplate |
| 1939 | |
| 1940 | }; |
| 1941 | |
| 1942 | /// Stashed information about a defaulted function definition whose body has |
| 1943 | /// not yet been lazily generated. |
| 1944 | class DefaultedFunctionInfo final |
| 1945 | : llvm::TrailingObjects<DefaultedFunctionInfo, DeclAccessPair> { |
| 1946 | friend TrailingObjects; |
| 1947 | unsigned NumLookups; |
| 1948 | |
| 1949 | public: |
| 1950 | static DefaultedFunctionInfo *Create(ASTContext &Context, |
| 1951 | ArrayRef<DeclAccessPair> Lookups); |
| 1952 | /// Get the unqualified lookup results that should be used in this |
| 1953 | /// defaulted function definition. |
| 1954 | ArrayRef<DeclAccessPair> getUnqualifiedLookups() const { |
| 1955 | return {getTrailingObjects<DeclAccessPair>(), NumLookups}; |
| 1956 | } |
| 1957 | }; |
| 1958 | |
| 1959 | private: |
| 1960 | /// A new[]'d array of pointers to VarDecls for the formal |
| 1961 | /// parameters of this function. This is null if a prototype or if there are |
| 1962 | /// no formals. |
| 1963 | ParmVarDecl **ParamInfo = nullptr; |
| 1964 | |
| 1965 | /// The active member of this union is determined by |
| 1966 | /// FunctionDeclBits.HasDefaultedFunctionInfo. |
| 1967 | union { |
| 1968 | /// The body of the function. |
| 1969 | LazyDeclStmtPtr Body; |
| 1970 | /// Information about a future defaulted function definition. |
| 1971 | DefaultedFunctionInfo *DefaultedInfo; |
| 1972 | }; |
| 1973 | |
| 1974 | unsigned ODRHash; |
| 1975 | |
| 1976 | /// End part of this FunctionDecl's source range. |
| 1977 | /// |
| 1978 | /// We could compute the full range in getSourceRange(). However, when we're |
| 1979 | /// dealing with a function definition deserialized from a PCH/AST file, |
| 1980 | /// we can only compute the full range once the function body has been |
| 1981 | /// de-serialized, so it's far better to have the (sometimes-redundant) |
| 1982 | /// EndRangeLoc. |
| 1983 | SourceLocation EndRangeLoc; |
| 1984 | |
| 1985 | SourceLocation DefaultKWLoc; |
| 1986 | |
| 1987 | /// The template or declaration that this declaration |
| 1988 | /// describes or was instantiated from, respectively. |
| 1989 | /// |
| 1990 | /// For non-templates this value will be NULL, unless this declaration was |
| 1991 | /// declared directly inside of a function template, in which case it will |
| 1992 | /// have a pointer to a FunctionDecl, stored in the NamedDecl. For function |
| 1993 | /// declarations that describe a function template, this will be a pointer to |
| 1994 | /// a FunctionTemplateDecl, stored in the NamedDecl. For member functions of |
| 1995 | /// class template specializations, this will be a MemberSpecializationInfo |
| 1996 | /// pointer containing information about the specialization. |
| 1997 | /// For function template specializations, this will be a |
| 1998 | /// FunctionTemplateSpecializationInfo, which contains information about |
| 1999 | /// the template being specialized and the template arguments involved in |
| 2000 | /// that specialization. |
| 2001 | llvm::PointerUnion<NamedDecl *, MemberSpecializationInfo *, |
| 2002 | FunctionTemplateSpecializationInfo *, |
| 2003 | DependentFunctionTemplateSpecializationInfo *> |
| 2004 | TemplateOrSpecialization; |
| 2005 | |
| 2006 | /// Provides source/type location info for the declaration name embedded in |
| 2007 | /// the DeclaratorDecl base class. |
| 2008 | DeclarationNameLoc DNLoc; |
| 2009 | |
| 2010 | /// Specify that this function declaration is actually a function |
| 2011 | /// template specialization. |
| 2012 | /// |
| 2013 | /// \param C the ASTContext. |
| 2014 | /// |
| 2015 | /// \param Template the function template that this function template |
| 2016 | /// specialization specializes. |
| 2017 | /// |
| 2018 | /// \param TemplateArgs the template arguments that produced this |
| 2019 | /// function template specialization from the template. |
| 2020 | /// |
| 2021 | /// \param InsertPos If non-NULL, the position in the function template |
| 2022 | /// specialization set where the function template specialization data will |
| 2023 | /// be inserted. |
| 2024 | /// |
| 2025 | /// \param TSK the kind of template specialization this is. |
| 2026 | /// |
| 2027 | /// \param TemplateArgsAsWritten location info of template arguments. |
| 2028 | /// |
| 2029 | /// \param PointOfInstantiation point at which the function template |
| 2030 | /// specialization was first instantiated. |
| 2031 | void setFunctionTemplateSpecialization(ASTContext &C, |
| 2032 | FunctionTemplateDecl *Template, |
| 2033 | const TemplateArgumentList *TemplateArgs, |
| 2034 | void *InsertPos, |
| 2035 | TemplateSpecializationKind TSK, |
| 2036 | const TemplateArgumentListInfo *TemplateArgsAsWritten, |
| 2037 | SourceLocation PointOfInstantiation); |
| 2038 | |
| 2039 | /// Specify that this record is an instantiation of the |
| 2040 | /// member function FD. |
| 2041 | void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD, |
| 2042 | TemplateSpecializationKind TSK); |
| 2043 | |
| 2044 | void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo); |
| 2045 | |
| 2046 | // This is unfortunately needed because ASTDeclWriter::VisitFunctionDecl |
| 2047 | // need to access this bit but we want to avoid making ASTDeclWriter |
| 2048 | // a friend of FunctionDeclBitfields just for this. |
| 2049 | bool isDeletedBit() const { return FunctionDeclBits.IsDeleted; } |
| 2050 | |
| 2051 | /// Whether an ODRHash has been stored. |
| 2052 | bool hasODRHash() const { return FunctionDeclBits.HasODRHash; } |
| 2053 | |
| 2054 | /// State that an ODRHash has been stored. |
| 2055 | void setHasODRHash(bool B = true) { FunctionDeclBits.HasODRHash = B; } |
| 2056 | |
| 2057 | protected: |
| 2058 | FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
| 2059 | const DeclarationNameInfo &NameInfo, QualType T, |
| 2060 | TypeSourceInfo *TInfo, StorageClass S, bool UsesFPIntrin, |
| 2061 | bool isInlineSpecified, ConstexprSpecKind ConstexprKind, |
| 2062 | Expr *TrailingRequiresClause = nullptr); |
| 2063 | |
| 2064 | using redeclarable_base = Redeclarable<FunctionDecl>; |
| 2065 | |
| 2066 | FunctionDecl *getNextRedeclarationImpl() override { |
| 2067 | return getNextRedeclaration(); |
| 2068 | } |
| 2069 | |
| 2070 | FunctionDecl *getPreviousDeclImpl() override { |
| 2071 | return getPreviousDecl(); |
| 2072 | } |
| 2073 | |
| 2074 | FunctionDecl *getMostRecentDeclImpl() override { |
| 2075 | return getMostRecentDecl(); |
| 2076 | } |
| 2077 | |
| 2078 | public: |
| 2079 | friend class ASTDeclReader; |
| 2080 | friend class ASTDeclWriter; |
| 2081 | |
| 2082 | using redecl_range = redeclarable_base::redecl_range; |
| 2083 | using redecl_iterator = redeclarable_base::redecl_iterator; |
| 2084 | |
| 2085 | using redeclarable_base::redecls_begin; |
| 2086 | using redeclarable_base::redecls_end; |
| 2087 | using redeclarable_base::redecls; |
| 2088 | using redeclarable_base::getPreviousDecl; |
| 2089 | using redeclarable_base::getMostRecentDecl; |
| 2090 | using redeclarable_base::isFirstDecl; |
| 2091 | |
| 2092 | static FunctionDecl * |
| 2093 | Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
| 2094 | SourceLocation NLoc, DeclarationName N, QualType T, |
| 2095 | TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin = false, |
| 2096 | bool isInlineSpecified = false, bool hasWrittenPrototype = true, |
| 2097 | ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified, |
| 2098 | Expr *TrailingRequiresClause = nullptr) { |
| 2099 | DeclarationNameInfo NameInfo(N, NLoc); |
| 2100 | return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, SC, |
| 2101 | UsesFPIntrin, isInlineSpecified, |
| 2102 | hasWrittenPrototype, ConstexprKind, |
| 2103 | TrailingRequiresClause); |
| 2104 | } |
| 2105 | |
| 2106 | static FunctionDecl * |
| 2107 | Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
| 2108 | const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, |
| 2109 | StorageClass SC, bool UsesFPIntrin, bool isInlineSpecified, |
| 2110 | bool hasWrittenPrototype, ConstexprSpecKind ConstexprKind, |
| 2111 | Expr *TrailingRequiresClause); |
| 2112 | |
| 2113 | static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 2114 | |
| 2115 | DeclarationNameInfo getNameInfo() const { |
| 2116 | return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); |
| 2117 | } |
| 2118 | |
| 2119 | void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, |
| 2120 | bool Qualified) const override; |
| 2121 | |
| 2122 | void setRangeEnd(SourceLocation E) { EndRangeLoc = E; } |
| 2123 | |
| 2124 | /// Returns the location of the ellipsis of a variadic function. |
| 2125 | SourceLocation getEllipsisLoc() const { |
| 2126 | const auto *FPT = getType()->getAs<FunctionProtoType>(); |
| 2127 | if (FPT && FPT->isVariadic()) |
| 2128 | return FPT->getEllipsisLoc(); |
| 2129 | return SourceLocation(); |
| 2130 | } |
| 2131 | |
| 2132 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
| 2133 | |
| 2134 | // Function definitions. |
| 2135 | // |
| 2136 | // A function declaration may be: |
| 2137 | // - a non defining declaration, |
| 2138 | // - a definition. A function may be defined because: |
| 2139 | // - it has a body, or will have it in the case of late parsing. |
| 2140 | // - it has an uninstantiated body. The body does not exist because the |
| 2141 | // function is not used yet, but the declaration is considered a |
| 2142 | // definition and does not allow other definition of this function. |
| 2143 | // - it does not have a user specified body, but it does not allow |
| 2144 | // redefinition, because it is deleted/defaulted or is defined through |
| 2145 | // some other mechanism (alias, ifunc). |
| 2146 | |
| 2147 | /// Returns true if the function has a body. |
| 2148 | /// |
| 2149 | /// The function body might be in any of the (re-)declarations of this |
| 2150 | /// function. The variant that accepts a FunctionDecl pointer will set that |
| 2151 | /// function declaration to the actual declaration containing the body (if |
| 2152 | /// there is one). |
| 2153 | bool hasBody(const FunctionDecl *&Definition) const; |
| 2154 | |
| 2155 | bool hasBody() const override { |
| 2156 | const FunctionDecl* Definition; |
| 2157 | return hasBody(Definition); |
| 2158 | } |
| 2159 | |
| 2160 | /// Returns whether the function has a trivial body that does not require any |
| 2161 | /// specific codegen. |
| 2162 | bool hasTrivialBody() const; |
| 2163 | |
| 2164 | /// Returns true if the function has a definition that does not need to be |
| 2165 | /// instantiated. |
| 2166 | /// |
| 2167 | /// The variant that accepts a FunctionDecl pointer will set that function |
| 2168 | /// declaration to the declaration that is a definition (if there is one). |
| 2169 | /// |
| 2170 | /// \param CheckForPendingFriendDefinition If \c true, also check for friend |
| 2171 | /// declarations that were instantiated from function definitions. |
| 2172 | /// Such a declaration behaves as if it is a definition for the |
| 2173 | /// purpose of redefinition checking, but isn't actually a "real" |
| 2174 | /// definition until its body is instantiated. |
| 2175 | bool isDefined(const FunctionDecl *&Definition, |
| 2176 | bool CheckForPendingFriendDefinition = false) const; |
| 2177 | |
| 2178 | bool isDefined() const { |
| 2179 | const FunctionDecl* Definition; |
| 2180 | return isDefined(Definition); |
| 2181 | } |
| 2182 | |
| 2183 | /// Get the definition for this declaration. |
| 2184 | FunctionDecl *getDefinition() { |
| 2185 | const FunctionDecl *Definition; |
| 2186 | if (isDefined(Definition)) |
| 2187 | return const_cast<FunctionDecl *>(Definition); |
| 2188 | return nullptr; |
| 2189 | } |
| 2190 | const FunctionDecl *getDefinition() const { |
| 2191 | return const_cast<FunctionDecl *>(this)->getDefinition(); |
| 2192 | } |
| 2193 | |
| 2194 | /// Retrieve the body (definition) of the function. The function body might be |
| 2195 | /// in any of the (re-)declarations of this function. The variant that accepts |
| 2196 | /// a FunctionDecl pointer will set that function declaration to the actual |
| 2197 | /// declaration containing the body (if there is one). |
| 2198 | /// NOTE: For checking if there is a body, use hasBody() instead, to avoid |
| 2199 | /// unnecessary AST de-serialization of the body. |
| 2200 | Stmt *getBody(const FunctionDecl *&Definition) const; |
| 2201 | |
| 2202 | Stmt *getBody() const override { |
| 2203 | const FunctionDecl* Definition; |
| 2204 | return getBody(Definition); |
| 2205 | } |
| 2206 | |
| 2207 | /// Returns whether this specific declaration of the function is also a |
| 2208 | /// definition that does not contain uninstantiated body. |
| 2209 | /// |
| 2210 | /// This does not determine whether the function has been defined (e.g., in a |
| 2211 | /// previous definition); for that information, use isDefined. |
| 2212 | /// |
| 2213 | /// Note: the function declaration does not become a definition until the |
| 2214 | /// parser reaches the definition, if called before, this function will return |
| 2215 | /// `false`. |
| 2216 | bool isThisDeclarationADefinition() const { |
| 2217 | return isDeletedAsWritten() || isDefaulted() || |
| 2218 | doesThisDeclarationHaveABody() || hasSkippedBody() || |
| 2219 | willHaveBody() || hasDefiningAttr(); |
| 2220 | } |
| 2221 | |
| 2222 | /// Determine whether this specific declaration of the function is a friend |
| 2223 | /// declaration that was instantiated from a function definition. Such |
| 2224 | /// declarations behave like definitions in some contexts. |
| 2225 | bool isThisDeclarationInstantiatedFromAFriendDefinition() const; |
| 2226 | |
| 2227 | /// Returns whether this specific declaration of the function has a body. |
| 2228 | bool doesThisDeclarationHaveABody() const { |
| 2229 | return (!FunctionDeclBits.HasDefaultedFunctionInfo && Body) || |
| 2230 | isLateTemplateParsed(); |
| 2231 | } |
| 2232 | |
| 2233 | void setBody(Stmt *B); |
| 2234 | void setLazyBody(uint64_t Offset) { |
| 2235 | FunctionDeclBits.HasDefaultedFunctionInfo = false; |
| 2236 | Body = LazyDeclStmtPtr(Offset); |
| 2237 | } |
| 2238 | |
| 2239 | void setDefaultedFunctionInfo(DefaultedFunctionInfo *Info); |
| 2240 | DefaultedFunctionInfo *getDefaultedFunctionInfo() const; |
| 2241 | |
| 2242 | /// Whether this function is variadic. |
| 2243 | bool isVariadic() const; |
| 2244 | |
| 2245 | /// Whether this function is marked as virtual explicitly. |
| 2246 | bool isVirtualAsWritten() const { |
| 2247 | return FunctionDeclBits.IsVirtualAsWritten; |
| 2248 | } |
| 2249 | |
| 2250 | /// State that this function is marked as virtual explicitly. |
| 2251 | void setVirtualAsWritten(bool V) { FunctionDeclBits.IsVirtualAsWritten = V; } |
| 2252 | |
| 2253 | /// Whether this virtual function is pure, i.e. makes the containing class |
| 2254 | /// abstract. |
| 2255 | bool isPure() const { return FunctionDeclBits.IsPure; } |
| 2256 | void setPure(bool P = true); |
| 2257 | |
| 2258 | /// Whether this templated function will be late parsed. |
| 2259 | bool isLateTemplateParsed() const { |
| 2260 | return FunctionDeclBits.IsLateTemplateParsed; |
| 2261 | } |
| 2262 | |
| 2263 | /// State that this templated function will be late parsed. |
| 2264 | void setLateTemplateParsed(bool ILT = true) { |
| 2265 | FunctionDeclBits.IsLateTemplateParsed = ILT; |
| 2266 | } |
| 2267 | |
| 2268 | /// Whether this function is "trivial" in some specialized C++ senses. |
| 2269 | /// Can only be true for default constructors, copy constructors, |
| 2270 | /// copy assignment operators, and destructors. Not meaningful until |
| 2271 | /// the class has been fully built by Sema. |
| 2272 | bool isTrivial() const { return FunctionDeclBits.IsTrivial; } |
| 2273 | void setTrivial(bool IT) { FunctionDeclBits.IsTrivial = IT; } |
| 2274 | |
| 2275 | bool isTrivialForCall() const { return FunctionDeclBits.IsTrivialForCall; } |
| 2276 | void setTrivialForCall(bool IT) { FunctionDeclBits.IsTrivialForCall = IT; } |
| 2277 | |
| 2278 | /// Whether this function is defaulted. Valid for e.g. |
| 2279 | /// special member functions, defaulted comparisions (not methods!). |
| 2280 | bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; } |
| 2281 | void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; } |
| 2282 | |
| 2283 | /// Whether this function is explicitly defaulted. |
| 2284 | bool isExplicitlyDefaulted() const { |
| 2285 | return FunctionDeclBits.IsExplicitlyDefaulted; |
| 2286 | } |
| 2287 | |
| 2288 | /// State that this function is explicitly defaulted. |
| 2289 | void setExplicitlyDefaulted(bool ED = true) { |
| 2290 | FunctionDeclBits.IsExplicitlyDefaulted = ED; |
| 2291 | } |
| 2292 | |
| 2293 | SourceLocation getDefaultLoc() const { |
| 2294 | return isExplicitlyDefaulted() ? DefaultKWLoc : SourceLocation(); |
| 2295 | } |
| 2296 | |
| 2297 | void setDefaultLoc(SourceLocation NewLoc) { |
| 2298 | assert((NewLoc.isInvalid() || isExplicitlyDefaulted()) &&(static_cast <bool> ((NewLoc.isInvalid() || isExplicitlyDefaulted ()) && "Can't set default loc is function isn't explicitly defaulted" ) ? void (0) : __assert_fail ("(NewLoc.isInvalid() || isExplicitlyDefaulted()) && \"Can't set default loc is function isn't explicitly defaulted\"" , "clang/include/clang/AST/Decl.h", 2299, __extension__ __PRETTY_FUNCTION__ )) |
| 2299 | "Can't set default loc is function isn't explicitly defaulted")(static_cast <bool> ((NewLoc.isInvalid() || isExplicitlyDefaulted ()) && "Can't set default loc is function isn't explicitly defaulted" ) ? void (0) : __assert_fail ("(NewLoc.isInvalid() || isExplicitlyDefaulted()) && \"Can't set default loc is function isn't explicitly defaulted\"" , "clang/include/clang/AST/Decl.h", 2299, __extension__ __PRETTY_FUNCTION__ )); |
| 2300 | DefaultKWLoc = NewLoc; |
| 2301 | } |
| 2302 | |
| 2303 | /// True if this method is user-declared and was not |
| 2304 | /// deleted or defaulted on its first declaration. |
| 2305 | bool isUserProvided() const { |
| 2306 | auto *DeclAsWritten = this; |
| 2307 | if (FunctionDecl *Pattern = getTemplateInstantiationPattern()) |
| 2308 | DeclAsWritten = Pattern; |
| 2309 | return !(DeclAsWritten->isDeleted() || |
| 2310 | DeclAsWritten->getCanonicalDecl()->isDefaulted()); |
| 2311 | } |
| 2312 | |
| 2313 | bool isIneligibleOrNotSelected() const { |
| 2314 | return FunctionDeclBits.IsIneligibleOrNotSelected; |
| 2315 | } |
| 2316 | void setIneligibleOrNotSelected(bool II) { |
| 2317 | FunctionDeclBits.IsIneligibleOrNotSelected = II; |
| 2318 | } |
| 2319 | |
| 2320 | /// Whether falling off this function implicitly returns null/zero. |
| 2321 | /// If a more specific implicit return value is required, front-ends |
| 2322 | /// should synthesize the appropriate return statements. |
| 2323 | bool hasImplicitReturnZero() const { |
| 2324 | return FunctionDeclBits.HasImplicitReturnZero; |
| 2325 | } |
| 2326 | |
| 2327 | /// State that falling off this function implicitly returns null/zero. |
| 2328 | /// If a more specific implicit return value is required, front-ends |
| 2329 | /// should synthesize the appropriate return statements. |
| 2330 | void setHasImplicitReturnZero(bool IRZ) { |
| 2331 | FunctionDeclBits.HasImplicitReturnZero = IRZ; |
| 2332 | } |
| 2333 | |
| 2334 | /// Whether this function has a prototype, either because one |
| 2335 | /// was explicitly written or because it was "inherited" by merging |
| 2336 | /// a declaration without a prototype with a declaration that has a |
| 2337 | /// prototype. |
| 2338 | bool hasPrototype() const { |
| 2339 | return hasWrittenPrototype() || hasInheritedPrototype(); |
| 2340 | } |
| 2341 | |
| 2342 | /// Whether this function has a written prototype. |
| 2343 | bool hasWrittenPrototype() const { |
| 2344 | return FunctionDeclBits.HasWrittenPrototype; |
| 2345 | } |
| 2346 | |
| 2347 | /// State that this function has a written prototype. |
| 2348 | void setHasWrittenPrototype(bool P = true) { |
| 2349 | FunctionDeclBits.HasWrittenPrototype = P; |
| 2350 | } |
| 2351 | |
| 2352 | /// Whether this function inherited its prototype from a |
| 2353 | /// previous declaration. |
| 2354 | bool hasInheritedPrototype() const { |
| 2355 | return FunctionDeclBits.HasInheritedPrototype; |
| 2356 | } |
| 2357 | |
| 2358 | /// State that this function inherited its prototype from a |
| 2359 | /// previous declaration. |
| 2360 | void setHasInheritedPrototype(bool P = true) { |
| 2361 | FunctionDeclBits.HasInheritedPrototype = P; |
| 2362 | } |
| 2363 | |
| 2364 | /// Whether this is a (C++11) constexpr function or constexpr constructor. |
| 2365 | bool isConstexpr() const { |
| 2366 | return getConstexprKind() != ConstexprSpecKind::Unspecified; |
| 2367 | } |
| 2368 | void setConstexprKind(ConstexprSpecKind CSK) { |
| 2369 | FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(CSK); |
| 2370 | } |
| 2371 | ConstexprSpecKind getConstexprKind() const { |
| 2372 | return static_cast<ConstexprSpecKind>(FunctionDeclBits.ConstexprKind); |
| 2373 | } |
| 2374 | bool isConstexprSpecified() const { |
| 2375 | return getConstexprKind() == ConstexprSpecKind::Constexpr; |
| 2376 | } |
| 2377 | bool isConsteval() const { |
| 2378 | return getConstexprKind() == ConstexprSpecKind::Consteval; |
| 2379 | } |
| 2380 | |
| 2381 | /// Whether the instantiation of this function is pending. |
| 2382 | /// This bit is set when the decision to instantiate this function is made |
| 2383 | /// and unset if and when the function body is created. That leaves out |
| 2384 | /// cases where instantiation did not happen because the template definition |
| 2385 | /// was not seen in this TU. This bit remains set in those cases, under the |
| 2386 | /// assumption that the instantiation will happen in some other TU. |
| 2387 | bool instantiationIsPending() const { |
| 2388 | return FunctionDeclBits.InstantiationIsPending; |
| 2389 | } |
| 2390 | |
| 2391 | /// State that the instantiation of this function is pending. |
| 2392 | /// (see instantiationIsPending) |
| 2393 | void setInstantiationIsPending(bool IC) { |
| 2394 | FunctionDeclBits.InstantiationIsPending = IC; |
| 2395 | } |
| 2396 | |
| 2397 | /// Indicates the function uses __try. |
| 2398 | bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; } |
| 2399 | void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; } |
| 2400 | |
| 2401 | /// Whether this function has been deleted. |
| 2402 | /// |
| 2403 | /// A function that is "deleted" (via the C++0x "= delete" syntax) |
| 2404 | /// acts like a normal function, except that it cannot actually be |
| 2405 | /// called or have its address taken. Deleted functions are |
| 2406 | /// typically used in C++ overload resolution to attract arguments |
| 2407 | /// whose type or lvalue/rvalue-ness would permit the use of a |
| 2408 | /// different overload that would behave incorrectly. For example, |
| 2409 | /// one might use deleted functions to ban implicit conversion from |
| 2410 | /// a floating-point number to an Integer type: |
| 2411 | /// |
| 2412 | /// @code |
| 2413 | /// struct Integer { |
| 2414 | /// Integer(long); // construct from a long |
| 2415 | /// Integer(double) = delete; // no construction from float or double |
| 2416 | /// Integer(long double) = delete; // no construction from long double |
| 2417 | /// }; |
| 2418 | /// @endcode |
| 2419 | // If a function is deleted, its first declaration must be. |
| 2420 | bool isDeleted() const { |
| 2421 | return getCanonicalDecl()->FunctionDeclBits.IsDeleted; |
| 2422 | } |
| 2423 | |
| 2424 | bool isDeletedAsWritten() const { |
| 2425 | return FunctionDeclBits.IsDeleted && !isDefaulted(); |
| 2426 | } |
| 2427 | |
| 2428 | void setDeletedAsWritten(bool D = true) { FunctionDeclBits.IsDeleted = D; } |
| 2429 | |
| 2430 | /// Determines whether this function is "main", which is the |
| 2431 | /// entry point into an executable program. |
| 2432 | bool isMain() const; |
| 2433 | |
| 2434 | /// Determines whether this function is a MSVCRT user defined entry |
| 2435 | /// point. |
| 2436 | bool isMSVCRTEntryPoint() const; |
| 2437 | |
| 2438 | /// Determines whether this operator new or delete is one |
| 2439 | /// of the reserved global placement operators: |
| 2440 | /// void *operator new(size_t, void *); |
| 2441 | /// void *operator new[](size_t, void *); |
| 2442 | /// void operator delete(void *, void *); |
| 2443 | /// void operator delete[](void *, void *); |
| 2444 | /// These functions have special behavior under [new.delete.placement]: |
| 2445 | /// These functions are reserved, a C++ program may not define |
| 2446 | /// functions that displace the versions in the Standard C++ library. |
| 2447 | /// The provisions of [basic.stc.dynamic] do not apply to these |
| 2448 | /// reserved placement forms of operator new and operator delete. |
| 2449 | /// |
| 2450 | /// This function must be an allocation or deallocation function. |
| 2451 | bool isReservedGlobalPlacementOperator() const; |
| 2452 | |
| 2453 | /// Determines whether this function is one of the replaceable |
| 2454 | /// global allocation functions: |
| 2455 | /// void *operator new(size_t); |
| 2456 | /// void *operator new(size_t, const std::nothrow_t &) noexcept; |
| 2457 | /// void *operator new[](size_t); |
| 2458 | /// void *operator new[](size_t, const std::nothrow_t &) noexcept; |
| 2459 | /// void operator delete(void *) noexcept; |
| 2460 | /// void operator delete(void *, std::size_t) noexcept; [C++1y] |
| 2461 | /// void operator delete(void *, const std::nothrow_t &) noexcept; |
| 2462 | /// void operator delete[](void *) noexcept; |
| 2463 | /// void operator delete[](void *, std::size_t) noexcept; [C++1y] |
| 2464 | /// void operator delete[](void *, const std::nothrow_t &) noexcept; |
| 2465 | /// These functions have special behavior under C++1y [expr.new]: |
| 2466 | /// An implementation is allowed to omit a call to a replaceable global |
| 2467 | /// allocation function. [...] |
| 2468 | /// |
| 2469 | /// If this function is an aligned allocation/deallocation function, return |
| 2470 | /// the parameter number of the requested alignment through AlignmentParam. |
| 2471 | /// |
| 2472 | /// If this function is an allocation/deallocation function that takes |
| 2473 | /// the `std::nothrow_t` tag, return true through IsNothrow, |
| 2474 | bool isReplaceableGlobalAllocationFunction( |
| 2475 | std::optional<unsigned> *AlignmentParam = nullptr, |
| 2476 | bool *IsNothrow = nullptr) const; |
| 2477 | |
| 2478 | /// Determine if this function provides an inline implementation of a builtin. |
| 2479 | bool isInlineBuiltinDeclaration() const; |
| 2480 | |
| 2481 | /// Determine whether this is a destroying operator delete. |
| 2482 | bool isDestroyingOperatorDelete() const; |
| 2483 | |
| 2484 | /// Compute the language linkage. |
| 2485 | LanguageLinkage getLanguageLinkage() const; |
| 2486 | |
| 2487 | /// Determines whether this function is a function with |
| 2488 | /// external, C linkage. |
| 2489 | bool isExternC() const; |
| 2490 | |
| 2491 | /// Determines whether this function's context is, or is nested within, |
| 2492 | /// a C++ extern "C" linkage spec. |
| 2493 | bool isInExternCContext() const; |
| 2494 | |
| 2495 | /// Determines whether this function's context is, or is nested within, |
| 2496 | /// a C++ extern "C++" linkage spec. |
| 2497 | bool isInExternCXXContext() const; |
| 2498 | |
| 2499 | /// Determines whether this is a global function. |
| 2500 | bool isGlobal() const; |
| 2501 | |
| 2502 | /// Determines whether this function is known to be 'noreturn', through |
| 2503 | /// an attribute on its declaration or its type. |
| 2504 | bool isNoReturn() const; |
| 2505 | |
| 2506 | /// True if the function was a definition but its body was skipped. |
| 2507 | bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; } |
| 2508 | void setHasSkippedBody(bool Skipped = true) { |
| 2509 | FunctionDeclBits.HasSkippedBody = Skipped; |
| 2510 | } |
| 2511 | |
| 2512 | /// True if this function will eventually have a body, once it's fully parsed. |
| 2513 | bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; } |
| 2514 | void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; } |
| 2515 | |
| 2516 | /// True if this function is considered a multiversioned function. |
| 2517 | bool isMultiVersion() const { |
| 2518 | return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion; |
| 2519 | } |
| 2520 | |
| 2521 | /// Sets the multiversion state for this declaration and all of its |
| 2522 | /// redeclarations. |
| 2523 | void setIsMultiVersion(bool V = true) { |
| 2524 | getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V; |
| 2525 | } |
| 2526 | |
| 2527 | // Sets that this is a constrained friend where the constraint refers to an |
| 2528 | // enclosing template. |
| 2529 | void setFriendConstraintRefersToEnclosingTemplate(bool V = true) { |
| 2530 | getCanonicalDecl() |
| 2531 | ->FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = V; |
| 2532 | } |
| 2533 | // Indicates this function is a constrained friend, where the constraint |
| 2534 | // refers to an enclosing template for hte purposes of [temp.friend]p9. |
| 2535 | bool FriendConstraintRefersToEnclosingTemplate() const { |
| 2536 | return getCanonicalDecl() |
| 2537 | ->FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate; |
| 2538 | } |
| 2539 | |
| 2540 | /// Determine whether a function is a friend function that cannot be |
| 2541 | /// redeclared outside of its class, per C++ [temp.friend]p9. |
| 2542 | bool isMemberLikeConstrainedFriend() const; |
| 2543 | |
| 2544 | /// Gets the kind of multiversioning attribute this declaration has. Note that |
| 2545 | /// this can return a value even if the function is not multiversion, such as |
| 2546 | /// the case of 'target'. |
| 2547 | MultiVersionKind getMultiVersionKind() const; |
| 2548 | |
| 2549 | |
| 2550 | /// True if this function is a multiversioned dispatch function as a part of |
| 2551 | /// the cpu_specific/cpu_dispatch functionality. |
| 2552 | bool isCPUDispatchMultiVersion() const; |
| 2553 | /// True if this function is a multiversioned processor specific function as a |
| 2554 | /// part of the cpu_specific/cpu_dispatch functionality. |
| 2555 | bool isCPUSpecificMultiVersion() const; |
| 2556 | |
| 2557 | /// True if this function is a multiversioned dispatch function as a part of |
| 2558 | /// the target functionality. |
| 2559 | bool isTargetMultiVersion() const; |
| 2560 | |
| 2561 | /// True if this function is a multiversioned dispatch function as a part of |
| 2562 | /// the target-clones functionality. |
| 2563 | bool isTargetClonesMultiVersion() const; |
| 2564 | |
| 2565 | /// \brief Get the associated-constraints of this function declaration. |
| 2566 | /// Currently, this will either be a vector of size 1 containing the |
| 2567 | /// trailing-requires-clause or an empty vector. |
| 2568 | /// |
| 2569 | /// Use this instead of getTrailingRequiresClause for concepts APIs that |
| 2570 | /// accept an ArrayRef of constraint expressions. |
| 2571 | void getAssociatedConstraints(SmallVectorImpl<const Expr *> &AC) const { |
| 2572 | if (auto *TRC = getTrailingRequiresClause()) |
| 2573 | AC.push_back(TRC); |
| 2574 | } |
| 2575 | |
| 2576 | void setPreviousDeclaration(FunctionDecl * PrevDecl); |
| 2577 | |
| 2578 | FunctionDecl *getCanonicalDecl() override; |
| 2579 | const FunctionDecl *getCanonicalDecl() const { |
| 2580 | return const_cast<FunctionDecl*>(this)->getCanonicalDecl(); |
| 2581 | } |
| 2582 | |
| 2583 | unsigned getBuiltinID(bool ConsiderWrapperFunctions = false) const; |
| 2584 | |
| 2585 | // ArrayRef interface to parameters. |
| 2586 | ArrayRef<ParmVarDecl *> parameters() const { |
| 2587 | return {ParamInfo, getNumParams()}; |
| 2588 | } |
| 2589 | MutableArrayRef<ParmVarDecl *> parameters() { |
| 2590 | return {ParamInfo, getNumParams()}; |
| 2591 | } |
| 2592 | |
| 2593 | // Iterator access to formal parameters. |
| 2594 | using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator; |
| 2595 | using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator; |
| 2596 | |
| 2597 | bool param_empty() const { return parameters().empty(); } |
| 2598 | param_iterator param_begin() { return parameters().begin(); } |
| 2599 | param_iterator param_end() { return parameters().end(); } |
| 2600 | param_const_iterator param_begin() const { return parameters().begin(); } |
| 2601 | param_const_iterator param_end() const { return parameters().end(); } |
| 2602 | size_t param_size() const { return parameters().size(); } |
| 2603 | |
| 2604 | /// Return the number of parameters this function must have based on its |
| 2605 | /// FunctionType. This is the length of the ParamInfo array after it has been |
| 2606 | /// created. |
| 2607 | unsigned getNumParams() const; |
| 2608 | |
| 2609 | const ParmVarDecl *getParamDecl(unsigned i) const { |
| 2610 | assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #" ) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "clang/include/clang/AST/Decl.h", 2610, __extension__ __PRETTY_FUNCTION__ )); |
| 2611 | return ParamInfo[i]; |
| 2612 | } |
| 2613 | ParmVarDecl *getParamDecl(unsigned i) { |
| 2614 | assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #" ) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "clang/include/clang/AST/Decl.h", 2614, __extension__ __PRETTY_FUNCTION__ )); |
| 2615 | return ParamInfo[i]; |
| 2616 | } |
| 2617 | void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { |
| 2618 | setParams(getASTContext(), NewParamInfo); |
| 2619 | } |
| 2620 | |
| 2621 | /// Returns the minimum number of arguments needed to call this function. This |
| 2622 | /// may be fewer than the number of function parameters, if some of the |
| 2623 | /// parameters have default arguments (in C++). |
| 2624 | unsigned getMinRequiredArguments() const; |
| 2625 | |
| 2626 | /// Determine whether this function has a single parameter, or multiple |
| 2627 | /// parameters where all but the first have default arguments. |
| 2628 | /// |
| 2629 | /// This notion is used in the definition of copy/move constructors and |
| 2630 | /// initializer list constructors. Note that, unlike getMinRequiredArguments, |
| 2631 | /// parameter packs are not treated specially here. |
| 2632 | bool hasOneParamOrDefaultArgs() const; |
| 2633 | |
| 2634 | /// Find the source location information for how the type of this function |
| 2635 | /// was written. May be absent (for example if the function was declared via |
| 2636 | /// a typedef) and may contain a different type from that of the function |
| 2637 | /// (for example if the function type was adjusted by an attribute). |
| 2638 | FunctionTypeLoc getFunctionTypeLoc() const; |
| 2639 | |
| 2640 | QualType getReturnType() const { |
| 2641 | return getType()->castAs<FunctionType>()->getReturnType(); |
| 2642 | } |
| 2643 | |
| 2644 | /// Attempt to compute an informative source range covering the |
| 2645 | /// function return type. This may omit qualifiers and other information with |
| 2646 | /// limited representation in the AST. |
| 2647 | SourceRange getReturnTypeSourceRange() const; |
| 2648 | |
| 2649 | /// Attempt to compute an informative source range covering the |
| 2650 | /// function parameters, including the ellipsis of a variadic function. |
| 2651 | /// The source range excludes the parentheses, and is invalid if there are |
| 2652 | /// no parameters and no ellipsis. |
| 2653 | SourceRange getParametersSourceRange() const; |
| 2654 | |
| 2655 | /// Get the declared return type, which may differ from the actual return |
| 2656 | /// type if the return type is deduced. |
| 2657 | QualType getDeclaredReturnType() const { |
| 2658 | auto *TSI = getTypeSourceInfo(); |
| 2659 | QualType T = TSI ? TSI->getType() : getType(); |
| 2660 | return T->castAs<FunctionType>()->getReturnType(); |
| 2661 | } |
| 2662 | |
| 2663 | /// Gets the ExceptionSpecificationType as declared. |
| 2664 | ExceptionSpecificationType getExceptionSpecType() const { |
| 2665 | auto *TSI = getTypeSourceInfo(); |
| 2666 | QualType T = TSI ? TSI->getType() : getType(); |
| 2667 | const auto *FPT = T->getAs<FunctionProtoType>(); |
| 2668 | return FPT ? FPT->getExceptionSpecType() : EST_None; |
| 2669 | } |
| 2670 | |
| 2671 | /// Attempt to compute an informative source range covering the |
| 2672 | /// function exception specification, if any. |
| 2673 | SourceRange getExceptionSpecSourceRange() const; |
| 2674 | |
| 2675 | /// Determine the type of an expression that calls this function. |
| 2676 | QualType getCallResultType() const { |
| 2677 | return getType()->castAs<FunctionType>()->getCallResultType( |
| 2678 | getASTContext()); |
| 2679 | } |
| 2680 | |
| 2681 | /// Returns the storage class as written in the source. For the |
| 2682 | /// computed linkage of symbol, see getLinkage. |
| 2683 | StorageClass getStorageClass() const { |
| 2684 | return static_cast<StorageClass>(FunctionDeclBits.SClass); |
| 2685 | } |
| 2686 | |
| 2687 | /// Sets the storage class as written in the source. |
| 2688 | void setStorageClass(StorageClass SClass) { |
| 2689 | FunctionDeclBits.SClass = SClass; |
| 2690 | } |
| 2691 | |
| 2692 | /// Determine whether the "inline" keyword was specified for this |
| 2693 | /// function. |
| 2694 | bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; } |
| 2695 | |
| 2696 | /// Set whether the "inline" keyword was specified for this function. |
| 2697 | void setInlineSpecified(bool I) { |
| 2698 | FunctionDeclBits.IsInlineSpecified = I; |
| 2699 | FunctionDeclBits.IsInline = I; |
| 2700 | } |
| 2701 | |
| 2702 | /// Determine whether the function was declared in source context |
| 2703 | /// that requires constrained FP intrinsics |
| 2704 | bool UsesFPIntrin() const { return FunctionDeclBits.UsesFPIntrin; } |
| 2705 | |
| 2706 | /// Set whether the function was declared in source context |
| 2707 | /// that requires constrained FP intrinsics |
| 2708 | void setUsesFPIntrin(bool I) { FunctionDeclBits.UsesFPIntrin = I; } |
| 2709 | |
| 2710 | /// Flag that this function is implicitly inline. |
| 2711 | void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; } |
| 2712 | |
| 2713 | /// Determine whether this function should be inlined, because it is |
| 2714 | /// either marked "inline" or "constexpr" or is a member function of a class |
| 2715 | /// that was defined in the class body. |
| 2716 | bool isInlined() const { return FunctionDeclBits.IsInline; } |
| 2717 | |
| 2718 | bool isInlineDefinitionExternallyVisible() const; |
| 2719 | |
| 2720 | bool isMSExternInline() const; |
| 2721 | |
| 2722 | bool doesDeclarationForceExternallyVisibleDefinition() const; |
| 2723 | |
| 2724 | bool isStatic() const { return getStorageClass() == SC_Static; } |
| 2725 | |
| 2726 | /// Whether this function declaration represents an C++ overloaded |
| 2727 | /// operator, e.g., "operator+". |
| 2728 | bool isOverloadedOperator() const { |
| 2729 | return getOverloadedOperator() != OO_None; |
| 2730 | } |
| 2731 | |
| 2732 | OverloadedOperatorKind getOverloadedOperator() const; |
| 2733 | |
| 2734 | const IdentifierInfo *getLiteralIdentifier() const; |
| 2735 | |
| 2736 | /// If this function is an instantiation of a member function |
| 2737 | /// of a class template specialization, retrieves the function from |
| 2738 | /// which it was instantiated. |
| 2739 | /// |
| 2740 | /// This routine will return non-NULL for (non-templated) member |
| 2741 | /// functions of class templates and for instantiations of function |
| 2742 | /// templates. For example, given: |
| 2743 | /// |
| 2744 | /// \code |
| 2745 | /// template<typename T> |
| 2746 | /// struct X { |
| 2747 | /// void f(T); |
| 2748 | /// }; |
| 2749 | /// \endcode |
| 2750 | /// |
| 2751 | /// The declaration for X<int>::f is a (non-templated) FunctionDecl |
| 2752 | /// whose parent is the class template specialization X<int>. For |
| 2753 | /// this declaration, getInstantiatedFromFunction() will return |
| 2754 | /// the FunctionDecl X<T>::A. When a complete definition of |
| 2755 | /// X<int>::A is required, it will be instantiated from the |
| 2756 | /// declaration returned by getInstantiatedFromMemberFunction(). |
| 2757 | FunctionDecl *getInstantiatedFromMemberFunction() const; |
| 2758 | |
| 2759 | /// What kind of templated function this is. |
| 2760 | TemplatedKind getTemplatedKind() const; |
| 2761 | |
| 2762 | /// If this function is an instantiation of a member function of a |
| 2763 | /// class template specialization, retrieves the member specialization |
| 2764 | /// information. |
| 2765 | MemberSpecializationInfo *getMemberSpecializationInfo() const; |
| 2766 | |
| 2767 | /// Specify that this record is an instantiation of the |
| 2768 | /// member function FD. |
| 2769 | void setInstantiationOfMemberFunction(FunctionDecl *FD, |
| 2770 | TemplateSpecializationKind TSK) { |
| 2771 | setInstantiationOfMemberFunction(getASTContext(), FD, TSK); |
| 2772 | } |
| 2773 | |
| 2774 | /// Specify that this function declaration was instantiated from a |
| 2775 | /// FunctionDecl FD. This is only used if this is a function declaration |
| 2776 | /// declared locally inside of a function template. |
| 2777 | void setInstantiatedFromDecl(FunctionDecl *FD); |
| 2778 | |
| 2779 | FunctionDecl *getInstantiatedFromDecl() const; |
| 2780 | |
| 2781 | /// Retrieves the function template that is described by this |
| 2782 | /// function declaration. |
| 2783 | /// |
| 2784 | /// Every function template is represented as a FunctionTemplateDecl |
| 2785 | /// and a FunctionDecl (or something derived from FunctionDecl). The |
| 2786 | /// former contains template properties (such as the template |
| 2787 | /// parameter lists) while the latter contains the actual |
| 2788 | /// description of the template's |
| 2789 | /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the |
| 2790 | /// FunctionDecl that describes the function template, |
| 2791 | /// getDescribedFunctionTemplate() retrieves the |
| 2792 | /// FunctionTemplateDecl from a FunctionDecl. |
| 2793 | FunctionTemplateDecl *getDescribedFunctionTemplate() const; |
| 2794 | |
| 2795 | void setDescribedFunctionTemplate(FunctionTemplateDecl *Template); |
| 2796 | |
| 2797 | /// Determine whether this function is a function template |
| 2798 | /// specialization. |
| 2799 | bool isFunctionTemplateSpecialization() const { |
| 2800 | return getPrimaryTemplate() != nullptr; |
| 2801 | } |
| 2802 | |
| 2803 | /// If this function is actually a function template specialization, |
| 2804 | /// retrieve information about this function template specialization. |
| 2805 | /// Otherwise, returns NULL. |
| 2806 | FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const; |
| 2807 | |
| 2808 | /// Determines whether this function is a function template |
| 2809 | /// specialization or a member of a class template specialization that can |
| 2810 | /// be implicitly instantiated. |
| 2811 | bool isImplicitlyInstantiable() const; |
| 2812 | |
| 2813 | /// Determines if the given function was instantiated from a |
| 2814 | /// function template. |
| 2815 | bool isTemplateInstantiation() const; |
| 2816 | |
| 2817 | /// Retrieve the function declaration from which this function could |
| 2818 | /// be instantiated, if it is an instantiation (rather than a non-template |
| 2819 | /// or a specialization, for example). |
| 2820 | /// |
| 2821 | /// If \p ForDefinition is \c false, explicit specializations will be treated |
| 2822 | /// as if they were implicit instantiations. This will then find the pattern |
| 2823 | /// corresponding to non-definition portions of the declaration, such as |
| 2824 | /// default arguments and the exception specification. |
| 2825 | FunctionDecl * |
| 2826 | getTemplateInstantiationPattern(bool ForDefinition = true) const; |
| 2827 | |
| 2828 | /// Retrieve the primary template that this function template |
| 2829 | /// specialization either specializes or was instantiated from. |
| 2830 | /// |
| 2831 | /// If this function declaration is not a function template specialization, |
| 2832 | /// returns NULL. |
| 2833 | FunctionTemplateDecl *getPrimaryTemplate() const; |
| 2834 | |
| 2835 | /// Retrieve the template arguments used to produce this function |
| 2836 | /// template specialization from the primary template. |
| 2837 | /// |
| 2838 | /// If this function declaration is not a function template specialization, |
| 2839 | /// returns NULL. |
| 2840 | const TemplateArgumentList *getTemplateSpecializationArgs() const; |
| 2841 | |
| 2842 | /// Retrieve the template argument list as written in the sources, |
| 2843 | /// if any. |
| 2844 | /// |
| 2845 | /// If this function declaration is not a function template specialization |
| 2846 | /// or if it had no explicit template argument list, returns NULL. |
| 2847 | /// Note that it an explicit template argument list may be written empty, |
| 2848 | /// e.g., template<> void foo<>(char* s); |
| 2849 | const ASTTemplateArgumentListInfo* |
| 2850 | getTemplateSpecializationArgsAsWritten() const; |
| 2851 | |
| 2852 | /// Specify that this function declaration is actually a function |
| 2853 | /// template specialization. |
| 2854 | /// |
| 2855 | /// \param Template the function template that this function template |
| 2856 | /// specialization specializes. |
| 2857 | /// |
| 2858 | /// \param TemplateArgs the template arguments that produced this |
| 2859 | /// function template specialization from the template. |
| 2860 | /// |
| 2861 | /// \param InsertPos If non-NULL, the position in the function template |
| 2862 | /// specialization set where the function template specialization data will |
| 2863 | /// be inserted. |
| 2864 | /// |
| 2865 | /// \param TSK the kind of template specialization this is. |
| 2866 | /// |
| 2867 | /// \param TemplateArgsAsWritten location info of template arguments. |
| 2868 | /// |
| 2869 | /// \param PointOfInstantiation point at which the function template |
| 2870 | /// specialization was first instantiated. |
| 2871 | void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template, |
| 2872 | const TemplateArgumentList *TemplateArgs, |
| 2873 | void *InsertPos, |
| 2874 | TemplateSpecializationKind TSK = TSK_ImplicitInstantiation, |
| 2875 | const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr, |
| 2876 | SourceLocation PointOfInstantiation = SourceLocation()) { |
| 2877 | setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs, |
| 2878 | InsertPos, TSK, TemplateArgsAsWritten, |
| 2879 | PointOfInstantiation); |
| 2880 | } |
| 2881 | |
| 2882 | /// Specifies that this function declaration is actually a |
| 2883 | /// dependent function template specialization. |
| 2884 | void setDependentTemplateSpecialization(ASTContext &Context, |
| 2885 | const UnresolvedSetImpl &Templates, |
| 2886 | const TemplateArgumentListInfo &TemplateArgs); |
| 2887 | |
| 2888 | DependentFunctionTemplateSpecializationInfo * |
| 2889 | getDependentSpecializationInfo() const; |
| 2890 | |
| 2891 | /// Determine what kind of template instantiation this function |
| 2892 | /// represents. |
| 2893 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
| 2894 | |
| 2895 | /// Determine the kind of template specialization this function represents |
| 2896 | /// for the purpose of template instantiation. |
| 2897 | TemplateSpecializationKind |
| 2898 | getTemplateSpecializationKindForInstantiation() const; |
| 2899 | |
| 2900 | /// Determine what kind of template instantiation this function |
| 2901 | /// represents. |
| 2902 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
| 2903 | SourceLocation PointOfInstantiation = SourceLocation()); |
| 2904 | |
| 2905 | /// Retrieve the (first) point of instantiation of a function template |
| 2906 | /// specialization or a member of a class template specialization. |
| 2907 | /// |
| 2908 | /// \returns the first point of instantiation, if this function was |
| 2909 | /// instantiated from a template; otherwise, returns an invalid source |
| 2910 | /// location. |
| 2911 | SourceLocation getPointOfInstantiation() const; |
| 2912 | |
| 2913 | /// Determine whether this is or was instantiated from an out-of-line |
| 2914 | /// definition of a member function. |
| 2915 | bool isOutOfLine() const override; |
| 2916 | |
| 2917 | /// Identify a memory copying or setting function. |
| 2918 | /// If the given function is a memory copy or setting function, returns |
| 2919 | /// the corresponding Builtin ID. If the function is not a memory function, |
| 2920 | /// returns 0. |
| 2921 | unsigned getMemoryFunctionKind() const; |
| 2922 | |
| 2923 | /// Returns ODRHash of the function. This value is calculated and |
| 2924 | /// stored on first call, then the stored value returned on the other calls. |
| 2925 | unsigned getODRHash(); |
| 2926 | |
| 2927 | /// Returns cached ODRHash of the function. This must have been previously |
| 2928 | /// computed and stored. |
| 2929 | unsigned getODRHash() const; |
| 2930 | |
| 2931 | // Implement isa/cast/dyncast/etc. |
| 2932 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 2933 | static bool classofKind(Kind K) { |
| 2934 | return K >= firstFunction && K <= lastFunction; |
| 2935 | } |
| 2936 | static DeclContext *castToDeclContext(const FunctionDecl *D) { |
| 2937 | return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D)); |
| 2938 | } |
| 2939 | static FunctionDecl *castFromDeclContext(const DeclContext *DC) { |
| 2940 | return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC)); |
| 2941 | } |
| 2942 | }; |
| 2943 | |
| 2944 | /// Represents a member of a struct/union/class. |
| 2945 | class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> { |
| 2946 | /// The kinds of value we can store in StorageKind. |
| 2947 | /// |
| 2948 | /// Note that this is compatible with InClassInitStyle except for |
| 2949 | /// ISK_CapturedVLAType. |
| 2950 | enum InitStorageKind { |
| 2951 | /// If the pointer is null, there's nothing special. Otherwise, |
| 2952 | /// this is a bitfield and the pointer is the Expr* storing the |
| 2953 | /// bit-width. |
| 2954 | ISK_NoInit = (unsigned) ICIS_NoInit, |
| 2955 | |
| 2956 | /// The pointer is an (optional due to delayed parsing) Expr* |
| 2957 | /// holding the copy-initializer. |
| 2958 | ISK_InClassCopyInit = (unsigned) ICIS_CopyInit, |
| 2959 | |
| 2960 | /// The pointer is an (optional due to delayed parsing) Expr* |
| 2961 | /// holding the list-initializer. |
| 2962 | ISK_InClassListInit = (unsigned) ICIS_ListInit, |
| 2963 | |
| 2964 | /// The pointer is a VariableArrayType* that's been captured; |
| 2965 | /// the enclosing context is a lambda or captured statement. |
| 2966 | ISK_CapturedVLAType, |
| 2967 | }; |
| 2968 | |
| 2969 | unsigned BitField : 1; |
| 2970 | unsigned Mutable : 1; |
| 2971 | unsigned StorageKind : 2; |
| 2972 | mutable unsigned CachedFieldIndex : 28; |
| 2973 | |
| 2974 | /// If this is a bitfield with a default member initializer, this |
| 2975 | /// structure is used to represent the two expressions. |
| 2976 | struct InitAndBitWidthStorage { |
| 2977 | LazyDeclStmtPtr Init; |
| 2978 | Expr *BitWidth; |
| 2979 | }; |
| 2980 | |
| 2981 | /// Storage for either the bit-width, the in-class initializer, or |
| 2982 | /// both (via InitAndBitWidth), or the captured variable length array bound. |
| 2983 | /// |
| 2984 | /// If the storage kind is ISK_InClassCopyInit or |
| 2985 | /// ISK_InClassListInit, but the initializer is null, then this |
| 2986 | /// field has an in-class initializer that has not yet been parsed |
| 2987 | /// and attached. |
| 2988 | // FIXME: Tail-allocate this to reduce the size of FieldDecl in the |
| 2989 | // overwhelmingly common case that we have none of these things. |
| 2990 | union { |
| 2991 | // Active member if ISK is not ISK_CapturedVLAType and BitField is false. |
| 2992 | LazyDeclStmtPtr Init; |
| 2993 | // Active member if ISK is ISK_NoInit and BitField is true. |
| 2994 | Expr *BitWidth; |
| 2995 | // Active member if ISK is ISK_InClass*Init and BitField is true. |
| 2996 | InitAndBitWidthStorage *InitAndBitWidth; |
| 2997 | // Active member if ISK is ISK_CapturedVLAType. |
| 2998 | const VariableArrayType *CapturedVLAType; |
| 2999 | }; |
| 3000 | |
| 3001 | protected: |
| 3002 | FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, |
| 3003 | SourceLocation IdLoc, IdentifierInfo *Id, QualType T, |
| 3004 | TypeSourceInfo *TInfo, Expr *BW, bool Mutable, |
| 3005 | InClassInitStyle InitStyle) |
| 3006 | : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), BitField(false), |
| 3007 | Mutable(Mutable), StorageKind((InitStorageKind)InitStyle), |
| 3008 | CachedFieldIndex(0), Init() { |
| 3009 | if (BW) |
| 3010 | setBitWidth(BW); |
| 3011 | } |
| 3012 | |
| 3013 | public: |
| 3014 | friend class ASTDeclReader; |
| 3015 | friend class ASTDeclWriter; |
| 3016 | |
| 3017 | static FieldDecl *Create(const ASTContext &C, DeclContext *DC, |
| 3018 | SourceLocation StartLoc, SourceLocation IdLoc, |
| 3019 | IdentifierInfo *Id, QualType T, |
| 3020 | TypeSourceInfo *TInfo, Expr *BW, bool Mutable, |
| 3021 | InClassInitStyle InitStyle); |
| 3022 | |
| 3023 | static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 3024 | |
| 3025 | /// Returns the index of this field within its record, |
| 3026 | /// as appropriate for passing to ASTRecordLayout::getFieldOffset. |
| 3027 | unsigned getFieldIndex() const; |
| 3028 | |
| 3029 | /// Determines whether this field is mutable (C++ only). |
| 3030 | bool isMutable() const { return Mutable; } |
| 3031 | |
| 3032 | /// Determines whether this field is a bitfield. |
| 3033 | bool isBitField() const { return BitField; } |
| 3034 | |
| 3035 | /// Determines whether this is an unnamed bitfield. |
| 3036 | bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); } |
| 3037 | |
| 3038 | /// Determines whether this field is a |
| 3039 | /// representative for an anonymous struct or union. Such fields are |
| 3040 | /// unnamed and are implicitly generated by the implementation to |
| 3041 | /// store the data for the anonymous union or struct. |
| 3042 | bool isAnonymousStructOrUnion() const; |
| 3043 | |
| 3044 | Expr *getBitWidth() const { |
| 3045 | if (!BitField) |
| 3046 | return nullptr; |
| 3047 | return hasInClassInitializer() ? InitAndBitWidth->BitWidth : BitWidth; |
| 3048 | } |
| 3049 | |
| 3050 | unsigned getBitWidthValue(const ASTContext &Ctx) const; |
| 3051 | |
| 3052 | /// Set the bit-field width for this member. |
| 3053 | // Note: used by some clients (i.e., do not remove it). |
| 3054 | void setBitWidth(Expr *Width) { |
| 3055 | assert(!hasCapturedVLAType() && !BitField &&(static_cast <bool> (!hasCapturedVLAType() && ! BitField && "bit width or captured type already set") ? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\"" , "clang/include/clang/AST/Decl.h", 3056, __extension__ __PRETTY_FUNCTION__ )) |
| 3056 | "bit width or captured type already set")(static_cast <bool> (!hasCapturedVLAType() && ! BitField && "bit width or captured type already set") ? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\"" , "clang/include/clang/AST/Decl.h", 3056, __extension__ __PRETTY_FUNCTION__ )); |
| 3057 | assert(Width && "no bit width specified")(static_cast <bool> (Width && "no bit width specified" ) ? void (0) : __assert_fail ("Width && \"no bit width specified\"" , "clang/include/clang/AST/Decl.h", 3057, __extension__ __PRETTY_FUNCTION__ )); |
| 3058 | if (hasInClassInitializer()) |
| 3059 | InitAndBitWidth = |
| 3060 | new (getASTContext()) InitAndBitWidthStorage{Init, Width}; |
| 3061 | else |
| 3062 | BitWidth = Width; |
| 3063 | BitField = true; |
| 3064 | } |
| 3065 | |
| 3066 | /// Remove the bit-field width from this member. |
| 3067 | // Note: used by some clients (i.e., do not remove it). |
| 3068 | void removeBitWidth() { |
| 3069 | assert(isBitField() && "no bitfield width to remove")(static_cast <bool> (isBitField() && "no bitfield width to remove" ) ? void (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\"" , "clang/include/clang/AST/Decl.h", 3069, __extension__ __PRETTY_FUNCTION__ )); |
| 3070 | if (hasInClassInitializer()) { |
| 3071 | // Read the old initializer before we change the active union member. |
| 3072 | auto ExistingInit = InitAndBitWidth->Init; |
| 3073 | Init = ExistingInit; |
| 3074 | } |
| 3075 | BitField = false; |
| 3076 | } |
| 3077 | |
| 3078 | /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields |
| 3079 | /// at all and instead act as a separator between contiguous runs of other |
| 3080 | /// bit-fields. |
| 3081 | bool isZeroLengthBitField(const ASTContext &Ctx) const; |
| 3082 | |
| 3083 | /// Determine if this field is a subobject of zero size, that is, either a |
| 3084 | /// zero-length bit-field or a field of empty class type with the |
| 3085 | /// [[no_unique_address]] attribute. |
| 3086 | bool isZeroSize(const ASTContext &Ctx) const; |
| 3087 | |
| 3088 | /// Determine if this field is of potentially-overlapping class type, that |
| 3089 | /// is, subobject with the [[no_unique_address]] attribute |
| 3090 | bool isPotentiallyOverlapping() const; |
| 3091 | |
| 3092 | /// Get the kind of (C++11) default member initializer that this field has. |
| 3093 | InClassInitStyle getInClassInitStyle() const { |
| 3094 | return (StorageKind == ISK_CapturedVLAType ? ICIS_NoInit |
| 3095 | : (InClassInitStyle)StorageKind); |
| 3096 | } |
| 3097 | |
| 3098 | /// Determine whether this member has a C++11 default member initializer. |
| 3099 | bool hasInClassInitializer() const { |
| 3100 | return getInClassInitStyle() != ICIS_NoInit; |
| 3101 | } |
| 3102 | |
| 3103 | /// Determine whether getInClassInitializer() would return a non-null pointer |
| 3104 | /// without deserializing the initializer. |
| 3105 | bool hasNonNullInClassInitializer() const { |
| 3106 | return hasInClassInitializer() && (BitField ? InitAndBitWidth->Init : Init); |
| 3107 | } |
| 3108 | |
| 3109 | /// Get the C++11 default member initializer for this member, or null if one |
| 3110 | /// has not been set. If a valid declaration has a default member initializer, |
| 3111 | /// but this returns null, then we have not parsed and attached it yet. |
| 3112 | Expr *getInClassInitializer() const; |
| 3113 | |
| 3114 | /// Set the C++11 in-class initializer for this member. |
| 3115 | void setInClassInitializer(Expr *NewInit); |
| 3116 | |
| 3117 | private: |
| 3118 | void setLazyInClassInitializer(LazyDeclStmtPtr NewInit); |
| 3119 | |
| 3120 | public: |
| 3121 | /// Remove the C++11 in-class initializer from this member. |
| 3122 | void removeInClassInitializer() { |
| 3123 | assert(hasInClassInitializer() && "no initializer to remove")(static_cast <bool> (hasInClassInitializer() && "no initializer to remove") ? void (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\"" , "clang/include/clang/AST/Decl.h", 3123, __extension__ __PRETTY_FUNCTION__ )); |
| 3124 | StorageKind = ISK_NoInit; |
| 3125 | if (BitField) { |
| 3126 | // Read the bit width before we change the active union member. |
| 3127 | Expr *ExistingBitWidth = InitAndBitWidth->BitWidth; |
| 3128 | BitWidth = ExistingBitWidth; |
| 3129 | } |
| 3130 | } |
| 3131 | |
| 3132 | /// Determine whether this member captures the variable length array |
| 3133 | /// type. |
| 3134 | bool hasCapturedVLAType() const { |
| 3135 | return StorageKind == ISK_CapturedVLAType; |
| 3136 | } |
| 3137 | |
| 3138 | /// Get the captured variable length array type. |
| 3139 | const VariableArrayType *getCapturedVLAType() const { |
| 3140 | return hasCapturedVLAType() ? CapturedVLAType : nullptr; |
| 3141 | } |
| 3142 | |
| 3143 | /// Set the captured variable length array type for this field. |
| 3144 | void setCapturedVLAType(const VariableArrayType *VLAType); |
| 3145 | |
| 3146 | /// Returns the parent of this field declaration, which |
| 3147 | /// is the struct in which this field is defined. |
| 3148 | /// |
| 3149 | /// Returns null if this is not a normal class/struct field declaration, e.g. |
| 3150 | /// ObjCAtDefsFieldDecl, ObjCIvarDecl. |
| 3151 | const RecordDecl *getParent() const { |
| 3152 | return dyn_cast<RecordDecl>(getDeclContext()); |
| 3153 | } |
| 3154 | |
| 3155 | RecordDecl *getParent() { |
| 3156 | return dyn_cast<RecordDecl>(getDeclContext()); |
| 3157 | } |
| 3158 | |
| 3159 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
| 3160 | |
| 3161 | /// Retrieves the canonical declaration of this field. |
| 3162 | FieldDecl *getCanonicalDecl() override { return getFirstDecl(); } |
| 3163 | const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); } |
| 3164 | |
| 3165 | // Implement isa/cast/dyncast/etc. |
| 3166 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 3167 | static bool classofKind(Kind K) { return K >= firstField && K <= lastField; } |
| 3168 | }; |
| 3169 | |
| 3170 | /// An instance of this object exists for each enum constant |
| 3171 | /// that is defined. For example, in "enum X {a,b}", each of a/b are |
| 3172 | /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a |
| 3173 | /// TagType for the X EnumDecl. |
| 3174 | class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> { |
| 3175 | Stmt *Init; // an integer constant expression |
| 3176 | llvm::APSInt Val; // The value. |
| 3177 | |
| 3178 | protected: |
| 3179 | EnumConstantDecl(DeclContext *DC, SourceLocation L, |
| 3180 | IdentifierInfo *Id, QualType T, Expr *E, |
| 3181 | const llvm::APSInt &V) |
| 3182 | : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {} |
| 3183 | |
| 3184 | public: |
| 3185 | friend class StmtIteratorBase; |
| 3186 | |
| 3187 | static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC, |
| 3188 | SourceLocation L, IdentifierInfo *Id, |
| 3189 | QualType T, Expr *E, |
| 3190 | const llvm::APSInt &V); |
| 3191 | static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 3192 | |
| 3193 | const Expr *getInitExpr() const { return (const Expr*) Init; } |
| 3194 | Expr *getInitExpr() { return (Expr*) Init; } |
| 3195 | const llvm::APSInt &getInitVal() const { return Val; } |
| 3196 | |
| 3197 | void setInitExpr(Expr *E) { Init = (Stmt*) E; } |
| 3198 | void setInitVal(const llvm::APSInt &V) { Val = V; } |
| 3199 | |
| 3200 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
| 3201 | |
| 3202 | /// Retrieves the canonical declaration of this enumerator. |
| 3203 | EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); } |
| 3204 | const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); } |
| 3205 | |
| 3206 | // Implement isa/cast/dyncast/etc. |
| 3207 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 3208 | static bool classofKind(Kind K) { return K == EnumConstant; } |
| 3209 | }; |
| 3210 | |
| 3211 | /// Represents a field injected from an anonymous union/struct into the parent |
| 3212 | /// scope. These are always implicit. |
| 3213 | class IndirectFieldDecl : public ValueDecl, |
| 3214 | public Mergeable<IndirectFieldDecl> { |
| 3215 | NamedDecl **Chaining; |
| 3216 | unsigned ChainingSize; |
| 3217 | |
| 3218 | IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L, |
| 3219 | DeclarationName N, QualType T, |
| 3220 | MutableArrayRef<NamedDecl *> CH); |
| 3221 | |
| 3222 | void anchor() override; |
| 3223 | |
| 3224 | public: |
| 3225 | friend class ASTDeclReader; |
| 3226 | |
| 3227 | static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC, |
| 3228 | SourceLocation L, IdentifierInfo *Id, |
| 3229 | QualType T, llvm::MutableArrayRef<NamedDecl *> CH); |
| 3230 | |
| 3231 | static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 3232 | |
| 3233 | using chain_iterator = ArrayRef<NamedDecl *>::const_iterator; |
| 3234 | |
| 3235 | ArrayRef<NamedDecl *> chain() const { |
| 3236 | return llvm::ArrayRef(Chaining, ChainingSize); |
| 3237 | } |
| 3238 | chain_iterator chain_begin() const { return chain().begin(); } |
| 3239 | chain_iterator chain_end() const { return chain().end(); } |
| 3240 | |
| 3241 | unsigned getChainingSize() const { return ChainingSize; } |
| 3242 | |
| 3243 | FieldDecl *getAnonField() const { |
| 3244 | assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0) : __assert_fail ("chain().size() >= 2", "clang/include/clang/AST/Decl.h" , 3244, __extension__ __PRETTY_FUNCTION__)); |
| 3245 | return cast<FieldDecl>(chain().back()); |
| 3246 | } |
| 3247 | |
| 3248 | VarDecl *getVarDecl() const { |
| 3249 | assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0) : __assert_fail ("chain().size() >= 2", "clang/include/clang/AST/Decl.h" , 3249, __extension__ __PRETTY_FUNCTION__)); |
| 3250 | return dyn_cast<VarDecl>(chain().front()); |
| 3251 | } |
| 3252 | |
| 3253 | IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); } |
| 3254 | const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); } |
| 3255 | |
| 3256 | // Implement isa/cast/dyncast/etc. |
| 3257 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 3258 | static bool classofKind(Kind K) { return K == IndirectField; } |
| 3259 | }; |
| 3260 | |
| 3261 | /// Represents a declaration of a type. |
| 3262 | class TypeDecl : public NamedDecl { |
| 3263 | friend class ASTContext; |
| 3264 | |
| 3265 | /// This indicates the Type object that represents |
| 3266 | /// this TypeDecl. It is a cache maintained by |
| 3267 | /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and |
| 3268 | /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl. |
| 3269 | mutable const Type *TypeForDecl = nullptr; |
| 3270 | |
| 3271 | /// The start of the source range for this declaration. |
| 3272 | SourceLocation LocStart; |
| 3273 | |
| 3274 | void anchor() override; |
| 3275 | |
| 3276 | protected: |
| 3277 | TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, |
| 3278 | SourceLocation StartL = SourceLocation()) |
| 3279 | : NamedDecl(DK, DC, L, Id), LocStart(StartL) {} |
| 3280 | |
| 3281 | public: |
| 3282 | // Low-level accessor. If you just want the type defined by this node, |
| 3283 | // check out ASTContext::getTypeDeclType or one of |
| 3284 | // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you |
| 3285 | // already know the specific kind of node this is. |
| 3286 | const Type *getTypeForDecl() const { return TypeForDecl; } |
| 3287 | void setTypeForDecl(const Type *TD) { TypeForDecl = TD; } |
| 3288 | |
| 3289 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; } |
| 3290 | void setLocStart(SourceLocation L) { LocStart = L; } |
| 3291 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
| 3292 | if (LocStart.isValid()) |
| 3293 | return SourceRange(LocStart, getLocation()); |
| 3294 | else |
| 3295 | return SourceRange(getLocation()); |
| 3296 | } |
| 3297 | |
| 3298 | // Implement isa/cast/dyncast/etc. |
| 3299 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 3300 | static bool classofKind(Kind K) { return K >= firstType && K <= lastType; } |
| 3301 | }; |
| 3302 | |
| 3303 | /// Base class for declarations which introduce a typedef-name. |
| 3304 | class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> { |
| 3305 | struct alignas(8) ModedTInfo { |
| 3306 | TypeSourceInfo *first; |
| 3307 | QualType second; |
| 3308 | }; |
| 3309 | |
| 3310 | /// If int part is 0, we have not computed IsTransparentTag. |
| 3311 | /// Otherwise, IsTransparentTag is (getInt() >> 1). |
| 3312 | mutable llvm::PointerIntPair< |
| 3313 | llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2> |
| 3314 | MaybeModedTInfo; |
| 3315 | |
| 3316 | void anchor() override; |
| 3317 | |
| 3318 | protected: |
| 3319 | TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC, |
| 3320 | SourceLocation StartLoc, SourceLocation IdLoc, |
| 3321 | IdentifierInfo *Id, TypeSourceInfo *TInfo) |
| 3322 | : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C), |
| 3323 | MaybeModedTInfo(TInfo, 0) {} |
| 3324 | |
| 3325 | using redeclarable_base = Redeclarable<TypedefNameDecl>; |
| 3326 | |
| 3327 | TypedefNameDecl *getNextRedeclarationImpl() override { |
| 3328 | return getNextRedeclaration(); |
| 3329 | } |
| 3330 | |
| 3331 | TypedefNameDecl *getPreviousDeclImpl() override { |
| 3332 | return getPreviousDecl(); |
| 3333 | } |
| 3334 | |
| 3335 | TypedefNameDecl *getMostRecentDeclImpl() override { |
| 3336 | return getMostRecentDecl(); |
| 3337 | } |
| 3338 | |
| 3339 | public: |
| 3340 | using redecl_range = redeclarable_base::redecl_range; |
| 3341 | using redecl_iterator = redeclarable_base::redecl_iterator; |
| 3342 | |
| 3343 | using redeclarable_base::redecls_begin; |
| 3344 | using redeclarable_base::redecls_end; |
| 3345 | using redeclarable_base::redecls; |
| 3346 | using redeclarable_base::getPreviousDecl; |
| 3347 | using redeclarable_base::getMostRecentDecl; |
| 3348 | using redeclarable_base::isFirstDecl; |
| 3349 | |
| 3350 | bool isModed() const { |
| 3351 | return MaybeModedTInfo.getPointer().is<ModedTInfo *>(); |
| 3352 | } |
| 3353 | |
| 3354 | TypeSourceInfo *getTypeSourceInfo() const { |
| 3355 | return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first |
| 3356 | : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>(); |
| 3357 | } |
| 3358 | |
| 3359 | QualType getUnderlyingType() const { |
| 3360 | return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second |
| 3361 | : MaybeModedTInfo.getPointer() |
| 3362 | .get<TypeSourceInfo *>() |
| 3363 | ->getType(); |
| 3364 | } |
| 3365 | |
| 3366 | void setTypeSourceInfo(TypeSourceInfo *newType) { |
| 3367 | MaybeModedTInfo.setPointer(newType); |
| 3368 | } |
| 3369 | |
| 3370 | void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) { |
| 3371 | MaybeModedTInfo.setPointer(new (getASTContext(), 8) |
| 3372 | ModedTInfo({unmodedTSI, modedTy})); |
| 3373 | } |
| 3374 | |
| 3375 | /// Retrieves the canonical declaration of this typedef-name. |
| 3376 | TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); } |
| 3377 | const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); } |
| 3378 | |
| 3379 | /// Retrieves the tag declaration for which this is the typedef name for |
| 3380 | /// linkage purposes, if any. |
| 3381 | /// |
| 3382 | /// \param AnyRedecl Look for the tag declaration in any redeclaration of |
| 3383 | /// this typedef declaration. |
| 3384 | TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const; |
| 3385 | |
| 3386 | /// Determines if this typedef shares a name and spelling location with its |
| 3387 | /// underlying tag type, as is the case with the NS_ENUM macro. |
| 3388 | bool isTransparentTag() const { |
| 3389 | if (MaybeModedTInfo.getInt()) |
| 3390 | return MaybeModedTInfo.getInt() & 0x2; |
| 3391 | return isTransparentTagSlow(); |
| 3392 | } |
| 3393 | |
| 3394 | // Implement isa/cast/dyncast/etc. |
| 3395 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 3396 | static bool classofKind(Kind K) { |
| 3397 | return K >= firstTypedefName && K <= lastTypedefName; |
| 3398 | } |
| 3399 | |
| 3400 | private: |
| 3401 | bool isTransparentTagSlow() const; |
| 3402 | }; |
| 3403 | |
| 3404 | /// Represents the declaration of a typedef-name via the 'typedef' |
| 3405 | /// type specifier. |
| 3406 | class TypedefDecl : public TypedefNameDecl { |
| 3407 | TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
| 3408 | SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo) |
| 3409 | : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {} |
| 3410 | |
| 3411 | public: |
| 3412 | static TypedefDecl *Create(ASTContext &C, DeclContext *DC, |
| 3413 | SourceLocation StartLoc, SourceLocation IdLoc, |
| 3414 | IdentifierInfo *Id, TypeSourceInfo *TInfo); |
| 3415 | static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 3416 | |
| 3417 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
| 3418 | |
| 3419 | // Implement isa/cast/dyncast/etc. |
| 3420 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 3421 | static bool classofKind(Kind K) { return K == Typedef; } |
| 3422 | }; |
| 3423 | |
| 3424 | /// Represents the declaration of a typedef-name via a C++11 |
| 3425 | /// alias-declaration. |
| 3426 | class TypeAliasDecl : public TypedefNameDecl { |
| 3427 | /// The template for which this is the pattern, if any. |
| 3428 | TypeAliasTemplateDecl *Template; |
| 3429 | |
| 3430 | TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
| 3431 | SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo) |
| 3432 | : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo), |
| 3433 | Template(nullptr) {} |
| 3434 | |
| 3435 | public: |
| 3436 | static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC, |
| 3437 | SourceLocation StartLoc, SourceLocation IdLoc, |
| 3438 | IdentifierInfo *Id, TypeSourceInfo *TInfo); |
| 3439 | static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 3440 | |
| 3441 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
| 3442 | |
| 3443 | TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; } |
| 3444 | void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; } |
| 3445 | |
| 3446 | // Implement isa/cast/dyncast/etc. |
| 3447 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 3448 | static bool classofKind(Kind K) { return K == TypeAlias; } |
| 3449 | }; |
| 3450 | |
| 3451 | /// Represents the declaration of a struct/union/class/enum. |
| 3452 | class TagDecl : public TypeDecl, |
| 3453 | public DeclContext, |
| 3454 | public Redeclarable<TagDecl> { |
| 3455 | // This class stores some data in DeclContext::TagDeclBits |
| 3456 | // to save some space. Use the provided accessors to access it. |
| 3457 | public: |
| 3458 | // This is really ugly. |
| 3459 | using TagKind = TagTypeKind; |
| 3460 | |
| 3461 | private: |
| 3462 | SourceRange BraceRange; |
| 3463 | |
| 3464 | // A struct representing syntactic qualifier info, |
| 3465 | // to be used for the (uncommon) case of out-of-line declarations. |
| 3466 | using ExtInfo = QualifierInfo; |
| 3467 | |
| 3468 | /// If the (out-of-line) tag declaration name |
| 3469 | /// is qualified, it points to the qualifier info (nns and range); |
| 3470 | /// otherwise, if the tag declaration is anonymous and it is part of |
| 3471 | /// a typedef or alias, it points to the TypedefNameDecl (used for mangling); |
| 3472 | /// otherwise, if the tag declaration is anonymous and it is used as a |
| 3473 | /// declaration specifier for variables, it points to the first VarDecl (used |
| 3474 | /// for mangling); |
| 3475 | /// otherwise, it is a null (TypedefNameDecl) pointer. |
| 3476 | llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier; |
| 3477 | |
| 3478 | bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); } |
| 3479 | ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); } |
| 3480 | const ExtInfo *getExtInfo() const { |
| 3481 | return TypedefNameDeclOrQualifier.get<ExtInfo *>(); |
| 3482 | } |
| 3483 | |
| 3484 | protected: |
| 3485 | TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, |
| 3486 | SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl, |
| 3487 | SourceLocation StartL); |
| 3488 | |
| 3489 | using redeclarable_base = Redeclarable<TagDecl>; |
| 3490 | |
| 3491 | TagDecl *getNextRedeclarationImpl() override { |
| 3492 | return getNextRedeclaration(); |
| 3493 | } |
| 3494 | |
| 3495 | TagDecl *getPreviousDeclImpl() override { |
| 3496 | return getPreviousDecl(); |
| 3497 | } |
| 3498 | |
| 3499 | TagDecl *getMostRecentDeclImpl() override { |
| 3500 | return getMostRecentDecl(); |
| 3501 | } |
| 3502 | |
| 3503 | /// Completes the definition of this tag declaration. |
| 3504 | /// |
| 3505 | /// This is a helper function for derived classes. |
| 3506 | void completeDefinition(); |
| 3507 | |
| 3508 | /// True if this decl is currently being defined. |
| 3509 | void setBeingDefined(bool V = true) { TagDeclBits.IsBeingDefined = V; } |
| 3510 | |
| 3511 | /// Indicates whether it is possible for declarations of this kind |
| 3512 | /// to have an out-of-date definition. |
| 3513 | /// |
| 3514 | /// This option is only enabled when modules are enabled. |
| 3515 | void setMayHaveOutOfDateDef(bool V = true) { |
| 3516 | TagDeclBits.MayHaveOutOfDateDef = V; |
| 3517 | } |
| 3518 | |
| 3519 | public: |
| 3520 | friend class ASTDeclReader; |
| 3521 | friend class ASTDeclWriter; |
| 3522 | |
| 3523 | using redecl_range = redeclarable_base::redecl_range; |
| 3524 | using redecl_iterator = redeclarable_base::redecl_iterator; |
| 3525 | |
| 3526 | using redeclarable_base::redecls_begin; |
| 3527 | using redeclarable_base::redecls_end; |
| 3528 | using redeclarable_base::redecls; |
| 3529 | using redeclarable_base::getPreviousDecl; |
| 3530 | using redeclarable_base::getMostRecentDecl; |
| 3531 | using redeclarable_base::isFirstDecl; |
| 3532 | |
| 3533 | SourceRange getBraceRange() const { return BraceRange; } |
| 3534 | void setBraceRange(SourceRange R) { BraceRange = R; } |
| 3535 | |
| 3536 | /// Return SourceLocation representing start of source |
| 3537 | /// range ignoring outer template declarations. |
| 3538 | SourceLocation getInnerLocStart() const { return getBeginLoc(); } |
| 3539 | |
| 3540 | /// Return SourceLocation representing start of source |
| 3541 | /// range taking into account any outer template declarations. |
| 3542 | SourceLocation getOuterLocStart() const; |
| 3543 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
| 3544 | |
| 3545 | TagDecl *getCanonicalDecl() override; |
| 3546 | const TagDecl *getCanonicalDecl() const { |
| 3547 | return const_cast<TagDecl*>(this)->getCanonicalDecl(); |
| 3548 | } |
| 3549 | |
| 3550 | /// Return true if this declaration is a completion definition of the type. |
| 3551 | /// Provided for consistency. |
| 3552 | bool isThisDeclarationADefinition() const { |
| 3553 | return isCompleteDefinition(); |
| 3554 | } |
| 3555 | |
| 3556 | /// Return true if this decl has its body fully specified. |
| 3557 | bool isCompleteDefinition() const { return TagDeclBits.IsCompleteDefinition; } |
| 3558 | |
| 3559 | /// True if this decl has its body fully specified. |
| 3560 | void setCompleteDefinition(bool V = true) { |
| 3561 | TagDeclBits.IsCompleteDefinition = V; |
| 3562 | } |
| 3563 | |
| 3564 | /// Return true if this complete decl is |
| 3565 | /// required to be complete for some existing use. |
| 3566 | bool isCompleteDefinitionRequired() const { |
| 3567 | return TagDeclBits.IsCompleteDefinitionRequired; |
| 3568 | } |
| 3569 | |
| 3570 | /// True if this complete decl is |
| 3571 | /// required to be complete for some existing use. |
| 3572 | void setCompleteDefinitionRequired(bool V = true) { |
| 3573 | TagDeclBits.IsCompleteDefinitionRequired = V; |
| 3574 | } |
| 3575 | |
| 3576 | /// Return true if this decl is currently being defined. |
| 3577 | bool isBeingDefined() const { return TagDeclBits.IsBeingDefined; } |
| 3578 | |
| 3579 | /// True if this tag declaration is "embedded" (i.e., defined or declared |
| 3580 | /// for the very first time) in the syntax of a declarator. |
| 3581 | bool isEmbeddedInDeclarator() const { |
| 3582 | return TagDeclBits.IsEmbeddedInDeclarator; |
| 3583 | } |
| 3584 | |
| 3585 | /// True if this tag declaration is "embedded" (i.e., defined or declared |
| 3586 | /// for the very first time) in the syntax of a declarator. |
| 3587 | void setEmbeddedInDeclarator(bool isInDeclarator) { |
| 3588 | TagDeclBits.IsEmbeddedInDeclarator = isInDeclarator; |
| 3589 | } |
| 3590 | |
| 3591 | /// True if this tag is free standing, e.g. "struct foo;". |
| 3592 | bool isFreeStanding() const { return TagDeclBits.IsFreeStanding; } |
| 3593 | |
| 3594 | /// True if this tag is free standing, e.g. "struct foo;". |
| 3595 | void setFreeStanding(bool isFreeStanding = true) { |
| 3596 | TagDeclBits.IsFreeStanding = isFreeStanding; |
| 3597 | } |
| 3598 | |
| 3599 | /// Indicates whether it is possible for declarations of this kind |
| 3600 | /// to have an out-of-date definition. |
| 3601 | /// |
| 3602 | /// This option is only enabled when modules are enabled. |
| 3603 | bool mayHaveOutOfDateDef() const { return TagDeclBits.MayHaveOutOfDateDef; } |
| 3604 | |
| 3605 | /// Whether this declaration declares a type that is |
| 3606 | /// dependent, i.e., a type that somehow depends on template |
| 3607 | /// parameters. |
| 3608 | bool isDependentType() const { return isDependentContext(); } |
| 3609 | |
| 3610 | /// Whether this declaration was a definition in some module but was forced |
| 3611 | /// to be a declaration. |
| 3612 | /// |
| 3613 | /// Useful for clients checking if a module has a definition of a specific |
| 3614 | /// symbol and not interested in the final AST with deduplicated definitions. |
| 3615 | bool isThisDeclarationADemotedDefinition() const { |
| 3616 | return TagDeclBits.IsThisDeclarationADemotedDefinition; |
| 3617 | } |
| 3618 | |
| 3619 | /// Mark a definition as a declaration and maintain information it _was_ |
| 3620 | /// a definition. |
| 3621 | void demoteThisDefinitionToDeclaration() { |
| 3622 | assert(isCompleteDefinition() &&(static_cast <bool> (isCompleteDefinition() && "Should demote definitions only, not forward declarations" ) ? void (0) : __assert_fail ("isCompleteDefinition() && \"Should demote definitions only, not forward declarations\"" , "clang/include/clang/AST/Decl.h", 3623, __extension__ __PRETTY_FUNCTION__ )) |
| 3623 | "Should demote definitions only, not forward declarations")(static_cast <bool> (isCompleteDefinition() && "Should demote definitions only, not forward declarations" ) ? void (0) : __assert_fail ("isCompleteDefinition() && \"Should demote definitions only, not forward declarations\"" , "clang/include/clang/AST/Decl.h", 3623, __extension__ __PRETTY_FUNCTION__ )); |
| 3624 | setCompleteDefinition(false); |
| 3625 | TagDeclBits.IsThisDeclarationADemotedDefinition = true; |
| 3626 | } |
| 3627 | |
| 3628 | /// Starts the definition of this tag declaration. |
| 3629 | /// |
| 3630 | /// This method should be invoked at the beginning of the definition |
| 3631 | /// of this tag declaration. It will set the tag type into a state |
| 3632 | /// where it is in the process of being defined. |
| 3633 | void startDefinition(); |
| 3634 | |
| 3635 | /// Returns the TagDecl that actually defines this |
| 3636 | /// struct/union/class/enum. When determining whether or not a |
| 3637 | /// struct/union/class/enum has a definition, one should use this |
| 3638 | /// method as opposed to 'isDefinition'. 'isDefinition' indicates |
| 3639 | /// whether or not a specific TagDecl is defining declaration, not |
| 3640 | /// whether or not the struct/union/class/enum type is defined. |
| 3641 | /// This method returns NULL if there is no TagDecl that defines |
| 3642 | /// the struct/union/class/enum. |
| 3643 | TagDecl *getDefinition() const; |
| 3644 | |
| 3645 | StringRef getKindName() const { |
| 3646 | return TypeWithKeyword::getTagTypeKindName(getTagKind()); |
| 3647 | } |
| 3648 | |
| 3649 | TagKind getTagKind() const { |
| 3650 | return static_cast<TagKind>(TagDeclBits.TagDeclKind); |
| 3651 | } |
| 3652 | |
| 3653 | void setTagKind(TagKind TK) { TagDeclBits.TagDeclKind = TK; } |
| 3654 | |
| 3655 | bool isStruct() const { return getTagKind() == TTK_Struct; } |
| 3656 | bool isInterface() const { return getTagKind() == TTK_Interface; } |
| 3657 | bool isClass() const { return getTagKind() == TTK_Class; } |
| 3658 | bool isUnion() const { return getTagKind() == TTK_Union; } |
| 3659 | bool isEnum() const { return getTagKind() == TTK_Enum; } |
| 3660 | |
| 3661 | /// Is this tag type named, either directly or via being defined in |
| 3662 | /// a typedef of this type? |
| 3663 | /// |
| 3664 | /// C++11 [basic.link]p8: |
| 3665 | /// A type is said to have linkage if and only if: |
| 3666 | /// - it is a class or enumeration type that is named (or has a |
| 3667 | /// name for linkage purposes) and the name has linkage; ... |
| 3668 | /// C++11 [dcl.typedef]p9: |
| 3669 | /// If the typedef declaration defines an unnamed class (or enum), |
| 3670 | /// the first typedef-name declared by the declaration to be that |
| 3671 | /// class type (or enum type) is used to denote the class type (or |
| 3672 | /// enum type) for linkage purposes only. |
| 3673 | /// |
| 3674 | /// C does not have an analogous rule, but the same concept is |
| 3675 | /// nonetheless useful in some places. |
| 3676 | bool hasNameForLinkage() const { |
| 3677 | return (getDeclName() || getTypedefNameForAnonDecl()); |
| 3678 | } |
| 3679 | |
| 3680 | TypedefNameDecl *getTypedefNameForAnonDecl() const { |
| 3681 | return hasExtInfo() ? nullptr |
| 3682 | : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>(); |
| 3683 | } |
| 3684 | |
| 3685 | void setTypedefNameForAnonDecl(TypedefNameDecl *TDD); |
| 3686 | |
| 3687 | /// Retrieve the nested-name-specifier that qualifies the name of this |
| 3688 | /// declaration, if it was present in the source. |
| 3689 | NestedNameSpecifier *getQualifier() const { |
| 3690 | return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() |
| 3691 | : nullptr; |
| 3692 | } |
| 3693 | |
| 3694 | /// Retrieve the nested-name-specifier (with source-location |
| 3695 | /// information) that qualifies the name of this declaration, if it was |
| 3696 | /// present in the source. |
| 3697 | NestedNameSpecifierLoc getQualifierLoc() const { |
| 3698 | return hasExtInfo() ? getExtInfo()->QualifierLoc |
| 3699 | : NestedNameSpecifierLoc(); |
| 3700 | } |
| 3701 | |
| 3702 | void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); |
| 3703 | |
| 3704 | unsigned getNumTemplateParameterLists() const { |
| 3705 | return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; |
| 3706 | } |
| 3707 | |
| 3708 | TemplateParameterList *getTemplateParameterList(unsigned i) const { |
| 3709 | assert(i < getNumTemplateParameterLists())(static_cast <bool> (i < getNumTemplateParameterLists ()) ? void (0) : __assert_fail ("i < getNumTemplateParameterLists()" , "clang/include/clang/AST/Decl.h", 3709, __extension__ __PRETTY_FUNCTION__ )); |
| 3710 | return getExtInfo()->TemplParamLists[i]; |
| 3711 | } |
| 3712 | |
| 3713 | void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override; |
| 3714 | |
| 3715 | void setTemplateParameterListsInfo(ASTContext &Context, |
| 3716 | ArrayRef<TemplateParameterList *> TPLists); |
| 3717 | |
| 3718 | // Implement isa/cast/dyncast/etc. |
| 3719 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 3720 | static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; } |
| 3721 | |
| 3722 | static DeclContext *castToDeclContext(const TagDecl *D) { |
| 3723 | return static_cast<DeclContext *>(const_cast<TagDecl*>(D)); |
| 3724 | } |
| 3725 | |
| 3726 | static TagDecl *castFromDeclContext(const DeclContext *DC) { |
| 3727 | return static_cast<TagDecl *>(const_cast<DeclContext*>(DC)); |
| 3728 | } |
| 3729 | }; |
| 3730 | |
| 3731 | /// Represents an enum. In C++11, enums can be forward-declared |
| 3732 | /// with a fixed underlying type, and in C we allow them to be forward-declared |
| 3733 | /// with no underlying type as an extension. |
| 3734 | class EnumDecl : public TagDecl { |
| 3735 | // This class stores some data in DeclContext::EnumDeclBits |
| 3736 | // to save some space. Use the provided accessors to access it. |
| 3737 | |
| 3738 | /// This represent the integer type that the enum corresponds |
| 3739 | /// to for code generation purposes. Note that the enumerator constants may |
| 3740 | /// have a different type than this does. |
| 3741 | /// |
| 3742 | /// If the underlying integer type was explicitly stated in the source |
| 3743 | /// code, this is a TypeSourceInfo* for that type. Otherwise this type |
| 3744 | /// was automatically deduced somehow, and this is a Type*. |
| 3745 | /// |
| 3746 | /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in |
| 3747 | /// some cases it won't. |
| 3748 | /// |
| 3749 | /// The underlying type of an enumeration never has any qualifiers, so |
| 3750 | /// we can get away with just storing a raw Type*, and thus save an |
| 3751 | /// extra pointer when TypeSourceInfo is needed. |
| 3752 | llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType; |
| 3753 | |
| 3754 | /// The integer type that values of this type should |
| 3755 | /// promote to. In C, enumerators are generally of an integer type |
| 3756 | /// directly, but gcc-style large enumerators (and all enumerators |
| 3757 | /// in C++) are of the enum type instead. |
| 3758 | QualType PromotionType; |
| 3759 | |
| 3760 | /// If this enumeration is an instantiation of a member enumeration |
| 3761 | /// of a class template specialization, this is the member specialization |
| 3762 | /// information. |
| 3763 | MemberSpecializationInfo *SpecializationInfo = nullptr; |
| 3764 | |
| 3765 | /// Store the ODRHash after first calculation. |
| 3766 | /// The corresponding flag HasODRHash is in EnumDeclBits |
| 3767 | /// and can be accessed with the provided accessors. |
| 3768 | unsigned ODRHash; |
| 3769 | |
| 3770 | EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
| 3771 | SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, |
| 3772 | bool Scoped, bool ScopedUsingClassTag, bool Fixed); |
| 3773 | |
| 3774 | void anchor() override; |
| 3775 | |
| 3776 | void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, |
| 3777 | TemplateSpecializationKind TSK); |
| 3778 | |
| 3779 | /// Sets the width in bits required to store all the |
| 3780 | /// non-negative enumerators of this enum. |
| 3781 | void setNumPositiveBits(unsigned Num) { |
| 3782 | EnumDeclBits.NumPositiveBits = Num; |
| 3783 | assert(EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount")(static_cast <bool> (EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount") ? void (0) : __assert_fail ("EnumDeclBits.NumPositiveBits == Num && \"can't store this bitcount\"" , "clang/include/clang/AST/Decl.h", 3783, __extension__ __PRETTY_FUNCTION__ )); |
| 3784 | } |
| 3785 | |
| 3786 | /// Returns the width in bits required to store all the |
| 3787 | /// negative enumerators of this enum. (see getNumNegativeBits) |
| 3788 | void setNumNegativeBits(unsigned Num) { EnumDeclBits.NumNegativeBits = Num; } |
| 3789 | |
| 3790 | public: |
| 3791 | /// True if this tag declaration is a scoped enumeration. Only |
| 3792 | /// possible in C++11 mode. |
| 3793 | void setScoped(bool Scoped = true) { EnumDeclBits.IsScoped = Scoped; } |
| 3794 | |
| 3795 | /// If this tag declaration is a scoped enum, |
| 3796 | /// then this is true if the scoped enum was declared using the class |
| 3797 | /// tag, false if it was declared with the struct tag. No meaning is |
| 3798 | /// associated if this tag declaration is not a scoped enum. |
| 3799 | void setScopedUsingClassTag(bool ScopedUCT = true) { |
| 3800 | EnumDeclBits.IsScopedUsingClassTag = ScopedUCT; |
| 3801 | } |
| 3802 | |
| 3803 | /// True if this is an Objective-C, C++11, or |
| 3804 | /// Microsoft-style enumeration with a fixed underlying type. |
| 3805 | void setFixed(bool Fixed = true) { EnumDeclBits.IsFixed = Fixed; } |
| 3806 | |
| 3807 | private: |
| 3808 | /// True if a valid hash is stored in ODRHash. |
| 3809 | bool hasODRHash() const { return EnumDeclBits.HasODRHash; } |
| 3810 | void setHasODRHash(bool Hash = true) { EnumDeclBits.HasODRHash = Hash; } |
| 3811 | |
| 3812 | public: |
| 3813 | friend class ASTDeclReader; |
| 3814 | |
| 3815 | EnumDecl *getCanonicalDecl() override { |
| 3816 | return cast<EnumDecl>(TagDecl::getCanonicalDecl()); |
| 3817 | } |
| 3818 | const EnumDecl *getCanonicalDecl() const { |
| 3819 | return const_cast<EnumDecl*>(this)->getCanonicalDecl(); |
| 3820 | } |
| 3821 | |
| 3822 | EnumDecl *getPreviousDecl() { |
| 3823 | return cast_or_null<EnumDecl>( |
| 3824 | static_cast<TagDecl *>(this)->getPreviousDecl()); |
| 3825 | } |
| 3826 | const EnumDecl *getPreviousDecl() const { |
| 3827 | return const_cast<EnumDecl*>(this)->getPreviousDecl(); |
| 3828 | } |
| 3829 | |
| 3830 | EnumDecl *getMostRecentDecl() { |
| 3831 | return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl()); |
| 3832 | } |
| 3833 | const EnumDecl *getMostRecentDecl() const { |
| 3834 | return const_cast<EnumDecl*>(this)->getMostRecentDecl(); |
| 3835 | } |
| 3836 | |
| 3837 | EnumDecl *getDefinition() const { |
| 3838 | return cast_or_null<EnumDecl>(TagDecl::getDefinition()); |
| 3839 | } |
| 3840 | |
| 3841 | static EnumDecl *Create(ASTContext &C, DeclContext *DC, |
| 3842 | SourceLocation StartLoc, SourceLocation IdLoc, |
| 3843 | IdentifierInfo *Id, EnumDecl *PrevDecl, |
| 3844 | bool IsScoped, bool IsScopedUsingClassTag, |
| 3845 | bool IsFixed); |
| 3846 | static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 3847 | |
| 3848 | /// Overrides to provide correct range when there's an enum-base specifier |
| 3849 | /// with forward declarations. |
| 3850 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
| 3851 | |
| 3852 | /// When created, the EnumDecl corresponds to a |
| 3853 | /// forward-declared enum. This method is used to mark the |
| 3854 | /// declaration as being defined; its enumerators have already been |
| 3855 | /// added (via DeclContext::addDecl). NewType is the new underlying |
| 3856 | /// type of the enumeration type. |
| 3857 | void completeDefinition(QualType NewType, |
| 3858 | QualType PromotionType, |
| 3859 | unsigned NumPositiveBits, |
| 3860 | unsigned NumNegativeBits); |
| 3861 | |
| 3862 | // Iterates through the enumerators of this enumeration. |
| 3863 | using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>; |
| 3864 | using enumerator_range = |
| 3865 | llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>; |
| 3866 | |
| 3867 | enumerator_range enumerators() const { |
| 3868 | return enumerator_range(enumerator_begin(), enumerator_end()); |
| 3869 | } |
| 3870 | |
| 3871 | enumerator_iterator enumerator_begin() const { |
| 3872 | const EnumDecl *E = getDefinition(); |
| 3873 | if (!E) |
| 3874 | E = this; |
| 3875 | return enumerator_iterator(E->decls_begin()); |
| 3876 | } |
| 3877 | |
| 3878 | enumerator_iterator enumerator_end() const { |
| 3879 | const EnumDecl *E = getDefinition(); |
| 3880 | if (!E) |
| 3881 | E = this; |
| 3882 | return enumerator_iterator(E->decls_end()); |
| 3883 | } |
| 3884 | |
| 3885 | /// Return the integer type that enumerators should promote to. |
| 3886 | QualType getPromotionType() const { return PromotionType; } |
| 3887 | |
| 3888 | /// Set the promotion type. |
| 3889 | void setPromotionType(QualType T) { PromotionType = T; } |
| 3890 | |
| 3891 | /// Return the integer type this enum decl corresponds to. |
| 3892 | /// This returns a null QualType for an enum forward definition with no fixed |
| 3893 | /// underlying type. |
| 3894 | QualType getIntegerType() const { |
| 3895 | if (!IntegerType) |
| 3896 | return QualType(); |
| 3897 | if (const Type *T = IntegerType.dyn_cast<const Type*>()) |
| 3898 | return QualType(T, 0); |
| 3899 | return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType(); |
| 3900 | } |
| 3901 | |
| 3902 | /// Set the underlying integer type. |
| 3903 | void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); } |
| 3904 | |
| 3905 | /// Set the underlying integer type source info. |
| 3906 | void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; } |
| 3907 | |
| 3908 | /// Return the type source info for the underlying integer type, |
| 3909 | /// if no type source info exists, return 0. |
| 3910 | TypeSourceInfo *getIntegerTypeSourceInfo() const { |
| 3911 | return IntegerType.dyn_cast<TypeSourceInfo*>(); |
| 3912 | } |
| 3913 | |
| 3914 | /// Retrieve the source range that covers the underlying type if |
| 3915 | /// specified. |
| 3916 | SourceRange getIntegerTypeRange() const LLVM_READONLY__attribute__((__pure__)); |
| 3917 | |
| 3918 | /// Returns the width in bits required to store all the |
| 3919 | /// non-negative enumerators of this enum. |
| 3920 | unsigned getNumPositiveBits() const { return EnumDeclBits.NumPositiveBits; } |
| 3921 | |
| 3922 | /// Returns the width in bits required to store all the |
| 3923 | /// negative enumerators of this enum. These widths include |
| 3924 | /// the rightmost leading 1; that is: |
| 3925 | /// |
| 3926 | /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS |
| 3927 | /// ------------------------ ------- ----------------- |
| 3928 | /// -1 1111111 1 |
| 3929 | /// -10 1110110 5 |
| 3930 | /// -101 1001011 8 |
| 3931 | unsigned getNumNegativeBits() const { return EnumDeclBits.NumNegativeBits; } |
| 3932 | |
| 3933 | /// Calculates the [Min,Max) values the enum can store based on the |
| 3934 | /// NumPositiveBits and NumNegativeBits. This matters for enums that do not |
| 3935 | /// have a fixed underlying type. |
| 3936 | void getValueRange(llvm::APInt &Max, llvm::APInt &Min) const; |
| 3937 | |
| 3938 | /// Returns true if this is a C++11 scoped enumeration. |
| 3939 | bool isScoped() const { return EnumDeclBits.IsScoped; } |
| 3940 | |
| 3941 | /// Returns true if this is a C++11 scoped enumeration. |
| 3942 | bool isScopedUsingClassTag() const { |
| 3943 | return EnumDeclBits.IsScopedUsingClassTag; |
| 3944 | } |
| 3945 | |
| 3946 | /// Returns true if this is an Objective-C, C++11, or |
| 3947 | /// Microsoft-style enumeration with a fixed underlying type. |
| 3948 | bool isFixed() const { return EnumDeclBits.IsFixed; } |
| 3949 | |
| 3950 | unsigned getODRHash(); |
| 3951 | |
| 3952 | /// Returns true if this can be considered a complete type. |
| 3953 | bool isComplete() const { |
| 3954 | // IntegerType is set for fixed type enums and non-fixed but implicitly |
| 3955 | // int-sized Microsoft enums. |
| 3956 | return isCompleteDefinition() || IntegerType; |
| 3957 | } |
| 3958 | |
| 3959 | /// Returns true if this enum is either annotated with |
| 3960 | /// enum_extensibility(closed) or isn't annotated with enum_extensibility. |
| 3961 | bool isClosed() const; |
| 3962 | |
| 3963 | /// Returns true if this enum is annotated with flag_enum and isn't annotated |
| 3964 | /// with enum_extensibility(open). |
| 3965 | bool isClosedFlag() const; |
| 3966 | |
| 3967 | /// Returns true if this enum is annotated with neither flag_enum nor |
| 3968 | /// enum_extensibility(open). |
| 3969 | bool isClosedNonFlag() const; |
| 3970 | |
| 3971 | /// Retrieve the enum definition from which this enumeration could |
| 3972 | /// be instantiated, if it is an instantiation (rather than a non-template). |
| 3973 | EnumDecl *getTemplateInstantiationPattern() const; |
| 3974 | |
| 3975 | /// Returns the enumeration (declared within the template) |
| 3976 | /// from which this enumeration type was instantiated, or NULL if |
| 3977 | /// this enumeration was not instantiated from any template. |
| 3978 | EnumDecl *getInstantiatedFromMemberEnum() const; |
| 3979 | |
| 3980 | /// If this enumeration is a member of a specialization of a |
| 3981 | /// templated class, determine what kind of template specialization |
| 3982 | /// or instantiation this is. |
| 3983 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
| 3984 | |
| 3985 | /// For an enumeration member that was instantiated from a member |
| 3986 | /// enumeration of a templated class, set the template specialiation kind. |
| 3987 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
| 3988 | SourceLocation PointOfInstantiation = SourceLocation()); |
| 3989 | |
| 3990 | /// If this enumeration is an instantiation of a member enumeration of |
| 3991 | /// a class template specialization, retrieves the member specialization |
| 3992 | /// information. |
| 3993 | MemberSpecializationInfo *getMemberSpecializationInfo() const { |
| 3994 | return SpecializationInfo; |
| 3995 | } |
| 3996 | |
| 3997 | /// Specify that this enumeration is an instantiation of the |
| 3998 | /// member enumeration ED. |
| 3999 | void setInstantiationOfMemberEnum(EnumDecl *ED, |
| 4000 | TemplateSpecializationKind TSK) { |
| 4001 | setInstantiationOfMemberEnum(getASTContext(), ED, TSK); |
| 4002 | } |
| 4003 | |
| 4004 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 4005 | static bool classofKind(Kind K) { return K == Enum; } |
| 4006 | }; |
| 4007 | |
| 4008 | /// Represents a struct/union/class. For example: |
| 4009 | /// struct X; // Forward declaration, no "body". |
| 4010 | /// union Y { int A, B; }; // Has body with members A and B (FieldDecls). |
| 4011 | /// This decl will be marked invalid if *any* members are invalid. |
| 4012 | class RecordDecl : public TagDecl { |
| 4013 | // This class stores some data in DeclContext::RecordDeclBits |
| 4014 | // to save some space. Use the provided accessors to access it. |
| 4015 | public: |
| 4016 | friend class DeclContext; |
| 4017 | friend class ASTDeclReader; |
| 4018 | /// Enum that represents the different ways arguments are passed to and |
| 4019 | /// returned from function calls. This takes into account the target-specific |
| 4020 | /// and version-specific rules along with the rules determined by the |
| 4021 | /// language. |
| 4022 | enum ArgPassingKind : unsigned { |
| 4023 | /// The argument of this type can be passed directly in registers. |
| 4024 | APK_CanPassInRegs, |
| 4025 | |
| 4026 | /// The argument of this type cannot be passed directly in registers. |
| 4027 | /// Records containing this type as a subobject are not forced to be passed |
| 4028 | /// indirectly. This value is used only in C++. This value is required by |
| 4029 | /// C++ because, in uncommon situations, it is possible for a class to have |
| 4030 | /// only trivial copy/move constructors even when one of its subobjects has |
| 4031 | /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move |
| 4032 | /// constructor in the derived class is deleted). |
| 4033 | APK_CannotPassInRegs, |
| 4034 | |
| 4035 | /// The argument of this type cannot be passed directly in registers. |
| 4036 | /// Records containing this type as a subobject are forced to be passed |
| 4037 | /// indirectly. |
| 4038 | APK_CanNeverPassInRegs |
| 4039 | }; |
| 4040 | |
| 4041 | protected: |
| 4042 | RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, |
| 4043 | SourceLocation StartLoc, SourceLocation IdLoc, |
| 4044 | IdentifierInfo *Id, RecordDecl *PrevDecl); |
| 4045 | |
| 4046 | public: |
| 4047 | static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC, |
| 4048 | SourceLocation StartLoc, SourceLocation IdLoc, |
| 4049 | IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr); |
| 4050 | static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID); |
| 4051 | |
| 4052 | RecordDecl *getPreviousDecl() { |
| 4053 | return cast_or_null<RecordDecl>( |
| 4054 | static_cast<TagDecl *>(this)->getPreviousDecl()); |
| 4055 | } |
| 4056 | const RecordDecl *getPreviousDecl() const { |
| 4057 | return const_cast<RecordDecl*>(this)->getPreviousDecl(); |
| 4058 | } |
| 4059 | |
| 4060 | RecordDecl *getMostRecentDecl() { |
| 4061 | return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl()); |
| 4062 | } |
| 4063 | const RecordDecl *getMostRecentDecl() const { |
| 4064 | return const_cast<RecordDecl*>(this)->getMostRecentDecl(); |
| 4065 | } |
| 4066 | |
| 4067 | bool hasFlexibleArrayMember() const { |
| 4068 | return RecordDeclBits.HasFlexibleArrayMember; |
| 4069 | } |
| 4070 | |
| 4071 | void setHasFlexibleArrayMember(bool V) { |
| 4072 | RecordDeclBits.HasFlexibleArrayMember = V; |
| 4073 | } |
| 4074 | |
| 4075 | /// Whether this is an anonymous struct or union. To be an anonymous |
| 4076 | /// struct or union, it must have been declared without a name and |
| 4077 | /// there must be no objects of this type declared, e.g., |
| 4078 | /// @code |
| 4079 | /// union { int i; float f; }; |
| 4080 | /// @endcode |
| 4081 | /// is an anonymous union but neither of the following are: |
| 4082 | /// @code |
| 4083 | /// union X { int i; float f; }; |
| 4084 | /// union { int i; float f; } obj; |
| 4085 | /// @endcode |
| 4086 | bool isAnonymousStructOrUnion() const { |
| 4087 | return RecordDeclBits.AnonymousStructOrUnion; |
| 4088 | } |
| 4089 | |
| 4090 | void setAnonymousStructOrUnion(bool Anon) { |
| 4091 | RecordDeclBits.AnonymousStructOrUnion = Anon; |
| 4092 | } |
| 4093 | |
| 4094 | bool hasObjectMember() const { return RecordDeclBits.HasObjectMember; } |
| 4095 | void setHasObjectMember(bool val) { RecordDeclBits.HasObjectMember = val; } |
| 4096 | |
| 4097 | bool hasVolatileMember() const { return RecordDeclBits.HasVolatileMember; } |
| 4098 | |
| 4099 | void setHasVolatileMember(bool val) { |
| 4100 | RecordDeclBits.HasVolatileMember = val; |
| 4101 | } |
| 4102 | |
| 4103 | bool hasLoadedFieldsFromExternalStorage() const { |
| 4104 | return RecordDeclBits.LoadedFieldsFromExternalStorage; |
| 4105 | } |
| 4106 | |
| 4107 | void setHasLoadedFieldsFromExternalStorage(bool val) const { |
| 4108 | RecordDeclBits.LoadedFieldsFromExternalStorage = val; |
| 4109 | } |
| 4110 | |
| 4111 | /// Functions to query basic properties of non-trivial C structs. |
| 4112 | bool isNonTrivialToPrimitiveDefaultInitialize() const { |
| 4113 | return RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize; |
| 4114 | } |
| 4115 | |
| 4116 | void setNonTrivialToPrimitiveDefaultInitialize(bool V) { |
| 4117 | RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize = V; |
| 4118 | } |
| 4119 | |
| 4120 | bool isNonTrivialToPrimitiveCopy() const { |
| 4121 | return RecordDeclBits.NonTrivialToPrimitiveCopy; |
| 4122 | } |
| 4123 | |
| 4124 | void setNonTrivialToPrimitiveCopy(bool V) { |
| 4125 | RecordDeclBits.NonTrivialToPrimitiveCopy = V; |
| 4126 | } |
| 4127 | |
| 4128 | bool isNonTrivialToPrimitiveDestroy() const { |
| 4129 | return RecordDeclBits.NonTrivialToPrimitiveDestroy; |
| 4130 | } |
| 4131 | |
| 4132 | void setNonTrivialToPrimitiveDestroy(bool V) { |
| 4133 | RecordDeclBits.NonTrivialToPrimitiveDestroy = V; |
| 4134 | } |
| 4135 | |
| 4136 | bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const { |
| 4137 | return RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion; |
| 4138 | } |
| 4139 | |
| 4140 | void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V) { |
| 4141 | RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion = V; |
| 4142 | } |
| 4143 | |
| 4144 | bool hasNonTrivialToPrimitiveDestructCUnion() const { |
| 4145 | return RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion; |
| 4146 | } |
| 4147 | |
| 4148 | void setHasNonTrivialToPrimitiveDestructCUnion(bool V) { |
| 4149 | RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion = V; |
| 4150 | } |
| 4151 | |
| 4152 | bool hasNonTrivialToPrimitiveCopyCUnion() const { |
| 4153 | return RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion; |
| 4154 | } |
| 4155 | |
| 4156 | void setHasNonTrivialToPrimitiveCopyCUnion(bool V) { |
| 4157 | RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion = V; |
| 4158 | } |
| 4159 | |
| 4160 | /// Determine whether this class can be passed in registers. In C++ mode, |
| 4161 | /// it must have at least one trivial, non-deleted copy or move constructor. |
| 4162 | /// FIXME: This should be set as part of completeDefinition. |
| 4163 | bool canPassInRegisters() const { |
| 4164 | return getArgPassingRestrictions() == APK_CanPassInRegs; |
| 4165 | } |
| 4166 | |
| 4167 | ArgPassingKind getArgPassingRestrictions() const { |
| 4168 | return static_cast<ArgPassingKind>(RecordDeclBits.ArgPassingRestrictions); |
| 4169 | } |
| 4170 | |
| 4171 | void setArgPassingRestrictions(ArgPassingKind Kind) { |
| 4172 | RecordDeclBits.ArgPassingRestrictions = Kind; |
| 4173 | } |
| 4174 | |
| 4175 | bool isParamDestroyedInCallee() const { |
| 4176 | return RecordDeclBits.ParamDestroyedInCallee; |
| 4177 | } |
| 4178 | |
| 4179 | void setParamDestroyedInCallee(bool V) { |
| 4180 | RecordDeclBits.ParamDestroyedInCallee = V; |
| 4181 | } |
| 4182 | |
| 4183 | bool isRandomized() const { return RecordDeclBits.IsRandomized; } |
| 4184 | |
| 4185 | void setIsRandomized(bool V) { RecordDeclBits.IsRandomized = V; } |
| 4186 | |
| 4187 | void reorderDecls(const SmallVectorImpl<Decl *> &Decls); |
| 4188 | |
| 4189 | /// Determines whether this declaration represents the |
| 4190 | /// injected class name. |
| 4191 | /// |
| 4192 | /// The injected class name in C++ is the name of the class that |
| 4193 | /// appears inside the class itself. For example: |
| 4194 | /// |
| 4195 | /// \code |
| 4196 | /// struct C { |
| 4197 | /// // C is implicitly declared here as a synonym for the class name. |
| 4198 | /// }; |
| 4199 | /// |
| 4200 | /// C::C c; // same as "C c;" |
| 4201 | /// \endcode |
| 4202 | bool isInjectedClassName() const; |
| 4203 | |
| 4204 | /// Determine whether this record is a class describing a lambda |
| 4205 | /// function object. |
| 4206 | bool isLambda() const; |
| 4207 | |
| 4208 | /// Determine whether this record is a record for captured variables in |
| 4209 | /// CapturedStmt construct. |
| 4210 | bool isCapturedRecord() const; |
| 4211 | |
| 4212 | /// Mark the record as a record for captured variables in CapturedStmt |
| 4213 | /// construct. |
| 4214 | void setCapturedRecord(); |
| 4215 | |
| 4216 | /// Returns the RecordDecl that actually defines |
| 4217 | /// this struct/union/class. When determining whether or not a |
| 4218 | /// struct/union/class is completely defined, one should use this |
| 4219 | /// method as opposed to 'isCompleteDefinition'. |
| 4220 | /// 'isCompleteDefinition' indicates whether or not a specific |
| 4221 | /// RecordDecl is a completed definition, not whether or not the |
| 4222 | /// record type is defined. This method returns NULL if there is |
| 4223 | /// no RecordDecl that defines the struct/union/tag. |
| 4224 | RecordDecl *getDefinition() const { |
| 4225 | return cast_or_null<RecordDecl>(TagDecl::getDefinition()); |
| 4226 | } |
| 4227 | |
| 4228 | /// Returns whether this record is a union, or contains (at any nesting level) |
| 4229 | /// a union member. This is used by CMSE to warn about possible information |
| 4230 | /// leaks. |
| 4231 | bool isOrContainsUnion() const; |
| 4232 | |
| 4233 | // Iterator access to field members. The field iterator only visits |
| 4234 | // the non-static data members of this class, ignoring any static |
| 4235 | // data members, functions, constructors, destructors, etc. |
| 4236 | using field_iterator = specific_decl_iterator<FieldDecl>; |
| 4237 | using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>; |
| 4238 | |
| 4239 | field_range fields() const { return field_range(field_begin(), field_end()); } |
| 4240 | field_iterator field_begin() const; |
| 4241 | |
| 4242 | field_iterator field_end() const { |
| 4243 | return field_iterator(decl_iterator()); |
| 4244 | } |
| 4245 | |
| 4246 | // Whether there are any fields (non-static data members) in this record. |
| 4247 | bool field_empty() const { |
| 4248 | return field_begin() == field_end(); |
| 4249 | } |
| 4250 | |
| 4251 | /// Note that the definition of this type is now complete. |
| 4252 | virtual void completeDefinition(); |
| 4253 | |
| 4254 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 4255 | static bool classofKind(Kind K) { |
| 4256 | return K >= firstRecord && K <= lastRecord; |
| 4257 | } |
| 4258 | |
| 4259 | /// Get whether or not this is an ms_struct which can |
| 4260 | /// be turned on with an attribute, pragma, or -mms-bitfields |
| 4261 | /// commandline option. |
| 4262 | bool isMsStruct(const ASTContext &C) const; |
| 4263 | |
| 4264 | /// Whether we are allowed to insert extra padding between fields. |
| 4265 | /// These padding are added to help AddressSanitizer detect |
| 4266 | /// intra-object-overflow bugs. |
| 4267 | bool mayInsertExtraPadding(bool EmitRemark = false) const; |
| 4268 | |
| 4269 | /// Finds the first data member which has a name. |
| 4270 | /// nullptr is returned if no named data member exists. |
| 4271 | const FieldDecl *findFirstNamedDataMember() const; |
| 4272 | |
| 4273 | /// Get precomputed ODRHash or add a new one. |
| 4274 | unsigned getODRHash(); |
| 4275 | |
| 4276 | private: |
| 4277 | /// Deserialize just the fields. |
| 4278 | void LoadFieldsFromExternalStorage() const; |
| 4279 | |
| 4280 | /// True if a valid hash is stored in ODRHash. |
| 4281 | bool hasODRHash() const { return RecordDeclBits.ODRHash; } |
| 4282 | void setODRHash(unsigned Hash) { RecordDeclBits.ODRHash = Hash; } |
| 4283 | }; |
| 4284 | |
| 4285 | class FileScopeAsmDecl : public Decl { |
| 4286 | StringLiteral *AsmString; |
| 4287 | SourceLocation RParenLoc; |
| 4288 | |
| 4289 | FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring, |
| 4290 | SourceLocation StartL, SourceLocation EndL) |
| 4291 | : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {} |
| 4292 | |
| 4293 | virtual void anchor(); |
| 4294 | |
| 4295 | public: |
| 4296 | static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC, |
| 4297 | StringLiteral *Str, SourceLocation AsmLoc, |
| 4298 | SourceLocation RParenLoc); |
| 4299 | |
| 4300 | static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 4301 | |
| 4302 | SourceLocation getAsmLoc() const { return getLocation(); } |
| 4303 | SourceLocation getRParenLoc() const { return RParenLoc; } |
| 4304 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
| 4305 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
| 4306 | return SourceRange(getAsmLoc(), getRParenLoc()); |
| 4307 | } |
| 4308 | |
| 4309 | const StringLiteral *getAsmString() const { return AsmString; } |
| 4310 | StringLiteral *getAsmString() { return AsmString; } |
| 4311 | void setAsmString(StringLiteral *Asm) { AsmString = Asm; } |
| 4312 | |
| 4313 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 4314 | static bool classofKind(Kind K) { return K == FileScopeAsm; } |
| 4315 | }; |
| 4316 | |
| 4317 | /// A declaration that models statements at global scope. This declaration |
| 4318 | /// supports incremental and interactive C/C++. |
| 4319 | /// |
| 4320 | /// \note This is used in libInterpreter, clang -cc1 -fincremental-extensions |
| 4321 | /// and in tools such as clang-repl. |
| 4322 | class TopLevelStmtDecl : public Decl { |
| 4323 | friend class ASTDeclReader; |
| 4324 | friend class ASTDeclWriter; |
| 4325 | |
| 4326 | Stmt *Statement = nullptr; |
| 4327 | |
| 4328 | TopLevelStmtDecl(DeclContext *DC, SourceLocation L, Stmt *S) |
| 4329 | : Decl(TopLevelStmt, DC, L), Statement(S) {} |
| 4330 | |
| 4331 | virtual void anchor(); |
| 4332 | |
| 4333 | public: |
| 4334 | static TopLevelStmtDecl *Create(ASTContext &C, Stmt *Statement); |
| 4335 | static TopLevelStmtDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 4336 | |
| 4337 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
| 4338 | Stmt *getStmt() { return Statement; } |
| 4339 | const Stmt *getStmt() const { return Statement; } |
| 4340 | |
| 4341 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 4342 | static bool classofKind(Kind K) { return K == TopLevelStmt; } |
| 4343 | }; |
| 4344 | |
| 4345 | /// Represents a block literal declaration, which is like an |
| 4346 | /// unnamed FunctionDecl. For example: |
| 4347 | /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } |
| 4348 | class BlockDecl : public Decl, public DeclContext { |
| 4349 | // This class stores some data in DeclContext::BlockDeclBits |
| 4350 | // to save some space. Use the provided accessors to access it. |
| 4351 | public: |
| 4352 | /// A class which contains all the information about a particular |
| 4353 | /// captured value. |
| 4354 | class Capture { |
| 4355 | enum { |
| 4356 | flag_isByRef = 0x1, |
| 4357 | flag_isNested = 0x2 |
| 4358 | }; |
| 4359 | |
| 4360 | /// The variable being captured. |
| 4361 | llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags; |
| 4362 | |
| 4363 | /// The copy expression, expressed in terms of a DeclRef (or |
| 4364 | /// BlockDeclRef) to the captured variable. Only required if the |
| 4365 | /// variable has a C++ class type. |
| 4366 | Expr *CopyExpr; |
| 4367 | |
| 4368 | public: |
| 4369 | Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy) |
| 4370 | : VariableAndFlags(variable, |
| 4371 | (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)), |
| 4372 | CopyExpr(copy) {} |
| 4373 | |
| 4374 | /// The variable being captured. |
| 4375 | VarDecl *getVariable() const { return VariableAndFlags.getPointer(); } |
| 4376 | |
| 4377 | /// Whether this is a "by ref" capture, i.e. a capture of a __block |
| 4378 | /// variable. |
| 4379 | bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; } |
| 4380 | |
| 4381 | bool isEscapingByref() const { |
| 4382 | return getVariable()->isEscapingByref(); |
| 4383 | } |
| 4384 | |
| 4385 | bool isNonEscapingByref() const { |
| 4386 | return getVariable()->isNonEscapingByref(); |
| 4387 | } |
| 4388 | |
| 4389 | /// Whether this is a nested capture, i.e. the variable captured |
| 4390 | /// is not from outside the immediately enclosing function/block. |
| 4391 | bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; } |
| 4392 | |
| 4393 | bool hasCopyExpr() const { return CopyExpr != nullptr; } |
| 4394 | Expr *getCopyExpr() const { return CopyExpr; } |
| 4395 | void setCopyExpr(Expr *e) { CopyExpr = e; } |
| 4396 | }; |
| 4397 | |
| 4398 | private: |
| 4399 | /// A new[]'d array of pointers to ParmVarDecls for the formal |
| 4400 | /// parameters of this function. This is null if a prototype or if there are |
| 4401 | /// no formals. |
| 4402 | ParmVarDecl **ParamInfo = nullptr; |
| 4403 | unsigned NumParams = 0; |
| 4404 | |
| 4405 | Stmt *Body = nullptr; |
| 4406 | TypeSourceInfo *SignatureAsWritten = nullptr; |
| 4407 | |
| 4408 | const Capture *Captures = nullptr; |
| 4409 | unsigned NumCaptures = 0; |
| 4410 | |
| 4411 | unsigned ManglingNumber = 0; |
| 4412 | Decl *ManglingContextDecl = nullptr; |
| 4413 | |
| 4414 | protected: |
| 4415 | BlockDecl(DeclContext *DC, SourceLocation CaretLoc); |
| 4416 | |
| 4417 | public: |
| 4418 | static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L); |
| 4419 | static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 4420 | |
| 4421 | SourceLocation getCaretLocation() const { return getLocation(); } |
| 4422 | |
| 4423 | bool isVariadic() const { return BlockDeclBits.IsVariadic; } |
| 4424 | void setIsVariadic(bool value) { BlockDeclBits.IsVariadic = value; } |
| 4425 | |
| 4426 | CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; } |
| 4427 | Stmt *getBody() const override { return (Stmt*) Body; } |
| 4428 | void setBody(CompoundStmt *B) { Body = (Stmt*) B; } |
| 4429 | |
| 4430 | void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; } |
| 4431 | TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; } |
| 4432 | |
| 4433 | // ArrayRef access to formal parameters. |
| 4434 | ArrayRef<ParmVarDecl *> parameters() const { |
| 4435 | return {ParamInfo, getNumParams()}; |
| 4436 | } |
| 4437 | MutableArrayRef<ParmVarDecl *> parameters() { |
| 4438 | return {ParamInfo, getNumParams()}; |
| 4439 | } |
| 4440 | |
| 4441 | // Iterator access to formal parameters. |
| 4442 | using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator; |
| 4443 | using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator; |
| 4444 | |
| 4445 | bool param_empty() const { return parameters().empty(); } |
| 4446 | param_iterator param_begin() { return parameters().begin(); } |
| 4447 | param_iterator param_end() { return parameters().end(); } |
| 4448 | param_const_iterator param_begin() const { return parameters().begin(); } |
| 4449 | param_const_iterator param_end() const { return parameters().end(); } |
| 4450 | size_t param_size() const { return parameters().size(); } |
| 4451 | |
| 4452 | unsigned getNumParams() const { return NumParams; } |
| 4453 | |
| 4454 | const ParmVarDecl *getParamDecl(unsigned i) const { |
| 4455 | assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #" ) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "clang/include/clang/AST/Decl.h", 4455, __extension__ __PRETTY_FUNCTION__ )); |
| 4456 | return ParamInfo[i]; |
| 4457 | } |
| 4458 | ParmVarDecl *getParamDecl(unsigned i) { |
| 4459 | assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #" ) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "clang/include/clang/AST/Decl.h", 4459, __extension__ __PRETTY_FUNCTION__ )); |
| 4460 | return ParamInfo[i]; |
| 4461 | } |
| 4462 | |
| 4463 | void setParams(ArrayRef<ParmVarDecl *> NewParamInfo); |
| 4464 | |
| 4465 | /// True if this block (or its nested blocks) captures |
| 4466 | /// anything of local storage from its enclosing scopes. |
| 4467 | bool hasCaptures() const { return NumCaptures || capturesCXXThis(); } |
| 4468 | |
| 4469 | /// Returns the number of captured variables. |
| 4470 | /// Does not include an entry for 'this'. |
| 4471 | unsigned getNumCaptures() const { return NumCaptures; } |
| 4472 | |
| 4473 | using capture_const_iterator = ArrayRef<Capture>::const_iterator; |
| 4474 | |
| 4475 | ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; } |
| 4476 | |
| 4477 | capture_const_iterator capture_begin() const { return captures().begin(); } |
| 4478 | capture_const_iterator capture_end() const { return captures().end(); } |
| 4479 | |
| 4480 | bool capturesCXXThis() const { return BlockDeclBits.CapturesCXXThis; } |
| 4481 | void setCapturesCXXThis(bool B = true) { BlockDeclBits.CapturesCXXThis = B; } |
| 4482 | |
| 4483 | bool blockMissingReturnType() const { |
| 4484 | return BlockDeclBits.BlockMissingReturnType; |
| 4485 | } |
| 4486 | |
| 4487 | void setBlockMissingReturnType(bool val = true) { |
| 4488 | BlockDeclBits.BlockMissingReturnType = val; |
| 4489 | } |
| 4490 | |
| 4491 | bool isConversionFromLambda() const { |
| 4492 | return BlockDeclBits.IsConversionFromLambda; |
| 4493 | } |
| 4494 | |
| 4495 | void setIsConversionFromLambda(bool val = true) { |
| 4496 | BlockDeclBits.IsConversionFromLambda = val; |
| 4497 | } |
| 4498 | |
| 4499 | bool doesNotEscape() const { return BlockDeclBits.DoesNotEscape; } |
| 4500 | void setDoesNotEscape(bool B = true) { BlockDeclBits.DoesNotEscape = B; } |
| 4501 | |
| 4502 | bool canAvoidCopyToHeap() const { |
| 4503 | return BlockDeclBits.CanAvoidCopyToHeap; |
| 4504 | } |
| 4505 | void setCanAvoidCopyToHeap(bool B = true) { |
| 4506 | BlockDeclBits.CanAvoidCopyToHeap = B; |
| 4507 | } |
| 4508 | |
| 4509 | bool capturesVariable(const VarDecl *var) const; |
| 4510 | |
| 4511 | void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures, |
| 4512 | bool CapturesCXXThis); |
| 4513 | |
| 4514 | unsigned getBlockManglingNumber() const { return ManglingNumber; } |
| 4515 | |
| 4516 | Decl *getBlockManglingContextDecl() const { return ManglingContextDecl; } |
| 4517 | |
| 4518 | void setBlockMangling(unsigned Number, Decl *Ctx) { |
| 4519 | ManglingNumber = Number; |
| 4520 | ManglingContextDecl = Ctx; |
| 4521 | } |
| 4522 | |
| 4523 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
| 4524 | |
| 4525 | // Implement isa/cast/dyncast/etc. |
| 4526 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 4527 | static bool classofKind(Kind K) { return K == Block; } |
| 4528 | static DeclContext *castToDeclContext(const BlockDecl *D) { |
| 4529 | return static_cast<DeclContext *>(const_cast<BlockDecl*>(D)); |
| 4530 | } |
| 4531 | static BlockDecl *castFromDeclContext(const DeclContext *DC) { |
| 4532 | return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC)); |
| 4533 | } |
| 4534 | }; |
| 4535 | |
| 4536 | /// Represents the body of a CapturedStmt, and serves as its DeclContext. |
| 4537 | class CapturedDecl final |
| 4538 | : public Decl, |
| 4539 | public DeclContext, |
| 4540 | private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> { |
| 4541 | protected: |
| 4542 | size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) { |
| 4543 | return NumParams; |
| 4544 | } |
| 4545 | |
| 4546 | private: |
| 4547 | /// The number of parameters to the outlined function. |
| 4548 | unsigned NumParams; |
| 4549 | |
| 4550 | /// The position of context parameter in list of parameters. |
| 4551 | unsigned ContextParam; |
| 4552 | |
| 4553 | /// The body of the outlined function. |
| 4554 | llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow; |
| 4555 | |
| 4556 | explicit CapturedDecl(DeclContext *DC, unsigned NumParams); |
| 4557 | |
| 4558 | ImplicitParamDecl *const *getParams() const { |
| 4559 | return getTrailingObjects<ImplicitParamDecl *>(); |
| 4560 | } |
| 4561 | |
| 4562 | ImplicitParamDecl **getParams() { |
| 4563 | return getTrailingObjects<ImplicitParamDecl *>(); |
| 4564 | } |
| 4565 | |
| 4566 | public: |
| 4567 | friend class ASTDeclReader; |
| 4568 | friend class ASTDeclWriter; |
| 4569 | friend TrailingObjects; |
| 4570 | |
| 4571 | static CapturedDecl *Create(ASTContext &C, DeclContext *DC, |
| 4572 | unsigned NumParams); |
| 4573 | static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
| 4574 | unsigned NumParams); |
| 4575 | |
| 4576 | Stmt *getBody() const override; |
| 4577 | void setBody(Stmt *B); |
| 4578 | |
| 4579 | bool isNothrow() const; |
| 4580 | void setNothrow(bool Nothrow = true); |
| 4581 | |
| 4582 | unsigned getNumParams() const { return NumParams; } |
| 4583 | |
| 4584 | ImplicitParamDecl *getParam(unsigned i) const { |
| 4585 | assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail ("i < NumParams", "clang/include/clang/AST/Decl.h", 4585, __extension__ __PRETTY_FUNCTION__)); |
| 4586 | return getParams()[i]; |
| 4587 | } |
| 4588 | void setParam(unsigned i, ImplicitParamDecl *P) { |
| 4589 | assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail ("i < NumParams", "clang/include/clang/AST/Decl.h", 4589, __extension__ __PRETTY_FUNCTION__)); |
| 4590 | getParams()[i] = P; |
| 4591 | } |
| 4592 | |
| 4593 | // ArrayRef interface to parameters. |
| 4594 | ArrayRef<ImplicitParamDecl *> parameters() const { |
| 4595 | return {getParams(), getNumParams()}; |
| 4596 | } |
| 4597 | MutableArrayRef<ImplicitParamDecl *> parameters() { |
| 4598 | return {getParams(), getNumParams()}; |
| 4599 | } |
| 4600 | |
| 4601 | /// Retrieve the parameter containing captured variables. |
| 4602 | ImplicitParamDecl *getContextParam() const { |
| 4603 | assert(ContextParam < NumParams)(static_cast <bool> (ContextParam < NumParams) ? void (0) : __assert_fail ("ContextParam < NumParams", "clang/include/clang/AST/Decl.h" , 4603, __extension__ __PRETTY_FUNCTION__)); |
| 4604 | return getParam(ContextParam); |
| 4605 | } |
| 4606 | void setContextParam(unsigned i, ImplicitParamDecl *P) { |
| 4607 | assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail ("i < NumParams", "clang/include/clang/AST/Decl.h", 4607, __extension__ __PRETTY_FUNCTION__)); |
| 4608 | ContextParam = i; |
| 4609 | setParam(i, P); |
| 4610 | } |
| 4611 | unsigned getContextParamPosition() const { return ContextParam; } |
| 4612 | |
| 4613 | using param_iterator = ImplicitParamDecl *const *; |
| 4614 | using param_range = llvm::iterator_range<param_iterator>; |
| 4615 | |
| 4616 | /// Retrieve an iterator pointing to the first parameter decl. |
| 4617 | param_iterator param_begin() const { return getParams(); } |
| 4618 | /// Retrieve an iterator one past the last parameter decl. |
| 4619 | param_iterator param_end() const { return getParams() + NumParams; } |
| 4620 | |
| 4621 | // Implement isa/cast/dyncast/etc. |
| 4622 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 4623 | static bool classofKind(Kind K) { return K == Captured; } |
| 4624 | static DeclContext *castToDeclContext(const CapturedDecl *D) { |
| 4625 | return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D)); |
| 4626 | } |
| 4627 | static CapturedDecl *castFromDeclContext(const DeclContext *DC) { |
| 4628 | return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC)); |
| 4629 | } |
| 4630 | }; |
| 4631 | |
| 4632 | /// Describes a module import declaration, which makes the contents |
| 4633 | /// of the named module visible in the current translation unit. |
| 4634 | /// |
| 4635 | /// An import declaration imports the named module (or submodule). For example: |
| 4636 | /// \code |
| 4637 | /// @import std.vector; |
| 4638 | /// \endcode |
| 4639 | /// |
| 4640 | /// A C++20 module import declaration imports the named module or partition. |
| 4641 | /// Periods are permitted in C++20 module names, but have no semantic meaning. |
| 4642 | /// For example: |
| 4643 | /// \code |
| 4644 | /// import NamedModule; |
| 4645 | /// import :SomePartition; // Must be a partition of the current module. |
| 4646 | /// import Names.Like.this; // Allowed. |
| 4647 | /// import :and.Also.Partition.names; |
| 4648 | /// \endcode |
| 4649 | /// |
| 4650 | /// Import declarations can also be implicitly generated from |
| 4651 | /// \#include/\#import directives. |
| 4652 | class ImportDecl final : public Decl, |
| 4653 | llvm::TrailingObjects<ImportDecl, SourceLocation> { |
| 4654 | friend class ASTContext; |
| 4655 | friend class ASTDeclReader; |
| 4656 | friend class ASTReader; |
| 4657 | friend TrailingObjects; |
| 4658 | |
| 4659 | /// The imported module. |
| 4660 | Module *ImportedModule = nullptr; |
| 4661 | |
| 4662 | /// The next import in the list of imports local to the translation |
| 4663 | /// unit being parsed (not loaded from an AST file). |
| 4664 | /// |
| 4665 | /// Includes a bit that indicates whether we have source-location information |
| 4666 | /// for each identifier in the module name. |
| 4667 | /// |
| 4668 | /// When the bit is false, we only have a single source location for the |
| 4669 | /// end of the import declaration. |
| 4670 | llvm::PointerIntPair<ImportDecl *, 1, bool> NextLocalImportAndComplete; |
| 4671 | |
| 4672 | ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, |
| 4673 | ArrayRef<SourceLocation> IdentifierLocs); |
| 4674 | |
| 4675 | ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, |
| 4676 | SourceLocation EndLoc); |
| 4677 | |
| 4678 | ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {} |
| 4679 | |
| 4680 | bool isImportComplete() const { return NextLocalImportAndComplete.getInt(); } |
| 4681 | |
| 4682 | void setImportComplete(bool C) { NextLocalImportAndComplete.setInt(C); } |
| 4683 | |
| 4684 | /// The next import in the list of imports local to the translation |
| 4685 | /// unit being parsed (not loaded from an AST file). |
| 4686 | ImportDecl *getNextLocalImport() const { |
| 4687 | return NextLocalImportAndComplete.getPointer(); |
| 4688 | } |
| 4689 | |
| 4690 | void setNextLocalImport(ImportDecl *Import) { |
| 4691 | NextLocalImportAndComplete.setPointer(Import); |
| 4692 | } |
| 4693 | |
| 4694 | public: |
| 4695 | /// Create a new module import declaration. |
| 4696 | static ImportDecl *Create(ASTContext &C, DeclContext *DC, |
| 4697 | SourceLocation StartLoc, Module *Imported, |
| 4698 | ArrayRef<SourceLocation> IdentifierLocs); |
| 4699 | |
| 4700 | /// Create a new module import declaration for an implicitly-generated |
| 4701 | /// import. |
| 4702 | static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC, |
| 4703 | SourceLocation StartLoc, Module *Imported, |
| 4704 | SourceLocation EndLoc); |
| 4705 | |
| 4706 | /// Create a new, deserialized module import declaration. |
| 4707 | static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
| 4708 | unsigned NumLocations); |
| 4709 | |
| 4710 | /// Retrieve the module that was imported by the import declaration. |
| 4711 | Module *getImportedModule() const { return ImportedModule; } |
| 4712 | |
| 4713 | /// Retrieves the locations of each of the identifiers that make up |
| 4714 | /// the complete module name in the import declaration. |
| 4715 | /// |
| 4716 | /// This will return an empty array if the locations of the individual |
| 4717 | /// identifiers aren't available. |
| 4718 | ArrayRef<SourceLocation> getIdentifierLocs() const; |
| 4719 | |
| 4720 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
| 4721 | |
| 4722 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 4723 | static bool classofKind(Kind K) { return K == Import; } |
| 4724 | }; |
| 4725 | |
| 4726 | /// Represents a standard C++ module export declaration. |
| 4727 | /// |
| 4728 | /// For example: |
| 4729 | /// \code |
| 4730 | /// export void foo(); |
| 4731 | /// \endcode |
| 4732 | class ExportDecl final : public Decl, public DeclContext { |
| 4733 | virtual void anchor(); |
| 4734 | |
| 4735 | private: |
| 4736 | friend class ASTDeclReader; |
| 4737 | |
| 4738 | /// The source location for the right brace (if valid). |
| 4739 | SourceLocation RBraceLoc; |
| 4740 | |
| 4741 | ExportDecl(DeclContext *DC, SourceLocation ExportLoc) |
| 4742 | : Decl(Export, DC, ExportLoc), DeclContext(Export), |
| 4743 | RBraceLoc(SourceLocation()) {} |
| 4744 | |
| 4745 | public: |
| 4746 | static ExportDecl *Create(ASTContext &C, DeclContext *DC, |
| 4747 | SourceLocation ExportLoc); |
| 4748 | static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 4749 | |
| 4750 | SourceLocation getExportLoc() const { return getLocation(); } |
| 4751 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
| 4752 | void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } |
| 4753 | |
| 4754 | bool hasBraces() const { return RBraceLoc.isValid(); } |
| 4755 | |
| 4756 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
| 4757 | if (hasBraces()) |
| 4758 | return RBraceLoc; |
| 4759 | // No braces: get the end location of the (only) declaration in context |
| 4760 | // (if present). |
| 4761 | return decls_empty() ? getLocation() : decls_begin()->getEndLoc(); |
| 4762 | } |
| 4763 | |
| 4764 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
| 4765 | return SourceRange(getLocation(), getEndLoc()); |
| 4766 | } |
| 4767 | |
| 4768 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 4769 | static bool classofKind(Kind K) { return K == Export; } |
| 4770 | static DeclContext *castToDeclContext(const ExportDecl *D) { |
| 4771 | return static_cast<DeclContext *>(const_cast<ExportDecl*>(D)); |
| 4772 | } |
| 4773 | static ExportDecl *castFromDeclContext(const DeclContext *DC) { |
| 4774 | return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC)); |
| 4775 | } |
| 4776 | }; |
| 4777 | |
| 4778 | /// Represents an empty-declaration. |
| 4779 | class EmptyDecl : public Decl { |
| 4780 | EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {} |
| 4781 | |
| 4782 | virtual void anchor(); |
| 4783 | |
| 4784 | public: |
| 4785 | static EmptyDecl *Create(ASTContext &C, DeclContext *DC, |
| 4786 | SourceLocation L); |
| 4787 | static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 4788 | |
| 4789 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 4790 | static bool classofKind(Kind K) { return K == Empty; } |
| 4791 | }; |
| 4792 | |
| 4793 | /// HLSLBufferDecl - Represent a cbuffer or tbuffer declaration. |
| 4794 | class HLSLBufferDecl final : public NamedDecl, public DeclContext { |
| 4795 | /// LBraceLoc - The ending location of the source range. |
| 4796 | SourceLocation LBraceLoc; |
| 4797 | /// RBraceLoc - The ending location of the source range. |
| 4798 | SourceLocation RBraceLoc; |
| 4799 | /// KwLoc - The location of the cbuffer or tbuffer keyword. |
| 4800 | SourceLocation KwLoc; |
| 4801 | /// IsCBuffer - Whether the buffer is a cbuffer (and not a tbuffer). |
| 4802 | bool IsCBuffer; |
| 4803 | |
| 4804 | HLSLBufferDecl(DeclContext *DC, bool CBuffer, SourceLocation KwLoc, |
| 4805 | IdentifierInfo *ID, SourceLocation IDLoc, |
| 4806 | SourceLocation LBrace); |
| 4807 | |
| 4808 | public: |
| 4809 | static HLSLBufferDecl *Create(ASTContext &C, DeclContext *LexicalParent, |
| 4810 | bool CBuffer, SourceLocation KwLoc, |
| 4811 | IdentifierInfo *ID, SourceLocation IDLoc, |
| 4812 | SourceLocation LBrace); |
| 4813 | static HLSLBufferDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
| 4814 | |
| 4815 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
| 4816 | return SourceRange(getLocStart(), RBraceLoc); |
| 4817 | } |
| 4818 | SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return KwLoc; } |
| 4819 | SourceLocation getLBraceLoc() const { return LBraceLoc; } |
| 4820 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
| 4821 | void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } |
| 4822 | bool isCBuffer() const { return IsCBuffer; } |
| 4823 | |
| 4824 | // Implement isa/cast/dyncast/etc. |
| 4825 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
| 4826 | static bool classofKind(Kind K) { return K == HLSLBuffer; } |
| 4827 | static DeclContext *castToDeclContext(const HLSLBufferDecl *D) { |
| 4828 | return static_cast<DeclContext *>(const_cast<HLSLBufferDecl *>(D)); |
| 4829 | } |
| 4830 | static HLSLBufferDecl *castFromDeclContext(const DeclContext *DC) { |
| 4831 | return static_cast<HLSLBufferDecl *>(const_cast<DeclContext *>(DC)); |
| 4832 | } |
| 4833 | |
| 4834 | friend class ASTDeclReader; |
| 4835 | friend class ASTDeclWriter; |
| 4836 | }; |
| 4837 | |
| 4838 | /// Insertion operator for diagnostics. This allows sending NamedDecl's |
| 4839 | /// into a diagnostic with <<. |
| 4840 | inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, |
| 4841 | const NamedDecl *ND) { |
| 4842 | PD.AddTaggedVal(reinterpret_cast<uint64_t>(ND), |
| 4843 | DiagnosticsEngine::ak_nameddecl); |
| 4844 | return PD; |
| 4845 | } |
| 4846 | |
| 4847 | template<typename decl_type> |
| 4848 | void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) { |
| 4849 | // Note: This routine is implemented here because we need both NamedDecl |
| 4850 | // and Redeclarable to be defined. |
| 4851 | assert(RedeclLink.isFirst() &&(static_cast <bool> (RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain" ) ? void (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\"" , "clang/include/clang/AST/Decl.h", 4852, __extension__ __PRETTY_FUNCTION__ )) |
| 4852 | "setPreviousDecl on a decl already in a redeclaration chain")(static_cast <bool> (RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain" ) ? void (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\"" , "clang/include/clang/AST/Decl.h", 4852, __extension__ __PRETTY_FUNCTION__ )); |
| 4853 | |
| 4854 | if (PrevDecl) { |
| 4855 | // Point to previous. Make sure that this is actually the most recent |
| 4856 | // redeclaration, or we can build invalid chains. If the most recent |
| 4857 | // redeclaration is invalid, it won't be PrevDecl, but we want it anyway. |
| 4858 | First = PrevDecl->getFirstDecl(); |
| 4859 | assert(First->RedeclLink.isFirst() && "Expected first")(static_cast <bool> (First->RedeclLink.isFirst() && "Expected first") ? void (0) : __assert_fail ("First->RedeclLink.isFirst() && \"Expected first\"" , "clang/include/clang/AST/Decl.h", 4859, __extension__ __PRETTY_FUNCTION__ )); |
| 4860 | decl_type *MostRecent = First->getNextRedeclaration(); |
| 4861 | RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent)); |
| 4862 | |
| 4863 | // If the declaration was previously visible, a redeclaration of it remains |
| 4864 | // visible even if it wouldn't be visible by itself. |
| 4865 | static_cast<decl_type*>(this)->IdentifierNamespace |= |
| 4866 | MostRecent->getIdentifierNamespace() & |
| 4867 | (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type); |
| 4868 | } else { |
| 4869 | // Make this first. |
| 4870 | First = static_cast<decl_type*>(this); |
| 4871 | } |
| 4872 | |
| 4873 | // First one will point to this one as latest. |
| 4874 | First->RedeclLink.setLatest(static_cast<decl_type*>(this)); |
| 4875 | |
| 4876 | assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||(static_cast <bool> (!isa<NamedDecl>(static_cast< decl_type*>(this)) || cast<NamedDecl>(static_cast< decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail ("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()" , "clang/include/clang/AST/Decl.h", 4877, __extension__ __PRETTY_FUNCTION__ )) |
| 4877 | cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid())(static_cast <bool> (!isa<NamedDecl>(static_cast< decl_type*>(this)) || cast<NamedDecl>(static_cast< decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail ("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()" , "clang/include/clang/AST/Decl.h", 4877, __extension__ __PRETTY_FUNCTION__ )); |
| 4878 | } |
| 4879 | |
| 4880 | // Inline function definitions. |
| 4881 | |
| 4882 | /// Check if the given decl is complete. |
| 4883 | /// |
| 4884 | /// We use this function to break a cycle between the inline definitions in |
| 4885 | /// Type.h and Decl.h. |
| 4886 | inline bool IsEnumDeclComplete(EnumDecl *ED) { |
| 4887 | return ED->isComplete(); |
| 4888 | } |
| 4889 | |
| 4890 | /// Check if the given decl is scoped. |
| 4891 | /// |
| 4892 | /// We use this function to break a cycle between the inline definitions in |
| 4893 | /// Type.h and Decl.h. |
| 4894 | inline bool IsEnumDeclScoped(EnumDecl *ED) { |
| 4895 | return ED->isScoped(); |
| 4896 | } |
| 4897 | |
| 4898 | /// OpenMP variants are mangled early based on their OpenMP context selector. |
| 4899 | /// The new name looks likes this: |
| 4900 | /// <name> + OpenMPVariantManglingSeparatorStr + <mangled OpenMP context> |
| 4901 | static constexpr StringRef getOpenMPVariantManglingSeparatorStr() { |
| 4902 | return "$ompvariant"; |
| 4903 | } |
| 4904 | |
| 4905 | } // namespace clang |
| 4906 | |
| 4907 | #endif // LLVM_CLANG_AST_DECL_H |