1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 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 the Expr constant evaluator. 10 // 11 // Constant expression evaluation produces four main results: 12 // 13 // * A success/failure flag indicating whether constant folding was successful. 14 // This is the 'bool' return value used by most of the code in this file. A 15 // 'false' return value indicates that constant folding has failed, and any 16 // appropriate diagnostic has already been produced. 17 // 18 // * An evaluated result, valid only if constant folding has not failed. 19 // 20 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 21 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 22 // where it is possible to determine the evaluated result regardless. 23 // 24 // * A set of notes indicating why the evaluation was not a constant expression 25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 26 // too, why the expression could not be folded. 27 // 28 // If we are checking for a potential constant expression, failure to constant 29 // fold a potential constant sub-expression will be indicated by a 'false' 30 // return value (the expression could not be folded) and no diagnostic (the 31 // expression is not necessarily non-constant). 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "Interp/Context.h" 36 #include "Interp/Frame.h" 37 #include "Interp/State.h" 38 #include "clang/AST/APValue.h" 39 #include "clang/AST/ASTContext.h" 40 #include "clang/AST/ASTDiagnostic.h" 41 #include "clang/AST/ASTLambda.h" 42 #include "clang/AST/Attr.h" 43 #include "clang/AST/CXXInheritance.h" 44 #include "clang/AST/CharUnits.h" 45 #include "clang/AST/CurrentSourceLocExprScope.h" 46 #include "clang/AST/Expr.h" 47 #include "clang/AST/OSLog.h" 48 #include "clang/AST/OptionalDiagnostic.h" 49 #include "clang/AST/RecordLayout.h" 50 #include "clang/AST/StmtVisitor.h" 51 #include "clang/AST/TypeLoc.h" 52 #include "clang/Basic/Builtins.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "llvm/ADT/APFixedPoint.h" 55 #include "llvm/ADT/Optional.h" 56 #include "llvm/ADT/SmallBitVector.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/SaveAndRestore.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include <cstring> 61 #include <functional> 62 63 #define DEBUG_TYPE "exprconstant" 64 65 using namespace clang; 66 using llvm::APFixedPoint; 67 using llvm::APInt; 68 using llvm::APSInt; 69 using llvm::APFloat; 70 using llvm::FixedPointSemantics; 71 using llvm::Optional; 72 73 namespace { 74 struct LValue; 75 class CallStackFrame; 76 class EvalInfo; 77 78 using SourceLocExprScopeGuard = 79 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 80 81 static QualType getType(APValue::LValueBase B) { 82 if (!B) return QualType(); 83 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 84 // FIXME: It's unclear where we're supposed to take the type from, and 85 // this actually matters for arrays of unknown bound. Eg: 86 // 87 // extern int arr[]; void f() { extern int arr[3]; }; 88 // constexpr int *p = &arr[1]; // valid? 89 // 90 // For now, we take the array bound from the most recent declaration. 91 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 92 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 93 QualType T = Redecl->getType(); 94 if (!T->isIncompleteArrayType()) 95 return T; 96 } 97 return D->getType(); 98 } 99 100 if (B.is<TypeInfoLValue>()) 101 return B.getTypeInfoType(); 102 103 if (B.is<DynamicAllocLValue>()) 104 return B.getDynamicAllocType(); 105 106 const Expr *Base = B.get<const Expr*>(); 107 108 // For a materialized temporary, the type of the temporary we materialized 109 // may not be the type of the expression. 110 if (const MaterializeTemporaryExpr *MTE = 111 dyn_cast<MaterializeTemporaryExpr>(Base)) { 112 SmallVector<const Expr *, 2> CommaLHSs; 113 SmallVector<SubobjectAdjustment, 2> Adjustments; 114 const Expr *Temp = MTE->getSubExpr(); 115 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 116 Adjustments); 117 // Keep any cv-qualifiers from the reference if we generated a temporary 118 // for it directly. Otherwise use the type after adjustment. 119 if (!Adjustments.empty()) 120 return Inner->getType(); 121 } 122 123 return Base->getType(); 124 } 125 126 /// Get an LValue path entry, which is known to not be an array index, as a 127 /// field declaration. 128 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 129 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 130 } 131 /// Get an LValue path entry, which is known to not be an array index, as a 132 /// base class declaration. 133 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 134 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 135 } 136 /// Determine whether this LValue path entry for a base class names a virtual 137 /// base class. 138 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 139 return E.getAsBaseOrMember().getInt(); 140 } 141 142 /// Given an expression, determine the type used to store the result of 143 /// evaluating that expression. 144 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 145 if (E->isRValue()) 146 return E->getType(); 147 return Ctx.getLValueReferenceType(E->getType()); 148 } 149 150 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 151 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 152 const FunctionDecl *Callee = CE->getDirectCallee(); 153 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 154 } 155 156 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 157 /// This will look through a single cast. 158 /// 159 /// Returns null if we couldn't unwrap a function with alloc_size. 160 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 161 if (!E->getType()->isPointerType()) 162 return nullptr; 163 164 E = E->IgnoreParens(); 165 // If we're doing a variable assignment from e.g. malloc(N), there will 166 // probably be a cast of some kind. In exotic cases, we might also see a 167 // top-level ExprWithCleanups. Ignore them either way. 168 if (const auto *FE = dyn_cast<FullExpr>(E)) 169 E = FE->getSubExpr()->IgnoreParens(); 170 171 if (const auto *Cast = dyn_cast<CastExpr>(E)) 172 E = Cast->getSubExpr()->IgnoreParens(); 173 174 if (const auto *CE = dyn_cast<CallExpr>(E)) 175 return getAllocSizeAttr(CE) ? CE : nullptr; 176 return nullptr; 177 } 178 179 /// Determines whether or not the given Base contains a call to a function 180 /// with the alloc_size attribute. 181 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 182 const auto *E = Base.dyn_cast<const Expr *>(); 183 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 184 } 185 186 /// The bound to claim that an array of unknown bound has. 187 /// The value in MostDerivedArraySize is undefined in this case. So, set it 188 /// to an arbitrary value that's likely to loudly break things if it's used. 189 static const uint64_t AssumedSizeForUnsizedArray = 190 std::numeric_limits<uint64_t>::max() / 2; 191 192 /// Determines if an LValue with the given LValueBase will have an unsized 193 /// array in its designator. 194 /// Find the path length and type of the most-derived subobject in the given 195 /// path, and find the size of the containing array, if any. 196 static unsigned 197 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 198 ArrayRef<APValue::LValuePathEntry> Path, 199 uint64_t &ArraySize, QualType &Type, bool &IsArray, 200 bool &FirstEntryIsUnsizedArray) { 201 // This only accepts LValueBases from APValues, and APValues don't support 202 // arrays that lack size info. 203 assert(!isBaseAnAllocSizeCall(Base) && 204 "Unsized arrays shouldn't appear here"); 205 unsigned MostDerivedLength = 0; 206 Type = getType(Base); 207 208 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 209 if (Type->isArrayType()) { 210 const ArrayType *AT = Ctx.getAsArrayType(Type); 211 Type = AT->getElementType(); 212 MostDerivedLength = I + 1; 213 IsArray = true; 214 215 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 216 ArraySize = CAT->getSize().getZExtValue(); 217 } else { 218 assert(I == 0 && "unexpected unsized array designator"); 219 FirstEntryIsUnsizedArray = true; 220 ArraySize = AssumedSizeForUnsizedArray; 221 } 222 } else if (Type->isAnyComplexType()) { 223 const ComplexType *CT = Type->castAs<ComplexType>(); 224 Type = CT->getElementType(); 225 ArraySize = 2; 226 MostDerivedLength = I + 1; 227 IsArray = true; 228 } else if (const FieldDecl *FD = getAsField(Path[I])) { 229 Type = FD->getType(); 230 ArraySize = 0; 231 MostDerivedLength = I + 1; 232 IsArray = false; 233 } else { 234 // Path[I] describes a base class. 235 ArraySize = 0; 236 IsArray = false; 237 } 238 } 239 return MostDerivedLength; 240 } 241 242 /// A path from a glvalue to a subobject of that glvalue. 243 struct SubobjectDesignator { 244 /// True if the subobject was named in a manner not supported by C++11. Such 245 /// lvalues can still be folded, but they are not core constant expressions 246 /// and we cannot perform lvalue-to-rvalue conversions on them. 247 unsigned Invalid : 1; 248 249 /// Is this a pointer one past the end of an object? 250 unsigned IsOnePastTheEnd : 1; 251 252 /// Indicator of whether the first entry is an unsized array. 253 unsigned FirstEntryIsAnUnsizedArray : 1; 254 255 /// Indicator of whether the most-derived object is an array element. 256 unsigned MostDerivedIsArrayElement : 1; 257 258 /// The length of the path to the most-derived object of which this is a 259 /// subobject. 260 unsigned MostDerivedPathLength : 28; 261 262 /// The size of the array of which the most-derived object is an element. 263 /// This will always be 0 if the most-derived object is not an array 264 /// element. 0 is not an indicator of whether or not the most-derived object 265 /// is an array, however, because 0-length arrays are allowed. 266 /// 267 /// If the current array is an unsized array, the value of this is 268 /// undefined. 269 uint64_t MostDerivedArraySize; 270 271 /// The type of the most derived object referred to by this address. 272 QualType MostDerivedType; 273 274 typedef APValue::LValuePathEntry PathEntry; 275 276 /// The entries on the path from the glvalue to the designated subobject. 277 SmallVector<PathEntry, 8> Entries; 278 279 SubobjectDesignator() : Invalid(true) {} 280 281 explicit SubobjectDesignator(QualType T) 282 : Invalid(false), IsOnePastTheEnd(false), 283 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 284 MostDerivedPathLength(0), MostDerivedArraySize(0), 285 MostDerivedType(T) {} 286 287 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 288 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 289 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 290 MostDerivedPathLength(0), MostDerivedArraySize(0) { 291 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 292 if (!Invalid) { 293 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 294 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 295 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 296 if (V.getLValueBase()) { 297 bool IsArray = false; 298 bool FirstIsUnsizedArray = false; 299 MostDerivedPathLength = findMostDerivedSubobject( 300 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 301 MostDerivedType, IsArray, FirstIsUnsizedArray); 302 MostDerivedIsArrayElement = IsArray; 303 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 304 } 305 } 306 } 307 308 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 309 unsigned NewLength) { 310 if (Invalid) 311 return; 312 313 assert(Base && "cannot truncate path for null pointer"); 314 assert(NewLength <= Entries.size() && "not a truncation"); 315 316 if (NewLength == Entries.size()) 317 return; 318 Entries.resize(NewLength); 319 320 bool IsArray = false; 321 bool FirstIsUnsizedArray = false; 322 MostDerivedPathLength = findMostDerivedSubobject( 323 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 324 FirstIsUnsizedArray); 325 MostDerivedIsArrayElement = IsArray; 326 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 327 } 328 329 void setInvalid() { 330 Invalid = true; 331 Entries.clear(); 332 } 333 334 /// Determine whether the most derived subobject is an array without a 335 /// known bound. 336 bool isMostDerivedAnUnsizedArray() const { 337 assert(!Invalid && "Calling this makes no sense on invalid designators"); 338 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 339 } 340 341 /// Determine what the most derived array's size is. Results in an assertion 342 /// failure if the most derived array lacks a size. 343 uint64_t getMostDerivedArraySize() const { 344 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 345 return MostDerivedArraySize; 346 } 347 348 /// Determine whether this is a one-past-the-end pointer. 349 bool isOnePastTheEnd() const { 350 assert(!Invalid); 351 if (IsOnePastTheEnd) 352 return true; 353 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 354 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 355 MostDerivedArraySize) 356 return true; 357 return false; 358 } 359 360 /// Get the range of valid index adjustments in the form 361 /// {maximum value that can be subtracted from this pointer, 362 /// maximum value that can be added to this pointer} 363 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 364 if (Invalid || isMostDerivedAnUnsizedArray()) 365 return {0, 0}; 366 367 // [expr.add]p4: For the purposes of these operators, a pointer to a 368 // nonarray object behaves the same as a pointer to the first element of 369 // an array of length one with the type of the object as its element type. 370 bool IsArray = MostDerivedPathLength == Entries.size() && 371 MostDerivedIsArrayElement; 372 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 373 : (uint64_t)IsOnePastTheEnd; 374 uint64_t ArraySize = 375 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 376 return {ArrayIndex, ArraySize - ArrayIndex}; 377 } 378 379 /// Check that this refers to a valid subobject. 380 bool isValidSubobject() const { 381 if (Invalid) 382 return false; 383 return !isOnePastTheEnd(); 384 } 385 /// Check that this refers to a valid subobject, and if not, produce a 386 /// relevant diagnostic and set the designator as invalid. 387 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 388 389 /// Get the type of the designated object. 390 QualType getType(ASTContext &Ctx) const { 391 assert(!Invalid && "invalid designator has no subobject type"); 392 return MostDerivedPathLength == Entries.size() 393 ? MostDerivedType 394 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 395 } 396 397 /// Update this designator to refer to the first element within this array. 398 void addArrayUnchecked(const ConstantArrayType *CAT) { 399 Entries.push_back(PathEntry::ArrayIndex(0)); 400 401 // This is a most-derived object. 402 MostDerivedType = CAT->getElementType(); 403 MostDerivedIsArrayElement = true; 404 MostDerivedArraySize = CAT->getSize().getZExtValue(); 405 MostDerivedPathLength = Entries.size(); 406 } 407 /// Update this designator to refer to the first element within the array of 408 /// elements of type T. This is an array of unknown size. 409 void addUnsizedArrayUnchecked(QualType ElemTy) { 410 Entries.push_back(PathEntry::ArrayIndex(0)); 411 412 MostDerivedType = ElemTy; 413 MostDerivedIsArrayElement = true; 414 // The value in MostDerivedArraySize is undefined in this case. So, set it 415 // to an arbitrary value that's likely to loudly break things if it's 416 // used. 417 MostDerivedArraySize = AssumedSizeForUnsizedArray; 418 MostDerivedPathLength = Entries.size(); 419 } 420 /// Update this designator to refer to the given base or member of this 421 /// object. 422 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 423 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 424 425 // If this isn't a base class, it's a new most-derived object. 426 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 427 MostDerivedType = FD->getType(); 428 MostDerivedIsArrayElement = false; 429 MostDerivedArraySize = 0; 430 MostDerivedPathLength = Entries.size(); 431 } 432 } 433 /// Update this designator to refer to the given complex component. 434 void addComplexUnchecked(QualType EltTy, bool Imag) { 435 Entries.push_back(PathEntry::ArrayIndex(Imag)); 436 437 // This is technically a most-derived object, though in practice this 438 // is unlikely to matter. 439 MostDerivedType = EltTy; 440 MostDerivedIsArrayElement = true; 441 MostDerivedArraySize = 2; 442 MostDerivedPathLength = Entries.size(); 443 } 444 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 445 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 446 const APSInt &N); 447 /// Add N to the address of this subobject. 448 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 449 if (Invalid || !N) return; 450 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 451 if (isMostDerivedAnUnsizedArray()) { 452 diagnoseUnsizedArrayPointerArithmetic(Info, E); 453 // Can't verify -- trust that the user is doing the right thing (or if 454 // not, trust that the caller will catch the bad behavior). 455 // FIXME: Should we reject if this overflows, at least? 456 Entries.back() = PathEntry::ArrayIndex( 457 Entries.back().getAsArrayIndex() + TruncatedN); 458 return; 459 } 460 461 // [expr.add]p4: For the purposes of these operators, a pointer to a 462 // nonarray object behaves the same as a pointer to the first element of 463 // an array of length one with the type of the object as its element type. 464 bool IsArray = MostDerivedPathLength == Entries.size() && 465 MostDerivedIsArrayElement; 466 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 467 : (uint64_t)IsOnePastTheEnd; 468 uint64_t ArraySize = 469 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 470 471 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 472 // Calculate the actual index in a wide enough type, so we can include 473 // it in the note. 474 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 475 (llvm::APInt&)N += ArrayIndex; 476 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 477 diagnosePointerArithmetic(Info, E, N); 478 setInvalid(); 479 return; 480 } 481 482 ArrayIndex += TruncatedN; 483 assert(ArrayIndex <= ArraySize && 484 "bounds check succeeded for out-of-bounds index"); 485 486 if (IsArray) 487 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 488 else 489 IsOnePastTheEnd = (ArrayIndex != 0); 490 } 491 }; 492 493 /// A stack frame in the constexpr call stack. 494 class CallStackFrame : public interp::Frame { 495 public: 496 EvalInfo &Info; 497 498 /// Parent - The caller of this stack frame. 499 CallStackFrame *Caller; 500 501 /// Callee - The function which was called. 502 const FunctionDecl *Callee; 503 504 /// This - The binding for the this pointer in this call, if any. 505 const LValue *This; 506 507 /// Arguments - Parameter bindings for this function call, indexed by 508 /// parameters' function scope indices. 509 APValue *Arguments; 510 511 /// Source location information about the default argument or default 512 /// initializer expression we're evaluating, if any. 513 CurrentSourceLocExprScope CurSourceLocExprScope; 514 515 // Note that we intentionally use std::map here so that references to 516 // values are stable. 517 typedef std::pair<const void *, unsigned> MapKeyTy; 518 typedef std::map<MapKeyTy, APValue> MapTy; 519 /// Temporaries - Temporary lvalues materialized within this stack frame. 520 MapTy Temporaries; 521 522 /// CallLoc - The location of the call expression for this call. 523 SourceLocation CallLoc; 524 525 /// Index - The call index of this call. 526 unsigned Index; 527 528 /// The stack of integers for tracking version numbers for temporaries. 529 SmallVector<unsigned, 2> TempVersionStack = {1}; 530 unsigned CurTempVersion = TempVersionStack.back(); 531 532 unsigned getTempVersion() const { return TempVersionStack.back(); } 533 534 void pushTempVersion() { 535 TempVersionStack.push_back(++CurTempVersion); 536 } 537 538 void popTempVersion() { 539 TempVersionStack.pop_back(); 540 } 541 542 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 543 // on the overall stack usage of deeply-recursing constexpr evaluations. 544 // (We should cache this map rather than recomputing it repeatedly.) 545 // But let's try this and see how it goes; we can look into caching the map 546 // as a later change. 547 548 /// LambdaCaptureFields - Mapping from captured variables/this to 549 /// corresponding data members in the closure class. 550 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 551 FieldDecl *LambdaThisCaptureField; 552 553 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 554 const FunctionDecl *Callee, const LValue *This, 555 APValue *Arguments); 556 ~CallStackFrame(); 557 558 // Return the temporary for Key whose version number is Version. 559 APValue *getTemporary(const void *Key, unsigned Version) { 560 MapKeyTy KV(Key, Version); 561 auto LB = Temporaries.lower_bound(KV); 562 if (LB != Temporaries.end() && LB->first == KV) 563 return &LB->second; 564 // Pair (Key,Version) wasn't found in the map. Check that no elements 565 // in the map have 'Key' as their key. 566 assert((LB == Temporaries.end() || LB->first.first != Key) && 567 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 568 "Element with key 'Key' found in map"); 569 return nullptr; 570 } 571 572 // Return the current temporary for Key in the map. 573 APValue *getCurrentTemporary(const void *Key) { 574 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 575 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 576 return &std::prev(UB)->second; 577 return nullptr; 578 } 579 580 // Return the version number of the current temporary for Key. 581 unsigned getCurrentTemporaryVersion(const void *Key) const { 582 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 583 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 584 return std::prev(UB)->first.second; 585 return 0; 586 } 587 588 /// Allocate storage for an object of type T in this stack frame. 589 /// Populates LV with a handle to the created object. Key identifies 590 /// the temporary within the stack frame, and must not be reused without 591 /// bumping the temporary version number. 592 template<typename KeyT> 593 APValue &createTemporary(const KeyT *Key, QualType T, 594 bool IsLifetimeExtended, LValue &LV); 595 596 void describe(llvm::raw_ostream &OS) override; 597 598 Frame *getCaller() const override { return Caller; } 599 SourceLocation getCallLocation() const override { return CallLoc; } 600 const FunctionDecl *getCallee() const override { return Callee; } 601 602 bool isStdFunction() const { 603 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 604 if (DC->isStdNamespace()) 605 return true; 606 return false; 607 } 608 }; 609 610 /// Temporarily override 'this'. 611 class ThisOverrideRAII { 612 public: 613 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 614 : Frame(Frame), OldThis(Frame.This) { 615 if (Enable) 616 Frame.This = NewThis; 617 } 618 ~ThisOverrideRAII() { 619 Frame.This = OldThis; 620 } 621 private: 622 CallStackFrame &Frame; 623 const LValue *OldThis; 624 }; 625 } 626 627 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 628 const LValue &This, QualType ThisType); 629 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 630 APValue::LValueBase LVBase, APValue &Value, 631 QualType T); 632 633 namespace { 634 /// A cleanup, and a flag indicating whether it is lifetime-extended. 635 class Cleanup { 636 llvm::PointerIntPair<APValue*, 1, bool> Value; 637 APValue::LValueBase Base; 638 QualType T; 639 640 public: 641 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 642 bool IsLifetimeExtended) 643 : Value(Val, IsLifetimeExtended), Base(Base), T(T) {} 644 645 bool isLifetimeExtended() const { return Value.getInt(); } 646 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 647 if (RunDestructors) { 648 SourceLocation Loc; 649 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 650 Loc = VD->getLocation(); 651 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 652 Loc = E->getExprLoc(); 653 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 654 } 655 *Value.getPointer() = APValue(); 656 return true; 657 } 658 659 bool hasSideEffect() { 660 return T.isDestructedType(); 661 } 662 }; 663 664 /// A reference to an object whose construction we are currently evaluating. 665 struct ObjectUnderConstruction { 666 APValue::LValueBase Base; 667 ArrayRef<APValue::LValuePathEntry> Path; 668 friend bool operator==(const ObjectUnderConstruction &LHS, 669 const ObjectUnderConstruction &RHS) { 670 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 671 } 672 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 673 return llvm::hash_combine(Obj.Base, Obj.Path); 674 } 675 }; 676 enum class ConstructionPhase { 677 None, 678 Bases, 679 AfterBases, 680 AfterFields, 681 Destroying, 682 DestroyingBases 683 }; 684 } 685 686 namespace llvm { 687 template<> struct DenseMapInfo<ObjectUnderConstruction> { 688 using Base = DenseMapInfo<APValue::LValueBase>; 689 static ObjectUnderConstruction getEmptyKey() { 690 return {Base::getEmptyKey(), {}}; } 691 static ObjectUnderConstruction getTombstoneKey() { 692 return {Base::getTombstoneKey(), {}}; 693 } 694 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 695 return hash_value(Object); 696 } 697 static bool isEqual(const ObjectUnderConstruction &LHS, 698 const ObjectUnderConstruction &RHS) { 699 return LHS == RHS; 700 } 701 }; 702 } 703 704 namespace { 705 /// A dynamically-allocated heap object. 706 struct DynAlloc { 707 /// The value of this heap-allocated object. 708 APValue Value; 709 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 710 /// or a CallExpr (the latter is for direct calls to operator new inside 711 /// std::allocator<T>::allocate). 712 const Expr *AllocExpr = nullptr; 713 714 enum Kind { 715 New, 716 ArrayNew, 717 StdAllocator 718 }; 719 720 /// Get the kind of the allocation. This must match between allocation 721 /// and deallocation. 722 Kind getKind() const { 723 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 724 return NE->isArray() ? ArrayNew : New; 725 assert(isa<CallExpr>(AllocExpr)); 726 return StdAllocator; 727 } 728 }; 729 730 struct DynAllocOrder { 731 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 732 return L.getIndex() < R.getIndex(); 733 } 734 }; 735 736 /// EvalInfo - This is a private struct used by the evaluator to capture 737 /// information about a subexpression as it is folded. It retains information 738 /// about the AST context, but also maintains information about the folded 739 /// expression. 740 /// 741 /// If an expression could be evaluated, it is still possible it is not a C 742 /// "integer constant expression" or constant expression. If not, this struct 743 /// captures information about how and why not. 744 /// 745 /// One bit of information passed *into* the request for constant folding 746 /// indicates whether the subexpression is "evaluated" or not according to C 747 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 748 /// evaluate the expression regardless of what the RHS is, but C only allows 749 /// certain things in certain situations. 750 class EvalInfo : public interp::State { 751 public: 752 ASTContext &Ctx; 753 754 /// EvalStatus - Contains information about the evaluation. 755 Expr::EvalStatus &EvalStatus; 756 757 /// CurrentCall - The top of the constexpr call stack. 758 CallStackFrame *CurrentCall; 759 760 /// CallStackDepth - The number of calls in the call stack right now. 761 unsigned CallStackDepth; 762 763 /// NextCallIndex - The next call index to assign. 764 unsigned NextCallIndex; 765 766 /// StepsLeft - The remaining number of evaluation steps we're permitted 767 /// to perform. This is essentially a limit for the number of statements 768 /// we will evaluate. 769 unsigned StepsLeft; 770 771 /// Enable the experimental new constant interpreter. If an expression is 772 /// not supported by the interpreter, an error is triggered. 773 bool EnableNewConstInterp; 774 775 /// BottomFrame - The frame in which evaluation started. This must be 776 /// initialized after CurrentCall and CallStackDepth. 777 CallStackFrame BottomFrame; 778 779 /// A stack of values whose lifetimes end at the end of some surrounding 780 /// evaluation frame. 781 llvm::SmallVector<Cleanup, 16> CleanupStack; 782 783 /// EvaluatingDecl - This is the declaration whose initializer is being 784 /// evaluated, if any. 785 APValue::LValueBase EvaluatingDecl; 786 787 enum class EvaluatingDeclKind { 788 None, 789 /// We're evaluating the construction of EvaluatingDecl. 790 Ctor, 791 /// We're evaluating the destruction of EvaluatingDecl. 792 Dtor, 793 }; 794 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 795 796 /// EvaluatingDeclValue - This is the value being constructed for the 797 /// declaration whose initializer is being evaluated, if any. 798 APValue *EvaluatingDeclValue; 799 800 /// Set of objects that are currently being constructed. 801 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 802 ObjectsUnderConstruction; 803 804 /// Current heap allocations, along with the location where each was 805 /// allocated. We use std::map here because we need stable addresses 806 /// for the stored APValues. 807 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 808 809 /// The number of heap allocations performed so far in this evaluation. 810 unsigned NumHeapAllocs = 0; 811 812 struct EvaluatingConstructorRAII { 813 EvalInfo &EI; 814 ObjectUnderConstruction Object; 815 bool DidInsert; 816 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 817 bool HasBases) 818 : EI(EI), Object(Object) { 819 DidInsert = 820 EI.ObjectsUnderConstruction 821 .insert({Object, HasBases ? ConstructionPhase::Bases 822 : ConstructionPhase::AfterBases}) 823 .second; 824 } 825 void finishedConstructingBases() { 826 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 827 } 828 void finishedConstructingFields() { 829 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 830 } 831 ~EvaluatingConstructorRAII() { 832 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 833 } 834 }; 835 836 struct EvaluatingDestructorRAII { 837 EvalInfo &EI; 838 ObjectUnderConstruction Object; 839 bool DidInsert; 840 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 841 : EI(EI), Object(Object) { 842 DidInsert = EI.ObjectsUnderConstruction 843 .insert({Object, ConstructionPhase::Destroying}) 844 .second; 845 } 846 void startedDestroyingBases() { 847 EI.ObjectsUnderConstruction[Object] = 848 ConstructionPhase::DestroyingBases; 849 } 850 ~EvaluatingDestructorRAII() { 851 if (DidInsert) 852 EI.ObjectsUnderConstruction.erase(Object); 853 } 854 }; 855 856 ConstructionPhase 857 isEvaluatingCtorDtor(APValue::LValueBase Base, 858 ArrayRef<APValue::LValuePathEntry> Path) { 859 return ObjectsUnderConstruction.lookup({Base, Path}); 860 } 861 862 /// If we're currently speculatively evaluating, the outermost call stack 863 /// depth at which we can mutate state, otherwise 0. 864 unsigned SpeculativeEvaluationDepth = 0; 865 866 /// The current array initialization index, if we're performing array 867 /// initialization. 868 uint64_t ArrayInitIndex = -1; 869 870 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 871 /// notes attached to it will also be stored, otherwise they will not be. 872 bool HasActiveDiagnostic; 873 874 /// Have we emitted a diagnostic explaining why we couldn't constant 875 /// fold (not just why it's not strictly a constant expression)? 876 bool HasFoldFailureDiagnostic; 877 878 /// Whether or not we're in a context where the front end requires a 879 /// constant value. 880 bool InConstantContext; 881 882 /// Whether we're checking that an expression is a potential constant 883 /// expression. If so, do not fail on constructs that could become constant 884 /// later on (such as a use of an undefined global). 885 bool CheckingPotentialConstantExpression = false; 886 887 /// Whether we're checking for an expression that has undefined behavior. 888 /// If so, we will produce warnings if we encounter an operation that is 889 /// always undefined. 890 bool CheckingForUndefinedBehavior = false; 891 892 enum EvaluationMode { 893 /// Evaluate as a constant expression. Stop if we find that the expression 894 /// is not a constant expression. 895 EM_ConstantExpression, 896 897 /// Evaluate as a constant expression. Stop if we find that the expression 898 /// is not a constant expression. Some expressions can be retried in the 899 /// optimizer if we don't constant fold them here, but in an unevaluated 900 /// context we try to fold them immediately since the optimizer never 901 /// gets a chance to look at it. 902 EM_ConstantExpressionUnevaluated, 903 904 /// Fold the expression to a constant. Stop if we hit a side-effect that 905 /// we can't model. 906 EM_ConstantFold, 907 908 /// Evaluate in any way we know how. Don't worry about side-effects that 909 /// can't be modeled. 910 EM_IgnoreSideEffects, 911 } EvalMode; 912 913 /// Are we checking whether the expression is a potential constant 914 /// expression? 915 bool checkingPotentialConstantExpression() const override { 916 return CheckingPotentialConstantExpression; 917 } 918 919 /// Are we checking an expression for overflow? 920 // FIXME: We should check for any kind of undefined or suspicious behavior 921 // in such constructs, not just overflow. 922 bool checkingForUndefinedBehavior() const override { 923 return CheckingForUndefinedBehavior; 924 } 925 926 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 927 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 928 CallStackDepth(0), NextCallIndex(1), 929 StepsLeft(C.getLangOpts().ConstexprStepLimit), 930 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 931 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 932 EvaluatingDecl((const ValueDecl *)nullptr), 933 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 934 HasFoldFailureDiagnostic(false), InConstantContext(false), 935 EvalMode(Mode) {} 936 937 ~EvalInfo() { 938 discardCleanups(); 939 } 940 941 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 942 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 943 EvaluatingDecl = Base; 944 IsEvaluatingDecl = EDK; 945 EvaluatingDeclValue = &Value; 946 } 947 948 bool CheckCallLimit(SourceLocation Loc) { 949 // Don't perform any constexpr calls (other than the call we're checking) 950 // when checking a potential constant expression. 951 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 952 return false; 953 if (NextCallIndex == 0) { 954 // NextCallIndex has wrapped around. 955 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 956 return false; 957 } 958 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 959 return true; 960 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 961 << getLangOpts().ConstexprCallDepth; 962 return false; 963 } 964 965 std::pair<CallStackFrame *, unsigned> 966 getCallFrameAndDepth(unsigned CallIndex) { 967 assert(CallIndex && "no call index in getCallFrameAndDepth"); 968 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 969 // be null in this loop. 970 unsigned Depth = CallStackDepth; 971 CallStackFrame *Frame = CurrentCall; 972 while (Frame->Index > CallIndex) { 973 Frame = Frame->Caller; 974 --Depth; 975 } 976 if (Frame->Index == CallIndex) 977 return {Frame, Depth}; 978 return {nullptr, 0}; 979 } 980 981 bool nextStep(const Stmt *S) { 982 if (!StepsLeft) { 983 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 984 return false; 985 } 986 --StepsLeft; 987 return true; 988 } 989 990 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 991 992 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 993 Optional<DynAlloc*> Result; 994 auto It = HeapAllocs.find(DA); 995 if (It != HeapAllocs.end()) 996 Result = &It->second; 997 return Result; 998 } 999 1000 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1001 struct StdAllocatorCaller { 1002 unsigned FrameIndex; 1003 QualType ElemType; 1004 explicit operator bool() const { return FrameIndex != 0; }; 1005 }; 1006 1007 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1008 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1009 Call = Call->Caller) { 1010 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1011 if (!MD) 1012 continue; 1013 const IdentifierInfo *FnII = MD->getIdentifier(); 1014 if (!FnII || !FnII->isStr(FnName)) 1015 continue; 1016 1017 const auto *CTSD = 1018 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1019 if (!CTSD) 1020 continue; 1021 1022 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1023 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1024 if (CTSD->isInStdNamespace() && ClassII && 1025 ClassII->isStr("allocator") && TAL.size() >= 1 && 1026 TAL[0].getKind() == TemplateArgument::Type) 1027 return {Call->Index, TAL[0].getAsType()}; 1028 } 1029 1030 return {}; 1031 } 1032 1033 void performLifetimeExtension() { 1034 // Disable the cleanups for lifetime-extended temporaries. 1035 CleanupStack.erase( 1036 std::remove_if(CleanupStack.begin(), CleanupStack.end(), 1037 [](Cleanup &C) { return C.isLifetimeExtended(); }), 1038 CleanupStack.end()); 1039 } 1040 1041 /// Throw away any remaining cleanups at the end of evaluation. If any 1042 /// cleanups would have had a side-effect, note that as an unmodeled 1043 /// side-effect and return false. Otherwise, return true. 1044 bool discardCleanups() { 1045 for (Cleanup &C : CleanupStack) { 1046 if (C.hasSideEffect() && !noteSideEffect()) { 1047 CleanupStack.clear(); 1048 return false; 1049 } 1050 } 1051 CleanupStack.clear(); 1052 return true; 1053 } 1054 1055 private: 1056 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1057 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1058 1059 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1060 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1061 1062 void setFoldFailureDiagnostic(bool Flag) override { 1063 HasFoldFailureDiagnostic = Flag; 1064 } 1065 1066 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1067 1068 ASTContext &getCtx() const override { return Ctx; } 1069 1070 // If we have a prior diagnostic, it will be noting that the expression 1071 // isn't a constant expression. This diagnostic is more important, 1072 // unless we require this evaluation to produce a constant expression. 1073 // 1074 // FIXME: We might want to show both diagnostics to the user in 1075 // EM_ConstantFold mode. 1076 bool hasPriorDiagnostic() override { 1077 if (!EvalStatus.Diag->empty()) { 1078 switch (EvalMode) { 1079 case EM_ConstantFold: 1080 case EM_IgnoreSideEffects: 1081 if (!HasFoldFailureDiagnostic) 1082 break; 1083 // We've already failed to fold something. Keep that diagnostic. 1084 LLVM_FALLTHROUGH; 1085 case EM_ConstantExpression: 1086 case EM_ConstantExpressionUnevaluated: 1087 setActiveDiagnostic(false); 1088 return true; 1089 } 1090 } 1091 return false; 1092 } 1093 1094 unsigned getCallStackDepth() override { return CallStackDepth; } 1095 1096 public: 1097 /// Should we continue evaluation after encountering a side-effect that we 1098 /// couldn't model? 1099 bool keepEvaluatingAfterSideEffect() { 1100 switch (EvalMode) { 1101 case EM_IgnoreSideEffects: 1102 return true; 1103 1104 case EM_ConstantExpression: 1105 case EM_ConstantExpressionUnevaluated: 1106 case EM_ConstantFold: 1107 // By default, assume any side effect might be valid in some other 1108 // evaluation of this expression from a different context. 1109 return checkingPotentialConstantExpression() || 1110 checkingForUndefinedBehavior(); 1111 } 1112 llvm_unreachable("Missed EvalMode case"); 1113 } 1114 1115 /// Note that we have had a side-effect, and determine whether we should 1116 /// keep evaluating. 1117 bool noteSideEffect() { 1118 EvalStatus.HasSideEffects = true; 1119 return keepEvaluatingAfterSideEffect(); 1120 } 1121 1122 /// Should we continue evaluation after encountering undefined behavior? 1123 bool keepEvaluatingAfterUndefinedBehavior() { 1124 switch (EvalMode) { 1125 case EM_IgnoreSideEffects: 1126 case EM_ConstantFold: 1127 return true; 1128 1129 case EM_ConstantExpression: 1130 case EM_ConstantExpressionUnevaluated: 1131 return checkingForUndefinedBehavior(); 1132 } 1133 llvm_unreachable("Missed EvalMode case"); 1134 } 1135 1136 /// Note that we hit something that was technically undefined behavior, but 1137 /// that we can evaluate past it (such as signed overflow or floating-point 1138 /// division by zero.) 1139 bool noteUndefinedBehavior() override { 1140 EvalStatus.HasUndefinedBehavior = true; 1141 return keepEvaluatingAfterUndefinedBehavior(); 1142 } 1143 1144 /// Should we continue evaluation as much as possible after encountering a 1145 /// construct which can't be reduced to a value? 1146 bool keepEvaluatingAfterFailure() const override { 1147 if (!StepsLeft) 1148 return false; 1149 1150 switch (EvalMode) { 1151 case EM_ConstantExpression: 1152 case EM_ConstantExpressionUnevaluated: 1153 case EM_ConstantFold: 1154 case EM_IgnoreSideEffects: 1155 return checkingPotentialConstantExpression() || 1156 checkingForUndefinedBehavior(); 1157 } 1158 llvm_unreachable("Missed EvalMode case"); 1159 } 1160 1161 /// Notes that we failed to evaluate an expression that other expressions 1162 /// directly depend on, and determine if we should keep evaluating. This 1163 /// should only be called if we actually intend to keep evaluating. 1164 /// 1165 /// Call noteSideEffect() instead if we may be able to ignore the value that 1166 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1167 /// 1168 /// (Foo(), 1) // use noteSideEffect 1169 /// (Foo() || true) // use noteSideEffect 1170 /// Foo() + 1 // use noteFailure 1171 LLVM_NODISCARD bool noteFailure() { 1172 // Failure when evaluating some expression often means there is some 1173 // subexpression whose evaluation was skipped. Therefore, (because we 1174 // don't track whether we skipped an expression when unwinding after an 1175 // evaluation failure) every evaluation failure that bubbles up from a 1176 // subexpression implies that a side-effect has potentially happened. We 1177 // skip setting the HasSideEffects flag to true until we decide to 1178 // continue evaluating after that point, which happens here. 1179 bool KeepGoing = keepEvaluatingAfterFailure(); 1180 EvalStatus.HasSideEffects |= KeepGoing; 1181 return KeepGoing; 1182 } 1183 1184 class ArrayInitLoopIndex { 1185 EvalInfo &Info; 1186 uint64_t OuterIndex; 1187 1188 public: 1189 ArrayInitLoopIndex(EvalInfo &Info) 1190 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1191 Info.ArrayInitIndex = 0; 1192 } 1193 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1194 1195 operator uint64_t&() { return Info.ArrayInitIndex; } 1196 }; 1197 }; 1198 1199 /// Object used to treat all foldable expressions as constant expressions. 1200 struct FoldConstant { 1201 EvalInfo &Info; 1202 bool Enabled; 1203 bool HadNoPriorDiags; 1204 EvalInfo::EvaluationMode OldMode; 1205 1206 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1207 : Info(Info), 1208 Enabled(Enabled), 1209 HadNoPriorDiags(Info.EvalStatus.Diag && 1210 Info.EvalStatus.Diag->empty() && 1211 !Info.EvalStatus.HasSideEffects), 1212 OldMode(Info.EvalMode) { 1213 if (Enabled) 1214 Info.EvalMode = EvalInfo::EM_ConstantFold; 1215 } 1216 void keepDiagnostics() { Enabled = false; } 1217 ~FoldConstant() { 1218 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1219 !Info.EvalStatus.HasSideEffects) 1220 Info.EvalStatus.Diag->clear(); 1221 Info.EvalMode = OldMode; 1222 } 1223 }; 1224 1225 /// RAII object used to set the current evaluation mode to ignore 1226 /// side-effects. 1227 struct IgnoreSideEffectsRAII { 1228 EvalInfo &Info; 1229 EvalInfo::EvaluationMode OldMode; 1230 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1231 : Info(Info), OldMode(Info.EvalMode) { 1232 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1233 } 1234 1235 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1236 }; 1237 1238 /// RAII object used to optionally suppress diagnostics and side-effects from 1239 /// a speculative evaluation. 1240 class SpeculativeEvaluationRAII { 1241 EvalInfo *Info = nullptr; 1242 Expr::EvalStatus OldStatus; 1243 unsigned OldSpeculativeEvaluationDepth; 1244 1245 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1246 Info = Other.Info; 1247 OldStatus = Other.OldStatus; 1248 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1249 Other.Info = nullptr; 1250 } 1251 1252 void maybeRestoreState() { 1253 if (!Info) 1254 return; 1255 1256 Info->EvalStatus = OldStatus; 1257 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1258 } 1259 1260 public: 1261 SpeculativeEvaluationRAII() = default; 1262 1263 SpeculativeEvaluationRAII( 1264 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1265 : Info(&Info), OldStatus(Info.EvalStatus), 1266 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1267 Info.EvalStatus.Diag = NewDiag; 1268 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1269 } 1270 1271 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1272 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1273 moveFromAndCancel(std::move(Other)); 1274 } 1275 1276 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1277 maybeRestoreState(); 1278 moveFromAndCancel(std::move(Other)); 1279 return *this; 1280 } 1281 1282 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1283 }; 1284 1285 /// RAII object wrapping a full-expression or block scope, and handling 1286 /// the ending of the lifetime of temporaries created within it. 1287 template<bool IsFullExpression> 1288 class ScopeRAII { 1289 EvalInfo &Info; 1290 unsigned OldStackSize; 1291 public: 1292 ScopeRAII(EvalInfo &Info) 1293 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1294 // Push a new temporary version. This is needed to distinguish between 1295 // temporaries created in different iterations of a loop. 1296 Info.CurrentCall->pushTempVersion(); 1297 } 1298 bool destroy(bool RunDestructors = true) { 1299 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1300 OldStackSize = -1U; 1301 return OK; 1302 } 1303 ~ScopeRAII() { 1304 if (OldStackSize != -1U) 1305 destroy(false); 1306 // Body moved to a static method to encourage the compiler to inline away 1307 // instances of this class. 1308 Info.CurrentCall->popTempVersion(); 1309 } 1310 private: 1311 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1312 unsigned OldStackSize) { 1313 assert(OldStackSize <= Info.CleanupStack.size() && 1314 "running cleanups out of order?"); 1315 1316 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1317 // for a full-expression scope. 1318 bool Success = true; 1319 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1320 if (!(IsFullExpression && 1321 Info.CleanupStack[I - 1].isLifetimeExtended())) { 1322 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1323 Success = false; 1324 break; 1325 } 1326 } 1327 } 1328 1329 // Compact lifetime-extended cleanups. 1330 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1331 if (IsFullExpression) 1332 NewEnd = 1333 std::remove_if(NewEnd, Info.CleanupStack.end(), 1334 [](Cleanup &C) { return !C.isLifetimeExtended(); }); 1335 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1336 return Success; 1337 } 1338 }; 1339 typedef ScopeRAII<false> BlockScopeRAII; 1340 typedef ScopeRAII<true> FullExpressionRAII; 1341 } 1342 1343 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1344 CheckSubobjectKind CSK) { 1345 if (Invalid) 1346 return false; 1347 if (isOnePastTheEnd()) { 1348 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1349 << CSK; 1350 setInvalid(); 1351 return false; 1352 } 1353 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1354 // must actually be at least one array element; even a VLA cannot have a 1355 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1356 return true; 1357 } 1358 1359 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1360 const Expr *E) { 1361 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1362 // Do not set the designator as invalid: we can represent this situation, 1363 // and correct handling of __builtin_object_size requires us to do so. 1364 } 1365 1366 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1367 const Expr *E, 1368 const APSInt &N) { 1369 // If we're complaining, we must be able to statically determine the size of 1370 // the most derived array. 1371 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1372 Info.CCEDiag(E, diag::note_constexpr_array_index) 1373 << N << /*array*/ 0 1374 << static_cast<unsigned>(getMostDerivedArraySize()); 1375 else 1376 Info.CCEDiag(E, diag::note_constexpr_array_index) 1377 << N << /*non-array*/ 1; 1378 setInvalid(); 1379 } 1380 1381 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1382 const FunctionDecl *Callee, const LValue *This, 1383 APValue *Arguments) 1384 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1385 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1386 Info.CurrentCall = this; 1387 ++Info.CallStackDepth; 1388 } 1389 1390 CallStackFrame::~CallStackFrame() { 1391 assert(Info.CurrentCall == this && "calls retired out of order"); 1392 --Info.CallStackDepth; 1393 Info.CurrentCall = Caller; 1394 } 1395 1396 static bool isRead(AccessKinds AK) { 1397 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1398 } 1399 1400 static bool isModification(AccessKinds AK) { 1401 switch (AK) { 1402 case AK_Read: 1403 case AK_ReadObjectRepresentation: 1404 case AK_MemberCall: 1405 case AK_DynamicCast: 1406 case AK_TypeId: 1407 return false; 1408 case AK_Assign: 1409 case AK_Increment: 1410 case AK_Decrement: 1411 case AK_Construct: 1412 case AK_Destroy: 1413 return true; 1414 } 1415 llvm_unreachable("unknown access kind"); 1416 } 1417 1418 static bool isAnyAccess(AccessKinds AK) { 1419 return isRead(AK) || isModification(AK); 1420 } 1421 1422 /// Is this an access per the C++ definition? 1423 static bool isFormalAccess(AccessKinds AK) { 1424 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1425 } 1426 1427 /// Is this kind of axcess valid on an indeterminate object value? 1428 static bool isValidIndeterminateAccess(AccessKinds AK) { 1429 switch (AK) { 1430 case AK_Read: 1431 case AK_Increment: 1432 case AK_Decrement: 1433 // These need the object's value. 1434 return false; 1435 1436 case AK_ReadObjectRepresentation: 1437 case AK_Assign: 1438 case AK_Construct: 1439 case AK_Destroy: 1440 // Construction and destruction don't need the value. 1441 return true; 1442 1443 case AK_MemberCall: 1444 case AK_DynamicCast: 1445 case AK_TypeId: 1446 // These aren't really meaningful on scalars. 1447 return true; 1448 } 1449 llvm_unreachable("unknown access kind"); 1450 } 1451 1452 namespace { 1453 struct ComplexValue { 1454 private: 1455 bool IsInt; 1456 1457 public: 1458 APSInt IntReal, IntImag; 1459 APFloat FloatReal, FloatImag; 1460 1461 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1462 1463 void makeComplexFloat() { IsInt = false; } 1464 bool isComplexFloat() const { return !IsInt; } 1465 APFloat &getComplexFloatReal() { return FloatReal; } 1466 APFloat &getComplexFloatImag() { return FloatImag; } 1467 1468 void makeComplexInt() { IsInt = true; } 1469 bool isComplexInt() const { return IsInt; } 1470 APSInt &getComplexIntReal() { return IntReal; } 1471 APSInt &getComplexIntImag() { return IntImag; } 1472 1473 void moveInto(APValue &v) const { 1474 if (isComplexFloat()) 1475 v = APValue(FloatReal, FloatImag); 1476 else 1477 v = APValue(IntReal, IntImag); 1478 } 1479 void setFrom(const APValue &v) { 1480 assert(v.isComplexFloat() || v.isComplexInt()); 1481 if (v.isComplexFloat()) { 1482 makeComplexFloat(); 1483 FloatReal = v.getComplexFloatReal(); 1484 FloatImag = v.getComplexFloatImag(); 1485 } else { 1486 makeComplexInt(); 1487 IntReal = v.getComplexIntReal(); 1488 IntImag = v.getComplexIntImag(); 1489 } 1490 } 1491 }; 1492 1493 struct LValue { 1494 APValue::LValueBase Base; 1495 CharUnits Offset; 1496 SubobjectDesignator Designator; 1497 bool IsNullPtr : 1; 1498 bool InvalidBase : 1; 1499 1500 const APValue::LValueBase getLValueBase() const { return Base; } 1501 CharUnits &getLValueOffset() { return Offset; } 1502 const CharUnits &getLValueOffset() const { return Offset; } 1503 SubobjectDesignator &getLValueDesignator() { return Designator; } 1504 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1505 bool isNullPointer() const { return IsNullPtr;} 1506 1507 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1508 unsigned getLValueVersion() const { return Base.getVersion(); } 1509 1510 void moveInto(APValue &V) const { 1511 if (Designator.Invalid) 1512 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1513 else { 1514 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1515 V = APValue(Base, Offset, Designator.Entries, 1516 Designator.IsOnePastTheEnd, IsNullPtr); 1517 } 1518 } 1519 void setFrom(ASTContext &Ctx, const APValue &V) { 1520 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1521 Base = V.getLValueBase(); 1522 Offset = V.getLValueOffset(); 1523 InvalidBase = false; 1524 Designator = SubobjectDesignator(Ctx, V); 1525 IsNullPtr = V.isNullPointer(); 1526 } 1527 1528 void set(APValue::LValueBase B, bool BInvalid = false) { 1529 #ifndef NDEBUG 1530 // We only allow a few types of invalid bases. Enforce that here. 1531 if (BInvalid) { 1532 const auto *E = B.get<const Expr *>(); 1533 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1534 "Unexpected type of invalid base"); 1535 } 1536 #endif 1537 1538 Base = B; 1539 Offset = CharUnits::fromQuantity(0); 1540 InvalidBase = BInvalid; 1541 Designator = SubobjectDesignator(getType(B)); 1542 IsNullPtr = false; 1543 } 1544 1545 void setNull(ASTContext &Ctx, QualType PointerTy) { 1546 Base = (Expr *)nullptr; 1547 Offset = 1548 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1549 InvalidBase = false; 1550 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1551 IsNullPtr = true; 1552 } 1553 1554 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1555 set(B, true); 1556 } 1557 1558 std::string toString(ASTContext &Ctx, QualType T) const { 1559 APValue Printable; 1560 moveInto(Printable); 1561 return Printable.getAsString(Ctx, T); 1562 } 1563 1564 private: 1565 // Check that this LValue is not based on a null pointer. If it is, produce 1566 // a diagnostic and mark the designator as invalid. 1567 template <typename GenDiagType> 1568 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1569 if (Designator.Invalid) 1570 return false; 1571 if (IsNullPtr) { 1572 GenDiag(); 1573 Designator.setInvalid(); 1574 return false; 1575 } 1576 return true; 1577 } 1578 1579 public: 1580 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1581 CheckSubobjectKind CSK) { 1582 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1583 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1584 }); 1585 } 1586 1587 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1588 AccessKinds AK) { 1589 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1590 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1591 }); 1592 } 1593 1594 // Check this LValue refers to an object. If not, set the designator to be 1595 // invalid and emit a diagnostic. 1596 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1597 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1598 Designator.checkSubobject(Info, E, CSK); 1599 } 1600 1601 void addDecl(EvalInfo &Info, const Expr *E, 1602 const Decl *D, bool Virtual = false) { 1603 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1604 Designator.addDeclUnchecked(D, Virtual); 1605 } 1606 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1607 if (!Designator.Entries.empty()) { 1608 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1609 Designator.setInvalid(); 1610 return; 1611 } 1612 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1613 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1614 Designator.FirstEntryIsAnUnsizedArray = true; 1615 Designator.addUnsizedArrayUnchecked(ElemTy); 1616 } 1617 } 1618 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1619 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1620 Designator.addArrayUnchecked(CAT); 1621 } 1622 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1623 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1624 Designator.addComplexUnchecked(EltTy, Imag); 1625 } 1626 void clearIsNullPointer() { 1627 IsNullPtr = false; 1628 } 1629 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1630 const APSInt &Index, CharUnits ElementSize) { 1631 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1632 // but we're not required to diagnose it and it's valid in C++.) 1633 if (!Index) 1634 return; 1635 1636 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1637 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1638 // offsets. 1639 uint64_t Offset64 = Offset.getQuantity(); 1640 uint64_t ElemSize64 = ElementSize.getQuantity(); 1641 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1642 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1643 1644 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1645 Designator.adjustIndex(Info, E, Index); 1646 clearIsNullPointer(); 1647 } 1648 void adjustOffset(CharUnits N) { 1649 Offset += N; 1650 if (N.getQuantity()) 1651 clearIsNullPointer(); 1652 } 1653 }; 1654 1655 struct MemberPtr { 1656 MemberPtr() {} 1657 explicit MemberPtr(const ValueDecl *Decl) : 1658 DeclAndIsDerivedMember(Decl, false), Path() {} 1659 1660 /// The member or (direct or indirect) field referred to by this member 1661 /// pointer, or 0 if this is a null member pointer. 1662 const ValueDecl *getDecl() const { 1663 return DeclAndIsDerivedMember.getPointer(); 1664 } 1665 /// Is this actually a member of some type derived from the relevant class? 1666 bool isDerivedMember() const { 1667 return DeclAndIsDerivedMember.getInt(); 1668 } 1669 /// Get the class which the declaration actually lives in. 1670 const CXXRecordDecl *getContainingRecord() const { 1671 return cast<CXXRecordDecl>( 1672 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1673 } 1674 1675 void moveInto(APValue &V) const { 1676 V = APValue(getDecl(), isDerivedMember(), Path); 1677 } 1678 void setFrom(const APValue &V) { 1679 assert(V.isMemberPointer()); 1680 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1681 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1682 Path.clear(); 1683 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1684 Path.insert(Path.end(), P.begin(), P.end()); 1685 } 1686 1687 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1688 /// whether the member is a member of some class derived from the class type 1689 /// of the member pointer. 1690 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1691 /// Path - The path of base/derived classes from the member declaration's 1692 /// class (exclusive) to the class type of the member pointer (inclusive). 1693 SmallVector<const CXXRecordDecl*, 4> Path; 1694 1695 /// Perform a cast towards the class of the Decl (either up or down the 1696 /// hierarchy). 1697 bool castBack(const CXXRecordDecl *Class) { 1698 assert(!Path.empty()); 1699 const CXXRecordDecl *Expected; 1700 if (Path.size() >= 2) 1701 Expected = Path[Path.size() - 2]; 1702 else 1703 Expected = getContainingRecord(); 1704 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1705 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1706 // if B does not contain the original member and is not a base or 1707 // derived class of the class containing the original member, the result 1708 // of the cast is undefined. 1709 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1710 // (D::*). We consider that to be a language defect. 1711 return false; 1712 } 1713 Path.pop_back(); 1714 return true; 1715 } 1716 /// Perform a base-to-derived member pointer cast. 1717 bool castToDerived(const CXXRecordDecl *Derived) { 1718 if (!getDecl()) 1719 return true; 1720 if (!isDerivedMember()) { 1721 Path.push_back(Derived); 1722 return true; 1723 } 1724 if (!castBack(Derived)) 1725 return false; 1726 if (Path.empty()) 1727 DeclAndIsDerivedMember.setInt(false); 1728 return true; 1729 } 1730 /// Perform a derived-to-base member pointer cast. 1731 bool castToBase(const CXXRecordDecl *Base) { 1732 if (!getDecl()) 1733 return true; 1734 if (Path.empty()) 1735 DeclAndIsDerivedMember.setInt(true); 1736 if (isDerivedMember()) { 1737 Path.push_back(Base); 1738 return true; 1739 } 1740 return castBack(Base); 1741 } 1742 }; 1743 1744 /// Compare two member pointers, which are assumed to be of the same type. 1745 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1746 if (!LHS.getDecl() || !RHS.getDecl()) 1747 return !LHS.getDecl() && !RHS.getDecl(); 1748 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1749 return false; 1750 return LHS.Path == RHS.Path; 1751 } 1752 } 1753 1754 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1755 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1756 const LValue &This, const Expr *E, 1757 bool AllowNonLiteralTypes = false); 1758 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1759 bool InvalidBaseOK = false); 1760 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1761 bool InvalidBaseOK = false); 1762 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1763 EvalInfo &Info); 1764 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1765 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1766 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1767 EvalInfo &Info); 1768 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1769 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1770 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1771 EvalInfo &Info); 1772 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1773 1774 /// Evaluate an integer or fixed point expression into an APResult. 1775 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1776 EvalInfo &Info); 1777 1778 /// Evaluate only a fixed point expression into an APResult. 1779 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1780 EvalInfo &Info); 1781 1782 //===----------------------------------------------------------------------===// 1783 // Misc utilities 1784 //===----------------------------------------------------------------------===// 1785 1786 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1787 /// preserving its value (by extending by up to one bit as needed). 1788 static void negateAsSigned(APSInt &Int) { 1789 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1790 Int = Int.extend(Int.getBitWidth() + 1); 1791 Int.setIsSigned(true); 1792 } 1793 Int = -Int; 1794 } 1795 1796 template<typename KeyT> 1797 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1798 bool IsLifetimeExtended, LValue &LV) { 1799 unsigned Version = getTempVersion(); 1800 APValue::LValueBase Base(Key, Index, Version); 1801 LV.set(Base); 1802 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1803 assert(Result.isAbsent() && "temporary created multiple times"); 1804 1805 // If we're creating a temporary immediately in the operand of a speculative 1806 // evaluation, don't register a cleanup to be run outside the speculative 1807 // evaluation context, since we won't actually be able to initialize this 1808 // object. 1809 if (Index <= Info.SpeculativeEvaluationDepth) { 1810 if (T.isDestructedType()) 1811 Info.noteSideEffect(); 1812 } else { 1813 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended)); 1814 } 1815 return Result; 1816 } 1817 1818 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1819 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1820 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1821 return nullptr; 1822 } 1823 1824 DynamicAllocLValue DA(NumHeapAllocs++); 1825 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1826 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1827 std::forward_as_tuple(DA), std::tuple<>()); 1828 assert(Result.second && "reused a heap alloc index?"); 1829 Result.first->second.AllocExpr = E; 1830 return &Result.first->second.Value; 1831 } 1832 1833 /// Produce a string describing the given constexpr call. 1834 void CallStackFrame::describe(raw_ostream &Out) { 1835 unsigned ArgIndex = 0; 1836 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1837 !isa<CXXConstructorDecl>(Callee) && 1838 cast<CXXMethodDecl>(Callee)->isInstance(); 1839 1840 if (!IsMemberCall) 1841 Out << *Callee << '('; 1842 1843 if (This && IsMemberCall) { 1844 APValue Val; 1845 This->moveInto(Val); 1846 Val.printPretty(Out, Info.Ctx, 1847 This->Designator.MostDerivedType); 1848 // FIXME: Add parens around Val if needed. 1849 Out << "->" << *Callee << '('; 1850 IsMemberCall = false; 1851 } 1852 1853 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1854 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1855 if (ArgIndex > (unsigned)IsMemberCall) 1856 Out << ", "; 1857 1858 const ParmVarDecl *Param = *I; 1859 if (Arguments) { 1860 const APValue &Arg = Arguments[ArgIndex]; 1861 Arg.printPretty(Out, Info.Ctx, Param->getType()); 1862 } else { 1863 Out << "<...>"; 1864 } 1865 1866 if (ArgIndex == 0 && IsMemberCall) 1867 Out << "->" << *Callee << '('; 1868 } 1869 1870 Out << ')'; 1871 } 1872 1873 /// Evaluate an expression to see if it had side-effects, and discard its 1874 /// result. 1875 /// \return \c true if the caller should keep evaluating. 1876 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1877 APValue Scratch; 1878 if (!Evaluate(Scratch, Info, E)) 1879 // We don't need the value, but we might have skipped a side effect here. 1880 return Info.noteSideEffect(); 1881 return true; 1882 } 1883 1884 /// Should this call expression be treated as a string literal? 1885 static bool IsStringLiteralCall(const CallExpr *E) { 1886 unsigned Builtin = E->getBuiltinCallee(); 1887 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1888 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1889 } 1890 1891 static bool IsGlobalLValue(APValue::LValueBase B) { 1892 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1893 // constant expression of pointer type that evaluates to... 1894 1895 // ... a null pointer value, or a prvalue core constant expression of type 1896 // std::nullptr_t. 1897 if (!B) return true; 1898 1899 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1900 // ... the address of an object with static storage duration, 1901 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1902 return VD->hasGlobalStorage(); 1903 // ... the address of a function, 1904 // ... the address of a GUID [MS extension], 1905 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1906 } 1907 1908 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1909 return true; 1910 1911 const Expr *E = B.get<const Expr*>(); 1912 switch (E->getStmtClass()) { 1913 default: 1914 return false; 1915 case Expr::CompoundLiteralExprClass: { 1916 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1917 return CLE->isFileScope() && CLE->isLValue(); 1918 } 1919 case Expr::MaterializeTemporaryExprClass: 1920 // A materialized temporary might have been lifetime-extended to static 1921 // storage duration. 1922 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1923 // A string literal has static storage duration. 1924 case Expr::StringLiteralClass: 1925 case Expr::PredefinedExprClass: 1926 case Expr::ObjCStringLiteralClass: 1927 case Expr::ObjCEncodeExprClass: 1928 return true; 1929 case Expr::ObjCBoxedExprClass: 1930 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 1931 case Expr::CallExprClass: 1932 return IsStringLiteralCall(cast<CallExpr>(E)); 1933 // For GCC compatibility, &&label has static storage duration. 1934 case Expr::AddrLabelExprClass: 1935 return true; 1936 // A Block literal expression may be used as the initialization value for 1937 // Block variables at global or local static scope. 1938 case Expr::BlockExprClass: 1939 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1940 case Expr::ImplicitValueInitExprClass: 1941 // FIXME: 1942 // We can never form an lvalue with an implicit value initialization as its 1943 // base through expression evaluation, so these only appear in one case: the 1944 // implicit variable declaration we invent when checking whether a constexpr 1945 // constructor can produce a constant expression. We must assume that such 1946 // an expression might be a global lvalue. 1947 return true; 1948 } 1949 } 1950 1951 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1952 return LVal.Base.dyn_cast<const ValueDecl*>(); 1953 } 1954 1955 static bool IsLiteralLValue(const LValue &Value) { 1956 if (Value.getLValueCallIndex()) 1957 return false; 1958 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1959 return E && !isa<MaterializeTemporaryExpr>(E); 1960 } 1961 1962 static bool IsWeakLValue(const LValue &Value) { 1963 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1964 return Decl && Decl->isWeak(); 1965 } 1966 1967 static bool isZeroSized(const LValue &Value) { 1968 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1969 if (Decl && isa<VarDecl>(Decl)) { 1970 QualType Ty = Decl->getType(); 1971 if (Ty->isArrayType()) 1972 return Ty->isIncompleteType() || 1973 Decl->getASTContext().getTypeSize(Ty) == 0; 1974 } 1975 return false; 1976 } 1977 1978 static bool HasSameBase(const LValue &A, const LValue &B) { 1979 if (!A.getLValueBase()) 1980 return !B.getLValueBase(); 1981 if (!B.getLValueBase()) 1982 return false; 1983 1984 if (A.getLValueBase().getOpaqueValue() != 1985 B.getLValueBase().getOpaqueValue()) 1986 return false; 1987 1988 return A.getLValueCallIndex() == B.getLValueCallIndex() && 1989 A.getLValueVersion() == B.getLValueVersion(); 1990 } 1991 1992 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1993 assert(Base && "no location for a null lvalue"); 1994 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1995 if (VD) 1996 Info.Note(VD->getLocation(), diag::note_declared_at); 1997 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 1998 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 1999 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2000 // FIXME: Produce a note for dangling pointers too. 2001 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2002 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2003 diag::note_constexpr_dynamic_alloc_here); 2004 } 2005 // We have no information to show for a typeid(T) object. 2006 } 2007 2008 enum class CheckEvaluationResultKind { 2009 ConstantExpression, 2010 FullyInitialized, 2011 }; 2012 2013 /// Materialized temporaries that we've already checked to determine if they're 2014 /// initializsed by a constant expression. 2015 using CheckedTemporaries = 2016 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2017 2018 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2019 EvalInfo &Info, SourceLocation DiagLoc, 2020 QualType Type, const APValue &Value, 2021 Expr::ConstExprUsage Usage, 2022 SourceLocation SubobjectLoc, 2023 CheckedTemporaries &CheckedTemps); 2024 2025 /// Check that this reference or pointer core constant expression is a valid 2026 /// value for an address or reference constant expression. Return true if we 2027 /// can fold this expression, whether or not it's a constant expression. 2028 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2029 QualType Type, const LValue &LVal, 2030 Expr::ConstExprUsage Usage, 2031 CheckedTemporaries &CheckedTemps) { 2032 bool IsReferenceType = Type->isReferenceType(); 2033 2034 APValue::LValueBase Base = LVal.getLValueBase(); 2035 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2036 2037 if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) { 2038 if (auto *FD = dyn_cast<FunctionDecl>(VD)) { 2039 if (FD->isConsteval()) { 2040 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2041 << !Type->isAnyPointerType(); 2042 Info.Note(FD->getLocation(), diag::note_declared_at); 2043 return false; 2044 } 2045 } 2046 } 2047 2048 // Check that the object is a global. Note that the fake 'this' object we 2049 // manufacture when checking potential constant expressions is conservatively 2050 // assumed to be global here. 2051 if (!IsGlobalLValue(Base)) { 2052 if (Info.getLangOpts().CPlusPlus11) { 2053 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2054 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2055 << IsReferenceType << !Designator.Entries.empty() 2056 << !!VD << VD; 2057 2058 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2059 if (VarD && VarD->isConstexpr()) { 2060 // Non-static local constexpr variables have unintuitive semantics: 2061 // constexpr int a = 1; 2062 // constexpr const int *p = &a; 2063 // ... is invalid because the address of 'a' is not constant. Suggest 2064 // adding a 'static' in this case. 2065 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2066 << VarD 2067 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2068 } else { 2069 NoteLValueLocation(Info, Base); 2070 } 2071 } else { 2072 Info.FFDiag(Loc); 2073 } 2074 // Don't allow references to temporaries to escape. 2075 return false; 2076 } 2077 assert((Info.checkingPotentialConstantExpression() || 2078 LVal.getLValueCallIndex() == 0) && 2079 "have call index for global lvalue"); 2080 2081 if (Base.is<DynamicAllocLValue>()) { 2082 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2083 << IsReferenceType << !Designator.Entries.empty(); 2084 NoteLValueLocation(Info, Base); 2085 return false; 2086 } 2087 2088 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 2089 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 2090 // Check if this is a thread-local variable. 2091 if (Var->getTLSKind()) 2092 // FIXME: Diagnostic! 2093 return false; 2094 2095 // A dllimport variable never acts like a constant. 2096 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 2097 // FIXME: Diagnostic! 2098 return false; 2099 } 2100 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 2101 // __declspec(dllimport) must be handled very carefully: 2102 // We must never initialize an expression with the thunk in C++. 2103 // Doing otherwise would allow the same id-expression to yield 2104 // different addresses for the same function in different translation 2105 // units. However, this means that we must dynamically initialize the 2106 // expression with the contents of the import address table at runtime. 2107 // 2108 // The C language has no notion of ODR; furthermore, it has no notion of 2109 // dynamic initialization. This means that we are permitted to 2110 // perform initialization with the address of the thunk. 2111 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 2112 FD->hasAttr<DLLImportAttr>()) 2113 // FIXME: Diagnostic! 2114 return false; 2115 } 2116 } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>( 2117 Base.dyn_cast<const Expr *>())) { 2118 if (CheckedTemps.insert(MTE).second) { 2119 QualType TempType = getType(Base); 2120 if (TempType.isDestructedType()) { 2121 Info.FFDiag(MTE->getExprLoc(), 2122 diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor) 2123 << TempType; 2124 return false; 2125 } 2126 2127 APValue *V = MTE->getOrCreateValue(false); 2128 assert(V && "evasluation result refers to uninitialised temporary"); 2129 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2130 Info, MTE->getExprLoc(), TempType, *V, 2131 Usage, SourceLocation(), CheckedTemps)) 2132 return false; 2133 } 2134 } 2135 2136 // Allow address constant expressions to be past-the-end pointers. This is 2137 // an extension: the standard requires them to point to an object. 2138 if (!IsReferenceType) 2139 return true; 2140 2141 // A reference constant expression must refer to an object. 2142 if (!Base) { 2143 // FIXME: diagnostic 2144 Info.CCEDiag(Loc); 2145 return true; 2146 } 2147 2148 // Does this refer one past the end of some object? 2149 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2150 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2151 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2152 << !Designator.Entries.empty() << !!VD << VD; 2153 NoteLValueLocation(Info, Base); 2154 } 2155 2156 return true; 2157 } 2158 2159 /// Member pointers are constant expressions unless they point to a 2160 /// non-virtual dllimport member function. 2161 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2162 SourceLocation Loc, 2163 QualType Type, 2164 const APValue &Value, 2165 Expr::ConstExprUsage Usage) { 2166 const ValueDecl *Member = Value.getMemberPointerDecl(); 2167 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2168 if (!FD) 2169 return true; 2170 if (FD->isConsteval()) { 2171 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2172 Info.Note(FD->getLocation(), diag::note_declared_at); 2173 return false; 2174 } 2175 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 2176 !FD->hasAttr<DLLImportAttr>(); 2177 } 2178 2179 /// Check that this core constant expression is of literal type, and if not, 2180 /// produce an appropriate diagnostic. 2181 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2182 const LValue *This = nullptr) { 2183 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2184 return true; 2185 2186 // C++1y: A constant initializer for an object o [...] may also invoke 2187 // constexpr constructors for o and its subobjects even if those objects 2188 // are of non-literal class types. 2189 // 2190 // C++11 missed this detail for aggregates, so classes like this: 2191 // struct foo_t { union { int i; volatile int j; } u; }; 2192 // are not (obviously) initializable like so: 2193 // __attribute__((__require_constant_initialization__)) 2194 // static const foo_t x = {{0}}; 2195 // because "i" is a subobject with non-literal initialization (due to the 2196 // volatile member of the union). See: 2197 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2198 // Therefore, we use the C++1y behavior. 2199 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2200 return true; 2201 2202 // Prvalue constant expressions must be of literal types. 2203 if (Info.getLangOpts().CPlusPlus11) 2204 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2205 << E->getType(); 2206 else 2207 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2208 return false; 2209 } 2210 2211 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2212 EvalInfo &Info, SourceLocation DiagLoc, 2213 QualType Type, const APValue &Value, 2214 Expr::ConstExprUsage Usage, 2215 SourceLocation SubobjectLoc, 2216 CheckedTemporaries &CheckedTemps) { 2217 if (!Value.hasValue()) { 2218 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2219 << true << Type; 2220 if (SubobjectLoc.isValid()) 2221 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2222 return false; 2223 } 2224 2225 // We allow _Atomic(T) to be initialized from anything that T can be 2226 // initialized from. 2227 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2228 Type = AT->getValueType(); 2229 2230 // Core issue 1454: For a literal constant expression of array or class type, 2231 // each subobject of its value shall have been initialized by a constant 2232 // expression. 2233 if (Value.isArray()) { 2234 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2235 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2236 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2237 Value.getArrayInitializedElt(I), Usage, 2238 SubobjectLoc, CheckedTemps)) 2239 return false; 2240 } 2241 if (!Value.hasArrayFiller()) 2242 return true; 2243 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2244 Value.getArrayFiller(), Usage, SubobjectLoc, 2245 CheckedTemps); 2246 } 2247 if (Value.isUnion() && Value.getUnionField()) { 2248 return CheckEvaluationResult( 2249 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2250 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(), 2251 CheckedTemps); 2252 } 2253 if (Value.isStruct()) { 2254 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2255 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2256 unsigned BaseIndex = 0; 2257 for (const CXXBaseSpecifier &BS : CD->bases()) { 2258 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2259 Value.getStructBase(BaseIndex), Usage, 2260 BS.getBeginLoc(), CheckedTemps)) 2261 return false; 2262 ++BaseIndex; 2263 } 2264 } 2265 for (const auto *I : RD->fields()) { 2266 if (I->isUnnamedBitfield()) 2267 continue; 2268 2269 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2270 Value.getStructField(I->getFieldIndex()), 2271 Usage, I->getLocation(), CheckedTemps)) 2272 return false; 2273 } 2274 } 2275 2276 if (Value.isLValue() && 2277 CERK == CheckEvaluationResultKind::ConstantExpression) { 2278 LValue LVal; 2279 LVal.setFrom(Info.Ctx, Value); 2280 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage, 2281 CheckedTemps); 2282 } 2283 2284 if (Value.isMemberPointer() && 2285 CERK == CheckEvaluationResultKind::ConstantExpression) 2286 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 2287 2288 // Everything else is fine. 2289 return true; 2290 } 2291 2292 /// Check that this core constant expression value is a valid value for a 2293 /// constant expression. If not, report an appropriate diagnostic. Does not 2294 /// check that the expression is of literal type. 2295 static bool 2296 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 2297 const APValue &Value, 2298 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) { 2299 // Nothing to check for a constant expression of type 'cv void'. 2300 if (Type->isVoidType()) 2301 return true; 2302 2303 CheckedTemporaries CheckedTemps; 2304 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2305 Info, DiagLoc, Type, Value, Usage, 2306 SourceLocation(), CheckedTemps); 2307 } 2308 2309 /// Check that this evaluated value is fully-initialized and can be loaded by 2310 /// an lvalue-to-rvalue conversion. 2311 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2312 QualType Type, const APValue &Value) { 2313 CheckedTemporaries CheckedTemps; 2314 return CheckEvaluationResult( 2315 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2316 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps); 2317 } 2318 2319 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2320 /// "the allocated storage is deallocated within the evaluation". 2321 static bool CheckMemoryLeaks(EvalInfo &Info) { 2322 if (!Info.HeapAllocs.empty()) { 2323 // We can still fold to a constant despite a compile-time memory leak, 2324 // so long as the heap allocation isn't referenced in the result (we check 2325 // that in CheckConstantExpression). 2326 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2327 diag::note_constexpr_memory_leak) 2328 << unsigned(Info.HeapAllocs.size() - 1); 2329 } 2330 return true; 2331 } 2332 2333 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2334 // A null base expression indicates a null pointer. These are always 2335 // evaluatable, and they are false unless the offset is zero. 2336 if (!Value.getLValueBase()) { 2337 Result = !Value.getLValueOffset().isZero(); 2338 return true; 2339 } 2340 2341 // We have a non-null base. These are generally known to be true, but if it's 2342 // a weak declaration it can be null at runtime. 2343 Result = true; 2344 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2345 return !Decl || !Decl->isWeak(); 2346 } 2347 2348 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2349 switch (Val.getKind()) { 2350 case APValue::None: 2351 case APValue::Indeterminate: 2352 return false; 2353 case APValue::Int: 2354 Result = Val.getInt().getBoolValue(); 2355 return true; 2356 case APValue::FixedPoint: 2357 Result = Val.getFixedPoint().getBoolValue(); 2358 return true; 2359 case APValue::Float: 2360 Result = !Val.getFloat().isZero(); 2361 return true; 2362 case APValue::ComplexInt: 2363 Result = Val.getComplexIntReal().getBoolValue() || 2364 Val.getComplexIntImag().getBoolValue(); 2365 return true; 2366 case APValue::ComplexFloat: 2367 Result = !Val.getComplexFloatReal().isZero() || 2368 !Val.getComplexFloatImag().isZero(); 2369 return true; 2370 case APValue::LValue: 2371 return EvalPointerValueAsBool(Val, Result); 2372 case APValue::MemberPointer: 2373 Result = Val.getMemberPointerDecl(); 2374 return true; 2375 case APValue::Vector: 2376 case APValue::Array: 2377 case APValue::Struct: 2378 case APValue::Union: 2379 case APValue::AddrLabelDiff: 2380 return false; 2381 } 2382 2383 llvm_unreachable("unknown APValue kind"); 2384 } 2385 2386 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2387 EvalInfo &Info) { 2388 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2389 APValue Val; 2390 if (!Evaluate(Val, Info, E)) 2391 return false; 2392 return HandleConversionToBool(Val, Result); 2393 } 2394 2395 template<typename T> 2396 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2397 const T &SrcValue, QualType DestType) { 2398 Info.CCEDiag(E, diag::note_constexpr_overflow) 2399 << SrcValue << DestType; 2400 return Info.noteUndefinedBehavior(); 2401 } 2402 2403 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2404 QualType SrcType, const APFloat &Value, 2405 QualType DestType, APSInt &Result) { 2406 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2407 // Determine whether we are converting to unsigned or signed. 2408 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2409 2410 Result = APSInt(DestWidth, !DestSigned); 2411 bool ignored; 2412 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2413 & APFloat::opInvalidOp) 2414 return HandleOverflow(Info, E, Value, DestType); 2415 return true; 2416 } 2417 2418 /// Get rounding mode used for evaluation of the specified expression. 2419 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2420 /// dynamic. 2421 /// If rounding mode is unknown at compile time, still try to evaluate the 2422 /// expression. If the result is exact, it does not depend on rounding mode. 2423 /// So return "tonearest" mode instead of "dynamic". 2424 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2425 bool &DynamicRM) { 2426 llvm::RoundingMode RM = 2427 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2428 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2429 if (DynamicRM) 2430 RM = llvm::RoundingMode::NearestTiesToEven; 2431 return RM; 2432 } 2433 2434 /// Check if the given evaluation result is allowed for constant evaluation. 2435 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2436 APFloat::opStatus St) { 2437 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2438 if ((St & APFloat::opInexact) && 2439 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2440 // Inexact result means that it depends on rounding mode. If the requested 2441 // mode is dynamic, the evaluation cannot be made in compile time. 2442 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2443 return false; 2444 } 2445 2446 if ((St & APFloat::opStatus::opInvalidOp) && 2447 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2448 // There is no usefully definable result. 2449 Info.FFDiag(E); 2450 return false; 2451 } 2452 2453 // FIXME: if: 2454 // - evaluation triggered other FP exception, and 2455 // - exception mode is not "ignore", and 2456 // - the expression being evaluated is not a part of global variable 2457 // initializer, 2458 // the evaluation probably need to be rejected. 2459 return true; 2460 } 2461 2462 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2463 QualType SrcType, QualType DestType, 2464 APFloat &Result) { 2465 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2466 bool DynamicRM; 2467 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2468 APFloat::opStatus St; 2469 APFloat Value = Result; 2470 bool ignored; 2471 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2472 return checkFloatingPointResult(Info, E, St); 2473 } 2474 2475 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2476 QualType DestType, QualType SrcType, 2477 const APSInt &Value) { 2478 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2479 // Figure out if this is a truncate, extend or noop cast. 2480 // If the input is signed, do a sign extend, noop, or truncate. 2481 APSInt Result = Value.extOrTrunc(DestWidth); 2482 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2483 if (DestType->isBooleanType()) 2484 Result = Value.getBoolValue(); 2485 return Result; 2486 } 2487 2488 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2489 QualType SrcType, const APSInt &Value, 2490 QualType DestType, APFloat &Result) { 2491 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2492 Result.convertFromAPInt(Value, Value.isSigned(), 2493 APFloat::rmNearestTiesToEven); 2494 return true; 2495 } 2496 2497 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2498 APValue &Value, const FieldDecl *FD) { 2499 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2500 2501 if (!Value.isInt()) { 2502 // Trying to store a pointer-cast-to-integer into a bitfield. 2503 // FIXME: In this case, we should provide the diagnostic for casting 2504 // a pointer to an integer. 2505 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2506 Info.FFDiag(E); 2507 return false; 2508 } 2509 2510 APSInt &Int = Value.getInt(); 2511 unsigned OldBitWidth = Int.getBitWidth(); 2512 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2513 if (NewBitWidth < OldBitWidth) 2514 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2515 return true; 2516 } 2517 2518 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2519 llvm::APInt &Res) { 2520 APValue SVal; 2521 if (!Evaluate(SVal, Info, E)) 2522 return false; 2523 if (SVal.isInt()) { 2524 Res = SVal.getInt(); 2525 return true; 2526 } 2527 if (SVal.isFloat()) { 2528 Res = SVal.getFloat().bitcastToAPInt(); 2529 return true; 2530 } 2531 if (SVal.isVector()) { 2532 QualType VecTy = E->getType(); 2533 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2534 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2535 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2536 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2537 Res = llvm::APInt::getNullValue(VecSize); 2538 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2539 APValue &Elt = SVal.getVectorElt(i); 2540 llvm::APInt EltAsInt; 2541 if (Elt.isInt()) { 2542 EltAsInt = Elt.getInt(); 2543 } else if (Elt.isFloat()) { 2544 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2545 } else { 2546 // Don't try to handle vectors of anything other than int or float 2547 // (not sure if it's possible to hit this case). 2548 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2549 return false; 2550 } 2551 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2552 if (BigEndian) 2553 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2554 else 2555 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2556 } 2557 return true; 2558 } 2559 // Give up if the input isn't an int, float, or vector. For example, we 2560 // reject "(v4i16)(intptr_t)&a". 2561 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2562 return false; 2563 } 2564 2565 /// Perform the given integer operation, which is known to need at most BitWidth 2566 /// bits, and check for overflow in the original type (if that type was not an 2567 /// unsigned type). 2568 template<typename Operation> 2569 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2570 const APSInt &LHS, const APSInt &RHS, 2571 unsigned BitWidth, Operation Op, 2572 APSInt &Result) { 2573 if (LHS.isUnsigned()) { 2574 Result = Op(LHS, RHS); 2575 return true; 2576 } 2577 2578 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2579 Result = Value.trunc(LHS.getBitWidth()); 2580 if (Result.extend(BitWidth) != Value) { 2581 if (Info.checkingForUndefinedBehavior()) 2582 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2583 diag::warn_integer_constant_overflow) 2584 << Result.toString(10) << E->getType(); 2585 else 2586 return HandleOverflow(Info, E, Value, E->getType()); 2587 } 2588 return true; 2589 } 2590 2591 /// Perform the given binary integer operation. 2592 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2593 BinaryOperatorKind Opcode, APSInt RHS, 2594 APSInt &Result) { 2595 switch (Opcode) { 2596 default: 2597 Info.FFDiag(E); 2598 return false; 2599 case BO_Mul: 2600 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2601 std::multiplies<APSInt>(), Result); 2602 case BO_Add: 2603 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2604 std::plus<APSInt>(), Result); 2605 case BO_Sub: 2606 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2607 std::minus<APSInt>(), Result); 2608 case BO_And: Result = LHS & RHS; return true; 2609 case BO_Xor: Result = LHS ^ RHS; return true; 2610 case BO_Or: Result = LHS | RHS; return true; 2611 case BO_Div: 2612 case BO_Rem: 2613 if (RHS == 0) { 2614 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2615 return false; 2616 } 2617 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2618 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2619 // this operation and gives the two's complement result. 2620 if (RHS.isNegative() && RHS.isAllOnesValue() && 2621 LHS.isSigned() && LHS.isMinSignedValue()) 2622 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2623 E->getType()); 2624 return true; 2625 case BO_Shl: { 2626 if (Info.getLangOpts().OpenCL) 2627 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2628 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2629 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2630 RHS.isUnsigned()); 2631 else if (RHS.isSigned() && RHS.isNegative()) { 2632 // During constant-folding, a negative shift is an opposite shift. Such 2633 // a shift is not a constant expression. 2634 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2635 RHS = -RHS; 2636 goto shift_right; 2637 } 2638 shift_left: 2639 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2640 // the shifted type. 2641 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2642 if (SA != RHS) { 2643 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2644 << RHS << E->getType() << LHS.getBitWidth(); 2645 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2646 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2647 // operand, and must not overflow the corresponding unsigned type. 2648 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2649 // E1 x 2^E2 module 2^N. 2650 if (LHS.isNegative()) 2651 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2652 else if (LHS.countLeadingZeros() < SA) 2653 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2654 } 2655 Result = LHS << SA; 2656 return true; 2657 } 2658 case BO_Shr: { 2659 if (Info.getLangOpts().OpenCL) 2660 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2661 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2662 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2663 RHS.isUnsigned()); 2664 else if (RHS.isSigned() && RHS.isNegative()) { 2665 // During constant-folding, a negative shift is an opposite shift. Such a 2666 // shift is not a constant expression. 2667 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2668 RHS = -RHS; 2669 goto shift_left; 2670 } 2671 shift_right: 2672 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2673 // shifted type. 2674 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2675 if (SA != RHS) 2676 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2677 << RHS << E->getType() << LHS.getBitWidth(); 2678 Result = LHS >> SA; 2679 return true; 2680 } 2681 2682 case BO_LT: Result = LHS < RHS; return true; 2683 case BO_GT: Result = LHS > RHS; return true; 2684 case BO_LE: Result = LHS <= RHS; return true; 2685 case BO_GE: Result = LHS >= RHS; return true; 2686 case BO_EQ: Result = LHS == RHS; return true; 2687 case BO_NE: Result = LHS != RHS; return true; 2688 case BO_Cmp: 2689 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2690 } 2691 } 2692 2693 /// Perform the given binary floating-point operation, in-place, on LHS. 2694 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2695 APFloat &LHS, BinaryOperatorKind Opcode, 2696 const APFloat &RHS) { 2697 bool DynamicRM; 2698 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2699 APFloat::opStatus St; 2700 switch (Opcode) { 2701 default: 2702 Info.FFDiag(E); 2703 return false; 2704 case BO_Mul: 2705 St = LHS.multiply(RHS, RM); 2706 break; 2707 case BO_Add: 2708 St = LHS.add(RHS, RM); 2709 break; 2710 case BO_Sub: 2711 St = LHS.subtract(RHS, RM); 2712 break; 2713 case BO_Div: 2714 // [expr.mul]p4: 2715 // If the second operand of / or % is zero the behavior is undefined. 2716 if (RHS.isZero()) 2717 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2718 St = LHS.divide(RHS, RM); 2719 break; 2720 } 2721 2722 // [expr.pre]p4: 2723 // If during the evaluation of an expression, the result is not 2724 // mathematically defined [...], the behavior is undefined. 2725 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2726 if (LHS.isNaN()) { 2727 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2728 return Info.noteUndefinedBehavior(); 2729 } 2730 2731 return checkFloatingPointResult(Info, E, St); 2732 } 2733 2734 static bool handleLogicalOpForVector(const APInt &LHSValue, 2735 BinaryOperatorKind Opcode, 2736 const APInt &RHSValue, APInt &Result) { 2737 bool LHS = (LHSValue != 0); 2738 bool RHS = (RHSValue != 0); 2739 2740 if (Opcode == BO_LAnd) 2741 Result = LHS && RHS; 2742 else 2743 Result = LHS || RHS; 2744 return true; 2745 } 2746 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2747 BinaryOperatorKind Opcode, 2748 const APFloat &RHSValue, APInt &Result) { 2749 bool LHS = !LHSValue.isZero(); 2750 bool RHS = !RHSValue.isZero(); 2751 2752 if (Opcode == BO_LAnd) 2753 Result = LHS && RHS; 2754 else 2755 Result = LHS || RHS; 2756 return true; 2757 } 2758 2759 static bool handleLogicalOpForVector(const APValue &LHSValue, 2760 BinaryOperatorKind Opcode, 2761 const APValue &RHSValue, APInt &Result) { 2762 // The result is always an int type, however operands match the first. 2763 if (LHSValue.getKind() == APValue::Int) 2764 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2765 RHSValue.getInt(), Result); 2766 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2767 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2768 RHSValue.getFloat(), Result); 2769 } 2770 2771 template <typename APTy> 2772 static bool 2773 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2774 const APTy &RHSValue, APInt &Result) { 2775 switch (Opcode) { 2776 default: 2777 llvm_unreachable("unsupported binary operator"); 2778 case BO_EQ: 2779 Result = (LHSValue == RHSValue); 2780 break; 2781 case BO_NE: 2782 Result = (LHSValue != RHSValue); 2783 break; 2784 case BO_LT: 2785 Result = (LHSValue < RHSValue); 2786 break; 2787 case BO_GT: 2788 Result = (LHSValue > RHSValue); 2789 break; 2790 case BO_LE: 2791 Result = (LHSValue <= RHSValue); 2792 break; 2793 case BO_GE: 2794 Result = (LHSValue >= RHSValue); 2795 break; 2796 } 2797 2798 return true; 2799 } 2800 2801 static bool handleCompareOpForVector(const APValue &LHSValue, 2802 BinaryOperatorKind Opcode, 2803 const APValue &RHSValue, APInt &Result) { 2804 // The result is always an int type, however operands match the first. 2805 if (LHSValue.getKind() == APValue::Int) 2806 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2807 RHSValue.getInt(), Result); 2808 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2809 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2810 RHSValue.getFloat(), Result); 2811 } 2812 2813 // Perform binary operations for vector types, in place on the LHS. 2814 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2815 BinaryOperatorKind Opcode, 2816 APValue &LHSValue, 2817 const APValue &RHSValue) { 2818 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2819 "Operation not supported on vector types"); 2820 2821 const auto *VT = E->getType()->castAs<VectorType>(); 2822 unsigned NumElements = VT->getNumElements(); 2823 QualType EltTy = VT->getElementType(); 2824 2825 // In the cases (typically C as I've observed) where we aren't evaluating 2826 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2827 // just give up. 2828 if (!LHSValue.isVector()) { 2829 assert(LHSValue.isLValue() && 2830 "A vector result that isn't a vector OR uncalculated LValue"); 2831 Info.FFDiag(E); 2832 return false; 2833 } 2834 2835 assert(LHSValue.getVectorLength() == NumElements && 2836 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2837 2838 SmallVector<APValue, 4> ResultElements; 2839 2840 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2841 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2842 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2843 2844 if (EltTy->isIntegerType()) { 2845 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2846 EltTy->isUnsignedIntegerType()}; 2847 bool Success = true; 2848 2849 if (BinaryOperator::isLogicalOp(Opcode)) 2850 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2851 else if (BinaryOperator::isComparisonOp(Opcode)) 2852 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2853 else 2854 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2855 RHSElt.getInt(), EltResult); 2856 2857 if (!Success) { 2858 Info.FFDiag(E); 2859 return false; 2860 } 2861 ResultElements.emplace_back(EltResult); 2862 2863 } else if (EltTy->isFloatingType()) { 2864 assert(LHSElt.getKind() == APValue::Float && 2865 RHSElt.getKind() == APValue::Float && 2866 "Mismatched LHS/RHS/Result Type"); 2867 APFloat LHSFloat = LHSElt.getFloat(); 2868 2869 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 2870 RHSElt.getFloat())) { 2871 Info.FFDiag(E); 2872 return false; 2873 } 2874 2875 ResultElements.emplace_back(LHSFloat); 2876 } 2877 } 2878 2879 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 2880 return true; 2881 } 2882 2883 /// Cast an lvalue referring to a base subobject to a derived class, by 2884 /// truncating the lvalue's path to the given length. 2885 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2886 const RecordDecl *TruncatedType, 2887 unsigned TruncatedElements) { 2888 SubobjectDesignator &D = Result.Designator; 2889 2890 // Check we actually point to a derived class object. 2891 if (TruncatedElements == D.Entries.size()) 2892 return true; 2893 assert(TruncatedElements >= D.MostDerivedPathLength && 2894 "not casting to a derived class"); 2895 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2896 return false; 2897 2898 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2899 const RecordDecl *RD = TruncatedType; 2900 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2901 if (RD->isInvalidDecl()) return false; 2902 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2903 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2904 if (isVirtualBaseClass(D.Entries[I])) 2905 Result.Offset -= Layout.getVBaseClassOffset(Base); 2906 else 2907 Result.Offset -= Layout.getBaseClassOffset(Base); 2908 RD = Base; 2909 } 2910 D.Entries.resize(TruncatedElements); 2911 return true; 2912 } 2913 2914 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2915 const CXXRecordDecl *Derived, 2916 const CXXRecordDecl *Base, 2917 const ASTRecordLayout *RL = nullptr) { 2918 if (!RL) { 2919 if (Derived->isInvalidDecl()) return false; 2920 RL = &Info.Ctx.getASTRecordLayout(Derived); 2921 } 2922 2923 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2924 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2925 return true; 2926 } 2927 2928 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2929 const CXXRecordDecl *DerivedDecl, 2930 const CXXBaseSpecifier *Base) { 2931 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2932 2933 if (!Base->isVirtual()) 2934 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2935 2936 SubobjectDesignator &D = Obj.Designator; 2937 if (D.Invalid) 2938 return false; 2939 2940 // Extract most-derived object and corresponding type. 2941 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2942 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2943 return false; 2944 2945 // Find the virtual base class. 2946 if (DerivedDecl->isInvalidDecl()) return false; 2947 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2948 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2949 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2950 return true; 2951 } 2952 2953 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2954 QualType Type, LValue &Result) { 2955 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2956 PathE = E->path_end(); 2957 PathI != PathE; ++PathI) { 2958 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2959 *PathI)) 2960 return false; 2961 Type = (*PathI)->getType(); 2962 } 2963 return true; 2964 } 2965 2966 /// Cast an lvalue referring to a derived class to a known base subobject. 2967 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 2968 const CXXRecordDecl *DerivedRD, 2969 const CXXRecordDecl *BaseRD) { 2970 CXXBasePaths Paths(/*FindAmbiguities=*/false, 2971 /*RecordPaths=*/true, /*DetectVirtual=*/false); 2972 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 2973 llvm_unreachable("Class must be derived from the passed in base class!"); 2974 2975 for (CXXBasePathElement &Elem : Paths.front()) 2976 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 2977 return false; 2978 return true; 2979 } 2980 2981 /// Update LVal to refer to the given field, which must be a member of the type 2982 /// currently described by LVal. 2983 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2984 const FieldDecl *FD, 2985 const ASTRecordLayout *RL = nullptr) { 2986 if (!RL) { 2987 if (FD->getParent()->isInvalidDecl()) return false; 2988 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2989 } 2990 2991 unsigned I = FD->getFieldIndex(); 2992 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2993 LVal.addDecl(Info, E, FD); 2994 return true; 2995 } 2996 2997 /// Update LVal to refer to the given indirect field. 2998 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2999 LValue &LVal, 3000 const IndirectFieldDecl *IFD) { 3001 for (const auto *C : IFD->chain()) 3002 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3003 return false; 3004 return true; 3005 } 3006 3007 /// Get the size of the given type in char units. 3008 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3009 QualType Type, CharUnits &Size) { 3010 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3011 // extension. 3012 if (Type->isVoidType() || Type->isFunctionType()) { 3013 Size = CharUnits::One(); 3014 return true; 3015 } 3016 3017 if (Type->isDependentType()) { 3018 Info.FFDiag(Loc); 3019 return false; 3020 } 3021 3022 if (!Type->isConstantSizeType()) { 3023 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3024 // FIXME: Better diagnostic. 3025 Info.FFDiag(Loc); 3026 return false; 3027 } 3028 3029 Size = Info.Ctx.getTypeSizeInChars(Type); 3030 return true; 3031 } 3032 3033 /// Update a pointer value to model pointer arithmetic. 3034 /// \param Info - Information about the ongoing evaluation. 3035 /// \param E - The expression being evaluated, for diagnostic purposes. 3036 /// \param LVal - The pointer value to be updated. 3037 /// \param EltTy - The pointee type represented by LVal. 3038 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3039 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3040 LValue &LVal, QualType EltTy, 3041 APSInt Adjustment) { 3042 CharUnits SizeOfPointee; 3043 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3044 return false; 3045 3046 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3047 return true; 3048 } 3049 3050 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3051 LValue &LVal, QualType EltTy, 3052 int64_t Adjustment) { 3053 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3054 APSInt::get(Adjustment)); 3055 } 3056 3057 /// Update an lvalue to refer to a component of a complex number. 3058 /// \param Info - Information about the ongoing evaluation. 3059 /// \param LVal - The lvalue to be updated. 3060 /// \param EltTy - The complex number's component type. 3061 /// \param Imag - False for the real component, true for the imaginary. 3062 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3063 LValue &LVal, QualType EltTy, 3064 bool Imag) { 3065 if (Imag) { 3066 CharUnits SizeOfComponent; 3067 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3068 return false; 3069 LVal.Offset += SizeOfComponent; 3070 } 3071 LVal.addComplex(Info, E, EltTy, Imag); 3072 return true; 3073 } 3074 3075 /// Try to evaluate the initializer for a variable declaration. 3076 /// 3077 /// \param Info Information about the ongoing evaluation. 3078 /// \param E An expression to be used when printing diagnostics. 3079 /// \param VD The variable whose initializer should be obtained. 3080 /// \param Frame The frame in which the variable was created. Must be null 3081 /// if this variable is not local to the evaluation. 3082 /// \param Result Filled in with a pointer to the value of the variable. 3083 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3084 const VarDecl *VD, CallStackFrame *Frame, 3085 APValue *&Result, const LValue *LVal) { 3086 3087 // If this is a parameter to an active constexpr function call, perform 3088 // argument substitution. 3089 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 3090 // Assume arguments of a potential constant expression are unknown 3091 // constant expressions. 3092 if (Info.checkingPotentialConstantExpression()) 3093 return false; 3094 if (!Frame || !Frame->Arguments) { 3095 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) << VD; 3096 return false; 3097 } 3098 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 3099 return true; 3100 } 3101 3102 // If this is a local variable, dig out its value. 3103 if (Frame) { 3104 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 3105 : Frame->getCurrentTemporary(VD); 3106 if (!Result) { 3107 // Assume variables referenced within a lambda's call operator that were 3108 // not declared within the call operator are captures and during checking 3109 // of a potential constant expression, assume they are unknown constant 3110 // expressions. 3111 assert(isLambdaCallOperator(Frame->Callee) && 3112 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3113 "missing value for local variable"); 3114 if (Info.checkingPotentialConstantExpression()) 3115 return false; 3116 // FIXME: implement capture evaluation during constant expr evaluation. 3117 Info.FFDiag(E->getBeginLoc(), 3118 diag::note_unimplemented_constexpr_lambda_feature_ast) 3119 << "captures not currently allowed"; 3120 return false; 3121 } 3122 return true; 3123 } 3124 3125 // Dig out the initializer, and use the declaration which it's attached to. 3126 // FIXME: We should eventually check whether the variable has a reachable 3127 // initializing declaration. 3128 const Expr *Init = VD->getAnyInitializer(VD); 3129 if (!Init) { 3130 // Don't diagnose during potential constant expression checking; an 3131 // initializer might be added later. 3132 if (!Info.checkingPotentialConstantExpression()) { 3133 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3134 << VD; 3135 Info.Note(VD->getLocation(), diag::note_declared_at); 3136 } 3137 return false; 3138 } 3139 3140 if (Init->isValueDependent()) { 3141 // The DeclRefExpr is not value-dependent, but the variable it refers to 3142 // has a value-dependent initializer. This should only happen in 3143 // constant-folding cases, where the variable is not actually of a suitable 3144 // type for use in a constant expression (otherwise the DeclRefExpr would 3145 // have been value-dependent too), so diagnose that. 3146 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3147 if (!Info.checkingPotentialConstantExpression()) { 3148 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3149 ? diag::note_constexpr_ltor_non_constexpr 3150 : diag::note_constexpr_ltor_non_integral, 1) 3151 << VD << VD->getType(); 3152 Info.Note(VD->getLocation(), diag::note_declared_at); 3153 } 3154 return false; 3155 } 3156 3157 // If we're currently evaluating the initializer of this declaration, use that 3158 // in-flight value. 3159 if (declaresSameEntity(Info.EvaluatingDecl.dyn_cast<const ValueDecl *>(), 3160 VD)) { 3161 Result = Info.EvaluatingDeclValue; 3162 return true; 3163 } 3164 3165 // Check that we can fold the initializer. In C++, we will have already done 3166 // this in the cases where it matters for conformance. 3167 SmallVector<PartialDiagnosticAt, 8> Notes; 3168 if (!VD->evaluateValue(Notes)) { 3169 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 3170 Notes.size() + 1) << VD; 3171 Info.Note(VD->getLocation(), diag::note_declared_at); 3172 Info.addNotes(Notes); 3173 return false; 3174 } 3175 3176 // Check that the variable is actually usable in constant expressions. 3177 if (!VD->checkInitIsICE()) { 3178 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 3179 Notes.size() + 1) << VD; 3180 Info.Note(VD->getLocation(), diag::note_declared_at); 3181 Info.addNotes(Notes); 3182 } 3183 3184 // Never use the initializer of a weak variable, not even for constant 3185 // folding. We can't be sure that this is the definition that will be used. 3186 if (VD->isWeak()) { 3187 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3188 Info.Note(VD->getLocation(), diag::note_declared_at); 3189 return false; 3190 } 3191 3192 Result = VD->getEvaluatedValue(); 3193 return true; 3194 } 3195 3196 static bool IsConstNonVolatile(QualType T) { 3197 Qualifiers Quals = T.getQualifiers(); 3198 return Quals.hasConst() && !Quals.hasVolatile(); 3199 } 3200 3201 /// Get the base index of the given base class within an APValue representing 3202 /// the given derived class. 3203 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3204 const CXXRecordDecl *Base) { 3205 Base = Base->getCanonicalDecl(); 3206 unsigned Index = 0; 3207 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3208 E = Derived->bases_end(); I != E; ++I, ++Index) { 3209 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3210 return Index; 3211 } 3212 3213 llvm_unreachable("base class missing from derived class's bases list"); 3214 } 3215 3216 /// Extract the value of a character from a string literal. 3217 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3218 uint64_t Index) { 3219 assert(!isa<SourceLocExpr>(Lit) && 3220 "SourceLocExpr should have already been converted to a StringLiteral"); 3221 3222 // FIXME: Support MakeStringConstant 3223 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3224 std::string Str; 3225 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3226 assert(Index <= Str.size() && "Index too large"); 3227 return APSInt::getUnsigned(Str.c_str()[Index]); 3228 } 3229 3230 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3231 Lit = PE->getFunctionName(); 3232 const StringLiteral *S = cast<StringLiteral>(Lit); 3233 const ConstantArrayType *CAT = 3234 Info.Ctx.getAsConstantArrayType(S->getType()); 3235 assert(CAT && "string literal isn't an array"); 3236 QualType CharType = CAT->getElementType(); 3237 assert(CharType->isIntegerType() && "unexpected character type"); 3238 3239 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3240 CharType->isUnsignedIntegerType()); 3241 if (Index < S->getLength()) 3242 Value = S->getCodeUnit(Index); 3243 return Value; 3244 } 3245 3246 // Expand a string literal into an array of characters. 3247 // 3248 // FIXME: This is inefficient; we should probably introduce something similar 3249 // to the LLVM ConstantDataArray to make this cheaper. 3250 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3251 APValue &Result, 3252 QualType AllocType = QualType()) { 3253 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3254 AllocType.isNull() ? S->getType() : AllocType); 3255 assert(CAT && "string literal isn't an array"); 3256 QualType CharType = CAT->getElementType(); 3257 assert(CharType->isIntegerType() && "unexpected character type"); 3258 3259 unsigned Elts = CAT->getSize().getZExtValue(); 3260 Result = APValue(APValue::UninitArray(), 3261 std::min(S->getLength(), Elts), Elts); 3262 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3263 CharType->isUnsignedIntegerType()); 3264 if (Result.hasArrayFiller()) 3265 Result.getArrayFiller() = APValue(Value); 3266 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3267 Value = S->getCodeUnit(I); 3268 Result.getArrayInitializedElt(I) = APValue(Value); 3269 } 3270 } 3271 3272 // Expand an array so that it has more than Index filled elements. 3273 static void expandArray(APValue &Array, unsigned Index) { 3274 unsigned Size = Array.getArraySize(); 3275 assert(Index < Size); 3276 3277 // Always at least double the number of elements for which we store a value. 3278 unsigned OldElts = Array.getArrayInitializedElts(); 3279 unsigned NewElts = std::max(Index+1, OldElts * 2); 3280 NewElts = std::min(Size, std::max(NewElts, 8u)); 3281 3282 // Copy the data across. 3283 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3284 for (unsigned I = 0; I != OldElts; ++I) 3285 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3286 for (unsigned I = OldElts; I != NewElts; ++I) 3287 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3288 if (NewValue.hasArrayFiller()) 3289 NewValue.getArrayFiller() = Array.getArrayFiller(); 3290 Array.swap(NewValue); 3291 } 3292 3293 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3294 /// conversion. If it's of class type, we may assume that the copy operation 3295 /// is trivial. Note that this is never true for a union type with fields 3296 /// (because the copy always "reads" the active member) and always true for 3297 /// a non-class type. 3298 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3299 static bool isReadByLvalueToRvalueConversion(QualType T) { 3300 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3301 return !RD || isReadByLvalueToRvalueConversion(RD); 3302 } 3303 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3304 // FIXME: A trivial copy of a union copies the object representation, even if 3305 // the union is empty. 3306 if (RD->isUnion()) 3307 return !RD->field_empty(); 3308 if (RD->isEmpty()) 3309 return false; 3310 3311 for (auto *Field : RD->fields()) 3312 if (!Field->isUnnamedBitfield() && 3313 isReadByLvalueToRvalueConversion(Field->getType())) 3314 return true; 3315 3316 for (auto &BaseSpec : RD->bases()) 3317 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3318 return true; 3319 3320 return false; 3321 } 3322 3323 /// Diagnose an attempt to read from any unreadable field within the specified 3324 /// type, which might be a class type. 3325 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3326 QualType T) { 3327 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3328 if (!RD) 3329 return false; 3330 3331 if (!RD->hasMutableFields()) 3332 return false; 3333 3334 for (auto *Field : RD->fields()) { 3335 // If we're actually going to read this field in some way, then it can't 3336 // be mutable. If we're in a union, then assigning to a mutable field 3337 // (even an empty one) can change the active member, so that's not OK. 3338 // FIXME: Add core issue number for the union case. 3339 if (Field->isMutable() && 3340 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3341 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3342 Info.Note(Field->getLocation(), diag::note_declared_at); 3343 return true; 3344 } 3345 3346 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3347 return true; 3348 } 3349 3350 for (auto &BaseSpec : RD->bases()) 3351 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3352 return true; 3353 3354 // All mutable fields were empty, and thus not actually read. 3355 return false; 3356 } 3357 3358 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3359 APValue::LValueBase Base, 3360 bool MutableSubobject = false) { 3361 // A temporary we created. 3362 if (Base.getCallIndex()) 3363 return true; 3364 3365 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3366 if (!Evaluating) 3367 return false; 3368 3369 auto *BaseD = Base.dyn_cast<const ValueDecl*>(); 3370 3371 switch (Info.IsEvaluatingDecl) { 3372 case EvalInfo::EvaluatingDeclKind::None: 3373 return false; 3374 3375 case EvalInfo::EvaluatingDeclKind::Ctor: 3376 // The variable whose initializer we're evaluating. 3377 if (BaseD) 3378 return declaresSameEntity(Evaluating, BaseD); 3379 3380 // A temporary lifetime-extended by the variable whose initializer we're 3381 // evaluating. 3382 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3383 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3384 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating); 3385 return false; 3386 3387 case EvalInfo::EvaluatingDeclKind::Dtor: 3388 // C++2a [expr.const]p6: 3389 // [during constant destruction] the lifetime of a and its non-mutable 3390 // subobjects (but not its mutable subobjects) [are] considered to start 3391 // within e. 3392 // 3393 // FIXME: We can meaningfully extend this to cover non-const objects, but 3394 // we will need special handling: we should be able to access only 3395 // subobjects of such objects that are themselves declared const. 3396 if (!BaseD || 3397 !(BaseD->getType().isConstQualified() || 3398 BaseD->getType()->isReferenceType()) || 3399 MutableSubobject) 3400 return false; 3401 return declaresSameEntity(Evaluating, BaseD); 3402 } 3403 3404 llvm_unreachable("unknown evaluating decl kind"); 3405 } 3406 3407 namespace { 3408 /// A handle to a complete object (an object that is not a subobject of 3409 /// another object). 3410 struct CompleteObject { 3411 /// The identity of the object. 3412 APValue::LValueBase Base; 3413 /// The value of the complete object. 3414 APValue *Value; 3415 /// The type of the complete object. 3416 QualType Type; 3417 3418 CompleteObject() : Value(nullptr) {} 3419 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3420 : Base(Base), Value(Value), Type(Type) {} 3421 3422 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3423 // If this isn't a "real" access (eg, if it's just accessing the type 3424 // info), allow it. We assume the type doesn't change dynamically for 3425 // subobjects of constexpr objects (even though we'd hit UB here if it 3426 // did). FIXME: Is this right? 3427 if (!isAnyAccess(AK)) 3428 return true; 3429 3430 // In C++14 onwards, it is permitted to read a mutable member whose 3431 // lifetime began within the evaluation. 3432 // FIXME: Should we also allow this in C++11? 3433 if (!Info.getLangOpts().CPlusPlus14) 3434 return false; 3435 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3436 } 3437 3438 explicit operator bool() const { return !Type.isNull(); } 3439 }; 3440 } // end anonymous namespace 3441 3442 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3443 bool IsMutable = false) { 3444 // C++ [basic.type.qualifier]p1: 3445 // - A const object is an object of type const T or a non-mutable subobject 3446 // of a const object. 3447 if (ObjType.isConstQualified() && !IsMutable) 3448 SubobjType.addConst(); 3449 // - A volatile object is an object of type const T or a subobject of a 3450 // volatile object. 3451 if (ObjType.isVolatileQualified()) 3452 SubobjType.addVolatile(); 3453 return SubobjType; 3454 } 3455 3456 /// Find the designated sub-object of an rvalue. 3457 template<typename SubobjectHandler> 3458 typename SubobjectHandler::result_type 3459 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3460 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3461 if (Sub.Invalid) 3462 // A diagnostic will have already been produced. 3463 return handler.failed(); 3464 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3465 if (Info.getLangOpts().CPlusPlus11) 3466 Info.FFDiag(E, Sub.isOnePastTheEnd() 3467 ? diag::note_constexpr_access_past_end 3468 : diag::note_constexpr_access_unsized_array) 3469 << handler.AccessKind; 3470 else 3471 Info.FFDiag(E); 3472 return handler.failed(); 3473 } 3474 3475 APValue *O = Obj.Value; 3476 QualType ObjType = Obj.Type; 3477 const FieldDecl *LastField = nullptr; 3478 const FieldDecl *VolatileField = nullptr; 3479 3480 // Walk the designator's path to find the subobject. 3481 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3482 // Reading an indeterminate value is undefined, but assigning over one is OK. 3483 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3484 (O->isIndeterminate() && 3485 !isValidIndeterminateAccess(handler.AccessKind))) { 3486 if (!Info.checkingPotentialConstantExpression()) 3487 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3488 << handler.AccessKind << O->isIndeterminate(); 3489 return handler.failed(); 3490 } 3491 3492 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3493 // const and volatile semantics are not applied on an object under 3494 // {con,de}struction. 3495 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3496 ObjType->isRecordType() && 3497 Info.isEvaluatingCtorDtor( 3498 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3499 Sub.Entries.begin() + I)) != 3500 ConstructionPhase::None) { 3501 ObjType = Info.Ctx.getCanonicalType(ObjType); 3502 ObjType.removeLocalConst(); 3503 ObjType.removeLocalVolatile(); 3504 } 3505 3506 // If this is our last pass, check that the final object type is OK. 3507 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3508 // Accesses to volatile objects are prohibited. 3509 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3510 if (Info.getLangOpts().CPlusPlus) { 3511 int DiagKind; 3512 SourceLocation Loc; 3513 const NamedDecl *Decl = nullptr; 3514 if (VolatileField) { 3515 DiagKind = 2; 3516 Loc = VolatileField->getLocation(); 3517 Decl = VolatileField; 3518 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3519 DiagKind = 1; 3520 Loc = VD->getLocation(); 3521 Decl = VD; 3522 } else { 3523 DiagKind = 0; 3524 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3525 Loc = E->getExprLoc(); 3526 } 3527 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3528 << handler.AccessKind << DiagKind << Decl; 3529 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3530 } else { 3531 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3532 } 3533 return handler.failed(); 3534 } 3535 3536 // If we are reading an object of class type, there may still be more 3537 // things we need to check: if there are any mutable subobjects, we 3538 // cannot perform this read. (This only happens when performing a trivial 3539 // copy or assignment.) 3540 if (ObjType->isRecordType() && 3541 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3542 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3543 return handler.failed(); 3544 } 3545 3546 if (I == N) { 3547 if (!handler.found(*O, ObjType)) 3548 return false; 3549 3550 // If we modified a bit-field, truncate it to the right width. 3551 if (isModification(handler.AccessKind) && 3552 LastField && LastField->isBitField() && 3553 !truncateBitfieldValue(Info, E, *O, LastField)) 3554 return false; 3555 3556 return true; 3557 } 3558 3559 LastField = nullptr; 3560 if (ObjType->isArrayType()) { 3561 // Next subobject is an array element. 3562 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3563 assert(CAT && "vla in literal type?"); 3564 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3565 if (CAT->getSize().ule(Index)) { 3566 // Note, it should not be possible to form a pointer with a valid 3567 // designator which points more than one past the end of the array. 3568 if (Info.getLangOpts().CPlusPlus11) 3569 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3570 << handler.AccessKind; 3571 else 3572 Info.FFDiag(E); 3573 return handler.failed(); 3574 } 3575 3576 ObjType = CAT->getElementType(); 3577 3578 if (O->getArrayInitializedElts() > Index) 3579 O = &O->getArrayInitializedElt(Index); 3580 else if (!isRead(handler.AccessKind)) { 3581 expandArray(*O, Index); 3582 O = &O->getArrayInitializedElt(Index); 3583 } else 3584 O = &O->getArrayFiller(); 3585 } else if (ObjType->isAnyComplexType()) { 3586 // Next subobject is a complex number. 3587 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3588 if (Index > 1) { 3589 if (Info.getLangOpts().CPlusPlus11) 3590 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3591 << handler.AccessKind; 3592 else 3593 Info.FFDiag(E); 3594 return handler.failed(); 3595 } 3596 3597 ObjType = getSubobjectType( 3598 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3599 3600 assert(I == N - 1 && "extracting subobject of scalar?"); 3601 if (O->isComplexInt()) { 3602 return handler.found(Index ? O->getComplexIntImag() 3603 : O->getComplexIntReal(), ObjType); 3604 } else { 3605 assert(O->isComplexFloat()); 3606 return handler.found(Index ? O->getComplexFloatImag() 3607 : O->getComplexFloatReal(), ObjType); 3608 } 3609 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3610 if (Field->isMutable() && 3611 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3612 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3613 << handler.AccessKind << Field; 3614 Info.Note(Field->getLocation(), diag::note_declared_at); 3615 return handler.failed(); 3616 } 3617 3618 // Next subobject is a class, struct or union field. 3619 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3620 if (RD->isUnion()) { 3621 const FieldDecl *UnionField = O->getUnionField(); 3622 if (!UnionField || 3623 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3624 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3625 // Placement new onto an inactive union member makes it active. 3626 O->setUnion(Field, APValue()); 3627 } else { 3628 // FIXME: If O->getUnionValue() is absent, report that there's no 3629 // active union member rather than reporting the prior active union 3630 // member. We'll need to fix nullptr_t to not use APValue() as its 3631 // representation first. 3632 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3633 << handler.AccessKind << Field << !UnionField << UnionField; 3634 return handler.failed(); 3635 } 3636 } 3637 O = &O->getUnionValue(); 3638 } else 3639 O = &O->getStructField(Field->getFieldIndex()); 3640 3641 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3642 LastField = Field; 3643 if (Field->getType().isVolatileQualified()) 3644 VolatileField = Field; 3645 } else { 3646 // Next subobject is a base class. 3647 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3648 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3649 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3650 3651 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3652 } 3653 } 3654 } 3655 3656 namespace { 3657 struct ExtractSubobjectHandler { 3658 EvalInfo &Info; 3659 const Expr *E; 3660 APValue &Result; 3661 const AccessKinds AccessKind; 3662 3663 typedef bool result_type; 3664 bool failed() { return false; } 3665 bool found(APValue &Subobj, QualType SubobjType) { 3666 Result = Subobj; 3667 if (AccessKind == AK_ReadObjectRepresentation) 3668 return true; 3669 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3670 } 3671 bool found(APSInt &Value, QualType SubobjType) { 3672 Result = APValue(Value); 3673 return true; 3674 } 3675 bool found(APFloat &Value, QualType SubobjType) { 3676 Result = APValue(Value); 3677 return true; 3678 } 3679 }; 3680 } // end anonymous namespace 3681 3682 /// Extract the designated sub-object of an rvalue. 3683 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3684 const CompleteObject &Obj, 3685 const SubobjectDesignator &Sub, APValue &Result, 3686 AccessKinds AK = AK_Read) { 3687 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3688 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3689 return findSubobject(Info, E, Obj, Sub, Handler); 3690 } 3691 3692 namespace { 3693 struct ModifySubobjectHandler { 3694 EvalInfo &Info; 3695 APValue &NewVal; 3696 const Expr *E; 3697 3698 typedef bool result_type; 3699 static const AccessKinds AccessKind = AK_Assign; 3700 3701 bool checkConst(QualType QT) { 3702 // Assigning to a const object has undefined behavior. 3703 if (QT.isConstQualified()) { 3704 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3705 return false; 3706 } 3707 return true; 3708 } 3709 3710 bool failed() { return false; } 3711 bool found(APValue &Subobj, QualType SubobjType) { 3712 if (!checkConst(SubobjType)) 3713 return false; 3714 // We've been given ownership of NewVal, so just swap it in. 3715 Subobj.swap(NewVal); 3716 return true; 3717 } 3718 bool found(APSInt &Value, QualType SubobjType) { 3719 if (!checkConst(SubobjType)) 3720 return false; 3721 if (!NewVal.isInt()) { 3722 // Maybe trying to write a cast pointer value into a complex? 3723 Info.FFDiag(E); 3724 return false; 3725 } 3726 Value = NewVal.getInt(); 3727 return true; 3728 } 3729 bool found(APFloat &Value, QualType SubobjType) { 3730 if (!checkConst(SubobjType)) 3731 return false; 3732 Value = NewVal.getFloat(); 3733 return true; 3734 } 3735 }; 3736 } // end anonymous namespace 3737 3738 const AccessKinds ModifySubobjectHandler::AccessKind; 3739 3740 /// Update the designated sub-object of an rvalue to the given value. 3741 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3742 const CompleteObject &Obj, 3743 const SubobjectDesignator &Sub, 3744 APValue &NewVal) { 3745 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3746 return findSubobject(Info, E, Obj, Sub, Handler); 3747 } 3748 3749 /// Find the position where two subobject designators diverge, or equivalently 3750 /// the length of the common initial subsequence. 3751 static unsigned FindDesignatorMismatch(QualType ObjType, 3752 const SubobjectDesignator &A, 3753 const SubobjectDesignator &B, 3754 bool &WasArrayIndex) { 3755 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3756 for (/**/; I != N; ++I) { 3757 if (!ObjType.isNull() && 3758 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3759 // Next subobject is an array element. 3760 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3761 WasArrayIndex = true; 3762 return I; 3763 } 3764 if (ObjType->isAnyComplexType()) 3765 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3766 else 3767 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3768 } else { 3769 if (A.Entries[I].getAsBaseOrMember() != 3770 B.Entries[I].getAsBaseOrMember()) { 3771 WasArrayIndex = false; 3772 return I; 3773 } 3774 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3775 // Next subobject is a field. 3776 ObjType = FD->getType(); 3777 else 3778 // Next subobject is a base class. 3779 ObjType = QualType(); 3780 } 3781 } 3782 WasArrayIndex = false; 3783 return I; 3784 } 3785 3786 /// Determine whether the given subobject designators refer to elements of the 3787 /// same array object. 3788 static bool AreElementsOfSameArray(QualType ObjType, 3789 const SubobjectDesignator &A, 3790 const SubobjectDesignator &B) { 3791 if (A.Entries.size() != B.Entries.size()) 3792 return false; 3793 3794 bool IsArray = A.MostDerivedIsArrayElement; 3795 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3796 // A is a subobject of the array element. 3797 return false; 3798 3799 // If A (and B) designates an array element, the last entry will be the array 3800 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3801 // of length 1' case, and the entire path must match. 3802 bool WasArrayIndex; 3803 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3804 return CommonLength >= A.Entries.size() - IsArray; 3805 } 3806 3807 /// Find the complete object to which an LValue refers. 3808 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3809 AccessKinds AK, const LValue &LVal, 3810 QualType LValType) { 3811 if (LVal.InvalidBase) { 3812 Info.FFDiag(E); 3813 return CompleteObject(); 3814 } 3815 3816 if (!LVal.Base) { 3817 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3818 return CompleteObject(); 3819 } 3820 3821 CallStackFrame *Frame = nullptr; 3822 unsigned Depth = 0; 3823 if (LVal.getLValueCallIndex()) { 3824 std::tie(Frame, Depth) = 3825 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3826 if (!Frame) { 3827 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3828 << AK << LVal.Base.is<const ValueDecl*>(); 3829 NoteLValueLocation(Info, LVal.Base); 3830 return CompleteObject(); 3831 } 3832 } 3833 3834 bool IsAccess = isAnyAccess(AK); 3835 3836 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3837 // is not a constant expression (even if the object is non-volatile). We also 3838 // apply this rule to C++98, in order to conform to the expected 'volatile' 3839 // semantics. 3840 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3841 if (Info.getLangOpts().CPlusPlus) 3842 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3843 << AK << LValType; 3844 else 3845 Info.FFDiag(E); 3846 return CompleteObject(); 3847 } 3848 3849 // Compute value storage location and type of base object. 3850 APValue *BaseVal = nullptr; 3851 QualType BaseType = getType(LVal.Base); 3852 3853 if (const ConstantExpr *CE = 3854 dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) { 3855 /// Nested immediate invocation have been previously removed so if we found 3856 /// a ConstantExpr it can only be the EvaluatingDecl. 3857 assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl); 3858 (void)CE; 3859 BaseVal = Info.EvaluatingDeclValue; 3860 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3861 // Allow reading from a GUID declaration. 3862 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 3863 if (isModification(AK)) { 3864 // All the remaining cases do not permit modification of the object. 3865 Info.FFDiag(E, diag::note_constexpr_modify_global); 3866 return CompleteObject(); 3867 } 3868 APValue &V = GD->getAsAPValue(); 3869 if (V.isAbsent()) { 3870 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 3871 << GD->getType(); 3872 return CompleteObject(); 3873 } 3874 return CompleteObject(LVal.Base, &V, GD->getType()); 3875 } 3876 3877 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3878 // In C++11, constexpr, non-volatile variables initialized with constant 3879 // expressions are constant expressions too. Inside constexpr functions, 3880 // parameters are constant expressions even if they're non-const. 3881 // In C++1y, objects local to a constant expression (those with a Frame) are 3882 // both readable and writable inside constant expressions. 3883 // In C, such things can also be folded, although they are not ICEs. 3884 const VarDecl *VD = dyn_cast<VarDecl>(D); 3885 if (VD) { 3886 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3887 VD = VDef; 3888 } 3889 if (!VD || VD->isInvalidDecl()) { 3890 Info.FFDiag(E); 3891 return CompleteObject(); 3892 } 3893 3894 // In OpenCL if a variable is in constant address space it is a const value. 3895 bool IsConstant = BaseType.isConstQualified() || 3896 (Info.getLangOpts().OpenCL && 3897 BaseType.getAddressSpace() == LangAS::opencl_constant); 3898 3899 // Unless we're looking at a local variable or argument in a constexpr call, 3900 // the variable we're reading must be const. 3901 if (!Frame) { 3902 if (Info.getLangOpts().CPlusPlus14 && 3903 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3904 // OK, we can read and modify an object if we're in the process of 3905 // evaluating its initializer, because its lifetime began in this 3906 // evaluation. 3907 } else if (isModification(AK)) { 3908 // All the remaining cases do not permit modification of the object. 3909 Info.FFDiag(E, diag::note_constexpr_modify_global); 3910 return CompleteObject(); 3911 } else if (VD->isConstexpr()) { 3912 // OK, we can read this variable. 3913 } else if (BaseType->isIntegralOrEnumerationType()) { 3914 // In OpenCL if a variable is in constant address space it is a const 3915 // value. 3916 if (!IsConstant) { 3917 if (!IsAccess) 3918 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3919 if (Info.getLangOpts().CPlusPlus) { 3920 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3921 Info.Note(VD->getLocation(), diag::note_declared_at); 3922 } else { 3923 Info.FFDiag(E); 3924 } 3925 return CompleteObject(); 3926 } 3927 } else if (!IsAccess) { 3928 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3929 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 3930 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 3931 // This variable might end up being constexpr. Don't diagnose it yet. 3932 } else if (IsConstant) { 3933 // Keep evaluating to see what we can do. In particular, we support 3934 // folding of const floating-point types, in order to make static const 3935 // data members of such types (supported as an extension) more useful. 3936 if (Info.getLangOpts().CPlusPlus) { 3937 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 3938 ? diag::note_constexpr_ltor_non_constexpr 3939 : diag::note_constexpr_ltor_non_integral, 1) 3940 << VD << BaseType; 3941 Info.Note(VD->getLocation(), diag::note_declared_at); 3942 } else { 3943 Info.CCEDiag(E); 3944 } 3945 } else { 3946 // Never allow reading a non-const value. 3947 if (Info.getLangOpts().CPlusPlus) { 3948 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3949 ? diag::note_constexpr_ltor_non_constexpr 3950 : diag::note_constexpr_ltor_non_integral, 1) 3951 << VD << BaseType; 3952 Info.Note(VD->getLocation(), diag::note_declared_at); 3953 } else { 3954 Info.FFDiag(E); 3955 } 3956 return CompleteObject(); 3957 } 3958 } 3959 3960 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3961 return CompleteObject(); 3962 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 3963 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 3964 if (!Alloc) { 3965 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 3966 return CompleteObject(); 3967 } 3968 return CompleteObject(LVal.Base, &(*Alloc)->Value, 3969 LVal.Base.getDynamicAllocType()); 3970 } else { 3971 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3972 3973 if (!Frame) { 3974 if (const MaterializeTemporaryExpr *MTE = 3975 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 3976 assert(MTE->getStorageDuration() == SD_Static && 3977 "should have a frame for a non-global materialized temporary"); 3978 3979 // Per C++1y [expr.const]p2: 3980 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3981 // - a [...] glvalue of integral or enumeration type that refers to 3982 // a non-volatile const object [...] 3983 // [...] 3984 // - a [...] glvalue of literal type that refers to a non-volatile 3985 // object whose lifetime began within the evaluation of e. 3986 // 3987 // C++11 misses the 'began within the evaluation of e' check and 3988 // instead allows all temporaries, including things like: 3989 // int &&r = 1; 3990 // int x = ++r; 3991 // constexpr int k = r; 3992 // Therefore we use the C++14 rules in C++11 too. 3993 // 3994 // Note that temporaries whose lifetimes began while evaluating a 3995 // variable's constructor are not usable while evaluating the 3996 // corresponding destructor, not even if they're of const-qualified 3997 // types. 3998 if (!(BaseType.isConstQualified() && 3999 BaseType->isIntegralOrEnumerationType()) && 4000 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4001 if (!IsAccess) 4002 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4003 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4004 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4005 return CompleteObject(); 4006 } 4007 4008 BaseVal = MTE->getOrCreateValue(false); 4009 assert(BaseVal && "got reference to unevaluated temporary"); 4010 } else { 4011 if (!IsAccess) 4012 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4013 APValue Val; 4014 LVal.moveInto(Val); 4015 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4016 << AK 4017 << Val.getAsString(Info.Ctx, 4018 Info.Ctx.getLValueReferenceType(LValType)); 4019 NoteLValueLocation(Info, LVal.Base); 4020 return CompleteObject(); 4021 } 4022 } else { 4023 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4024 assert(BaseVal && "missing value for temporary"); 4025 } 4026 } 4027 4028 // In C++14, we can't safely access any mutable state when we might be 4029 // evaluating after an unmodeled side effect. 4030 // 4031 // FIXME: Not all local state is mutable. Allow local constant subobjects 4032 // to be read here (but take care with 'mutable' fields). 4033 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4034 Info.EvalStatus.HasSideEffects) || 4035 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth)) 4036 return CompleteObject(); 4037 4038 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4039 } 4040 4041 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4042 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4043 /// glvalue referred to by an entity of reference type. 4044 /// 4045 /// \param Info - Information about the ongoing evaluation. 4046 /// \param Conv - The expression for which we are performing the conversion. 4047 /// Used for diagnostics. 4048 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4049 /// case of a non-class type). 4050 /// \param LVal - The glvalue on which we are attempting to perform this action. 4051 /// \param RVal - The produced value will be placed here. 4052 /// \param WantObjectRepresentation - If true, we're looking for the object 4053 /// representation rather than the value, and in particular, 4054 /// there is no requirement that the result be fully initialized. 4055 static bool 4056 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4057 const LValue &LVal, APValue &RVal, 4058 bool WantObjectRepresentation = false) { 4059 if (LVal.Designator.Invalid) 4060 return false; 4061 4062 // Check for special cases where there is no existing APValue to look at. 4063 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4064 4065 AccessKinds AK = 4066 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4067 4068 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4069 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4070 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4071 // initializer until now for such expressions. Such an expression can't be 4072 // an ICE in C, so this only matters for fold. 4073 if (Type.isVolatileQualified()) { 4074 Info.FFDiag(Conv); 4075 return false; 4076 } 4077 APValue Lit; 4078 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4079 return false; 4080 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4081 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4082 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4083 // Special-case character extraction so we don't have to construct an 4084 // APValue for the whole string. 4085 assert(LVal.Designator.Entries.size() <= 1 && 4086 "Can only read characters from string literals"); 4087 if (LVal.Designator.Entries.empty()) { 4088 // Fail for now for LValue to RValue conversion of an array. 4089 // (This shouldn't show up in C/C++, but it could be triggered by a 4090 // weird EvaluateAsRValue call from a tool.) 4091 Info.FFDiag(Conv); 4092 return false; 4093 } 4094 if (LVal.Designator.isOnePastTheEnd()) { 4095 if (Info.getLangOpts().CPlusPlus11) 4096 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4097 else 4098 Info.FFDiag(Conv); 4099 return false; 4100 } 4101 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4102 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4103 return true; 4104 } 4105 } 4106 4107 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4108 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4109 } 4110 4111 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4112 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4113 QualType LValType, APValue &Val) { 4114 if (LVal.Designator.Invalid) 4115 return false; 4116 4117 if (!Info.getLangOpts().CPlusPlus14) { 4118 Info.FFDiag(E); 4119 return false; 4120 } 4121 4122 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4123 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4124 } 4125 4126 namespace { 4127 struct CompoundAssignSubobjectHandler { 4128 EvalInfo &Info; 4129 const CompoundAssignOperator *E; 4130 QualType PromotedLHSType; 4131 BinaryOperatorKind Opcode; 4132 const APValue &RHS; 4133 4134 static const AccessKinds AccessKind = AK_Assign; 4135 4136 typedef bool result_type; 4137 4138 bool checkConst(QualType QT) { 4139 // Assigning to a const object has undefined behavior. 4140 if (QT.isConstQualified()) { 4141 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4142 return false; 4143 } 4144 return true; 4145 } 4146 4147 bool failed() { return false; } 4148 bool found(APValue &Subobj, QualType SubobjType) { 4149 switch (Subobj.getKind()) { 4150 case APValue::Int: 4151 return found(Subobj.getInt(), SubobjType); 4152 case APValue::Float: 4153 return found(Subobj.getFloat(), SubobjType); 4154 case APValue::ComplexInt: 4155 case APValue::ComplexFloat: 4156 // FIXME: Implement complex compound assignment. 4157 Info.FFDiag(E); 4158 return false; 4159 case APValue::LValue: 4160 return foundPointer(Subobj, SubobjType); 4161 case APValue::Vector: 4162 return foundVector(Subobj, SubobjType); 4163 default: 4164 // FIXME: can this happen? 4165 Info.FFDiag(E); 4166 return false; 4167 } 4168 } 4169 4170 bool foundVector(APValue &Value, QualType SubobjType) { 4171 if (!checkConst(SubobjType)) 4172 return false; 4173 4174 if (!SubobjType->isVectorType()) { 4175 Info.FFDiag(E); 4176 return false; 4177 } 4178 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4179 } 4180 4181 bool found(APSInt &Value, QualType SubobjType) { 4182 if (!checkConst(SubobjType)) 4183 return false; 4184 4185 if (!SubobjType->isIntegerType()) { 4186 // We don't support compound assignment on integer-cast-to-pointer 4187 // values. 4188 Info.FFDiag(E); 4189 return false; 4190 } 4191 4192 if (RHS.isInt()) { 4193 APSInt LHS = 4194 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4195 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4196 return false; 4197 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4198 return true; 4199 } else if (RHS.isFloat()) { 4200 APFloat FValue(0.0); 4201 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, 4202 FValue) && 4203 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4204 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4205 Value); 4206 } 4207 4208 Info.FFDiag(E); 4209 return false; 4210 } 4211 bool found(APFloat &Value, QualType SubobjType) { 4212 return checkConst(SubobjType) && 4213 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4214 Value) && 4215 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4216 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4217 } 4218 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4219 if (!checkConst(SubobjType)) 4220 return false; 4221 4222 QualType PointeeType; 4223 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4224 PointeeType = PT->getPointeeType(); 4225 4226 if (PointeeType.isNull() || !RHS.isInt() || 4227 (Opcode != BO_Add && Opcode != BO_Sub)) { 4228 Info.FFDiag(E); 4229 return false; 4230 } 4231 4232 APSInt Offset = RHS.getInt(); 4233 if (Opcode == BO_Sub) 4234 negateAsSigned(Offset); 4235 4236 LValue LVal; 4237 LVal.setFrom(Info.Ctx, Subobj); 4238 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4239 return false; 4240 LVal.moveInto(Subobj); 4241 return true; 4242 } 4243 }; 4244 } // end anonymous namespace 4245 4246 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4247 4248 /// Perform a compound assignment of LVal <op>= RVal. 4249 static bool handleCompoundAssignment(EvalInfo &Info, 4250 const CompoundAssignOperator *E, 4251 const LValue &LVal, QualType LValType, 4252 QualType PromotedLValType, 4253 BinaryOperatorKind Opcode, 4254 const APValue &RVal) { 4255 if (LVal.Designator.Invalid) 4256 return false; 4257 4258 if (!Info.getLangOpts().CPlusPlus14) { 4259 Info.FFDiag(E); 4260 return false; 4261 } 4262 4263 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4264 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4265 RVal }; 4266 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4267 } 4268 4269 namespace { 4270 struct IncDecSubobjectHandler { 4271 EvalInfo &Info; 4272 const UnaryOperator *E; 4273 AccessKinds AccessKind; 4274 APValue *Old; 4275 4276 typedef bool result_type; 4277 4278 bool checkConst(QualType QT) { 4279 // Assigning to a const object has undefined behavior. 4280 if (QT.isConstQualified()) { 4281 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4282 return false; 4283 } 4284 return true; 4285 } 4286 4287 bool failed() { return false; } 4288 bool found(APValue &Subobj, QualType SubobjType) { 4289 // Stash the old value. Also clear Old, so we don't clobber it later 4290 // if we're post-incrementing a complex. 4291 if (Old) { 4292 *Old = Subobj; 4293 Old = nullptr; 4294 } 4295 4296 switch (Subobj.getKind()) { 4297 case APValue::Int: 4298 return found(Subobj.getInt(), SubobjType); 4299 case APValue::Float: 4300 return found(Subobj.getFloat(), SubobjType); 4301 case APValue::ComplexInt: 4302 return found(Subobj.getComplexIntReal(), 4303 SubobjType->castAs<ComplexType>()->getElementType() 4304 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4305 case APValue::ComplexFloat: 4306 return found(Subobj.getComplexFloatReal(), 4307 SubobjType->castAs<ComplexType>()->getElementType() 4308 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4309 case APValue::LValue: 4310 return foundPointer(Subobj, SubobjType); 4311 default: 4312 // FIXME: can this happen? 4313 Info.FFDiag(E); 4314 return false; 4315 } 4316 } 4317 bool found(APSInt &Value, QualType SubobjType) { 4318 if (!checkConst(SubobjType)) 4319 return false; 4320 4321 if (!SubobjType->isIntegerType()) { 4322 // We don't support increment / decrement on integer-cast-to-pointer 4323 // values. 4324 Info.FFDiag(E); 4325 return false; 4326 } 4327 4328 if (Old) *Old = APValue(Value); 4329 4330 // bool arithmetic promotes to int, and the conversion back to bool 4331 // doesn't reduce mod 2^n, so special-case it. 4332 if (SubobjType->isBooleanType()) { 4333 if (AccessKind == AK_Increment) 4334 Value = 1; 4335 else 4336 Value = !Value; 4337 return true; 4338 } 4339 4340 bool WasNegative = Value.isNegative(); 4341 if (AccessKind == AK_Increment) { 4342 ++Value; 4343 4344 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4345 APSInt ActualValue(Value, /*IsUnsigned*/true); 4346 return HandleOverflow(Info, E, ActualValue, SubobjType); 4347 } 4348 } else { 4349 --Value; 4350 4351 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4352 unsigned BitWidth = Value.getBitWidth(); 4353 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4354 ActualValue.setBit(BitWidth); 4355 return HandleOverflow(Info, E, ActualValue, SubobjType); 4356 } 4357 } 4358 return true; 4359 } 4360 bool found(APFloat &Value, QualType SubobjType) { 4361 if (!checkConst(SubobjType)) 4362 return false; 4363 4364 if (Old) *Old = APValue(Value); 4365 4366 APFloat One(Value.getSemantics(), 1); 4367 if (AccessKind == AK_Increment) 4368 Value.add(One, APFloat::rmNearestTiesToEven); 4369 else 4370 Value.subtract(One, APFloat::rmNearestTiesToEven); 4371 return true; 4372 } 4373 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4374 if (!checkConst(SubobjType)) 4375 return false; 4376 4377 QualType PointeeType; 4378 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4379 PointeeType = PT->getPointeeType(); 4380 else { 4381 Info.FFDiag(E); 4382 return false; 4383 } 4384 4385 LValue LVal; 4386 LVal.setFrom(Info.Ctx, Subobj); 4387 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4388 AccessKind == AK_Increment ? 1 : -1)) 4389 return false; 4390 LVal.moveInto(Subobj); 4391 return true; 4392 } 4393 }; 4394 } // end anonymous namespace 4395 4396 /// Perform an increment or decrement on LVal. 4397 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4398 QualType LValType, bool IsIncrement, APValue *Old) { 4399 if (LVal.Designator.Invalid) 4400 return false; 4401 4402 if (!Info.getLangOpts().CPlusPlus14) { 4403 Info.FFDiag(E); 4404 return false; 4405 } 4406 4407 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4408 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4409 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4410 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4411 } 4412 4413 /// Build an lvalue for the object argument of a member function call. 4414 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4415 LValue &This) { 4416 if (Object->getType()->isPointerType() && Object->isRValue()) 4417 return EvaluatePointer(Object, This, Info); 4418 4419 if (Object->isGLValue()) 4420 return EvaluateLValue(Object, This, Info); 4421 4422 if (Object->getType()->isLiteralType(Info.Ctx)) 4423 return EvaluateTemporary(Object, This, Info); 4424 4425 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4426 return false; 4427 } 4428 4429 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4430 /// lvalue referring to the result. 4431 /// 4432 /// \param Info - Information about the ongoing evaluation. 4433 /// \param LV - An lvalue referring to the base of the member pointer. 4434 /// \param RHS - The member pointer expression. 4435 /// \param IncludeMember - Specifies whether the member itself is included in 4436 /// the resulting LValue subobject designator. This is not possible when 4437 /// creating a bound member function. 4438 /// \return The field or method declaration to which the member pointer refers, 4439 /// or 0 if evaluation fails. 4440 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4441 QualType LVType, 4442 LValue &LV, 4443 const Expr *RHS, 4444 bool IncludeMember = true) { 4445 MemberPtr MemPtr; 4446 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4447 return nullptr; 4448 4449 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4450 // member value, the behavior is undefined. 4451 if (!MemPtr.getDecl()) { 4452 // FIXME: Specific diagnostic. 4453 Info.FFDiag(RHS); 4454 return nullptr; 4455 } 4456 4457 if (MemPtr.isDerivedMember()) { 4458 // This is a member of some derived class. Truncate LV appropriately. 4459 // The end of the derived-to-base path for the base object must match the 4460 // derived-to-base path for the member pointer. 4461 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4462 LV.Designator.Entries.size()) { 4463 Info.FFDiag(RHS); 4464 return nullptr; 4465 } 4466 unsigned PathLengthToMember = 4467 LV.Designator.Entries.size() - MemPtr.Path.size(); 4468 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4469 const CXXRecordDecl *LVDecl = getAsBaseClass( 4470 LV.Designator.Entries[PathLengthToMember + I]); 4471 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4472 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4473 Info.FFDiag(RHS); 4474 return nullptr; 4475 } 4476 } 4477 4478 // Truncate the lvalue to the appropriate derived class. 4479 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4480 PathLengthToMember)) 4481 return nullptr; 4482 } else if (!MemPtr.Path.empty()) { 4483 // Extend the LValue path with the member pointer's path. 4484 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4485 MemPtr.Path.size() + IncludeMember); 4486 4487 // Walk down to the appropriate base class. 4488 if (const PointerType *PT = LVType->getAs<PointerType>()) 4489 LVType = PT->getPointeeType(); 4490 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4491 assert(RD && "member pointer access on non-class-type expression"); 4492 // The first class in the path is that of the lvalue. 4493 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4494 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4495 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4496 return nullptr; 4497 RD = Base; 4498 } 4499 // Finally cast to the class containing the member. 4500 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4501 MemPtr.getContainingRecord())) 4502 return nullptr; 4503 } 4504 4505 // Add the member. Note that we cannot build bound member functions here. 4506 if (IncludeMember) { 4507 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4508 if (!HandleLValueMember(Info, RHS, LV, FD)) 4509 return nullptr; 4510 } else if (const IndirectFieldDecl *IFD = 4511 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4512 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4513 return nullptr; 4514 } else { 4515 llvm_unreachable("can't construct reference to bound member function"); 4516 } 4517 } 4518 4519 return MemPtr.getDecl(); 4520 } 4521 4522 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4523 const BinaryOperator *BO, 4524 LValue &LV, 4525 bool IncludeMember = true) { 4526 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4527 4528 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4529 if (Info.noteFailure()) { 4530 MemberPtr MemPtr; 4531 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4532 } 4533 return nullptr; 4534 } 4535 4536 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4537 BO->getRHS(), IncludeMember); 4538 } 4539 4540 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4541 /// the provided lvalue, which currently refers to the base object. 4542 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4543 LValue &Result) { 4544 SubobjectDesignator &D = Result.Designator; 4545 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4546 return false; 4547 4548 QualType TargetQT = E->getType(); 4549 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4550 TargetQT = PT->getPointeeType(); 4551 4552 // Check this cast lands within the final derived-to-base subobject path. 4553 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4554 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4555 << D.MostDerivedType << TargetQT; 4556 return false; 4557 } 4558 4559 // Check the type of the final cast. We don't need to check the path, 4560 // since a cast can only be formed if the path is unique. 4561 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4562 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4563 const CXXRecordDecl *FinalType; 4564 if (NewEntriesSize == D.MostDerivedPathLength) 4565 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4566 else 4567 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4568 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4569 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4570 << D.MostDerivedType << TargetQT; 4571 return false; 4572 } 4573 4574 // Truncate the lvalue to the appropriate derived class. 4575 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4576 } 4577 4578 /// Get the value to use for a default-initialized object of type T. 4579 /// Return false if it encounters something invalid. 4580 static bool getDefaultInitValue(QualType T, APValue &Result) { 4581 bool Success = true; 4582 if (auto *RD = T->getAsCXXRecordDecl()) { 4583 if (RD->isInvalidDecl()) { 4584 Result = APValue(); 4585 return false; 4586 } 4587 if (RD->isUnion()) { 4588 Result = APValue((const FieldDecl *)nullptr); 4589 return true; 4590 } 4591 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4592 std::distance(RD->field_begin(), RD->field_end())); 4593 4594 unsigned Index = 0; 4595 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4596 End = RD->bases_end(); 4597 I != End; ++I, ++Index) 4598 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4599 4600 for (const auto *I : RD->fields()) { 4601 if (I->isUnnamedBitfield()) 4602 continue; 4603 Success &= getDefaultInitValue(I->getType(), 4604 Result.getStructField(I->getFieldIndex())); 4605 } 4606 return Success; 4607 } 4608 4609 if (auto *AT = 4610 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4611 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4612 if (Result.hasArrayFiller()) 4613 Success &= 4614 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4615 4616 return Success; 4617 } 4618 4619 Result = APValue::IndeterminateValue(); 4620 return true; 4621 } 4622 4623 namespace { 4624 enum EvalStmtResult { 4625 /// Evaluation failed. 4626 ESR_Failed, 4627 /// Hit a 'return' statement. 4628 ESR_Returned, 4629 /// Evaluation succeeded. 4630 ESR_Succeeded, 4631 /// Hit a 'continue' statement. 4632 ESR_Continue, 4633 /// Hit a 'break' statement. 4634 ESR_Break, 4635 /// Still scanning for 'case' or 'default' statement. 4636 ESR_CaseNotFound 4637 }; 4638 } 4639 4640 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4641 // We don't need to evaluate the initializer for a static local. 4642 if (!VD->hasLocalStorage()) 4643 return true; 4644 4645 LValue Result; 4646 APValue &Val = 4647 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result); 4648 4649 const Expr *InitE = VD->getInit(); 4650 if (!InitE) 4651 return getDefaultInitValue(VD->getType(), Val); 4652 4653 if (InitE->isValueDependent()) 4654 return false; 4655 4656 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4657 // Wipe out any partially-computed value, to allow tracking that this 4658 // evaluation failed. 4659 Val = APValue(); 4660 return false; 4661 } 4662 4663 return true; 4664 } 4665 4666 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4667 bool OK = true; 4668 4669 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4670 OK &= EvaluateVarDecl(Info, VD); 4671 4672 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4673 for (auto *BD : DD->bindings()) 4674 if (auto *VD = BD->getHoldingVar()) 4675 OK &= EvaluateDecl(Info, VD); 4676 4677 return OK; 4678 } 4679 4680 4681 /// Evaluate a condition (either a variable declaration or an expression). 4682 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4683 const Expr *Cond, bool &Result) { 4684 FullExpressionRAII Scope(Info); 4685 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4686 return false; 4687 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4688 return false; 4689 return Scope.destroy(); 4690 } 4691 4692 namespace { 4693 /// A location where the result (returned value) of evaluating a 4694 /// statement should be stored. 4695 struct StmtResult { 4696 /// The APValue that should be filled in with the returned value. 4697 APValue &Value; 4698 /// The location containing the result, if any (used to support RVO). 4699 const LValue *Slot; 4700 }; 4701 4702 struct TempVersionRAII { 4703 CallStackFrame &Frame; 4704 4705 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4706 Frame.pushTempVersion(); 4707 } 4708 4709 ~TempVersionRAII() { 4710 Frame.popTempVersion(); 4711 } 4712 }; 4713 4714 } 4715 4716 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4717 const Stmt *S, 4718 const SwitchCase *SC = nullptr); 4719 4720 /// Evaluate the body of a loop, and translate the result as appropriate. 4721 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4722 const Stmt *Body, 4723 const SwitchCase *Case = nullptr) { 4724 BlockScopeRAII Scope(Info); 4725 4726 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4727 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4728 ESR = ESR_Failed; 4729 4730 switch (ESR) { 4731 case ESR_Break: 4732 return ESR_Succeeded; 4733 case ESR_Succeeded: 4734 case ESR_Continue: 4735 return ESR_Continue; 4736 case ESR_Failed: 4737 case ESR_Returned: 4738 case ESR_CaseNotFound: 4739 return ESR; 4740 } 4741 llvm_unreachable("Invalid EvalStmtResult!"); 4742 } 4743 4744 /// Evaluate a switch statement. 4745 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4746 const SwitchStmt *SS) { 4747 BlockScopeRAII Scope(Info); 4748 4749 // Evaluate the switch condition. 4750 APSInt Value; 4751 { 4752 if (const Stmt *Init = SS->getInit()) { 4753 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4754 if (ESR != ESR_Succeeded) { 4755 if (ESR != ESR_Failed && !Scope.destroy()) 4756 ESR = ESR_Failed; 4757 return ESR; 4758 } 4759 } 4760 4761 FullExpressionRAII CondScope(Info); 4762 if (SS->getConditionVariable() && 4763 !EvaluateDecl(Info, SS->getConditionVariable())) 4764 return ESR_Failed; 4765 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4766 return ESR_Failed; 4767 if (!CondScope.destroy()) 4768 return ESR_Failed; 4769 } 4770 4771 // Find the switch case corresponding to the value of the condition. 4772 // FIXME: Cache this lookup. 4773 const SwitchCase *Found = nullptr; 4774 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4775 SC = SC->getNextSwitchCase()) { 4776 if (isa<DefaultStmt>(SC)) { 4777 Found = SC; 4778 continue; 4779 } 4780 4781 const CaseStmt *CS = cast<CaseStmt>(SC); 4782 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4783 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4784 : LHS; 4785 if (LHS <= Value && Value <= RHS) { 4786 Found = SC; 4787 break; 4788 } 4789 } 4790 4791 if (!Found) 4792 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4793 4794 // Search the switch body for the switch case and evaluate it from there. 4795 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4796 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4797 return ESR_Failed; 4798 4799 switch (ESR) { 4800 case ESR_Break: 4801 return ESR_Succeeded; 4802 case ESR_Succeeded: 4803 case ESR_Continue: 4804 case ESR_Failed: 4805 case ESR_Returned: 4806 return ESR; 4807 case ESR_CaseNotFound: 4808 // This can only happen if the switch case is nested within a statement 4809 // expression. We have no intention of supporting that. 4810 Info.FFDiag(Found->getBeginLoc(), 4811 diag::note_constexpr_stmt_expr_unsupported); 4812 return ESR_Failed; 4813 } 4814 llvm_unreachable("Invalid EvalStmtResult!"); 4815 } 4816 4817 // Evaluate a statement. 4818 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4819 const Stmt *S, const SwitchCase *Case) { 4820 if (!Info.nextStep(S)) 4821 return ESR_Failed; 4822 4823 // If we're hunting down a 'case' or 'default' label, recurse through 4824 // substatements until we hit the label. 4825 if (Case) { 4826 switch (S->getStmtClass()) { 4827 case Stmt::CompoundStmtClass: 4828 // FIXME: Precompute which substatement of a compound statement we 4829 // would jump to, and go straight there rather than performing a 4830 // linear scan each time. 4831 case Stmt::LabelStmtClass: 4832 case Stmt::AttributedStmtClass: 4833 case Stmt::DoStmtClass: 4834 break; 4835 4836 case Stmt::CaseStmtClass: 4837 case Stmt::DefaultStmtClass: 4838 if (Case == S) 4839 Case = nullptr; 4840 break; 4841 4842 case Stmt::IfStmtClass: { 4843 // FIXME: Precompute which side of an 'if' we would jump to, and go 4844 // straight there rather than scanning both sides. 4845 const IfStmt *IS = cast<IfStmt>(S); 4846 4847 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4848 // preceded by our switch label. 4849 BlockScopeRAII Scope(Info); 4850 4851 // Step into the init statement in case it brings an (uninitialized) 4852 // variable into scope. 4853 if (const Stmt *Init = IS->getInit()) { 4854 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4855 if (ESR != ESR_CaseNotFound) { 4856 assert(ESR != ESR_Succeeded); 4857 return ESR; 4858 } 4859 } 4860 4861 // Condition variable must be initialized if it exists. 4862 // FIXME: We can skip evaluating the body if there's a condition 4863 // variable, as there can't be any case labels within it. 4864 // (The same is true for 'for' statements.) 4865 4866 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4867 if (ESR == ESR_Failed) 4868 return ESR; 4869 if (ESR != ESR_CaseNotFound) 4870 return Scope.destroy() ? ESR : ESR_Failed; 4871 if (!IS->getElse()) 4872 return ESR_CaseNotFound; 4873 4874 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 4875 if (ESR == ESR_Failed) 4876 return ESR; 4877 if (ESR != ESR_CaseNotFound) 4878 return Scope.destroy() ? ESR : ESR_Failed; 4879 return ESR_CaseNotFound; 4880 } 4881 4882 case Stmt::WhileStmtClass: { 4883 EvalStmtResult ESR = 4884 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4885 if (ESR != ESR_Continue) 4886 return ESR; 4887 break; 4888 } 4889 4890 case Stmt::ForStmtClass: { 4891 const ForStmt *FS = cast<ForStmt>(S); 4892 BlockScopeRAII Scope(Info); 4893 4894 // Step into the init statement in case it brings an (uninitialized) 4895 // variable into scope. 4896 if (const Stmt *Init = FS->getInit()) { 4897 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4898 if (ESR != ESR_CaseNotFound) { 4899 assert(ESR != ESR_Succeeded); 4900 return ESR; 4901 } 4902 } 4903 4904 EvalStmtResult ESR = 4905 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4906 if (ESR != ESR_Continue) 4907 return ESR; 4908 if (FS->getInc()) { 4909 FullExpressionRAII IncScope(Info); 4910 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 4911 return ESR_Failed; 4912 } 4913 break; 4914 } 4915 4916 case Stmt::DeclStmtClass: { 4917 // Start the lifetime of any uninitialized variables we encounter. They 4918 // might be used by the selected branch of the switch. 4919 const DeclStmt *DS = cast<DeclStmt>(S); 4920 for (const auto *D : DS->decls()) { 4921 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4922 if (VD->hasLocalStorage() && !VD->getInit()) 4923 if (!EvaluateVarDecl(Info, VD)) 4924 return ESR_Failed; 4925 // FIXME: If the variable has initialization that can't be jumped 4926 // over, bail out of any immediately-surrounding compound-statement 4927 // too. There can't be any case labels here. 4928 } 4929 } 4930 return ESR_CaseNotFound; 4931 } 4932 4933 default: 4934 return ESR_CaseNotFound; 4935 } 4936 } 4937 4938 switch (S->getStmtClass()) { 4939 default: 4940 if (const Expr *E = dyn_cast<Expr>(S)) { 4941 // Don't bother evaluating beyond an expression-statement which couldn't 4942 // be evaluated. 4943 // FIXME: Do we need the FullExpressionRAII object here? 4944 // VisitExprWithCleanups should create one when necessary. 4945 FullExpressionRAII Scope(Info); 4946 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 4947 return ESR_Failed; 4948 return ESR_Succeeded; 4949 } 4950 4951 Info.FFDiag(S->getBeginLoc()); 4952 return ESR_Failed; 4953 4954 case Stmt::NullStmtClass: 4955 return ESR_Succeeded; 4956 4957 case Stmt::DeclStmtClass: { 4958 const DeclStmt *DS = cast<DeclStmt>(S); 4959 for (const auto *D : DS->decls()) { 4960 // Each declaration initialization is its own full-expression. 4961 FullExpressionRAII Scope(Info); 4962 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 4963 return ESR_Failed; 4964 if (!Scope.destroy()) 4965 return ESR_Failed; 4966 } 4967 return ESR_Succeeded; 4968 } 4969 4970 case Stmt::ReturnStmtClass: { 4971 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4972 FullExpressionRAII Scope(Info); 4973 if (RetExpr && 4974 !(Result.Slot 4975 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4976 : Evaluate(Result.Value, Info, RetExpr))) 4977 return ESR_Failed; 4978 return Scope.destroy() ? ESR_Returned : ESR_Failed; 4979 } 4980 4981 case Stmt::CompoundStmtClass: { 4982 BlockScopeRAII Scope(Info); 4983 4984 const CompoundStmt *CS = cast<CompoundStmt>(S); 4985 for (const auto *BI : CS->body()) { 4986 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4987 if (ESR == ESR_Succeeded) 4988 Case = nullptr; 4989 else if (ESR != ESR_CaseNotFound) { 4990 if (ESR != ESR_Failed && !Scope.destroy()) 4991 return ESR_Failed; 4992 return ESR; 4993 } 4994 } 4995 if (Case) 4996 return ESR_CaseNotFound; 4997 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4998 } 4999 5000 case Stmt::IfStmtClass: { 5001 const IfStmt *IS = cast<IfStmt>(S); 5002 5003 // Evaluate the condition, as either a var decl or as an expression. 5004 BlockScopeRAII Scope(Info); 5005 if (const Stmt *Init = IS->getInit()) { 5006 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5007 if (ESR != ESR_Succeeded) { 5008 if (ESR != ESR_Failed && !Scope.destroy()) 5009 return ESR_Failed; 5010 return ESR; 5011 } 5012 } 5013 bool Cond; 5014 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 5015 return ESR_Failed; 5016 5017 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5018 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5019 if (ESR != ESR_Succeeded) { 5020 if (ESR != ESR_Failed && !Scope.destroy()) 5021 return ESR_Failed; 5022 return ESR; 5023 } 5024 } 5025 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5026 } 5027 5028 case Stmt::WhileStmtClass: { 5029 const WhileStmt *WS = cast<WhileStmt>(S); 5030 while (true) { 5031 BlockScopeRAII Scope(Info); 5032 bool Continue; 5033 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5034 Continue)) 5035 return ESR_Failed; 5036 if (!Continue) 5037 break; 5038 5039 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5040 if (ESR != ESR_Continue) { 5041 if (ESR != ESR_Failed && !Scope.destroy()) 5042 return ESR_Failed; 5043 return ESR; 5044 } 5045 if (!Scope.destroy()) 5046 return ESR_Failed; 5047 } 5048 return ESR_Succeeded; 5049 } 5050 5051 case Stmt::DoStmtClass: { 5052 const DoStmt *DS = cast<DoStmt>(S); 5053 bool Continue; 5054 do { 5055 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5056 if (ESR != ESR_Continue) 5057 return ESR; 5058 Case = nullptr; 5059 5060 FullExpressionRAII CondScope(Info); 5061 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5062 !CondScope.destroy()) 5063 return ESR_Failed; 5064 } while (Continue); 5065 return ESR_Succeeded; 5066 } 5067 5068 case Stmt::ForStmtClass: { 5069 const ForStmt *FS = cast<ForStmt>(S); 5070 BlockScopeRAII ForScope(Info); 5071 if (FS->getInit()) { 5072 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5073 if (ESR != ESR_Succeeded) { 5074 if (ESR != ESR_Failed && !ForScope.destroy()) 5075 return ESR_Failed; 5076 return ESR; 5077 } 5078 } 5079 while (true) { 5080 BlockScopeRAII IterScope(Info); 5081 bool Continue = true; 5082 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5083 FS->getCond(), Continue)) 5084 return ESR_Failed; 5085 if (!Continue) 5086 break; 5087 5088 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5089 if (ESR != ESR_Continue) { 5090 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5091 return ESR_Failed; 5092 return ESR; 5093 } 5094 5095 if (FS->getInc()) { 5096 FullExpressionRAII IncScope(Info); 5097 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 5098 return ESR_Failed; 5099 } 5100 5101 if (!IterScope.destroy()) 5102 return ESR_Failed; 5103 } 5104 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5105 } 5106 5107 case Stmt::CXXForRangeStmtClass: { 5108 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5109 BlockScopeRAII Scope(Info); 5110 5111 // Evaluate the init-statement if present. 5112 if (FS->getInit()) { 5113 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5114 if (ESR != ESR_Succeeded) { 5115 if (ESR != ESR_Failed && !Scope.destroy()) 5116 return ESR_Failed; 5117 return ESR; 5118 } 5119 } 5120 5121 // Initialize the __range variable. 5122 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5123 if (ESR != ESR_Succeeded) { 5124 if (ESR != ESR_Failed && !Scope.destroy()) 5125 return ESR_Failed; 5126 return ESR; 5127 } 5128 5129 // Create the __begin and __end iterators. 5130 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5131 if (ESR != ESR_Succeeded) { 5132 if (ESR != ESR_Failed && !Scope.destroy()) 5133 return ESR_Failed; 5134 return ESR; 5135 } 5136 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5137 if (ESR != ESR_Succeeded) { 5138 if (ESR != ESR_Failed && !Scope.destroy()) 5139 return ESR_Failed; 5140 return ESR; 5141 } 5142 5143 while (true) { 5144 // Condition: __begin != __end. 5145 { 5146 bool Continue = true; 5147 FullExpressionRAII CondExpr(Info); 5148 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5149 return ESR_Failed; 5150 if (!Continue) 5151 break; 5152 } 5153 5154 // User's variable declaration, initialized by *__begin. 5155 BlockScopeRAII InnerScope(Info); 5156 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5157 if (ESR != ESR_Succeeded) { 5158 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5159 return ESR_Failed; 5160 return ESR; 5161 } 5162 5163 // Loop body. 5164 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5165 if (ESR != ESR_Continue) { 5166 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5167 return ESR_Failed; 5168 return ESR; 5169 } 5170 5171 // Increment: ++__begin 5172 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5173 return ESR_Failed; 5174 5175 if (!InnerScope.destroy()) 5176 return ESR_Failed; 5177 } 5178 5179 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5180 } 5181 5182 case Stmt::SwitchStmtClass: 5183 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5184 5185 case Stmt::ContinueStmtClass: 5186 return ESR_Continue; 5187 5188 case Stmt::BreakStmtClass: 5189 return ESR_Break; 5190 5191 case Stmt::LabelStmtClass: 5192 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5193 5194 case Stmt::AttributedStmtClass: 5195 // As a general principle, C++11 attributes can be ignored without 5196 // any semantic impact. 5197 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5198 Case); 5199 5200 case Stmt::CaseStmtClass: 5201 case Stmt::DefaultStmtClass: 5202 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5203 case Stmt::CXXTryStmtClass: 5204 // Evaluate try blocks by evaluating all sub statements. 5205 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5206 } 5207 } 5208 5209 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5210 /// default constructor. If so, we'll fold it whether or not it's marked as 5211 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5212 /// so we need special handling. 5213 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5214 const CXXConstructorDecl *CD, 5215 bool IsValueInitialization) { 5216 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5217 return false; 5218 5219 // Value-initialization does not call a trivial default constructor, so such a 5220 // call is a core constant expression whether or not the constructor is 5221 // constexpr. 5222 if (!CD->isConstexpr() && !IsValueInitialization) { 5223 if (Info.getLangOpts().CPlusPlus11) { 5224 // FIXME: If DiagDecl is an implicitly-declared special member function, 5225 // we should be much more explicit about why it's not constexpr. 5226 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5227 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5228 Info.Note(CD->getLocation(), diag::note_declared_at); 5229 } else { 5230 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5231 } 5232 } 5233 return true; 5234 } 5235 5236 /// CheckConstexprFunction - Check that a function can be called in a constant 5237 /// expression. 5238 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5239 const FunctionDecl *Declaration, 5240 const FunctionDecl *Definition, 5241 const Stmt *Body) { 5242 // Potential constant expressions can contain calls to declared, but not yet 5243 // defined, constexpr functions. 5244 if (Info.checkingPotentialConstantExpression() && !Definition && 5245 Declaration->isConstexpr()) 5246 return false; 5247 5248 // Bail out if the function declaration itself is invalid. We will 5249 // have produced a relevant diagnostic while parsing it, so just 5250 // note the problematic sub-expression. 5251 if (Declaration->isInvalidDecl()) { 5252 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5253 return false; 5254 } 5255 5256 // DR1872: An instantiated virtual constexpr function can't be called in a 5257 // constant expression (prior to C++20). We can still constant-fold such a 5258 // call. 5259 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5260 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5261 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5262 5263 if (Definition && Definition->isInvalidDecl()) { 5264 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5265 return false; 5266 } 5267 5268 if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) { 5269 for (const auto *InitExpr : CtorDecl->inits()) { 5270 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 5271 return false; 5272 } 5273 } 5274 5275 // Can we evaluate this function call? 5276 if (Definition && Definition->isConstexpr() && Body) 5277 return true; 5278 5279 if (Info.getLangOpts().CPlusPlus11) { 5280 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5281 5282 // If this function is not constexpr because it is an inherited 5283 // non-constexpr constructor, diagnose that directly. 5284 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5285 if (CD && CD->isInheritingConstructor()) { 5286 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5287 if (!Inherited->isConstexpr()) 5288 DiagDecl = CD = Inherited; 5289 } 5290 5291 // FIXME: If DiagDecl is an implicitly-declared special member function 5292 // or an inheriting constructor, we should be much more explicit about why 5293 // it's not constexpr. 5294 if (CD && CD->isInheritingConstructor()) 5295 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5296 << CD->getInheritedConstructor().getConstructor()->getParent(); 5297 else 5298 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5299 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5300 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5301 } else { 5302 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5303 } 5304 return false; 5305 } 5306 5307 namespace { 5308 struct CheckDynamicTypeHandler { 5309 AccessKinds AccessKind; 5310 typedef bool result_type; 5311 bool failed() { return false; } 5312 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5313 bool found(APSInt &Value, QualType SubobjType) { return true; } 5314 bool found(APFloat &Value, QualType SubobjType) { return true; } 5315 }; 5316 } // end anonymous namespace 5317 5318 /// Check that we can access the notional vptr of an object / determine its 5319 /// dynamic type. 5320 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5321 AccessKinds AK, bool Polymorphic) { 5322 if (This.Designator.Invalid) 5323 return false; 5324 5325 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5326 5327 if (!Obj) 5328 return false; 5329 5330 if (!Obj.Value) { 5331 // The object is not usable in constant expressions, so we can't inspect 5332 // its value to see if it's in-lifetime or what the active union members 5333 // are. We can still check for a one-past-the-end lvalue. 5334 if (This.Designator.isOnePastTheEnd() || 5335 This.Designator.isMostDerivedAnUnsizedArray()) { 5336 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5337 ? diag::note_constexpr_access_past_end 5338 : diag::note_constexpr_access_unsized_array) 5339 << AK; 5340 return false; 5341 } else if (Polymorphic) { 5342 // Conservatively refuse to perform a polymorphic operation if we would 5343 // not be able to read a notional 'vptr' value. 5344 APValue Val; 5345 This.moveInto(Val); 5346 QualType StarThisType = 5347 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5348 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5349 << AK << Val.getAsString(Info.Ctx, StarThisType); 5350 return false; 5351 } 5352 return true; 5353 } 5354 5355 CheckDynamicTypeHandler Handler{AK}; 5356 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5357 } 5358 5359 /// Check that the pointee of the 'this' pointer in a member function call is 5360 /// either within its lifetime or in its period of construction or destruction. 5361 static bool 5362 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5363 const LValue &This, 5364 const CXXMethodDecl *NamedMember) { 5365 return checkDynamicType( 5366 Info, E, This, 5367 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5368 } 5369 5370 struct DynamicType { 5371 /// The dynamic class type of the object. 5372 const CXXRecordDecl *Type; 5373 /// The corresponding path length in the lvalue. 5374 unsigned PathLength; 5375 }; 5376 5377 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5378 unsigned PathLength) { 5379 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5380 Designator.Entries.size() && "invalid path length"); 5381 return (PathLength == Designator.MostDerivedPathLength) 5382 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5383 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5384 } 5385 5386 /// Determine the dynamic type of an object. 5387 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5388 LValue &This, AccessKinds AK) { 5389 // If we don't have an lvalue denoting an object of class type, there is no 5390 // meaningful dynamic type. (We consider objects of non-class type to have no 5391 // dynamic type.) 5392 if (!checkDynamicType(Info, E, This, AK, true)) 5393 return None; 5394 5395 // Refuse to compute a dynamic type in the presence of virtual bases. This 5396 // shouldn't happen other than in constant-folding situations, since literal 5397 // types can't have virtual bases. 5398 // 5399 // Note that consumers of DynamicType assume that the type has no virtual 5400 // bases, and will need modifications if this restriction is relaxed. 5401 const CXXRecordDecl *Class = 5402 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5403 if (!Class || Class->getNumVBases()) { 5404 Info.FFDiag(E); 5405 return None; 5406 } 5407 5408 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5409 // binary search here instead. But the overwhelmingly common case is that 5410 // we're not in the middle of a constructor, so it probably doesn't matter 5411 // in practice. 5412 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5413 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5414 PathLength <= Path.size(); ++PathLength) { 5415 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5416 Path.slice(0, PathLength))) { 5417 case ConstructionPhase::Bases: 5418 case ConstructionPhase::DestroyingBases: 5419 // We're constructing or destroying a base class. This is not the dynamic 5420 // type. 5421 break; 5422 5423 case ConstructionPhase::None: 5424 case ConstructionPhase::AfterBases: 5425 case ConstructionPhase::AfterFields: 5426 case ConstructionPhase::Destroying: 5427 // We've finished constructing the base classes and not yet started 5428 // destroying them again, so this is the dynamic type. 5429 return DynamicType{getBaseClassType(This.Designator, PathLength), 5430 PathLength}; 5431 } 5432 } 5433 5434 // CWG issue 1517: we're constructing a base class of the object described by 5435 // 'This', so that object has not yet begun its period of construction and 5436 // any polymorphic operation on it results in undefined behavior. 5437 Info.FFDiag(E); 5438 return None; 5439 } 5440 5441 /// Perform virtual dispatch. 5442 static const CXXMethodDecl *HandleVirtualDispatch( 5443 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5444 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5445 Optional<DynamicType> DynType = ComputeDynamicType( 5446 Info, E, This, 5447 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5448 if (!DynType) 5449 return nullptr; 5450 5451 // Find the final overrider. It must be declared in one of the classes on the 5452 // path from the dynamic type to the static type. 5453 // FIXME: If we ever allow literal types to have virtual base classes, that 5454 // won't be true. 5455 const CXXMethodDecl *Callee = Found; 5456 unsigned PathLength = DynType->PathLength; 5457 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5458 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5459 const CXXMethodDecl *Overrider = 5460 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5461 if (Overrider) { 5462 Callee = Overrider; 5463 break; 5464 } 5465 } 5466 5467 // C++2a [class.abstract]p6: 5468 // the effect of making a virtual call to a pure virtual function [...] is 5469 // undefined 5470 if (Callee->isPure()) { 5471 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5472 Info.Note(Callee->getLocation(), diag::note_declared_at); 5473 return nullptr; 5474 } 5475 5476 // If necessary, walk the rest of the path to determine the sequence of 5477 // covariant adjustment steps to apply. 5478 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5479 Found->getReturnType())) { 5480 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5481 for (unsigned CovariantPathLength = PathLength + 1; 5482 CovariantPathLength != This.Designator.Entries.size(); 5483 ++CovariantPathLength) { 5484 const CXXRecordDecl *NextClass = 5485 getBaseClassType(This.Designator, CovariantPathLength); 5486 const CXXMethodDecl *Next = 5487 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5488 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5489 Next->getReturnType(), CovariantAdjustmentPath.back())) 5490 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5491 } 5492 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5493 CovariantAdjustmentPath.back())) 5494 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5495 } 5496 5497 // Perform 'this' adjustment. 5498 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5499 return nullptr; 5500 5501 return Callee; 5502 } 5503 5504 /// Perform the adjustment from a value returned by a virtual function to 5505 /// a value of the statically expected type, which may be a pointer or 5506 /// reference to a base class of the returned type. 5507 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5508 APValue &Result, 5509 ArrayRef<QualType> Path) { 5510 assert(Result.isLValue() && 5511 "unexpected kind of APValue for covariant return"); 5512 if (Result.isNullPointer()) 5513 return true; 5514 5515 LValue LVal; 5516 LVal.setFrom(Info.Ctx, Result); 5517 5518 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5519 for (unsigned I = 1; I != Path.size(); ++I) { 5520 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5521 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5522 if (OldClass != NewClass && 5523 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5524 return false; 5525 OldClass = NewClass; 5526 } 5527 5528 LVal.moveInto(Result); 5529 return true; 5530 } 5531 5532 /// Determine whether \p Base, which is known to be a direct base class of 5533 /// \p Derived, is a public base class. 5534 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5535 const CXXRecordDecl *Base) { 5536 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5537 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5538 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5539 return BaseSpec.getAccessSpecifier() == AS_public; 5540 } 5541 llvm_unreachable("Base is not a direct base of Derived"); 5542 } 5543 5544 /// Apply the given dynamic cast operation on the provided lvalue. 5545 /// 5546 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5547 /// to find a suitable target subobject. 5548 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5549 LValue &Ptr) { 5550 // We can't do anything with a non-symbolic pointer value. 5551 SubobjectDesignator &D = Ptr.Designator; 5552 if (D.Invalid) 5553 return false; 5554 5555 // C++ [expr.dynamic.cast]p6: 5556 // If v is a null pointer value, the result is a null pointer value. 5557 if (Ptr.isNullPointer() && !E->isGLValue()) 5558 return true; 5559 5560 // For all the other cases, we need the pointer to point to an object within 5561 // its lifetime / period of construction / destruction, and we need to know 5562 // its dynamic type. 5563 Optional<DynamicType> DynType = 5564 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5565 if (!DynType) 5566 return false; 5567 5568 // C++ [expr.dynamic.cast]p7: 5569 // If T is "pointer to cv void", then the result is a pointer to the most 5570 // derived object 5571 if (E->getType()->isVoidPointerType()) 5572 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5573 5574 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5575 assert(C && "dynamic_cast target is not void pointer nor class"); 5576 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5577 5578 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5579 // C++ [expr.dynamic.cast]p9: 5580 if (!E->isGLValue()) { 5581 // The value of a failed cast to pointer type is the null pointer value 5582 // of the required result type. 5583 Ptr.setNull(Info.Ctx, E->getType()); 5584 return true; 5585 } 5586 5587 // A failed cast to reference type throws [...] std::bad_cast. 5588 unsigned DiagKind; 5589 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5590 DynType->Type->isDerivedFrom(C))) 5591 DiagKind = 0; 5592 else if (!Paths || Paths->begin() == Paths->end()) 5593 DiagKind = 1; 5594 else if (Paths->isAmbiguous(CQT)) 5595 DiagKind = 2; 5596 else { 5597 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5598 DiagKind = 3; 5599 } 5600 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5601 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5602 << Info.Ctx.getRecordType(DynType->Type) 5603 << E->getType().getUnqualifiedType(); 5604 return false; 5605 }; 5606 5607 // Runtime check, phase 1: 5608 // Walk from the base subobject towards the derived object looking for the 5609 // target type. 5610 for (int PathLength = Ptr.Designator.Entries.size(); 5611 PathLength >= (int)DynType->PathLength; --PathLength) { 5612 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5613 if (declaresSameEntity(Class, C)) 5614 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5615 // We can only walk across public inheritance edges. 5616 if (PathLength > (int)DynType->PathLength && 5617 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5618 Class)) 5619 return RuntimeCheckFailed(nullptr); 5620 } 5621 5622 // Runtime check, phase 2: 5623 // Search the dynamic type for an unambiguous public base of type C. 5624 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5625 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5626 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5627 Paths.front().Access == AS_public) { 5628 // Downcast to the dynamic type... 5629 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5630 return false; 5631 // ... then upcast to the chosen base class subobject. 5632 for (CXXBasePathElement &Elem : Paths.front()) 5633 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5634 return false; 5635 return true; 5636 } 5637 5638 // Otherwise, the runtime check fails. 5639 return RuntimeCheckFailed(&Paths); 5640 } 5641 5642 namespace { 5643 struct StartLifetimeOfUnionMemberHandler { 5644 EvalInfo &Info; 5645 const Expr *LHSExpr; 5646 const FieldDecl *Field; 5647 bool DuringInit; 5648 bool Failed = false; 5649 static const AccessKinds AccessKind = AK_Assign; 5650 5651 typedef bool result_type; 5652 bool failed() { return Failed; } 5653 bool found(APValue &Subobj, QualType SubobjType) { 5654 // We are supposed to perform no initialization but begin the lifetime of 5655 // the object. We interpret that as meaning to do what default 5656 // initialization of the object would do if all constructors involved were 5657 // trivial: 5658 // * All base, non-variant member, and array element subobjects' lifetimes 5659 // begin 5660 // * No variant members' lifetimes begin 5661 // * All scalar subobjects whose lifetimes begin have indeterminate values 5662 assert(SubobjType->isUnionType()); 5663 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5664 // This union member is already active. If it's also in-lifetime, there's 5665 // nothing to do. 5666 if (Subobj.getUnionValue().hasValue()) 5667 return true; 5668 } else if (DuringInit) { 5669 // We're currently in the process of initializing a different union 5670 // member. If we carried on, that initialization would attempt to 5671 // store to an inactive union member, resulting in undefined behavior. 5672 Info.FFDiag(LHSExpr, 5673 diag::note_constexpr_union_member_change_during_init); 5674 return false; 5675 } 5676 APValue Result; 5677 Failed = !getDefaultInitValue(Field->getType(), Result); 5678 Subobj.setUnion(Field, Result); 5679 return true; 5680 } 5681 bool found(APSInt &Value, QualType SubobjType) { 5682 llvm_unreachable("wrong value kind for union object"); 5683 } 5684 bool found(APFloat &Value, QualType SubobjType) { 5685 llvm_unreachable("wrong value kind for union object"); 5686 } 5687 }; 5688 } // end anonymous namespace 5689 5690 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5691 5692 /// Handle a builtin simple-assignment or a call to a trivial assignment 5693 /// operator whose left-hand side might involve a union member access. If it 5694 /// does, implicitly start the lifetime of any accessed union elements per 5695 /// C++20 [class.union]5. 5696 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5697 const LValue &LHS) { 5698 if (LHS.InvalidBase || LHS.Designator.Invalid) 5699 return false; 5700 5701 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5702 // C++ [class.union]p5: 5703 // define the set S(E) of subexpressions of E as follows: 5704 unsigned PathLength = LHS.Designator.Entries.size(); 5705 for (const Expr *E = LHSExpr; E != nullptr;) { 5706 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5707 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5708 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5709 // Note that we can't implicitly start the lifetime of a reference, 5710 // so we don't need to proceed any further if we reach one. 5711 if (!FD || FD->getType()->isReferenceType()) 5712 break; 5713 5714 // ... and also contains A.B if B names a union member ... 5715 if (FD->getParent()->isUnion()) { 5716 // ... of a non-class, non-array type, or of a class type with a 5717 // trivial default constructor that is not deleted, or an array of 5718 // such types. 5719 auto *RD = 5720 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5721 if (!RD || RD->hasTrivialDefaultConstructor()) 5722 UnionPathLengths.push_back({PathLength - 1, FD}); 5723 } 5724 5725 E = ME->getBase(); 5726 --PathLength; 5727 assert(declaresSameEntity(FD, 5728 LHS.Designator.Entries[PathLength] 5729 .getAsBaseOrMember().getPointer())); 5730 5731 // -- If E is of the form A[B] and is interpreted as a built-in array 5732 // subscripting operator, S(E) is [S(the array operand, if any)]. 5733 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5734 // Step over an ArrayToPointerDecay implicit cast. 5735 auto *Base = ASE->getBase()->IgnoreImplicit(); 5736 if (!Base->getType()->isArrayType()) 5737 break; 5738 5739 E = Base; 5740 --PathLength; 5741 5742 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5743 // Step over a derived-to-base conversion. 5744 E = ICE->getSubExpr(); 5745 if (ICE->getCastKind() == CK_NoOp) 5746 continue; 5747 if (ICE->getCastKind() != CK_DerivedToBase && 5748 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5749 break; 5750 // Walk path backwards as we walk up from the base to the derived class. 5751 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5752 --PathLength; 5753 (void)Elt; 5754 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5755 LHS.Designator.Entries[PathLength] 5756 .getAsBaseOrMember().getPointer())); 5757 } 5758 5759 // -- Otherwise, S(E) is empty. 5760 } else { 5761 break; 5762 } 5763 } 5764 5765 // Common case: no unions' lifetimes are started. 5766 if (UnionPathLengths.empty()) 5767 return true; 5768 5769 // if modification of X [would access an inactive union member], an object 5770 // of the type of X is implicitly created 5771 CompleteObject Obj = 5772 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5773 if (!Obj) 5774 return false; 5775 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5776 llvm::reverse(UnionPathLengths)) { 5777 // Form a designator for the union object. 5778 SubobjectDesignator D = LHS.Designator; 5779 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5780 5781 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5782 ConstructionPhase::AfterBases; 5783 StartLifetimeOfUnionMemberHandler StartLifetime{ 5784 Info, LHSExpr, LengthAndField.second, DuringInit}; 5785 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5786 return false; 5787 } 5788 5789 return true; 5790 } 5791 5792 namespace { 5793 typedef SmallVector<APValue, 8> ArgVector; 5794 } 5795 5796 /// EvaluateArgs - Evaluate the arguments to a function call. 5797 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues, 5798 EvalInfo &Info, const FunctionDecl *Callee) { 5799 ArgValues.resize(Args.size()); 5800 5801 bool Success = true; 5802 llvm::SmallBitVector ForbiddenNullArgs; 5803 if (Callee->hasAttr<NonNullAttr>()) { 5804 ForbiddenNullArgs.resize(Args.size()); 5805 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 5806 if (!Attr->args_size()) { 5807 ForbiddenNullArgs.set(); 5808 break; 5809 } else 5810 for (auto Idx : Attr->args()) { 5811 unsigned ASTIdx = Idx.getASTIndex(); 5812 if (ASTIdx >= Args.size()) 5813 continue; 5814 ForbiddenNullArgs[ASTIdx] = 1; 5815 } 5816 } 5817 } 5818 for (unsigned Idx = 0; Idx < Args.size(); Idx++) { 5819 if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) { 5820 // If we're checking for a potential constant expression, evaluate all 5821 // initializers even if some of them fail. 5822 if (!Info.noteFailure()) 5823 return false; 5824 Success = false; 5825 } else if (!ForbiddenNullArgs.empty() && 5826 ForbiddenNullArgs[Idx] && 5827 ArgValues[Idx].isLValue() && 5828 ArgValues[Idx].isNullPointer()) { 5829 Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed); 5830 if (!Info.noteFailure()) 5831 return false; 5832 Success = false; 5833 } 5834 } 5835 return Success; 5836 } 5837 5838 /// Evaluate a function call. 5839 static bool HandleFunctionCall(SourceLocation CallLoc, 5840 const FunctionDecl *Callee, const LValue *This, 5841 ArrayRef<const Expr *> Args, APValue *ArgValues, 5842 const Stmt *Body, EvalInfo &Info, 5843 APValue &Result, const LValue *ResultSlot) { 5844 if (!Info.CheckCallLimit(CallLoc)) 5845 return false; 5846 5847 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues); 5848 5849 // For a trivial copy or move assignment, perform an APValue copy. This is 5850 // essential for unions, where the operations performed by the assignment 5851 // operator cannot be represented as statements. 5852 // 5853 // Skip this for non-union classes with no fields; in that case, the defaulted 5854 // copy/move does not actually read the object. 5855 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 5856 if (MD && MD->isDefaulted() && 5857 (MD->getParent()->isUnion() || 5858 (MD->isTrivial() && 5859 isReadByLvalueToRvalueConversion(MD->getParent())))) { 5860 assert(This && 5861 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 5862 LValue RHS; 5863 RHS.setFrom(Info.Ctx, ArgValues[0]); 5864 APValue RHSValue; 5865 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS, 5866 RHSValue, MD->getParent()->isUnion())) 5867 return false; 5868 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 5869 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 5870 return false; 5871 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 5872 RHSValue)) 5873 return false; 5874 This->moveInto(Result); 5875 return true; 5876 } else if (MD && isLambdaCallOperator(MD)) { 5877 // We're in a lambda; determine the lambda capture field maps unless we're 5878 // just constexpr checking a lambda's call operator. constexpr checking is 5879 // done before the captures have been added to the closure object (unless 5880 // we're inferring constexpr-ness), so we don't have access to them in this 5881 // case. But since we don't need the captures to constexpr check, we can 5882 // just ignore them. 5883 if (!Info.checkingPotentialConstantExpression()) 5884 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 5885 Frame.LambdaThisCaptureField); 5886 } 5887 5888 StmtResult Ret = {Result, ResultSlot}; 5889 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 5890 if (ESR == ESR_Succeeded) { 5891 if (Callee->getReturnType()->isVoidType()) 5892 return true; 5893 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 5894 } 5895 return ESR == ESR_Returned; 5896 } 5897 5898 /// Evaluate a constructor call. 5899 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5900 APValue *ArgValues, 5901 const CXXConstructorDecl *Definition, 5902 EvalInfo &Info, APValue &Result) { 5903 SourceLocation CallLoc = E->getExprLoc(); 5904 if (!Info.CheckCallLimit(CallLoc)) 5905 return false; 5906 5907 const CXXRecordDecl *RD = Definition->getParent(); 5908 if (RD->getNumVBases()) { 5909 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 5910 return false; 5911 } 5912 5913 EvalInfo::EvaluatingConstructorRAII EvalObj( 5914 Info, 5915 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 5916 RD->getNumBases()); 5917 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 5918 5919 // FIXME: Creating an APValue just to hold a nonexistent return value is 5920 // wasteful. 5921 APValue RetVal; 5922 StmtResult Ret = {RetVal, nullptr}; 5923 5924 // If it's a delegating constructor, delegate. 5925 if (Definition->isDelegatingConstructor()) { 5926 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 5927 { 5928 FullExpressionRAII InitScope(Info); 5929 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 5930 !InitScope.destroy()) 5931 return false; 5932 } 5933 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5934 } 5935 5936 // For a trivial copy or move constructor, perform an APValue copy. This is 5937 // essential for unions (or classes with anonymous union members), where the 5938 // operations performed by the constructor cannot be represented by 5939 // ctor-initializers. 5940 // 5941 // Skip this for empty non-union classes; we should not perform an 5942 // lvalue-to-rvalue conversion on them because their copy constructor does not 5943 // actually read them. 5944 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 5945 (Definition->getParent()->isUnion() || 5946 (Definition->isTrivial() && 5947 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 5948 LValue RHS; 5949 RHS.setFrom(Info.Ctx, ArgValues[0]); 5950 return handleLValueToRValueConversion( 5951 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 5952 RHS, Result, Definition->getParent()->isUnion()); 5953 } 5954 5955 // Reserve space for the struct members. 5956 if (!Result.hasValue()) { 5957 if (!RD->isUnion()) 5958 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 5959 std::distance(RD->field_begin(), RD->field_end())); 5960 else 5961 // A union starts with no active member. 5962 Result = APValue((const FieldDecl*)nullptr); 5963 } 5964 5965 if (RD->isInvalidDecl()) return false; 5966 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5967 5968 // A scope for temporaries lifetime-extended by reference members. 5969 BlockScopeRAII LifetimeExtendedScope(Info); 5970 5971 bool Success = true; 5972 unsigned BasesSeen = 0; 5973 #ifndef NDEBUG 5974 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 5975 #endif 5976 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 5977 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 5978 // We might be initializing the same field again if this is an indirect 5979 // field initialization. 5980 if (FieldIt == RD->field_end() || 5981 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 5982 assert(Indirect && "fields out of order?"); 5983 return; 5984 } 5985 5986 // Default-initialize any fields with no explicit initializer. 5987 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 5988 assert(FieldIt != RD->field_end() && "missing field?"); 5989 if (!FieldIt->isUnnamedBitfield()) 5990 Success &= getDefaultInitValue( 5991 FieldIt->getType(), 5992 Result.getStructField(FieldIt->getFieldIndex())); 5993 } 5994 ++FieldIt; 5995 }; 5996 for (const auto *I : Definition->inits()) { 5997 LValue Subobject = This; 5998 LValue SubobjectParent = This; 5999 APValue *Value = &Result; 6000 6001 // Determine the subobject to initialize. 6002 FieldDecl *FD = nullptr; 6003 if (I->isBaseInitializer()) { 6004 QualType BaseType(I->getBaseClass(), 0); 6005 #ifndef NDEBUG 6006 // Non-virtual base classes are initialized in the order in the class 6007 // definition. We have already checked for virtual base classes. 6008 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6009 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6010 "base class initializers not in expected order"); 6011 ++BaseIt; 6012 #endif 6013 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6014 BaseType->getAsCXXRecordDecl(), &Layout)) 6015 return false; 6016 Value = &Result.getStructBase(BasesSeen++); 6017 } else if ((FD = I->getMember())) { 6018 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6019 return false; 6020 if (RD->isUnion()) { 6021 Result = APValue(FD); 6022 Value = &Result.getUnionValue(); 6023 } else { 6024 SkipToField(FD, false); 6025 Value = &Result.getStructField(FD->getFieldIndex()); 6026 } 6027 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6028 // Walk the indirect field decl's chain to find the object to initialize, 6029 // and make sure we've initialized every step along it. 6030 auto IndirectFieldChain = IFD->chain(); 6031 for (auto *C : IndirectFieldChain) { 6032 FD = cast<FieldDecl>(C); 6033 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6034 // Switch the union field if it differs. This happens if we had 6035 // preceding zero-initialization, and we're now initializing a union 6036 // subobject other than the first. 6037 // FIXME: In this case, the values of the other subobjects are 6038 // specified, since zero-initialization sets all padding bits to zero. 6039 if (!Value->hasValue() || 6040 (Value->isUnion() && Value->getUnionField() != FD)) { 6041 if (CD->isUnion()) 6042 *Value = APValue(FD); 6043 else 6044 // FIXME: This immediately starts the lifetime of all members of 6045 // an anonymous struct. It would be preferable to strictly start 6046 // member lifetime in initialization order. 6047 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6048 } 6049 // Store Subobject as its parent before updating it for the last element 6050 // in the chain. 6051 if (C == IndirectFieldChain.back()) 6052 SubobjectParent = Subobject; 6053 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6054 return false; 6055 if (CD->isUnion()) 6056 Value = &Value->getUnionValue(); 6057 else { 6058 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6059 SkipToField(FD, true); 6060 Value = &Value->getStructField(FD->getFieldIndex()); 6061 } 6062 } 6063 } else { 6064 llvm_unreachable("unknown base initializer kind"); 6065 } 6066 6067 // Need to override This for implicit field initializers as in this case 6068 // This refers to innermost anonymous struct/union containing initializer, 6069 // not to currently constructed class. 6070 const Expr *Init = I->getInit(); 6071 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6072 isa<CXXDefaultInitExpr>(Init)); 6073 FullExpressionRAII InitScope(Info); 6074 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6075 (FD && FD->isBitField() && 6076 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6077 // If we're checking for a potential constant expression, evaluate all 6078 // initializers even if some of them fail. 6079 if (!Info.noteFailure()) 6080 return false; 6081 Success = false; 6082 } 6083 6084 // This is the point at which the dynamic type of the object becomes this 6085 // class type. 6086 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6087 EvalObj.finishedConstructingBases(); 6088 } 6089 6090 // Default-initialize any remaining fields. 6091 if (!RD->isUnion()) { 6092 for (; FieldIt != RD->field_end(); ++FieldIt) { 6093 if (!FieldIt->isUnnamedBitfield()) 6094 Success &= getDefaultInitValue( 6095 FieldIt->getType(), 6096 Result.getStructField(FieldIt->getFieldIndex())); 6097 } 6098 } 6099 6100 EvalObj.finishedConstructingFields(); 6101 6102 return Success && 6103 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6104 LifetimeExtendedScope.destroy(); 6105 } 6106 6107 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6108 ArrayRef<const Expr*> Args, 6109 const CXXConstructorDecl *Definition, 6110 EvalInfo &Info, APValue &Result) { 6111 ArgVector ArgValues(Args.size()); 6112 if (!EvaluateArgs(Args, ArgValues, Info, Definition)) 6113 return false; 6114 6115 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 6116 Info, Result); 6117 } 6118 6119 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6120 const LValue &This, APValue &Value, 6121 QualType T) { 6122 // Objects can only be destroyed while they're within their lifetimes. 6123 // FIXME: We have no representation for whether an object of type nullptr_t 6124 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6125 // as indeterminate instead? 6126 if (Value.isAbsent() && !T->isNullPtrType()) { 6127 APValue Printable; 6128 This.moveInto(Printable); 6129 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6130 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6131 return false; 6132 } 6133 6134 // Invent an expression for location purposes. 6135 // FIXME: We shouldn't need to do this. 6136 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 6137 6138 // For arrays, destroy elements right-to-left. 6139 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6140 uint64_t Size = CAT->getSize().getZExtValue(); 6141 QualType ElemT = CAT->getElementType(); 6142 6143 LValue ElemLV = This; 6144 ElemLV.addArray(Info, &LocE, CAT); 6145 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6146 return false; 6147 6148 // Ensure that we have actual array elements available to destroy; the 6149 // destructors might mutate the value, so we can't run them on the array 6150 // filler. 6151 if (Size && Size > Value.getArrayInitializedElts()) 6152 expandArray(Value, Value.getArraySize() - 1); 6153 6154 for (; Size != 0; --Size) { 6155 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6156 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6157 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6158 return false; 6159 } 6160 6161 // End the lifetime of this array now. 6162 Value = APValue(); 6163 return true; 6164 } 6165 6166 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6167 if (!RD) { 6168 if (T.isDestructedType()) { 6169 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6170 return false; 6171 } 6172 6173 Value = APValue(); 6174 return true; 6175 } 6176 6177 if (RD->getNumVBases()) { 6178 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6179 return false; 6180 } 6181 6182 const CXXDestructorDecl *DD = RD->getDestructor(); 6183 if (!DD && !RD->hasTrivialDestructor()) { 6184 Info.FFDiag(CallLoc); 6185 return false; 6186 } 6187 6188 if (!DD || DD->isTrivial() || 6189 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6190 // A trivial destructor just ends the lifetime of the object. Check for 6191 // this case before checking for a body, because we might not bother 6192 // building a body for a trivial destructor. Note that it doesn't matter 6193 // whether the destructor is constexpr in this case; all trivial 6194 // destructors are constexpr. 6195 // 6196 // If an anonymous union would be destroyed, some enclosing destructor must 6197 // have been explicitly defined, and the anonymous union destruction should 6198 // have no effect. 6199 Value = APValue(); 6200 return true; 6201 } 6202 6203 if (!Info.CheckCallLimit(CallLoc)) 6204 return false; 6205 6206 const FunctionDecl *Definition = nullptr; 6207 const Stmt *Body = DD->getBody(Definition); 6208 6209 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6210 return false; 6211 6212 CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr); 6213 6214 // We're now in the period of destruction of this object. 6215 unsigned BasesLeft = RD->getNumBases(); 6216 EvalInfo::EvaluatingDestructorRAII EvalObj( 6217 Info, 6218 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6219 if (!EvalObj.DidInsert) { 6220 // C++2a [class.dtor]p19: 6221 // the behavior is undefined if the destructor is invoked for an object 6222 // whose lifetime has ended 6223 // (Note that formally the lifetime ends when the period of destruction 6224 // begins, even though certain uses of the object remain valid until the 6225 // period of destruction ends.) 6226 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6227 return false; 6228 } 6229 6230 // FIXME: Creating an APValue just to hold a nonexistent return value is 6231 // wasteful. 6232 APValue RetVal; 6233 StmtResult Ret = {RetVal, nullptr}; 6234 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6235 return false; 6236 6237 // A union destructor does not implicitly destroy its members. 6238 if (RD->isUnion()) 6239 return true; 6240 6241 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6242 6243 // We don't have a good way to iterate fields in reverse, so collect all the 6244 // fields first and then walk them backwards. 6245 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6246 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6247 if (FD->isUnnamedBitfield()) 6248 continue; 6249 6250 LValue Subobject = This; 6251 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6252 return false; 6253 6254 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6255 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6256 FD->getType())) 6257 return false; 6258 } 6259 6260 if (BasesLeft != 0) 6261 EvalObj.startedDestroyingBases(); 6262 6263 // Destroy base classes in reverse order. 6264 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6265 --BasesLeft; 6266 6267 QualType BaseType = Base.getType(); 6268 LValue Subobject = This; 6269 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6270 BaseType->getAsCXXRecordDecl(), &Layout)) 6271 return false; 6272 6273 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6274 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6275 BaseType)) 6276 return false; 6277 } 6278 assert(BasesLeft == 0 && "NumBases was wrong?"); 6279 6280 // The period of destruction ends now. The object is gone. 6281 Value = APValue(); 6282 return true; 6283 } 6284 6285 namespace { 6286 struct DestroyObjectHandler { 6287 EvalInfo &Info; 6288 const Expr *E; 6289 const LValue &This; 6290 const AccessKinds AccessKind; 6291 6292 typedef bool result_type; 6293 bool failed() { return false; } 6294 bool found(APValue &Subobj, QualType SubobjType) { 6295 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6296 SubobjType); 6297 } 6298 bool found(APSInt &Value, QualType SubobjType) { 6299 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6300 return false; 6301 } 6302 bool found(APFloat &Value, QualType SubobjType) { 6303 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6304 return false; 6305 } 6306 }; 6307 } 6308 6309 /// Perform a destructor or pseudo-destructor call on the given object, which 6310 /// might in general not be a complete object. 6311 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6312 const LValue &This, QualType ThisType) { 6313 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6314 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6315 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6316 } 6317 6318 /// Destroy and end the lifetime of the given complete object. 6319 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6320 APValue::LValueBase LVBase, APValue &Value, 6321 QualType T) { 6322 // If we've had an unmodeled side-effect, we can't rely on mutable state 6323 // (such as the object we're about to destroy) being correct. 6324 if (Info.EvalStatus.HasSideEffects) 6325 return false; 6326 6327 LValue LV; 6328 LV.set({LVBase}); 6329 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6330 } 6331 6332 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6333 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6334 LValue &Result) { 6335 if (Info.checkingPotentialConstantExpression() || 6336 Info.SpeculativeEvaluationDepth) 6337 return false; 6338 6339 // This is permitted only within a call to std::allocator<T>::allocate. 6340 auto Caller = Info.getStdAllocatorCaller("allocate"); 6341 if (!Caller) { 6342 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6343 ? diag::note_constexpr_new_untyped 6344 : diag::note_constexpr_new); 6345 return false; 6346 } 6347 6348 QualType ElemType = Caller.ElemType; 6349 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6350 Info.FFDiag(E->getExprLoc(), 6351 diag::note_constexpr_new_not_complete_object_type) 6352 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6353 return false; 6354 } 6355 6356 APSInt ByteSize; 6357 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6358 return false; 6359 bool IsNothrow = false; 6360 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6361 EvaluateIgnoredValue(Info, E->getArg(I)); 6362 IsNothrow |= E->getType()->isNothrowT(); 6363 } 6364 6365 CharUnits ElemSize; 6366 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6367 return false; 6368 APInt Size, Remainder; 6369 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6370 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6371 if (Remainder != 0) { 6372 // This likely indicates a bug in the implementation of 'std::allocator'. 6373 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6374 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6375 return false; 6376 } 6377 6378 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6379 if (IsNothrow) { 6380 Result.setNull(Info.Ctx, E->getType()); 6381 return true; 6382 } 6383 6384 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6385 return false; 6386 } 6387 6388 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6389 ArrayType::Normal, 0); 6390 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6391 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6392 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6393 return true; 6394 } 6395 6396 static bool hasVirtualDestructor(QualType T) { 6397 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6398 if (CXXDestructorDecl *DD = RD->getDestructor()) 6399 return DD->isVirtual(); 6400 return false; 6401 } 6402 6403 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6404 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6405 if (CXXDestructorDecl *DD = RD->getDestructor()) 6406 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6407 return nullptr; 6408 } 6409 6410 /// Check that the given object is a suitable pointer to a heap allocation that 6411 /// still exists and is of the right kind for the purpose of a deletion. 6412 /// 6413 /// On success, returns the heap allocation to deallocate. On failure, produces 6414 /// a diagnostic and returns None. 6415 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6416 const LValue &Pointer, 6417 DynAlloc::Kind DeallocKind) { 6418 auto PointerAsString = [&] { 6419 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6420 }; 6421 6422 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6423 if (!DA) { 6424 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6425 << PointerAsString(); 6426 if (Pointer.Base) 6427 NoteLValueLocation(Info, Pointer.Base); 6428 return None; 6429 } 6430 6431 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6432 if (!Alloc) { 6433 Info.FFDiag(E, diag::note_constexpr_double_delete); 6434 return None; 6435 } 6436 6437 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6438 if (DeallocKind != (*Alloc)->getKind()) { 6439 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6440 << DeallocKind << (*Alloc)->getKind() << AllocType; 6441 NoteLValueLocation(Info, Pointer.Base); 6442 return None; 6443 } 6444 6445 bool Subobject = false; 6446 if (DeallocKind == DynAlloc::New) { 6447 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6448 Pointer.Designator.isOnePastTheEnd(); 6449 } else { 6450 Subobject = Pointer.Designator.Entries.size() != 1 || 6451 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6452 } 6453 if (Subobject) { 6454 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6455 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6456 return None; 6457 } 6458 6459 return Alloc; 6460 } 6461 6462 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6463 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6464 if (Info.checkingPotentialConstantExpression() || 6465 Info.SpeculativeEvaluationDepth) 6466 return false; 6467 6468 // This is permitted only within a call to std::allocator<T>::deallocate. 6469 if (!Info.getStdAllocatorCaller("deallocate")) { 6470 Info.FFDiag(E->getExprLoc()); 6471 return true; 6472 } 6473 6474 LValue Pointer; 6475 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6476 return false; 6477 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6478 EvaluateIgnoredValue(Info, E->getArg(I)); 6479 6480 if (Pointer.Designator.Invalid) 6481 return false; 6482 6483 // Deleting a null pointer has no effect. 6484 if (Pointer.isNullPointer()) 6485 return true; 6486 6487 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6488 return false; 6489 6490 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6491 return true; 6492 } 6493 6494 //===----------------------------------------------------------------------===// 6495 // Generic Evaluation 6496 //===----------------------------------------------------------------------===// 6497 namespace { 6498 6499 class BitCastBuffer { 6500 // FIXME: We're going to need bit-level granularity when we support 6501 // bit-fields. 6502 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6503 // we don't support a host or target where that is the case. Still, we should 6504 // use a more generic type in case we ever do. 6505 SmallVector<Optional<unsigned char>, 32> Bytes; 6506 6507 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6508 "Need at least 8 bit unsigned char"); 6509 6510 bool TargetIsLittleEndian; 6511 6512 public: 6513 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6514 : Bytes(Width.getQuantity()), 6515 TargetIsLittleEndian(TargetIsLittleEndian) {} 6516 6517 LLVM_NODISCARD 6518 bool readObject(CharUnits Offset, CharUnits Width, 6519 SmallVectorImpl<unsigned char> &Output) const { 6520 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6521 // If a byte of an integer is uninitialized, then the whole integer is 6522 // uninitalized. 6523 if (!Bytes[I.getQuantity()]) 6524 return false; 6525 Output.push_back(*Bytes[I.getQuantity()]); 6526 } 6527 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6528 std::reverse(Output.begin(), Output.end()); 6529 return true; 6530 } 6531 6532 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6533 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6534 std::reverse(Input.begin(), Input.end()); 6535 6536 size_t Index = 0; 6537 for (unsigned char Byte : Input) { 6538 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6539 Bytes[Offset.getQuantity() + Index] = Byte; 6540 ++Index; 6541 } 6542 } 6543 6544 size_t size() { return Bytes.size(); } 6545 }; 6546 6547 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6548 /// target would represent the value at runtime. 6549 class APValueToBufferConverter { 6550 EvalInfo &Info; 6551 BitCastBuffer Buffer; 6552 const CastExpr *BCE; 6553 6554 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6555 const CastExpr *BCE) 6556 : Info(Info), 6557 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6558 BCE(BCE) {} 6559 6560 bool visit(const APValue &Val, QualType Ty) { 6561 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6562 } 6563 6564 // Write out Val with type Ty into Buffer starting at Offset. 6565 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6566 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6567 6568 // As a special case, nullptr_t has an indeterminate value. 6569 if (Ty->isNullPtrType()) 6570 return true; 6571 6572 // Dig through Src to find the byte at SrcOffset. 6573 switch (Val.getKind()) { 6574 case APValue::Indeterminate: 6575 case APValue::None: 6576 return true; 6577 6578 case APValue::Int: 6579 return visitInt(Val.getInt(), Ty, Offset); 6580 case APValue::Float: 6581 return visitFloat(Val.getFloat(), Ty, Offset); 6582 case APValue::Array: 6583 return visitArray(Val, Ty, Offset); 6584 case APValue::Struct: 6585 return visitRecord(Val, Ty, Offset); 6586 6587 case APValue::ComplexInt: 6588 case APValue::ComplexFloat: 6589 case APValue::Vector: 6590 case APValue::FixedPoint: 6591 // FIXME: We should support these. 6592 6593 case APValue::Union: 6594 case APValue::MemberPointer: 6595 case APValue::AddrLabelDiff: { 6596 Info.FFDiag(BCE->getBeginLoc(), 6597 diag::note_constexpr_bit_cast_unsupported_type) 6598 << Ty; 6599 return false; 6600 } 6601 6602 case APValue::LValue: 6603 llvm_unreachable("LValue subobject in bit_cast?"); 6604 } 6605 llvm_unreachable("Unhandled APValue::ValueKind"); 6606 } 6607 6608 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6609 const RecordDecl *RD = Ty->getAsRecordDecl(); 6610 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6611 6612 // Visit the base classes. 6613 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6614 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6615 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6616 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6617 6618 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6619 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6620 return false; 6621 } 6622 } 6623 6624 // Visit the fields. 6625 unsigned FieldIdx = 0; 6626 for (FieldDecl *FD : RD->fields()) { 6627 if (FD->isBitField()) { 6628 Info.FFDiag(BCE->getBeginLoc(), 6629 diag::note_constexpr_bit_cast_unsupported_bitfield); 6630 return false; 6631 } 6632 6633 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6634 6635 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6636 "only bit-fields can have sub-char alignment"); 6637 CharUnits FieldOffset = 6638 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6639 QualType FieldTy = FD->getType(); 6640 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6641 return false; 6642 ++FieldIdx; 6643 } 6644 6645 return true; 6646 } 6647 6648 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6649 const auto *CAT = 6650 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6651 if (!CAT) 6652 return false; 6653 6654 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6655 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6656 unsigned ArraySize = Val.getArraySize(); 6657 // First, initialize the initialized elements. 6658 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6659 const APValue &SubObj = Val.getArrayInitializedElt(I); 6660 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6661 return false; 6662 } 6663 6664 // Next, initialize the rest of the array using the filler. 6665 if (Val.hasArrayFiller()) { 6666 const APValue &Filler = Val.getArrayFiller(); 6667 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6668 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6669 return false; 6670 } 6671 } 6672 6673 return true; 6674 } 6675 6676 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6677 APSInt AdjustedVal = Val; 6678 unsigned Width = AdjustedVal.getBitWidth(); 6679 if (Ty->isBooleanType()) { 6680 Width = Info.Ctx.getTypeSize(Ty); 6681 AdjustedVal = AdjustedVal.extend(Width); 6682 } 6683 6684 SmallVector<unsigned char, 8> Bytes(Width / 8); 6685 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6686 Buffer.writeObject(Offset, Bytes); 6687 return true; 6688 } 6689 6690 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6691 APSInt AsInt(Val.bitcastToAPInt()); 6692 return visitInt(AsInt, Ty, Offset); 6693 } 6694 6695 public: 6696 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6697 const CastExpr *BCE) { 6698 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6699 APValueToBufferConverter Converter(Info, DstSize, BCE); 6700 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6701 return None; 6702 return Converter.Buffer; 6703 } 6704 }; 6705 6706 /// Write an BitCastBuffer into an APValue. 6707 class BufferToAPValueConverter { 6708 EvalInfo &Info; 6709 const BitCastBuffer &Buffer; 6710 const CastExpr *BCE; 6711 6712 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6713 const CastExpr *BCE) 6714 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6715 6716 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6717 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6718 // Ideally this will be unreachable. 6719 llvm::NoneType unsupportedType(QualType Ty) { 6720 Info.FFDiag(BCE->getBeginLoc(), 6721 diag::note_constexpr_bit_cast_unsupported_type) 6722 << Ty; 6723 return None; 6724 } 6725 6726 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6727 Info.FFDiag(BCE->getBeginLoc(), 6728 diag::note_constexpr_bit_cast_unrepresentable_value) 6729 << Ty << Val.toString(/*Radix=*/10); 6730 return None; 6731 } 6732 6733 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6734 const EnumType *EnumSugar = nullptr) { 6735 if (T->isNullPtrType()) { 6736 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6737 return APValue((Expr *)nullptr, 6738 /*Offset=*/CharUnits::fromQuantity(NullValue), 6739 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6740 } 6741 6742 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6743 6744 // Work around floating point types that contain unused padding bytes. This 6745 // is really just `long double` on x86, which is the only fundamental type 6746 // with padding bytes. 6747 if (T->isRealFloatingType()) { 6748 const llvm::fltSemantics &Semantics = 6749 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6750 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 6751 assert(NumBits % 8 == 0); 6752 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 6753 if (NumBytes != SizeOf) 6754 SizeOf = NumBytes; 6755 } 6756 6757 SmallVector<uint8_t, 8> Bytes; 6758 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6759 // If this is std::byte or unsigned char, then its okay to store an 6760 // indeterminate value. 6761 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 6762 bool IsUChar = 6763 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 6764 T->isSpecificBuiltinType(BuiltinType::Char_U)); 6765 if (!IsStdByte && !IsUChar) { 6766 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 6767 Info.FFDiag(BCE->getExprLoc(), 6768 diag::note_constexpr_bit_cast_indet_dest) 6769 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 6770 return None; 6771 } 6772 6773 return APValue::IndeterminateValue(); 6774 } 6775 6776 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 6777 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 6778 6779 if (T->isIntegralOrEnumerationType()) { 6780 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 6781 6782 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 6783 if (IntWidth != Val.getBitWidth()) { 6784 APSInt Truncated = Val.trunc(IntWidth); 6785 if (Truncated.extend(Val.getBitWidth()) != Val) 6786 return unrepresentableValue(QualType(T, 0), Val); 6787 Val = Truncated; 6788 } 6789 6790 return APValue(Val); 6791 } 6792 6793 if (T->isRealFloatingType()) { 6794 const llvm::fltSemantics &Semantics = 6795 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6796 return APValue(APFloat(Semantics, Val)); 6797 } 6798 6799 return unsupportedType(QualType(T, 0)); 6800 } 6801 6802 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 6803 const RecordDecl *RD = RTy->getAsRecordDecl(); 6804 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6805 6806 unsigned NumBases = 0; 6807 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6808 NumBases = CXXRD->getNumBases(); 6809 6810 APValue ResultVal(APValue::UninitStruct(), NumBases, 6811 std::distance(RD->field_begin(), RD->field_end())); 6812 6813 // Visit the base classes. 6814 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6815 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6816 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6817 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6818 if (BaseDecl->isEmpty() || 6819 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 6820 continue; 6821 6822 Optional<APValue> SubObj = visitType( 6823 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 6824 if (!SubObj) 6825 return None; 6826 ResultVal.getStructBase(I) = *SubObj; 6827 } 6828 } 6829 6830 // Visit the fields. 6831 unsigned FieldIdx = 0; 6832 for (FieldDecl *FD : RD->fields()) { 6833 // FIXME: We don't currently support bit-fields. A lot of the logic for 6834 // this is in CodeGen, so we need to factor it around. 6835 if (FD->isBitField()) { 6836 Info.FFDiag(BCE->getBeginLoc(), 6837 diag::note_constexpr_bit_cast_unsupported_bitfield); 6838 return None; 6839 } 6840 6841 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6842 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 6843 6844 CharUnits FieldOffset = 6845 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 6846 Offset; 6847 QualType FieldTy = FD->getType(); 6848 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 6849 if (!SubObj) 6850 return None; 6851 ResultVal.getStructField(FieldIdx) = *SubObj; 6852 ++FieldIdx; 6853 } 6854 6855 return ResultVal; 6856 } 6857 6858 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 6859 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 6860 assert(!RepresentationType.isNull() && 6861 "enum forward decl should be caught by Sema"); 6862 const auto *AsBuiltin = 6863 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 6864 // Recurse into the underlying type. Treat std::byte transparently as 6865 // unsigned char. 6866 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 6867 } 6868 6869 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 6870 size_t Size = Ty->getSize().getLimitedValue(); 6871 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 6872 6873 APValue ArrayValue(APValue::UninitArray(), Size, Size); 6874 for (size_t I = 0; I != Size; ++I) { 6875 Optional<APValue> ElementValue = 6876 visitType(Ty->getElementType(), Offset + I * ElementWidth); 6877 if (!ElementValue) 6878 return None; 6879 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 6880 } 6881 6882 return ArrayValue; 6883 } 6884 6885 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 6886 return unsupportedType(QualType(Ty, 0)); 6887 } 6888 6889 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 6890 QualType Can = Ty.getCanonicalType(); 6891 6892 switch (Can->getTypeClass()) { 6893 #define TYPE(Class, Base) \ 6894 case Type::Class: \ 6895 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 6896 #define ABSTRACT_TYPE(Class, Base) 6897 #define NON_CANONICAL_TYPE(Class, Base) \ 6898 case Type::Class: \ 6899 llvm_unreachable("non-canonical type should be impossible!"); 6900 #define DEPENDENT_TYPE(Class, Base) \ 6901 case Type::Class: \ 6902 llvm_unreachable( \ 6903 "dependent types aren't supported in the constant evaluator!"); 6904 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 6905 case Type::Class: \ 6906 llvm_unreachable("either dependent or not canonical!"); 6907 #include "clang/AST/TypeNodes.inc" 6908 } 6909 llvm_unreachable("Unhandled Type::TypeClass"); 6910 } 6911 6912 public: 6913 // Pull out a full value of type DstType. 6914 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 6915 const CastExpr *BCE) { 6916 BufferToAPValueConverter Converter(Info, Buffer, BCE); 6917 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 6918 } 6919 }; 6920 6921 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 6922 QualType Ty, EvalInfo *Info, 6923 const ASTContext &Ctx, 6924 bool CheckingDest) { 6925 Ty = Ty.getCanonicalType(); 6926 6927 auto diag = [&](int Reason) { 6928 if (Info) 6929 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 6930 << CheckingDest << (Reason == 4) << Reason; 6931 return false; 6932 }; 6933 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 6934 if (Info) 6935 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 6936 << NoteTy << Construct << Ty; 6937 return false; 6938 }; 6939 6940 if (Ty->isUnionType()) 6941 return diag(0); 6942 if (Ty->isPointerType()) 6943 return diag(1); 6944 if (Ty->isMemberPointerType()) 6945 return diag(2); 6946 if (Ty.isVolatileQualified()) 6947 return diag(3); 6948 6949 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 6950 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 6951 for (CXXBaseSpecifier &BS : CXXRD->bases()) 6952 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 6953 CheckingDest)) 6954 return note(1, BS.getType(), BS.getBeginLoc()); 6955 } 6956 for (FieldDecl *FD : Record->fields()) { 6957 if (FD->getType()->isReferenceType()) 6958 return diag(4); 6959 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 6960 CheckingDest)) 6961 return note(0, FD->getType(), FD->getBeginLoc()); 6962 } 6963 } 6964 6965 if (Ty->isArrayType() && 6966 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 6967 Info, Ctx, CheckingDest)) 6968 return false; 6969 6970 return true; 6971 } 6972 6973 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 6974 const ASTContext &Ctx, 6975 const CastExpr *BCE) { 6976 bool DestOK = checkBitCastConstexprEligibilityType( 6977 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 6978 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 6979 BCE->getBeginLoc(), 6980 BCE->getSubExpr()->getType(), Info, Ctx, false); 6981 return SourceOK; 6982 } 6983 6984 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 6985 APValue &SourceValue, 6986 const CastExpr *BCE) { 6987 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 6988 "no host or target supports non 8-bit chars"); 6989 assert(SourceValue.isLValue() && 6990 "LValueToRValueBitcast requires an lvalue operand!"); 6991 6992 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 6993 return false; 6994 6995 LValue SourceLValue; 6996 APValue SourceRValue; 6997 SourceLValue.setFrom(Info.Ctx, SourceValue); 6998 if (!handleLValueToRValueConversion( 6999 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7000 SourceRValue, /*WantObjectRepresentation=*/true)) 7001 return false; 7002 7003 // Read out SourceValue into a char buffer. 7004 Optional<BitCastBuffer> Buffer = 7005 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7006 if (!Buffer) 7007 return false; 7008 7009 // Write out the buffer into a new APValue. 7010 Optional<APValue> MaybeDestValue = 7011 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7012 if (!MaybeDestValue) 7013 return false; 7014 7015 DestValue = std::move(*MaybeDestValue); 7016 return true; 7017 } 7018 7019 template <class Derived> 7020 class ExprEvaluatorBase 7021 : public ConstStmtVisitor<Derived, bool> { 7022 private: 7023 Derived &getDerived() { return static_cast<Derived&>(*this); } 7024 bool DerivedSuccess(const APValue &V, const Expr *E) { 7025 return getDerived().Success(V, E); 7026 } 7027 bool DerivedZeroInitialization(const Expr *E) { 7028 return getDerived().ZeroInitialization(E); 7029 } 7030 7031 // Check whether a conditional operator with a non-constant condition is a 7032 // potential constant expression. If neither arm is a potential constant 7033 // expression, then the conditional operator is not either. 7034 template<typename ConditionalOperator> 7035 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7036 assert(Info.checkingPotentialConstantExpression()); 7037 7038 // Speculatively evaluate both arms. 7039 SmallVector<PartialDiagnosticAt, 8> Diag; 7040 { 7041 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7042 StmtVisitorTy::Visit(E->getFalseExpr()); 7043 if (Diag.empty()) 7044 return; 7045 } 7046 7047 { 7048 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7049 Diag.clear(); 7050 StmtVisitorTy::Visit(E->getTrueExpr()); 7051 if (Diag.empty()) 7052 return; 7053 } 7054 7055 Error(E, diag::note_constexpr_conditional_never_const); 7056 } 7057 7058 7059 template<typename ConditionalOperator> 7060 bool HandleConditionalOperator(const ConditionalOperator *E) { 7061 bool BoolResult; 7062 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7063 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7064 CheckPotentialConstantConditional(E); 7065 return false; 7066 } 7067 if (Info.noteFailure()) { 7068 StmtVisitorTy::Visit(E->getTrueExpr()); 7069 StmtVisitorTy::Visit(E->getFalseExpr()); 7070 } 7071 return false; 7072 } 7073 7074 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7075 return StmtVisitorTy::Visit(EvalExpr); 7076 } 7077 7078 protected: 7079 EvalInfo &Info; 7080 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7081 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7082 7083 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7084 return Info.CCEDiag(E, D); 7085 } 7086 7087 bool ZeroInitialization(const Expr *E) { return Error(E); } 7088 7089 public: 7090 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7091 7092 EvalInfo &getEvalInfo() { return Info; } 7093 7094 /// Report an evaluation error. This should only be called when an error is 7095 /// first discovered. When propagating an error, just return false. 7096 bool Error(const Expr *E, diag::kind D) { 7097 Info.FFDiag(E, D); 7098 return false; 7099 } 7100 bool Error(const Expr *E) { 7101 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7102 } 7103 7104 bool VisitStmt(const Stmt *) { 7105 llvm_unreachable("Expression evaluator should not be called on stmts"); 7106 } 7107 bool VisitExpr(const Expr *E) { 7108 return Error(E); 7109 } 7110 7111 bool VisitConstantExpr(const ConstantExpr *E) { 7112 if (E->hasAPValueResult()) 7113 return DerivedSuccess(E->getAPValueResult(), E); 7114 7115 return StmtVisitorTy::Visit(E->getSubExpr()); 7116 } 7117 7118 bool VisitParenExpr(const ParenExpr *E) 7119 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7120 bool VisitUnaryExtension(const UnaryOperator *E) 7121 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7122 bool VisitUnaryPlus(const UnaryOperator *E) 7123 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7124 bool VisitChooseExpr(const ChooseExpr *E) 7125 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7126 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7127 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7128 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7129 { return StmtVisitorTy::Visit(E->getReplacement()); } 7130 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7131 TempVersionRAII RAII(*Info.CurrentCall); 7132 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7133 return StmtVisitorTy::Visit(E->getExpr()); 7134 } 7135 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7136 TempVersionRAII RAII(*Info.CurrentCall); 7137 // The initializer may not have been parsed yet, or might be erroneous. 7138 if (!E->getExpr()) 7139 return Error(E); 7140 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7141 return StmtVisitorTy::Visit(E->getExpr()); 7142 } 7143 7144 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7145 FullExpressionRAII Scope(Info); 7146 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7147 } 7148 7149 // Temporaries are registered when created, so we don't care about 7150 // CXXBindTemporaryExpr. 7151 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7152 return StmtVisitorTy::Visit(E->getSubExpr()); 7153 } 7154 7155 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7156 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7157 return static_cast<Derived*>(this)->VisitCastExpr(E); 7158 } 7159 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7160 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7161 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7162 return static_cast<Derived*>(this)->VisitCastExpr(E); 7163 } 7164 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7165 return static_cast<Derived*>(this)->VisitCastExpr(E); 7166 } 7167 7168 bool VisitBinaryOperator(const BinaryOperator *E) { 7169 switch (E->getOpcode()) { 7170 default: 7171 return Error(E); 7172 7173 case BO_Comma: 7174 VisitIgnoredValue(E->getLHS()); 7175 return StmtVisitorTy::Visit(E->getRHS()); 7176 7177 case BO_PtrMemD: 7178 case BO_PtrMemI: { 7179 LValue Obj; 7180 if (!HandleMemberPointerAccess(Info, E, Obj)) 7181 return false; 7182 APValue Result; 7183 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7184 return false; 7185 return DerivedSuccess(Result, E); 7186 } 7187 } 7188 } 7189 7190 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7191 return StmtVisitorTy::Visit(E->getSemanticForm()); 7192 } 7193 7194 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7195 // Evaluate and cache the common expression. We treat it as a temporary, 7196 // even though it's not quite the same thing. 7197 LValue CommonLV; 7198 if (!Evaluate(Info.CurrentCall->createTemporary( 7199 E->getOpaqueValue(), 7200 getStorageType(Info.Ctx, E->getOpaqueValue()), false, 7201 CommonLV), 7202 Info, E->getCommon())) 7203 return false; 7204 7205 return HandleConditionalOperator(E); 7206 } 7207 7208 bool VisitConditionalOperator(const ConditionalOperator *E) { 7209 bool IsBcpCall = false; 7210 // If the condition (ignoring parens) is a __builtin_constant_p call, 7211 // the result is a constant expression if it can be folded without 7212 // side-effects. This is an important GNU extension. See GCC PR38377 7213 // for discussion. 7214 if (const CallExpr *CallCE = 7215 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7216 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7217 IsBcpCall = true; 7218 7219 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7220 // constant expression; we can't check whether it's potentially foldable. 7221 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7222 // it would return 'false' in this mode. 7223 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7224 return false; 7225 7226 FoldConstant Fold(Info, IsBcpCall); 7227 if (!HandleConditionalOperator(E)) { 7228 Fold.keepDiagnostics(); 7229 return false; 7230 } 7231 7232 return true; 7233 } 7234 7235 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7236 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7237 return DerivedSuccess(*Value, E); 7238 7239 const Expr *Source = E->getSourceExpr(); 7240 if (!Source) 7241 return Error(E); 7242 if (Source == E) { // sanity checking. 7243 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7244 return Error(E); 7245 } 7246 return StmtVisitorTy::Visit(Source); 7247 } 7248 7249 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7250 for (const Expr *SemE : E->semantics()) { 7251 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7252 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7253 // result expression: there could be two different LValues that would 7254 // refer to the same object in that case, and we can't model that. 7255 if (SemE == E->getResultExpr()) 7256 return Error(E); 7257 7258 // Unique OVEs get evaluated if and when we encounter them when 7259 // emitting the rest of the semantic form, rather than eagerly. 7260 if (OVE->isUnique()) 7261 continue; 7262 7263 LValue LV; 7264 if (!Evaluate(Info.CurrentCall->createTemporary( 7265 OVE, getStorageType(Info.Ctx, OVE), false, LV), 7266 Info, OVE->getSourceExpr())) 7267 return false; 7268 } else if (SemE == E->getResultExpr()) { 7269 if (!StmtVisitorTy::Visit(SemE)) 7270 return false; 7271 } else { 7272 if (!EvaluateIgnoredValue(Info, SemE)) 7273 return false; 7274 } 7275 } 7276 return true; 7277 } 7278 7279 bool VisitCallExpr(const CallExpr *E) { 7280 APValue Result; 7281 if (!handleCallExpr(E, Result, nullptr)) 7282 return false; 7283 return DerivedSuccess(Result, E); 7284 } 7285 7286 bool handleCallExpr(const CallExpr *E, APValue &Result, 7287 const LValue *ResultSlot) { 7288 const Expr *Callee = E->getCallee()->IgnoreParens(); 7289 QualType CalleeType = Callee->getType(); 7290 7291 const FunctionDecl *FD = nullptr; 7292 LValue *This = nullptr, ThisVal; 7293 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7294 bool HasQualifier = false; 7295 7296 ArgVector ArgValues; 7297 7298 // Extract function decl and 'this' pointer from the callee. 7299 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7300 const CXXMethodDecl *Member = nullptr; 7301 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7302 // Explicit bound member calls, such as x.f() or p->g(); 7303 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7304 return false; 7305 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7306 if (!Member) 7307 return Error(Callee); 7308 This = &ThisVal; 7309 HasQualifier = ME->hasQualifier(); 7310 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7311 // Indirect bound member calls ('.*' or '->*'). 7312 const ValueDecl *D = 7313 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7314 if (!D) 7315 return false; 7316 Member = dyn_cast<CXXMethodDecl>(D); 7317 if (!Member) 7318 return Error(Callee); 7319 This = &ThisVal; 7320 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7321 if (!Info.getLangOpts().CPlusPlus20) 7322 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7323 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7324 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7325 } else 7326 return Error(Callee); 7327 FD = Member; 7328 } else if (CalleeType->isFunctionPointerType()) { 7329 LValue Call; 7330 if (!EvaluatePointer(Callee, Call, Info)) 7331 return false; 7332 7333 if (!Call.getLValueOffset().isZero()) 7334 return Error(Callee); 7335 FD = dyn_cast_or_null<FunctionDecl>( 7336 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 7337 if (!FD) 7338 return Error(Callee); 7339 // Don't call function pointers which have been cast to some other type. 7340 // Per DR (no number yet), the caller and callee can differ in noexcept. 7341 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7342 CalleeType->getPointeeType(), FD->getType())) { 7343 return Error(E); 7344 } 7345 7346 // For an (overloaded) assignment expression, evaluate the RHS before the 7347 // LHS. 7348 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7349 if (OCE && OCE->isAssignmentOp()) { 7350 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7351 if (isa<CXXMethodDecl>(FD)) { 7352 // Args[0] is the object argument. 7353 if (!EvaluateArgs({Args[1]}, ArgValues, Info, FD)) 7354 return false; 7355 } else { 7356 if (!EvaluateArgs({Args[1], Args[0]}, ArgValues, Info, FD)) 7357 return false; 7358 std::swap(ArgValues[0], ArgValues[1]); 7359 } 7360 } 7361 7362 // Overloaded operator calls to member functions are represented as normal 7363 // calls with '*this' as the first argument. 7364 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7365 if (MD && !MD->isStatic()) { 7366 // FIXME: When selecting an implicit conversion for an overloaded 7367 // operator delete, we sometimes try to evaluate calls to conversion 7368 // operators without a 'this' parameter! 7369 if (Args.empty()) 7370 return Error(E); 7371 7372 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7373 return false; 7374 This = &ThisVal; 7375 Args = Args.slice(1); 7376 } else if (MD && MD->isLambdaStaticInvoker()) { 7377 // Map the static invoker for the lambda back to the call operator. 7378 // Conveniently, we don't have to slice out the 'this' argument (as is 7379 // being done for the non-static case), since a static member function 7380 // doesn't have an implicit argument passed in. 7381 const CXXRecordDecl *ClosureClass = MD->getParent(); 7382 assert( 7383 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7384 "Number of captures must be zero for conversion to function-ptr"); 7385 7386 const CXXMethodDecl *LambdaCallOp = 7387 ClosureClass->getLambdaCallOperator(); 7388 7389 // Set 'FD', the function that will be called below, to the call 7390 // operator. If the closure object represents a generic lambda, find 7391 // the corresponding specialization of the call operator. 7392 7393 if (ClosureClass->isGenericLambda()) { 7394 assert(MD->isFunctionTemplateSpecialization() && 7395 "A generic lambda's static-invoker function must be a " 7396 "template specialization"); 7397 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7398 FunctionTemplateDecl *CallOpTemplate = 7399 LambdaCallOp->getDescribedFunctionTemplate(); 7400 void *InsertPos = nullptr; 7401 FunctionDecl *CorrespondingCallOpSpecialization = 7402 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7403 assert(CorrespondingCallOpSpecialization && 7404 "We must always have a function call operator specialization " 7405 "that corresponds to our static invoker specialization"); 7406 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7407 } else 7408 FD = LambdaCallOp; 7409 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7410 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7411 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7412 LValue Ptr; 7413 if (!HandleOperatorNewCall(Info, E, Ptr)) 7414 return false; 7415 Ptr.moveInto(Result); 7416 return true; 7417 } else { 7418 return HandleOperatorDeleteCall(Info, E); 7419 } 7420 } 7421 } else 7422 return Error(E); 7423 7424 // Evaluate the arguments now if we've not already done so. 7425 if (ArgValues.empty() && !Args.empty() && 7426 !EvaluateArgs(Args, ArgValues, Info, FD)) 7427 return false; 7428 7429 SmallVector<QualType, 4> CovariantAdjustmentPath; 7430 if (This) { 7431 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7432 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7433 // Perform virtual dispatch, if necessary. 7434 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7435 CovariantAdjustmentPath); 7436 if (!FD) 7437 return false; 7438 } else { 7439 // Check that the 'this' pointer points to an object of the right type. 7440 // FIXME: If this is an assignment operator call, we may need to change 7441 // the active union member before we check this. 7442 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7443 return false; 7444 } 7445 } 7446 7447 // Destructor calls are different enough that they have their own codepath. 7448 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7449 assert(This && "no 'this' pointer for destructor call"); 7450 assert(ArgValues.empty() && "unexpected destructor arguments"); 7451 return HandleDestruction(Info, E, *This, 7452 Info.Ctx.getRecordType(DD->getParent())); 7453 } 7454 7455 const FunctionDecl *Definition = nullptr; 7456 Stmt *Body = FD->getBody(Definition); 7457 7458 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7459 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, 7460 ArgValues.data(), Body, Info, Result, ResultSlot)) 7461 return false; 7462 7463 if (!CovariantAdjustmentPath.empty() && 7464 !HandleCovariantReturnAdjustment(Info, E, Result, 7465 CovariantAdjustmentPath)) 7466 return false; 7467 7468 return true; 7469 } 7470 7471 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7472 return StmtVisitorTy::Visit(E->getInitializer()); 7473 } 7474 bool VisitInitListExpr(const InitListExpr *E) { 7475 if (E->getNumInits() == 0) 7476 return DerivedZeroInitialization(E); 7477 if (E->getNumInits() == 1) 7478 return StmtVisitorTy::Visit(E->getInit(0)); 7479 return Error(E); 7480 } 7481 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7482 return DerivedZeroInitialization(E); 7483 } 7484 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7485 return DerivedZeroInitialization(E); 7486 } 7487 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7488 return DerivedZeroInitialization(E); 7489 } 7490 7491 /// A member expression where the object is a prvalue is itself a prvalue. 7492 bool VisitMemberExpr(const MemberExpr *E) { 7493 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7494 "missing temporary materialization conversion"); 7495 assert(!E->isArrow() && "missing call to bound member function?"); 7496 7497 APValue Val; 7498 if (!Evaluate(Val, Info, E->getBase())) 7499 return false; 7500 7501 QualType BaseTy = E->getBase()->getType(); 7502 7503 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7504 if (!FD) return Error(E); 7505 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7506 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7507 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7508 7509 // Note: there is no lvalue base here. But this case should only ever 7510 // happen in C or in C++98, where we cannot be evaluating a constexpr 7511 // constructor, which is the only case the base matters. 7512 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7513 SubobjectDesignator Designator(BaseTy); 7514 Designator.addDeclUnchecked(FD); 7515 7516 APValue Result; 7517 return extractSubobject(Info, E, Obj, Designator, Result) && 7518 DerivedSuccess(Result, E); 7519 } 7520 7521 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7522 APValue Val; 7523 if (!Evaluate(Val, Info, E->getBase())) 7524 return false; 7525 7526 if (Val.isVector()) { 7527 SmallVector<uint32_t, 4> Indices; 7528 E->getEncodedElementAccess(Indices); 7529 if (Indices.size() == 1) { 7530 // Return scalar. 7531 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7532 } else { 7533 // Construct new APValue vector. 7534 SmallVector<APValue, 4> Elts; 7535 for (unsigned I = 0; I < Indices.size(); ++I) { 7536 Elts.push_back(Val.getVectorElt(Indices[I])); 7537 } 7538 APValue VecResult(Elts.data(), Indices.size()); 7539 return DerivedSuccess(VecResult, E); 7540 } 7541 } 7542 7543 return false; 7544 } 7545 7546 bool VisitCastExpr(const CastExpr *E) { 7547 switch (E->getCastKind()) { 7548 default: 7549 break; 7550 7551 case CK_AtomicToNonAtomic: { 7552 APValue AtomicVal; 7553 // This does not need to be done in place even for class/array types: 7554 // atomic-to-non-atomic conversion implies copying the object 7555 // representation. 7556 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7557 return false; 7558 return DerivedSuccess(AtomicVal, E); 7559 } 7560 7561 case CK_NoOp: 7562 case CK_UserDefinedConversion: 7563 return StmtVisitorTy::Visit(E->getSubExpr()); 7564 7565 case CK_LValueToRValue: { 7566 LValue LVal; 7567 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7568 return false; 7569 APValue RVal; 7570 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7571 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7572 LVal, RVal)) 7573 return false; 7574 return DerivedSuccess(RVal, E); 7575 } 7576 case CK_LValueToRValueBitCast: { 7577 APValue DestValue, SourceValue; 7578 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7579 return false; 7580 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7581 return false; 7582 return DerivedSuccess(DestValue, E); 7583 } 7584 7585 case CK_AddressSpaceConversion: { 7586 APValue Value; 7587 if (!Evaluate(Value, Info, E->getSubExpr())) 7588 return false; 7589 return DerivedSuccess(Value, E); 7590 } 7591 } 7592 7593 return Error(E); 7594 } 7595 7596 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7597 return VisitUnaryPostIncDec(UO); 7598 } 7599 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7600 return VisitUnaryPostIncDec(UO); 7601 } 7602 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7603 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7604 return Error(UO); 7605 7606 LValue LVal; 7607 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7608 return false; 7609 APValue RVal; 7610 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7611 UO->isIncrementOp(), &RVal)) 7612 return false; 7613 return DerivedSuccess(RVal, UO); 7614 } 7615 7616 bool VisitStmtExpr(const StmtExpr *E) { 7617 // We will have checked the full-expressions inside the statement expression 7618 // when they were completed, and don't need to check them again now. 7619 if (Info.checkingForUndefinedBehavior()) 7620 return Error(E); 7621 7622 const CompoundStmt *CS = E->getSubStmt(); 7623 if (CS->body_empty()) 7624 return true; 7625 7626 BlockScopeRAII Scope(Info); 7627 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7628 BE = CS->body_end(); 7629 /**/; ++BI) { 7630 if (BI + 1 == BE) { 7631 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7632 if (!FinalExpr) { 7633 Info.FFDiag((*BI)->getBeginLoc(), 7634 diag::note_constexpr_stmt_expr_unsupported); 7635 return false; 7636 } 7637 return this->Visit(FinalExpr) && Scope.destroy(); 7638 } 7639 7640 APValue ReturnValue; 7641 StmtResult Result = { ReturnValue, nullptr }; 7642 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7643 if (ESR != ESR_Succeeded) { 7644 // FIXME: If the statement-expression terminated due to 'return', 7645 // 'break', or 'continue', it would be nice to propagate that to 7646 // the outer statement evaluation rather than bailing out. 7647 if (ESR != ESR_Failed) 7648 Info.FFDiag((*BI)->getBeginLoc(), 7649 diag::note_constexpr_stmt_expr_unsupported); 7650 return false; 7651 } 7652 } 7653 7654 llvm_unreachable("Return from function from the loop above."); 7655 } 7656 7657 /// Visit a value which is evaluated, but whose value is ignored. 7658 void VisitIgnoredValue(const Expr *E) { 7659 EvaluateIgnoredValue(Info, E); 7660 } 7661 7662 /// Potentially visit a MemberExpr's base expression. 7663 void VisitIgnoredBaseExpression(const Expr *E) { 7664 // While MSVC doesn't evaluate the base expression, it does diagnose the 7665 // presence of side-effecting behavior. 7666 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7667 return; 7668 VisitIgnoredValue(E); 7669 } 7670 }; 7671 7672 } // namespace 7673 7674 //===----------------------------------------------------------------------===// 7675 // Common base class for lvalue and temporary evaluation. 7676 //===----------------------------------------------------------------------===// 7677 namespace { 7678 template<class Derived> 7679 class LValueExprEvaluatorBase 7680 : public ExprEvaluatorBase<Derived> { 7681 protected: 7682 LValue &Result; 7683 bool InvalidBaseOK; 7684 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7685 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7686 7687 bool Success(APValue::LValueBase B) { 7688 Result.set(B); 7689 return true; 7690 } 7691 7692 bool evaluatePointer(const Expr *E, LValue &Result) { 7693 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7694 } 7695 7696 public: 7697 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7698 : ExprEvaluatorBaseTy(Info), Result(Result), 7699 InvalidBaseOK(InvalidBaseOK) {} 7700 7701 bool Success(const APValue &V, const Expr *E) { 7702 Result.setFrom(this->Info.Ctx, V); 7703 return true; 7704 } 7705 7706 bool VisitMemberExpr(const MemberExpr *E) { 7707 // Handle non-static data members. 7708 QualType BaseTy; 7709 bool EvalOK; 7710 if (E->isArrow()) { 7711 EvalOK = evaluatePointer(E->getBase(), Result); 7712 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7713 } else if (E->getBase()->isRValue()) { 7714 assert(E->getBase()->getType()->isRecordType()); 7715 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7716 BaseTy = E->getBase()->getType(); 7717 } else { 7718 EvalOK = this->Visit(E->getBase()); 7719 BaseTy = E->getBase()->getType(); 7720 } 7721 if (!EvalOK) { 7722 if (!InvalidBaseOK) 7723 return false; 7724 Result.setInvalid(E); 7725 return true; 7726 } 7727 7728 const ValueDecl *MD = E->getMemberDecl(); 7729 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7730 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7731 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7732 (void)BaseTy; 7733 if (!HandleLValueMember(this->Info, E, Result, FD)) 7734 return false; 7735 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7736 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7737 return false; 7738 } else 7739 return this->Error(E); 7740 7741 if (MD->getType()->isReferenceType()) { 7742 APValue RefValue; 7743 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7744 RefValue)) 7745 return false; 7746 return Success(RefValue, E); 7747 } 7748 return true; 7749 } 7750 7751 bool VisitBinaryOperator(const BinaryOperator *E) { 7752 switch (E->getOpcode()) { 7753 default: 7754 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7755 7756 case BO_PtrMemD: 7757 case BO_PtrMemI: 7758 return HandleMemberPointerAccess(this->Info, E, Result); 7759 } 7760 } 7761 7762 bool VisitCastExpr(const CastExpr *E) { 7763 switch (E->getCastKind()) { 7764 default: 7765 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7766 7767 case CK_DerivedToBase: 7768 case CK_UncheckedDerivedToBase: 7769 if (!this->Visit(E->getSubExpr())) 7770 return false; 7771 7772 // Now figure out the necessary offset to add to the base LV to get from 7773 // the derived class to the base class. 7774 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 7775 Result); 7776 } 7777 } 7778 }; 7779 } 7780 7781 //===----------------------------------------------------------------------===// 7782 // LValue Evaluation 7783 // 7784 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 7785 // function designators (in C), decl references to void objects (in C), and 7786 // temporaries (if building with -Wno-address-of-temporary). 7787 // 7788 // LValue evaluation produces values comprising a base expression of one of the 7789 // following types: 7790 // - Declarations 7791 // * VarDecl 7792 // * FunctionDecl 7793 // - Literals 7794 // * CompoundLiteralExpr in C (and in global scope in C++) 7795 // * StringLiteral 7796 // * PredefinedExpr 7797 // * ObjCStringLiteralExpr 7798 // * ObjCEncodeExpr 7799 // * AddrLabelExpr 7800 // * BlockExpr 7801 // * CallExpr for a MakeStringConstant builtin 7802 // - typeid(T) expressions, as TypeInfoLValues 7803 // - Locals and temporaries 7804 // * MaterializeTemporaryExpr 7805 // * Any Expr, with a CallIndex indicating the function in which the temporary 7806 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 7807 // from the AST (FIXME). 7808 // * A MaterializeTemporaryExpr that has static storage duration, with no 7809 // CallIndex, for a lifetime-extended temporary. 7810 // * The ConstantExpr that is currently being evaluated during evaluation of an 7811 // immediate invocation. 7812 // plus an offset in bytes. 7813 //===----------------------------------------------------------------------===// 7814 namespace { 7815 class LValueExprEvaluator 7816 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 7817 public: 7818 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 7819 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 7820 7821 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 7822 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 7823 7824 bool VisitDeclRefExpr(const DeclRefExpr *E); 7825 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 7826 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 7827 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 7828 bool VisitMemberExpr(const MemberExpr *E); 7829 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 7830 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 7831 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 7832 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 7833 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 7834 bool VisitUnaryDeref(const UnaryOperator *E); 7835 bool VisitUnaryReal(const UnaryOperator *E); 7836 bool VisitUnaryImag(const UnaryOperator *E); 7837 bool VisitUnaryPreInc(const UnaryOperator *UO) { 7838 return VisitUnaryPreIncDec(UO); 7839 } 7840 bool VisitUnaryPreDec(const UnaryOperator *UO) { 7841 return VisitUnaryPreIncDec(UO); 7842 } 7843 bool VisitBinAssign(const BinaryOperator *BO); 7844 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 7845 7846 bool VisitCastExpr(const CastExpr *E) { 7847 switch (E->getCastKind()) { 7848 default: 7849 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 7850 7851 case CK_LValueBitCast: 7852 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7853 if (!Visit(E->getSubExpr())) 7854 return false; 7855 Result.Designator.setInvalid(); 7856 return true; 7857 7858 case CK_BaseToDerived: 7859 if (!Visit(E->getSubExpr())) 7860 return false; 7861 return HandleBaseToDerivedCast(Info, E, Result); 7862 7863 case CK_Dynamic: 7864 if (!Visit(E->getSubExpr())) 7865 return false; 7866 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 7867 } 7868 } 7869 }; 7870 } // end anonymous namespace 7871 7872 /// Evaluate an expression as an lvalue. This can be legitimately called on 7873 /// expressions which are not glvalues, in three cases: 7874 /// * function designators in C, and 7875 /// * "extern void" objects 7876 /// * @selector() expressions in Objective-C 7877 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 7878 bool InvalidBaseOK) { 7879 assert(E->isGLValue() || E->getType()->isFunctionType() || 7880 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 7881 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 7882 } 7883 7884 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 7885 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 7886 return Success(FD); 7887 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 7888 return VisitVarDecl(E, VD); 7889 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 7890 return Visit(BD->getBinding()); 7891 if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(E->getDecl())) 7892 return Success(GD); 7893 return Error(E); 7894 } 7895 7896 7897 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 7898 7899 // If we are within a lambda's call operator, check whether the 'VD' referred 7900 // to within 'E' actually represents a lambda-capture that maps to a 7901 // data-member/field within the closure object, and if so, evaluate to the 7902 // field or what the field refers to. 7903 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 7904 isa<DeclRefExpr>(E) && 7905 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 7906 // We don't always have a complete capture-map when checking or inferring if 7907 // the function call operator meets the requirements of a constexpr function 7908 // - but we don't need to evaluate the captures to determine constexprness 7909 // (dcl.constexpr C++17). 7910 if (Info.checkingPotentialConstantExpression()) 7911 return false; 7912 7913 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 7914 // Start with 'Result' referring to the complete closure object... 7915 Result = *Info.CurrentCall->This; 7916 // ... then update it to refer to the field of the closure object 7917 // that represents the capture. 7918 if (!HandleLValueMember(Info, E, Result, FD)) 7919 return false; 7920 // And if the field is of reference type, update 'Result' to refer to what 7921 // the field refers to. 7922 if (FD->getType()->isReferenceType()) { 7923 APValue RVal; 7924 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 7925 RVal)) 7926 return false; 7927 Result.setFrom(Info.Ctx, RVal); 7928 } 7929 return true; 7930 } 7931 } 7932 CallStackFrame *Frame = nullptr; 7933 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 7934 // Only if a local variable was declared in the function currently being 7935 // evaluated, do we expect to be able to find its value in the current 7936 // frame. (Otherwise it was likely declared in an enclosing context and 7937 // could either have a valid evaluatable value (for e.g. a constexpr 7938 // variable) or be ill-formed (and trigger an appropriate evaluation 7939 // diagnostic)). 7940 if (Info.CurrentCall->Callee && 7941 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 7942 Frame = Info.CurrentCall; 7943 } 7944 } 7945 7946 if (!VD->getType()->isReferenceType()) { 7947 if (Frame) { 7948 Result.set({VD, Frame->Index, 7949 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 7950 return true; 7951 } 7952 return Success(VD); 7953 } 7954 7955 APValue *V; 7956 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 7957 return false; 7958 if (!V->hasValue()) { 7959 // FIXME: Is it possible for V to be indeterminate here? If so, we should 7960 // adjust the diagnostic to say that. 7961 if (!Info.checkingPotentialConstantExpression()) 7962 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 7963 return false; 7964 } 7965 return Success(*V, E); 7966 } 7967 7968 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 7969 const MaterializeTemporaryExpr *E) { 7970 // Walk through the expression to find the materialized temporary itself. 7971 SmallVector<const Expr *, 2> CommaLHSs; 7972 SmallVector<SubobjectAdjustment, 2> Adjustments; 7973 const Expr *Inner = 7974 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 7975 7976 // If we passed any comma operators, evaluate their LHSs. 7977 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 7978 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 7979 return false; 7980 7981 // A materialized temporary with static storage duration can appear within the 7982 // result of a constant expression evaluation, so we need to preserve its 7983 // value for use outside this evaluation. 7984 APValue *Value; 7985 if (E->getStorageDuration() == SD_Static) { 7986 Value = E->getOrCreateValue(true); 7987 *Value = APValue(); 7988 Result.set(E); 7989 } else { 7990 Value = &Info.CurrentCall->createTemporary( 7991 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result); 7992 } 7993 7994 QualType Type = Inner->getType(); 7995 7996 // Materialize the temporary itself. 7997 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 7998 *Value = APValue(); 7999 return false; 8000 } 8001 8002 // Adjust our lvalue to refer to the desired subobject. 8003 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8004 --I; 8005 switch (Adjustments[I].Kind) { 8006 case SubobjectAdjustment::DerivedToBaseAdjustment: 8007 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8008 Type, Result)) 8009 return false; 8010 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8011 break; 8012 8013 case SubobjectAdjustment::FieldAdjustment: 8014 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8015 return false; 8016 Type = Adjustments[I].Field->getType(); 8017 break; 8018 8019 case SubobjectAdjustment::MemberPointerAdjustment: 8020 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8021 Adjustments[I].Ptr.RHS)) 8022 return false; 8023 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8024 break; 8025 } 8026 } 8027 8028 return true; 8029 } 8030 8031 bool 8032 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8033 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8034 "lvalue compound literal in c++?"); 8035 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8036 // only see this when folding in C, so there's no standard to follow here. 8037 return Success(E); 8038 } 8039 8040 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8041 TypeInfoLValue TypeInfo; 8042 8043 if (!E->isPotentiallyEvaluated()) { 8044 if (E->isTypeOperand()) 8045 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8046 else 8047 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8048 } else { 8049 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8050 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8051 << E->getExprOperand()->getType() 8052 << E->getExprOperand()->getSourceRange(); 8053 } 8054 8055 if (!Visit(E->getExprOperand())) 8056 return false; 8057 8058 Optional<DynamicType> DynType = 8059 ComputeDynamicType(Info, E, Result, AK_TypeId); 8060 if (!DynType) 8061 return false; 8062 8063 TypeInfo = 8064 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8065 } 8066 8067 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8068 } 8069 8070 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8071 return Success(E->getGuidDecl()); 8072 } 8073 8074 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8075 // Handle static data members. 8076 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8077 VisitIgnoredBaseExpression(E->getBase()); 8078 return VisitVarDecl(E, VD); 8079 } 8080 8081 // Handle static member functions. 8082 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8083 if (MD->isStatic()) { 8084 VisitIgnoredBaseExpression(E->getBase()); 8085 return Success(MD); 8086 } 8087 } 8088 8089 // Handle non-static data members. 8090 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8091 } 8092 8093 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8094 // FIXME: Deal with vectors as array subscript bases. 8095 if (E->getBase()->getType()->isVectorType()) 8096 return Error(E); 8097 8098 APSInt Index; 8099 bool Success = true; 8100 8101 // C++17's rules require us to evaluate the LHS first, regardless of which 8102 // side is the base. 8103 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8104 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8105 : !EvaluateInteger(SubExpr, Index, Info)) { 8106 if (!Info.noteFailure()) 8107 return false; 8108 Success = false; 8109 } 8110 } 8111 8112 return Success && 8113 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8114 } 8115 8116 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8117 return evaluatePointer(E->getSubExpr(), Result); 8118 } 8119 8120 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8121 if (!Visit(E->getSubExpr())) 8122 return false; 8123 // __real is a no-op on scalar lvalues. 8124 if (E->getSubExpr()->getType()->isAnyComplexType()) 8125 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8126 return true; 8127 } 8128 8129 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8130 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8131 "lvalue __imag__ on scalar?"); 8132 if (!Visit(E->getSubExpr())) 8133 return false; 8134 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8135 return true; 8136 } 8137 8138 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8139 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8140 return Error(UO); 8141 8142 if (!this->Visit(UO->getSubExpr())) 8143 return false; 8144 8145 return handleIncDec( 8146 this->Info, UO, Result, UO->getSubExpr()->getType(), 8147 UO->isIncrementOp(), nullptr); 8148 } 8149 8150 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8151 const CompoundAssignOperator *CAO) { 8152 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8153 return Error(CAO); 8154 8155 // C++17 onwards require that we evaluate the RHS first. 8156 APValue RHS; 8157 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 8158 return false; 8159 8160 // The overall lvalue result is the result of evaluating the LHS. 8161 if (!this->Visit(CAO->getLHS())) { 8162 if (Info.noteFailure()) 8163 Evaluate(RHS, this->Info, CAO->getRHS()); 8164 return false; 8165 } 8166 8167 return handleCompoundAssignment( 8168 this->Info, CAO, 8169 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8170 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8171 } 8172 8173 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8174 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8175 return Error(E); 8176 8177 // C++17 onwards require that we evaluate the RHS first. 8178 APValue NewVal; 8179 if (!Evaluate(NewVal, this->Info, E->getRHS())) 8180 return false; 8181 8182 if (!this->Visit(E->getLHS())) { 8183 if (Info.noteFailure()) 8184 Evaluate(NewVal, this->Info, E->getRHS()); 8185 return false; 8186 } 8187 8188 if (Info.getLangOpts().CPlusPlus20 && 8189 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8190 return false; 8191 8192 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8193 NewVal); 8194 } 8195 8196 //===----------------------------------------------------------------------===// 8197 // Pointer Evaluation 8198 //===----------------------------------------------------------------------===// 8199 8200 /// Attempts to compute the number of bytes available at the pointer 8201 /// returned by a function with the alloc_size attribute. Returns true if we 8202 /// were successful. Places an unsigned number into `Result`. 8203 /// 8204 /// This expects the given CallExpr to be a call to a function with an 8205 /// alloc_size attribute. 8206 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8207 const CallExpr *Call, 8208 llvm::APInt &Result) { 8209 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8210 8211 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8212 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8213 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8214 if (Call->getNumArgs() <= SizeArgNo) 8215 return false; 8216 8217 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8218 Expr::EvalResult ExprResult; 8219 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8220 return false; 8221 Into = ExprResult.Val.getInt(); 8222 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8223 return false; 8224 Into = Into.zextOrSelf(BitsInSizeT); 8225 return true; 8226 }; 8227 8228 APSInt SizeOfElem; 8229 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8230 return false; 8231 8232 if (!AllocSize->getNumElemsParam().isValid()) { 8233 Result = std::move(SizeOfElem); 8234 return true; 8235 } 8236 8237 APSInt NumberOfElems; 8238 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8239 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8240 return false; 8241 8242 bool Overflow; 8243 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8244 if (Overflow) 8245 return false; 8246 8247 Result = std::move(BytesAvailable); 8248 return true; 8249 } 8250 8251 /// Convenience function. LVal's base must be a call to an alloc_size 8252 /// function. 8253 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8254 const LValue &LVal, 8255 llvm::APInt &Result) { 8256 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8257 "Can't get the size of a non alloc_size function"); 8258 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8259 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8260 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8261 } 8262 8263 /// Attempts to evaluate the given LValueBase as the result of a call to 8264 /// a function with the alloc_size attribute. If it was possible to do so, this 8265 /// function will return true, make Result's Base point to said function call, 8266 /// and mark Result's Base as invalid. 8267 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8268 LValue &Result) { 8269 if (Base.isNull()) 8270 return false; 8271 8272 // Because we do no form of static analysis, we only support const variables. 8273 // 8274 // Additionally, we can't support parameters, nor can we support static 8275 // variables (in the latter case, use-before-assign isn't UB; in the former, 8276 // we have no clue what they'll be assigned to). 8277 const auto *VD = 8278 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8279 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8280 return false; 8281 8282 const Expr *Init = VD->getAnyInitializer(); 8283 if (!Init) 8284 return false; 8285 8286 const Expr *E = Init->IgnoreParens(); 8287 if (!tryUnwrapAllocSizeCall(E)) 8288 return false; 8289 8290 // Store E instead of E unwrapped so that the type of the LValue's base is 8291 // what the user wanted. 8292 Result.setInvalid(E); 8293 8294 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8295 Result.addUnsizedArray(Info, E, Pointee); 8296 return true; 8297 } 8298 8299 namespace { 8300 class PointerExprEvaluator 8301 : public ExprEvaluatorBase<PointerExprEvaluator> { 8302 LValue &Result; 8303 bool InvalidBaseOK; 8304 8305 bool Success(const Expr *E) { 8306 Result.set(E); 8307 return true; 8308 } 8309 8310 bool evaluateLValue(const Expr *E, LValue &Result) { 8311 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8312 } 8313 8314 bool evaluatePointer(const Expr *E, LValue &Result) { 8315 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8316 } 8317 8318 bool visitNonBuiltinCallExpr(const CallExpr *E); 8319 public: 8320 8321 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8322 : ExprEvaluatorBaseTy(info), Result(Result), 8323 InvalidBaseOK(InvalidBaseOK) {} 8324 8325 bool Success(const APValue &V, const Expr *E) { 8326 Result.setFrom(Info.Ctx, V); 8327 return true; 8328 } 8329 bool ZeroInitialization(const Expr *E) { 8330 Result.setNull(Info.Ctx, E->getType()); 8331 return true; 8332 } 8333 8334 bool VisitBinaryOperator(const BinaryOperator *E); 8335 bool VisitCastExpr(const CastExpr* E); 8336 bool VisitUnaryAddrOf(const UnaryOperator *E); 8337 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8338 { return Success(E); } 8339 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8340 if (E->isExpressibleAsConstantInitializer()) 8341 return Success(E); 8342 if (Info.noteFailure()) 8343 EvaluateIgnoredValue(Info, E->getSubExpr()); 8344 return Error(E); 8345 } 8346 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8347 { return Success(E); } 8348 bool VisitCallExpr(const CallExpr *E); 8349 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8350 bool VisitBlockExpr(const BlockExpr *E) { 8351 if (!E->getBlockDecl()->hasCaptures()) 8352 return Success(E); 8353 return Error(E); 8354 } 8355 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8356 // Can't look at 'this' when checking a potential constant expression. 8357 if (Info.checkingPotentialConstantExpression()) 8358 return false; 8359 if (!Info.CurrentCall->This) { 8360 if (Info.getLangOpts().CPlusPlus11) 8361 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8362 else 8363 Info.FFDiag(E); 8364 return false; 8365 } 8366 Result = *Info.CurrentCall->This; 8367 // If we are inside a lambda's call operator, the 'this' expression refers 8368 // to the enclosing '*this' object (either by value or reference) which is 8369 // either copied into the closure object's field that represents the '*this' 8370 // or refers to '*this'. 8371 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8372 // Ensure we actually have captured 'this'. (an error will have 8373 // been previously reported if not). 8374 if (!Info.CurrentCall->LambdaThisCaptureField) 8375 return false; 8376 8377 // Update 'Result' to refer to the data member/field of the closure object 8378 // that represents the '*this' capture. 8379 if (!HandleLValueMember(Info, E, Result, 8380 Info.CurrentCall->LambdaThisCaptureField)) 8381 return false; 8382 // If we captured '*this' by reference, replace the field with its referent. 8383 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8384 ->isPointerType()) { 8385 APValue RVal; 8386 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8387 RVal)) 8388 return false; 8389 8390 Result.setFrom(Info.Ctx, RVal); 8391 } 8392 } 8393 return true; 8394 } 8395 8396 bool VisitCXXNewExpr(const CXXNewExpr *E); 8397 8398 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8399 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8400 APValue LValResult = E->EvaluateInContext( 8401 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8402 Result.setFrom(Info.Ctx, LValResult); 8403 return true; 8404 } 8405 8406 // FIXME: Missing: @protocol, @selector 8407 }; 8408 } // end anonymous namespace 8409 8410 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8411 bool InvalidBaseOK) { 8412 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8413 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8414 } 8415 8416 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8417 if (E->getOpcode() != BO_Add && 8418 E->getOpcode() != BO_Sub) 8419 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8420 8421 const Expr *PExp = E->getLHS(); 8422 const Expr *IExp = E->getRHS(); 8423 if (IExp->getType()->isPointerType()) 8424 std::swap(PExp, IExp); 8425 8426 bool EvalPtrOK = evaluatePointer(PExp, Result); 8427 if (!EvalPtrOK && !Info.noteFailure()) 8428 return false; 8429 8430 llvm::APSInt Offset; 8431 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8432 return false; 8433 8434 if (E->getOpcode() == BO_Sub) 8435 negateAsSigned(Offset); 8436 8437 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8438 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8439 } 8440 8441 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8442 return evaluateLValue(E->getSubExpr(), Result); 8443 } 8444 8445 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8446 const Expr *SubExpr = E->getSubExpr(); 8447 8448 switch (E->getCastKind()) { 8449 default: 8450 break; 8451 case CK_BitCast: 8452 case CK_CPointerToObjCPointerCast: 8453 case CK_BlockPointerToObjCPointerCast: 8454 case CK_AnyPointerToBlockPointerCast: 8455 case CK_AddressSpaceConversion: 8456 if (!Visit(SubExpr)) 8457 return false; 8458 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8459 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8460 // also static_casts, but we disallow them as a resolution to DR1312. 8461 if (!E->getType()->isVoidPointerType()) { 8462 if (!Result.InvalidBase && !Result.Designator.Invalid && 8463 !Result.IsNullPtr && 8464 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8465 E->getType()->getPointeeType()) && 8466 Info.getStdAllocatorCaller("allocate")) { 8467 // Inside a call to std::allocator::allocate and friends, we permit 8468 // casting from void* back to cv1 T* for a pointer that points to a 8469 // cv2 T. 8470 } else { 8471 Result.Designator.setInvalid(); 8472 if (SubExpr->getType()->isVoidPointerType()) 8473 CCEDiag(E, diag::note_constexpr_invalid_cast) 8474 << 3 << SubExpr->getType(); 8475 else 8476 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8477 } 8478 } 8479 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8480 ZeroInitialization(E); 8481 return true; 8482 8483 case CK_DerivedToBase: 8484 case CK_UncheckedDerivedToBase: 8485 if (!evaluatePointer(E->getSubExpr(), Result)) 8486 return false; 8487 if (!Result.Base && Result.Offset.isZero()) 8488 return true; 8489 8490 // Now figure out the necessary offset to add to the base LV to get from 8491 // the derived class to the base class. 8492 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8493 castAs<PointerType>()->getPointeeType(), 8494 Result); 8495 8496 case CK_BaseToDerived: 8497 if (!Visit(E->getSubExpr())) 8498 return false; 8499 if (!Result.Base && Result.Offset.isZero()) 8500 return true; 8501 return HandleBaseToDerivedCast(Info, E, Result); 8502 8503 case CK_Dynamic: 8504 if (!Visit(E->getSubExpr())) 8505 return false; 8506 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8507 8508 case CK_NullToPointer: 8509 VisitIgnoredValue(E->getSubExpr()); 8510 return ZeroInitialization(E); 8511 8512 case CK_IntegralToPointer: { 8513 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8514 8515 APValue Value; 8516 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8517 break; 8518 8519 if (Value.isInt()) { 8520 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8521 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8522 Result.Base = (Expr*)nullptr; 8523 Result.InvalidBase = false; 8524 Result.Offset = CharUnits::fromQuantity(N); 8525 Result.Designator.setInvalid(); 8526 Result.IsNullPtr = false; 8527 return true; 8528 } else { 8529 // Cast is of an lvalue, no need to change value. 8530 Result.setFrom(Info.Ctx, Value); 8531 return true; 8532 } 8533 } 8534 8535 case CK_ArrayToPointerDecay: { 8536 if (SubExpr->isGLValue()) { 8537 if (!evaluateLValue(SubExpr, Result)) 8538 return false; 8539 } else { 8540 APValue &Value = Info.CurrentCall->createTemporary( 8541 SubExpr, SubExpr->getType(), false, Result); 8542 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8543 return false; 8544 } 8545 // The result is a pointer to the first element of the array. 8546 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8547 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8548 Result.addArray(Info, E, CAT); 8549 else 8550 Result.addUnsizedArray(Info, E, AT->getElementType()); 8551 return true; 8552 } 8553 8554 case CK_FunctionToPointerDecay: 8555 return evaluateLValue(SubExpr, Result); 8556 8557 case CK_LValueToRValue: { 8558 LValue LVal; 8559 if (!evaluateLValue(E->getSubExpr(), LVal)) 8560 return false; 8561 8562 APValue RVal; 8563 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8564 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8565 LVal, RVal)) 8566 return InvalidBaseOK && 8567 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8568 return Success(RVal, E); 8569 } 8570 } 8571 8572 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8573 } 8574 8575 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8576 UnaryExprOrTypeTrait ExprKind) { 8577 // C++ [expr.alignof]p3: 8578 // When alignof is applied to a reference type, the result is the 8579 // alignment of the referenced type. 8580 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8581 T = Ref->getPointeeType(); 8582 8583 if (T.getQualifiers().hasUnaligned()) 8584 return CharUnits::One(); 8585 8586 const bool AlignOfReturnsPreferred = 8587 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8588 8589 // __alignof is defined to return the preferred alignment. 8590 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8591 // as well. 8592 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8593 return Info.Ctx.toCharUnitsFromBits( 8594 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8595 // alignof and _Alignof are defined to return the ABI alignment. 8596 else if (ExprKind == UETT_AlignOf) 8597 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8598 else 8599 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8600 } 8601 8602 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8603 UnaryExprOrTypeTrait ExprKind) { 8604 E = E->IgnoreParens(); 8605 8606 // The kinds of expressions that we have special-case logic here for 8607 // should be kept up to date with the special checks for those 8608 // expressions in Sema. 8609 8610 // alignof decl is always accepted, even if it doesn't make sense: we default 8611 // to 1 in those cases. 8612 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8613 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8614 /*RefAsPointee*/true); 8615 8616 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8617 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8618 /*RefAsPointee*/true); 8619 8620 return GetAlignOfType(Info, E->getType(), ExprKind); 8621 } 8622 8623 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8624 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8625 return Info.Ctx.getDeclAlign(VD); 8626 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8627 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8628 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8629 } 8630 8631 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8632 /// __builtin_is_aligned and __builtin_assume_aligned. 8633 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8634 EvalInfo &Info, APSInt &Alignment) { 8635 if (!EvaluateInteger(E, Alignment, Info)) 8636 return false; 8637 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8638 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8639 return false; 8640 } 8641 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8642 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8643 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8644 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8645 << MaxValue << ForType << Alignment; 8646 return false; 8647 } 8648 // Ensure both alignment and source value have the same bit width so that we 8649 // don't assert when computing the resulting value. 8650 APSInt ExtAlignment = 8651 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8652 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8653 "Alignment should not be changed by ext/trunc"); 8654 Alignment = ExtAlignment; 8655 assert(Alignment.getBitWidth() == SrcWidth); 8656 return true; 8657 } 8658 8659 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8660 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8661 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8662 return true; 8663 8664 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8665 return false; 8666 8667 Result.setInvalid(E); 8668 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8669 Result.addUnsizedArray(Info, E, PointeeTy); 8670 return true; 8671 } 8672 8673 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8674 if (IsStringLiteralCall(E)) 8675 return Success(E); 8676 8677 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8678 return VisitBuiltinCallExpr(E, BuiltinOp); 8679 8680 return visitNonBuiltinCallExpr(E); 8681 } 8682 8683 // Determine if T is a character type for which we guarantee that 8684 // sizeof(T) == 1. 8685 static bool isOneByteCharacterType(QualType T) { 8686 return T->isCharType() || T->isChar8Type(); 8687 } 8688 8689 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8690 unsigned BuiltinOp) { 8691 switch (BuiltinOp) { 8692 case Builtin::BI__builtin_addressof: 8693 return evaluateLValue(E->getArg(0), Result); 8694 case Builtin::BI__builtin_assume_aligned: { 8695 // We need to be very careful here because: if the pointer does not have the 8696 // asserted alignment, then the behavior is undefined, and undefined 8697 // behavior is non-constant. 8698 if (!evaluatePointer(E->getArg(0), Result)) 8699 return false; 8700 8701 LValue OffsetResult(Result); 8702 APSInt Alignment; 8703 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8704 Alignment)) 8705 return false; 8706 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8707 8708 if (E->getNumArgs() > 2) { 8709 APSInt Offset; 8710 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8711 return false; 8712 8713 int64_t AdditionalOffset = -Offset.getZExtValue(); 8714 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8715 } 8716 8717 // If there is a base object, then it must have the correct alignment. 8718 if (OffsetResult.Base) { 8719 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 8720 8721 if (BaseAlignment < Align) { 8722 Result.Designator.setInvalid(); 8723 // FIXME: Add support to Diagnostic for long / long long. 8724 CCEDiag(E->getArg(0), 8725 diag::note_constexpr_baa_insufficient_alignment) << 0 8726 << (unsigned)BaseAlignment.getQuantity() 8727 << (unsigned)Align.getQuantity(); 8728 return false; 8729 } 8730 } 8731 8732 // The offset must also have the correct alignment. 8733 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 8734 Result.Designator.setInvalid(); 8735 8736 (OffsetResult.Base 8737 ? CCEDiag(E->getArg(0), 8738 diag::note_constexpr_baa_insufficient_alignment) << 1 8739 : CCEDiag(E->getArg(0), 8740 diag::note_constexpr_baa_value_insufficient_alignment)) 8741 << (int)OffsetResult.Offset.getQuantity() 8742 << (unsigned)Align.getQuantity(); 8743 return false; 8744 } 8745 8746 return true; 8747 } 8748 case Builtin::BI__builtin_align_up: 8749 case Builtin::BI__builtin_align_down: { 8750 if (!evaluatePointer(E->getArg(0), Result)) 8751 return false; 8752 APSInt Alignment; 8753 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8754 Alignment)) 8755 return false; 8756 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 8757 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 8758 // For align_up/align_down, we can return the same value if the alignment 8759 // is known to be greater or equal to the requested value. 8760 if (PtrAlign.getQuantity() >= Alignment) 8761 return true; 8762 8763 // The alignment could be greater than the minimum at run-time, so we cannot 8764 // infer much about the resulting pointer value. One case is possible: 8765 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 8766 // can infer the correct index if the requested alignment is smaller than 8767 // the base alignment so we can perform the computation on the offset. 8768 if (BaseAlignment.getQuantity() >= Alignment) { 8769 assert(Alignment.getBitWidth() <= 64 && 8770 "Cannot handle > 64-bit address-space"); 8771 uint64_t Alignment64 = Alignment.getZExtValue(); 8772 CharUnits NewOffset = CharUnits::fromQuantity( 8773 BuiltinOp == Builtin::BI__builtin_align_down 8774 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 8775 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 8776 Result.adjustOffset(NewOffset - Result.Offset); 8777 // TODO: diagnose out-of-bounds values/only allow for arrays? 8778 return true; 8779 } 8780 // Otherwise, we cannot constant-evaluate the result. 8781 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 8782 << Alignment; 8783 return false; 8784 } 8785 case Builtin::BI__builtin_operator_new: 8786 return HandleOperatorNewCall(Info, E, Result); 8787 case Builtin::BI__builtin_launder: 8788 return evaluatePointer(E->getArg(0), Result); 8789 case Builtin::BIstrchr: 8790 case Builtin::BIwcschr: 8791 case Builtin::BImemchr: 8792 case Builtin::BIwmemchr: 8793 if (Info.getLangOpts().CPlusPlus11) 8794 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8795 << /*isConstexpr*/0 << /*isConstructor*/0 8796 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8797 else 8798 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8799 LLVM_FALLTHROUGH; 8800 case Builtin::BI__builtin_strchr: 8801 case Builtin::BI__builtin_wcschr: 8802 case Builtin::BI__builtin_memchr: 8803 case Builtin::BI__builtin_char_memchr: 8804 case Builtin::BI__builtin_wmemchr: { 8805 if (!Visit(E->getArg(0))) 8806 return false; 8807 APSInt Desired; 8808 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 8809 return false; 8810 uint64_t MaxLength = uint64_t(-1); 8811 if (BuiltinOp != Builtin::BIstrchr && 8812 BuiltinOp != Builtin::BIwcschr && 8813 BuiltinOp != Builtin::BI__builtin_strchr && 8814 BuiltinOp != Builtin::BI__builtin_wcschr) { 8815 APSInt N; 8816 if (!EvaluateInteger(E->getArg(2), N, Info)) 8817 return false; 8818 MaxLength = N.getExtValue(); 8819 } 8820 // We cannot find the value if there are no candidates to match against. 8821 if (MaxLength == 0u) 8822 return ZeroInitialization(E); 8823 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 8824 Result.Designator.Invalid) 8825 return false; 8826 QualType CharTy = Result.Designator.getType(Info.Ctx); 8827 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 8828 BuiltinOp == Builtin::BI__builtin_memchr; 8829 assert(IsRawByte || 8830 Info.Ctx.hasSameUnqualifiedType( 8831 CharTy, E->getArg(0)->getType()->getPointeeType())); 8832 // Pointers to const void may point to objects of incomplete type. 8833 if (IsRawByte && CharTy->isIncompleteType()) { 8834 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 8835 return false; 8836 } 8837 // Give up on byte-oriented matching against multibyte elements. 8838 // FIXME: We can compare the bytes in the correct order. 8839 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 8840 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 8841 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 8842 << CharTy; 8843 return false; 8844 } 8845 // Figure out what value we're actually looking for (after converting to 8846 // the corresponding unsigned type if necessary). 8847 uint64_t DesiredVal; 8848 bool StopAtNull = false; 8849 switch (BuiltinOp) { 8850 case Builtin::BIstrchr: 8851 case Builtin::BI__builtin_strchr: 8852 // strchr compares directly to the passed integer, and therefore 8853 // always fails if given an int that is not a char. 8854 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 8855 E->getArg(1)->getType(), 8856 Desired), 8857 Desired)) 8858 return ZeroInitialization(E); 8859 StopAtNull = true; 8860 LLVM_FALLTHROUGH; 8861 case Builtin::BImemchr: 8862 case Builtin::BI__builtin_memchr: 8863 case Builtin::BI__builtin_char_memchr: 8864 // memchr compares by converting both sides to unsigned char. That's also 8865 // correct for strchr if we get this far (to cope with plain char being 8866 // unsigned in the strchr case). 8867 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 8868 break; 8869 8870 case Builtin::BIwcschr: 8871 case Builtin::BI__builtin_wcschr: 8872 StopAtNull = true; 8873 LLVM_FALLTHROUGH; 8874 case Builtin::BIwmemchr: 8875 case Builtin::BI__builtin_wmemchr: 8876 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 8877 DesiredVal = Desired.getZExtValue(); 8878 break; 8879 } 8880 8881 for (; MaxLength; --MaxLength) { 8882 APValue Char; 8883 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 8884 !Char.isInt()) 8885 return false; 8886 if (Char.getInt().getZExtValue() == DesiredVal) 8887 return true; 8888 if (StopAtNull && !Char.getInt()) 8889 break; 8890 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 8891 return false; 8892 } 8893 // Not found: return nullptr. 8894 return ZeroInitialization(E); 8895 } 8896 8897 case Builtin::BImemcpy: 8898 case Builtin::BImemmove: 8899 case Builtin::BIwmemcpy: 8900 case Builtin::BIwmemmove: 8901 if (Info.getLangOpts().CPlusPlus11) 8902 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8903 << /*isConstexpr*/0 << /*isConstructor*/0 8904 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8905 else 8906 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8907 LLVM_FALLTHROUGH; 8908 case Builtin::BI__builtin_memcpy: 8909 case Builtin::BI__builtin_memmove: 8910 case Builtin::BI__builtin_wmemcpy: 8911 case Builtin::BI__builtin_wmemmove: { 8912 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 8913 BuiltinOp == Builtin::BIwmemmove || 8914 BuiltinOp == Builtin::BI__builtin_wmemcpy || 8915 BuiltinOp == Builtin::BI__builtin_wmemmove; 8916 bool Move = BuiltinOp == Builtin::BImemmove || 8917 BuiltinOp == Builtin::BIwmemmove || 8918 BuiltinOp == Builtin::BI__builtin_memmove || 8919 BuiltinOp == Builtin::BI__builtin_wmemmove; 8920 8921 // The result of mem* is the first argument. 8922 if (!Visit(E->getArg(0))) 8923 return false; 8924 LValue Dest = Result; 8925 8926 LValue Src; 8927 if (!EvaluatePointer(E->getArg(1), Src, Info)) 8928 return false; 8929 8930 APSInt N; 8931 if (!EvaluateInteger(E->getArg(2), N, Info)) 8932 return false; 8933 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 8934 8935 // If the size is zero, we treat this as always being a valid no-op. 8936 // (Even if one of the src and dest pointers is null.) 8937 if (!N) 8938 return true; 8939 8940 // Otherwise, if either of the operands is null, we can't proceed. Don't 8941 // try to determine the type of the copied objects, because there aren't 8942 // any. 8943 if (!Src.Base || !Dest.Base) { 8944 APValue Val; 8945 (!Src.Base ? Src : Dest).moveInto(Val); 8946 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 8947 << Move << WChar << !!Src.Base 8948 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 8949 return false; 8950 } 8951 if (Src.Designator.Invalid || Dest.Designator.Invalid) 8952 return false; 8953 8954 // We require that Src and Dest are both pointers to arrays of 8955 // trivially-copyable type. (For the wide version, the designator will be 8956 // invalid if the designated object is not a wchar_t.) 8957 QualType T = Dest.Designator.getType(Info.Ctx); 8958 QualType SrcT = Src.Designator.getType(Info.Ctx); 8959 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 8960 // FIXME: Consider using our bit_cast implementation to support this. 8961 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 8962 return false; 8963 } 8964 if (T->isIncompleteType()) { 8965 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 8966 return false; 8967 } 8968 if (!T.isTriviallyCopyableType(Info.Ctx)) { 8969 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 8970 return false; 8971 } 8972 8973 // Figure out how many T's we're copying. 8974 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 8975 if (!WChar) { 8976 uint64_t Remainder; 8977 llvm::APInt OrigN = N; 8978 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 8979 if (Remainder) { 8980 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8981 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 8982 << (unsigned)TSize; 8983 return false; 8984 } 8985 } 8986 8987 // Check that the copying will remain within the arrays, just so that we 8988 // can give a more meaningful diagnostic. This implicitly also checks that 8989 // N fits into 64 bits. 8990 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 8991 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 8992 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 8993 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8994 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 8995 << N.toString(10, /*Signed*/false); 8996 return false; 8997 } 8998 uint64_t NElems = N.getZExtValue(); 8999 uint64_t NBytes = NElems * TSize; 9000 9001 // Check for overlap. 9002 int Direction = 1; 9003 if (HasSameBase(Src, Dest)) { 9004 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9005 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9006 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9007 // Dest is inside the source region. 9008 if (!Move) { 9009 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9010 return false; 9011 } 9012 // For memmove and friends, copy backwards. 9013 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9014 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9015 return false; 9016 Direction = -1; 9017 } else if (!Move && SrcOffset >= DestOffset && 9018 SrcOffset - DestOffset < NBytes) { 9019 // Src is inside the destination region for memcpy: invalid. 9020 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9021 return false; 9022 } 9023 } 9024 9025 while (true) { 9026 APValue Val; 9027 // FIXME: Set WantObjectRepresentation to true if we're copying a 9028 // char-like type? 9029 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9030 !handleAssignment(Info, E, Dest, T, Val)) 9031 return false; 9032 // Do not iterate past the last element; if we're copying backwards, that 9033 // might take us off the start of the array. 9034 if (--NElems == 0) 9035 return true; 9036 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9037 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9038 return false; 9039 } 9040 } 9041 9042 default: 9043 break; 9044 } 9045 9046 return visitNonBuiltinCallExpr(E); 9047 } 9048 9049 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9050 APValue &Result, const InitListExpr *ILE, 9051 QualType AllocType); 9052 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9053 APValue &Result, 9054 const CXXConstructExpr *CCE, 9055 QualType AllocType); 9056 9057 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9058 if (!Info.getLangOpts().CPlusPlus20) 9059 Info.CCEDiag(E, diag::note_constexpr_new); 9060 9061 // We cannot speculatively evaluate a delete expression. 9062 if (Info.SpeculativeEvaluationDepth) 9063 return false; 9064 9065 FunctionDecl *OperatorNew = E->getOperatorNew(); 9066 9067 bool IsNothrow = false; 9068 bool IsPlacement = false; 9069 if (OperatorNew->isReservedGlobalPlacementOperator() && 9070 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9071 // FIXME Support array placement new. 9072 assert(E->getNumPlacementArgs() == 1); 9073 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9074 return false; 9075 if (Result.Designator.Invalid) 9076 return false; 9077 IsPlacement = true; 9078 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9079 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9080 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9081 return false; 9082 } else if (E->getNumPlacementArgs()) { 9083 // The only new-placement list we support is of the form (std::nothrow). 9084 // 9085 // FIXME: There is no restriction on this, but it's not clear that any 9086 // other form makes any sense. We get here for cases such as: 9087 // 9088 // new (std::align_val_t{N}) X(int) 9089 // 9090 // (which should presumably be valid only if N is a multiple of 9091 // alignof(int), and in any case can't be deallocated unless N is 9092 // alignof(X) and X has new-extended alignment). 9093 if (E->getNumPlacementArgs() != 1 || 9094 !E->getPlacementArg(0)->getType()->isNothrowT()) 9095 return Error(E, diag::note_constexpr_new_placement); 9096 9097 LValue Nothrow; 9098 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9099 return false; 9100 IsNothrow = true; 9101 } 9102 9103 const Expr *Init = E->getInitializer(); 9104 const InitListExpr *ResizedArrayILE = nullptr; 9105 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9106 bool ValueInit = false; 9107 9108 QualType AllocType = E->getAllocatedType(); 9109 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9110 const Expr *Stripped = *ArraySize; 9111 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9112 Stripped = ICE->getSubExpr()) 9113 if (ICE->getCastKind() != CK_NoOp && 9114 ICE->getCastKind() != CK_IntegralCast) 9115 break; 9116 9117 llvm::APSInt ArrayBound; 9118 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9119 return false; 9120 9121 // C++ [expr.new]p9: 9122 // The expression is erroneous if: 9123 // -- [...] its value before converting to size_t [or] applying the 9124 // second standard conversion sequence is less than zero 9125 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9126 if (IsNothrow) 9127 return ZeroInitialization(E); 9128 9129 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9130 << ArrayBound << (*ArraySize)->getSourceRange(); 9131 return false; 9132 } 9133 9134 // -- its value is such that the size of the allocated object would 9135 // exceed the implementation-defined limit 9136 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9137 ArrayBound) > 9138 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9139 if (IsNothrow) 9140 return ZeroInitialization(E); 9141 9142 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9143 << ArrayBound << (*ArraySize)->getSourceRange(); 9144 return false; 9145 } 9146 9147 // -- the new-initializer is a braced-init-list and the number of 9148 // array elements for which initializers are provided [...] 9149 // exceeds the number of elements to initialize 9150 if (!Init) { 9151 // No initialization is performed. 9152 } else if (isa<CXXScalarValueInitExpr>(Init) || 9153 isa<ImplicitValueInitExpr>(Init)) { 9154 ValueInit = true; 9155 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9156 ResizedArrayCCE = CCE; 9157 } else { 9158 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9159 assert(CAT && "unexpected type for array initializer"); 9160 9161 unsigned Bits = 9162 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9163 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9164 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9165 if (InitBound.ugt(AllocBound)) { 9166 if (IsNothrow) 9167 return ZeroInitialization(E); 9168 9169 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9170 << AllocBound.toString(10, /*Signed=*/false) 9171 << InitBound.toString(10, /*Signed=*/false) 9172 << (*ArraySize)->getSourceRange(); 9173 return false; 9174 } 9175 9176 // If the sizes differ, we must have an initializer list, and we need 9177 // special handling for this case when we initialize. 9178 if (InitBound != AllocBound) 9179 ResizedArrayILE = cast<InitListExpr>(Init); 9180 } 9181 9182 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9183 ArrayType::Normal, 0); 9184 } else { 9185 assert(!AllocType->isArrayType() && 9186 "array allocation with non-array new"); 9187 } 9188 9189 APValue *Val; 9190 if (IsPlacement) { 9191 AccessKinds AK = AK_Construct; 9192 struct FindObjectHandler { 9193 EvalInfo &Info; 9194 const Expr *E; 9195 QualType AllocType; 9196 const AccessKinds AccessKind; 9197 APValue *Value; 9198 9199 typedef bool result_type; 9200 bool failed() { return false; } 9201 bool found(APValue &Subobj, QualType SubobjType) { 9202 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9203 // old name of the object to be used to name the new object. 9204 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9205 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9206 SubobjType << AllocType; 9207 return false; 9208 } 9209 Value = &Subobj; 9210 return true; 9211 } 9212 bool found(APSInt &Value, QualType SubobjType) { 9213 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9214 return false; 9215 } 9216 bool found(APFloat &Value, QualType SubobjType) { 9217 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9218 return false; 9219 } 9220 } Handler = {Info, E, AllocType, AK, nullptr}; 9221 9222 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9223 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9224 return false; 9225 9226 Val = Handler.Value; 9227 9228 // [basic.life]p1: 9229 // The lifetime of an object o of type T ends when [...] the storage 9230 // which the object occupies is [...] reused by an object that is not 9231 // nested within o (6.6.2). 9232 *Val = APValue(); 9233 } else { 9234 // Perform the allocation and obtain a pointer to the resulting object. 9235 Val = Info.createHeapAlloc(E, AllocType, Result); 9236 if (!Val) 9237 return false; 9238 } 9239 9240 if (ValueInit) { 9241 ImplicitValueInitExpr VIE(AllocType); 9242 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9243 return false; 9244 } else if (ResizedArrayILE) { 9245 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9246 AllocType)) 9247 return false; 9248 } else if (ResizedArrayCCE) { 9249 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9250 AllocType)) 9251 return false; 9252 } else if (Init) { 9253 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9254 return false; 9255 } else if (!getDefaultInitValue(AllocType, *Val)) { 9256 return false; 9257 } 9258 9259 // Array new returns a pointer to the first element, not a pointer to the 9260 // array. 9261 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9262 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9263 9264 return true; 9265 } 9266 //===----------------------------------------------------------------------===// 9267 // Member Pointer Evaluation 9268 //===----------------------------------------------------------------------===// 9269 9270 namespace { 9271 class MemberPointerExprEvaluator 9272 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9273 MemberPtr &Result; 9274 9275 bool Success(const ValueDecl *D) { 9276 Result = MemberPtr(D); 9277 return true; 9278 } 9279 public: 9280 9281 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9282 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9283 9284 bool Success(const APValue &V, const Expr *E) { 9285 Result.setFrom(V); 9286 return true; 9287 } 9288 bool ZeroInitialization(const Expr *E) { 9289 return Success((const ValueDecl*)nullptr); 9290 } 9291 9292 bool VisitCastExpr(const CastExpr *E); 9293 bool VisitUnaryAddrOf(const UnaryOperator *E); 9294 }; 9295 } // end anonymous namespace 9296 9297 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9298 EvalInfo &Info) { 9299 assert(E->isRValue() && E->getType()->isMemberPointerType()); 9300 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9301 } 9302 9303 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9304 switch (E->getCastKind()) { 9305 default: 9306 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9307 9308 case CK_NullToMemberPointer: 9309 VisitIgnoredValue(E->getSubExpr()); 9310 return ZeroInitialization(E); 9311 9312 case CK_BaseToDerivedMemberPointer: { 9313 if (!Visit(E->getSubExpr())) 9314 return false; 9315 if (E->path_empty()) 9316 return true; 9317 // Base-to-derived member pointer casts store the path in derived-to-base 9318 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9319 // the wrong end of the derived->base arc, so stagger the path by one class. 9320 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9321 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9322 PathI != PathE; ++PathI) { 9323 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9324 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9325 if (!Result.castToDerived(Derived)) 9326 return Error(E); 9327 } 9328 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9329 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9330 return Error(E); 9331 return true; 9332 } 9333 9334 case CK_DerivedToBaseMemberPointer: 9335 if (!Visit(E->getSubExpr())) 9336 return false; 9337 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9338 PathE = E->path_end(); PathI != PathE; ++PathI) { 9339 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9340 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9341 if (!Result.castToBase(Base)) 9342 return Error(E); 9343 } 9344 return true; 9345 } 9346 } 9347 9348 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9349 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9350 // member can be formed. 9351 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9352 } 9353 9354 //===----------------------------------------------------------------------===// 9355 // Record Evaluation 9356 //===----------------------------------------------------------------------===// 9357 9358 namespace { 9359 class RecordExprEvaluator 9360 : public ExprEvaluatorBase<RecordExprEvaluator> { 9361 const LValue &This; 9362 APValue &Result; 9363 public: 9364 9365 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9366 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9367 9368 bool Success(const APValue &V, const Expr *E) { 9369 Result = V; 9370 return true; 9371 } 9372 bool ZeroInitialization(const Expr *E) { 9373 return ZeroInitialization(E, E->getType()); 9374 } 9375 bool ZeroInitialization(const Expr *E, QualType T); 9376 9377 bool VisitCallExpr(const CallExpr *E) { 9378 return handleCallExpr(E, Result, &This); 9379 } 9380 bool VisitCastExpr(const CastExpr *E); 9381 bool VisitInitListExpr(const InitListExpr *E); 9382 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9383 return VisitCXXConstructExpr(E, E->getType()); 9384 } 9385 bool VisitLambdaExpr(const LambdaExpr *E); 9386 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9387 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9388 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9389 bool VisitBinCmp(const BinaryOperator *E); 9390 }; 9391 } 9392 9393 /// Perform zero-initialization on an object of non-union class type. 9394 /// C++11 [dcl.init]p5: 9395 /// To zero-initialize an object or reference of type T means: 9396 /// [...] 9397 /// -- if T is a (possibly cv-qualified) non-union class type, 9398 /// each non-static data member and each base-class subobject is 9399 /// zero-initialized 9400 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9401 const RecordDecl *RD, 9402 const LValue &This, APValue &Result) { 9403 assert(!RD->isUnion() && "Expected non-union class type"); 9404 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9405 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9406 std::distance(RD->field_begin(), RD->field_end())); 9407 9408 if (RD->isInvalidDecl()) return false; 9409 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9410 9411 if (CD) { 9412 unsigned Index = 0; 9413 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9414 End = CD->bases_end(); I != End; ++I, ++Index) { 9415 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9416 LValue Subobject = This; 9417 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9418 return false; 9419 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9420 Result.getStructBase(Index))) 9421 return false; 9422 } 9423 } 9424 9425 for (const auto *I : RD->fields()) { 9426 // -- if T is a reference type, no initialization is performed. 9427 if (I->getType()->isReferenceType()) 9428 continue; 9429 9430 LValue Subobject = This; 9431 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9432 return false; 9433 9434 ImplicitValueInitExpr VIE(I->getType()); 9435 if (!EvaluateInPlace( 9436 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9437 return false; 9438 } 9439 9440 return true; 9441 } 9442 9443 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9444 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9445 if (RD->isInvalidDecl()) return false; 9446 if (RD->isUnion()) { 9447 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9448 // object's first non-static named data member is zero-initialized 9449 RecordDecl::field_iterator I = RD->field_begin(); 9450 if (I == RD->field_end()) { 9451 Result = APValue((const FieldDecl*)nullptr); 9452 return true; 9453 } 9454 9455 LValue Subobject = This; 9456 if (!HandleLValueMember(Info, E, Subobject, *I)) 9457 return false; 9458 Result = APValue(*I); 9459 ImplicitValueInitExpr VIE(I->getType()); 9460 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9461 } 9462 9463 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9464 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9465 return false; 9466 } 9467 9468 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9469 } 9470 9471 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9472 switch (E->getCastKind()) { 9473 default: 9474 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9475 9476 case CK_ConstructorConversion: 9477 return Visit(E->getSubExpr()); 9478 9479 case CK_DerivedToBase: 9480 case CK_UncheckedDerivedToBase: { 9481 APValue DerivedObject; 9482 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9483 return false; 9484 if (!DerivedObject.isStruct()) 9485 return Error(E->getSubExpr()); 9486 9487 // Derived-to-base rvalue conversion: just slice off the derived part. 9488 APValue *Value = &DerivedObject; 9489 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9490 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9491 PathE = E->path_end(); PathI != PathE; ++PathI) { 9492 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9493 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9494 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9495 RD = Base; 9496 } 9497 Result = *Value; 9498 return true; 9499 } 9500 } 9501 } 9502 9503 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9504 if (E->isTransparent()) 9505 return Visit(E->getInit(0)); 9506 9507 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9508 if (RD->isInvalidDecl()) return false; 9509 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9510 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9511 9512 EvalInfo::EvaluatingConstructorRAII EvalObj( 9513 Info, 9514 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9515 CXXRD && CXXRD->getNumBases()); 9516 9517 if (RD->isUnion()) { 9518 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9519 Result = APValue(Field); 9520 if (!Field) 9521 return true; 9522 9523 // If the initializer list for a union does not contain any elements, the 9524 // first element of the union is value-initialized. 9525 // FIXME: The element should be initialized from an initializer list. 9526 // Is this difference ever observable for initializer lists which 9527 // we don't build? 9528 ImplicitValueInitExpr VIE(Field->getType()); 9529 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9530 9531 LValue Subobject = This; 9532 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9533 return false; 9534 9535 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9536 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9537 isa<CXXDefaultInitExpr>(InitExpr)); 9538 9539 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 9540 } 9541 9542 if (!Result.hasValue()) 9543 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9544 std::distance(RD->field_begin(), RD->field_end())); 9545 unsigned ElementNo = 0; 9546 bool Success = true; 9547 9548 // Initialize base classes. 9549 if (CXXRD && CXXRD->getNumBases()) { 9550 for (const auto &Base : CXXRD->bases()) { 9551 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9552 const Expr *Init = E->getInit(ElementNo); 9553 9554 LValue Subobject = This; 9555 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9556 return false; 9557 9558 APValue &FieldVal = Result.getStructBase(ElementNo); 9559 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9560 if (!Info.noteFailure()) 9561 return false; 9562 Success = false; 9563 } 9564 ++ElementNo; 9565 } 9566 9567 EvalObj.finishedConstructingBases(); 9568 } 9569 9570 // Initialize members. 9571 for (const auto *Field : RD->fields()) { 9572 // Anonymous bit-fields are not considered members of the class for 9573 // purposes of aggregate initialization. 9574 if (Field->isUnnamedBitfield()) 9575 continue; 9576 9577 LValue Subobject = This; 9578 9579 bool HaveInit = ElementNo < E->getNumInits(); 9580 9581 // FIXME: Diagnostics here should point to the end of the initializer 9582 // list, not the start. 9583 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9584 Subobject, Field, &Layout)) 9585 return false; 9586 9587 // Perform an implicit value-initialization for members beyond the end of 9588 // the initializer list. 9589 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9590 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9591 9592 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9593 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9594 isa<CXXDefaultInitExpr>(Init)); 9595 9596 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9597 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9598 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9599 FieldVal, Field))) { 9600 if (!Info.noteFailure()) 9601 return false; 9602 Success = false; 9603 } 9604 } 9605 9606 EvalObj.finishedConstructingFields(); 9607 9608 return Success; 9609 } 9610 9611 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9612 QualType T) { 9613 // Note that E's type is not necessarily the type of our class here; we might 9614 // be initializing an array element instead. 9615 const CXXConstructorDecl *FD = E->getConstructor(); 9616 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9617 9618 bool ZeroInit = E->requiresZeroInitialization(); 9619 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9620 // If we've already performed zero-initialization, we're already done. 9621 if (Result.hasValue()) 9622 return true; 9623 9624 if (ZeroInit) 9625 return ZeroInitialization(E, T); 9626 9627 return getDefaultInitValue(T, Result); 9628 } 9629 9630 const FunctionDecl *Definition = nullptr; 9631 auto Body = FD->getBody(Definition); 9632 9633 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9634 return false; 9635 9636 // Avoid materializing a temporary for an elidable copy/move constructor. 9637 if (E->isElidable() && !ZeroInit) 9638 if (const MaterializeTemporaryExpr *ME 9639 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9640 return Visit(ME->getSubExpr()); 9641 9642 if (ZeroInit && !ZeroInitialization(E, T)) 9643 return false; 9644 9645 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9646 return HandleConstructorCall(E, This, Args, 9647 cast<CXXConstructorDecl>(Definition), Info, 9648 Result); 9649 } 9650 9651 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9652 const CXXInheritedCtorInitExpr *E) { 9653 if (!Info.CurrentCall) { 9654 assert(Info.checkingPotentialConstantExpression()); 9655 return false; 9656 } 9657 9658 const CXXConstructorDecl *FD = E->getConstructor(); 9659 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9660 return false; 9661 9662 const FunctionDecl *Definition = nullptr; 9663 auto Body = FD->getBody(Definition); 9664 9665 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9666 return false; 9667 9668 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9669 cast<CXXConstructorDecl>(Definition), Info, 9670 Result); 9671 } 9672 9673 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9674 const CXXStdInitializerListExpr *E) { 9675 const ConstantArrayType *ArrayType = 9676 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9677 9678 LValue Array; 9679 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9680 return false; 9681 9682 // Get a pointer to the first element of the array. 9683 Array.addArray(Info, E, ArrayType); 9684 9685 auto InvalidType = [&] { 9686 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9687 << E->getType(); 9688 return false; 9689 }; 9690 9691 // FIXME: Perform the checks on the field types in SemaInit. 9692 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9693 RecordDecl::field_iterator Field = Record->field_begin(); 9694 if (Field == Record->field_end()) 9695 return InvalidType(); 9696 9697 // Start pointer. 9698 if (!Field->getType()->isPointerType() || 9699 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9700 ArrayType->getElementType())) 9701 return InvalidType(); 9702 9703 // FIXME: What if the initializer_list type has base classes, etc? 9704 Result = APValue(APValue::UninitStruct(), 0, 2); 9705 Array.moveInto(Result.getStructField(0)); 9706 9707 if (++Field == Record->field_end()) 9708 return InvalidType(); 9709 9710 if (Field->getType()->isPointerType() && 9711 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9712 ArrayType->getElementType())) { 9713 // End pointer. 9714 if (!HandleLValueArrayAdjustment(Info, E, Array, 9715 ArrayType->getElementType(), 9716 ArrayType->getSize().getZExtValue())) 9717 return false; 9718 Array.moveInto(Result.getStructField(1)); 9719 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9720 // Length. 9721 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9722 else 9723 return InvalidType(); 9724 9725 if (++Field != Record->field_end()) 9726 return InvalidType(); 9727 9728 return true; 9729 } 9730 9731 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 9732 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 9733 if (ClosureClass->isInvalidDecl()) 9734 return false; 9735 9736 const size_t NumFields = 9737 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 9738 9739 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 9740 E->capture_init_end()) && 9741 "The number of lambda capture initializers should equal the number of " 9742 "fields within the closure type"); 9743 9744 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 9745 // Iterate through all the lambda's closure object's fields and initialize 9746 // them. 9747 auto *CaptureInitIt = E->capture_init_begin(); 9748 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 9749 bool Success = true; 9750 for (const auto *Field : ClosureClass->fields()) { 9751 assert(CaptureInitIt != E->capture_init_end()); 9752 // Get the initializer for this field 9753 Expr *const CurFieldInit = *CaptureInitIt++; 9754 9755 // If there is no initializer, either this is a VLA or an error has 9756 // occurred. 9757 if (!CurFieldInit) 9758 return Error(E); 9759 9760 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9761 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 9762 if (!Info.keepEvaluatingAfterFailure()) 9763 return false; 9764 Success = false; 9765 } 9766 ++CaptureIt; 9767 } 9768 return Success; 9769 } 9770 9771 static bool EvaluateRecord(const Expr *E, const LValue &This, 9772 APValue &Result, EvalInfo &Info) { 9773 assert(E->isRValue() && E->getType()->isRecordType() && 9774 "can't evaluate expression as a record rvalue"); 9775 return RecordExprEvaluator(Info, This, Result).Visit(E); 9776 } 9777 9778 //===----------------------------------------------------------------------===// 9779 // Temporary Evaluation 9780 // 9781 // Temporaries are represented in the AST as rvalues, but generally behave like 9782 // lvalues. The full-object of which the temporary is a subobject is implicitly 9783 // materialized so that a reference can bind to it. 9784 //===----------------------------------------------------------------------===// 9785 namespace { 9786 class TemporaryExprEvaluator 9787 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 9788 public: 9789 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 9790 LValueExprEvaluatorBaseTy(Info, Result, false) {} 9791 9792 /// Visit an expression which constructs the value of this temporary. 9793 bool VisitConstructExpr(const Expr *E) { 9794 APValue &Value = 9795 Info.CurrentCall->createTemporary(E, E->getType(), false, Result); 9796 return EvaluateInPlace(Value, Info, Result, E); 9797 } 9798 9799 bool VisitCastExpr(const CastExpr *E) { 9800 switch (E->getCastKind()) { 9801 default: 9802 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 9803 9804 case CK_ConstructorConversion: 9805 return VisitConstructExpr(E->getSubExpr()); 9806 } 9807 } 9808 bool VisitInitListExpr(const InitListExpr *E) { 9809 return VisitConstructExpr(E); 9810 } 9811 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9812 return VisitConstructExpr(E); 9813 } 9814 bool VisitCallExpr(const CallExpr *E) { 9815 return VisitConstructExpr(E); 9816 } 9817 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 9818 return VisitConstructExpr(E); 9819 } 9820 bool VisitLambdaExpr(const LambdaExpr *E) { 9821 return VisitConstructExpr(E); 9822 } 9823 }; 9824 } // end anonymous namespace 9825 9826 /// Evaluate an expression of record type as a temporary. 9827 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 9828 assert(E->isRValue() && E->getType()->isRecordType()); 9829 return TemporaryExprEvaluator(Info, Result).Visit(E); 9830 } 9831 9832 //===----------------------------------------------------------------------===// 9833 // Vector Evaluation 9834 //===----------------------------------------------------------------------===// 9835 9836 namespace { 9837 class VectorExprEvaluator 9838 : public ExprEvaluatorBase<VectorExprEvaluator> { 9839 APValue &Result; 9840 public: 9841 9842 VectorExprEvaluator(EvalInfo &info, APValue &Result) 9843 : ExprEvaluatorBaseTy(info), Result(Result) {} 9844 9845 bool Success(ArrayRef<APValue> V, const Expr *E) { 9846 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 9847 // FIXME: remove this APValue copy. 9848 Result = APValue(V.data(), V.size()); 9849 return true; 9850 } 9851 bool Success(const APValue &V, const Expr *E) { 9852 assert(V.isVector()); 9853 Result = V; 9854 return true; 9855 } 9856 bool ZeroInitialization(const Expr *E); 9857 9858 bool VisitUnaryReal(const UnaryOperator *E) 9859 { return Visit(E->getSubExpr()); } 9860 bool VisitCastExpr(const CastExpr* E); 9861 bool VisitInitListExpr(const InitListExpr *E); 9862 bool VisitUnaryImag(const UnaryOperator *E); 9863 bool VisitBinaryOperator(const BinaryOperator *E); 9864 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 9865 // conditional select), shufflevector, ExtVectorElementExpr 9866 }; 9867 } // end anonymous namespace 9868 9869 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 9870 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 9871 return VectorExprEvaluator(Info, Result).Visit(E); 9872 } 9873 9874 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 9875 const VectorType *VTy = E->getType()->castAs<VectorType>(); 9876 unsigned NElts = VTy->getNumElements(); 9877 9878 const Expr *SE = E->getSubExpr(); 9879 QualType SETy = SE->getType(); 9880 9881 switch (E->getCastKind()) { 9882 case CK_VectorSplat: { 9883 APValue Val = APValue(); 9884 if (SETy->isIntegerType()) { 9885 APSInt IntResult; 9886 if (!EvaluateInteger(SE, IntResult, Info)) 9887 return false; 9888 Val = APValue(std::move(IntResult)); 9889 } else if (SETy->isRealFloatingType()) { 9890 APFloat FloatResult(0.0); 9891 if (!EvaluateFloat(SE, FloatResult, Info)) 9892 return false; 9893 Val = APValue(std::move(FloatResult)); 9894 } else { 9895 return Error(E); 9896 } 9897 9898 // Splat and create vector APValue. 9899 SmallVector<APValue, 4> Elts(NElts, Val); 9900 return Success(Elts, E); 9901 } 9902 case CK_BitCast: { 9903 // Evaluate the operand into an APInt we can extract from. 9904 llvm::APInt SValInt; 9905 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 9906 return false; 9907 // Extract the elements 9908 QualType EltTy = VTy->getElementType(); 9909 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 9910 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 9911 SmallVector<APValue, 4> Elts; 9912 if (EltTy->isRealFloatingType()) { 9913 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 9914 unsigned FloatEltSize = EltSize; 9915 if (&Sem == &APFloat::x87DoubleExtended()) 9916 FloatEltSize = 80; 9917 for (unsigned i = 0; i < NElts; i++) { 9918 llvm::APInt Elt; 9919 if (BigEndian) 9920 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 9921 else 9922 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 9923 Elts.push_back(APValue(APFloat(Sem, Elt))); 9924 } 9925 } else if (EltTy->isIntegerType()) { 9926 for (unsigned i = 0; i < NElts; i++) { 9927 llvm::APInt Elt; 9928 if (BigEndian) 9929 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 9930 else 9931 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 9932 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 9933 } 9934 } else { 9935 return Error(E); 9936 } 9937 return Success(Elts, E); 9938 } 9939 default: 9940 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9941 } 9942 } 9943 9944 bool 9945 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9946 const VectorType *VT = E->getType()->castAs<VectorType>(); 9947 unsigned NumInits = E->getNumInits(); 9948 unsigned NumElements = VT->getNumElements(); 9949 9950 QualType EltTy = VT->getElementType(); 9951 SmallVector<APValue, 4> Elements; 9952 9953 // The number of initializers can be less than the number of 9954 // vector elements. For OpenCL, this can be due to nested vector 9955 // initialization. For GCC compatibility, missing trailing elements 9956 // should be initialized with zeroes. 9957 unsigned CountInits = 0, CountElts = 0; 9958 while (CountElts < NumElements) { 9959 // Handle nested vector initialization. 9960 if (CountInits < NumInits 9961 && E->getInit(CountInits)->getType()->isVectorType()) { 9962 APValue v; 9963 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 9964 return Error(E); 9965 unsigned vlen = v.getVectorLength(); 9966 for (unsigned j = 0; j < vlen; j++) 9967 Elements.push_back(v.getVectorElt(j)); 9968 CountElts += vlen; 9969 } else if (EltTy->isIntegerType()) { 9970 llvm::APSInt sInt(32); 9971 if (CountInits < NumInits) { 9972 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 9973 return false; 9974 } else // trailing integer zero. 9975 sInt = Info.Ctx.MakeIntValue(0, EltTy); 9976 Elements.push_back(APValue(sInt)); 9977 CountElts++; 9978 } else { 9979 llvm::APFloat f(0.0); 9980 if (CountInits < NumInits) { 9981 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 9982 return false; 9983 } else // trailing float zero. 9984 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 9985 Elements.push_back(APValue(f)); 9986 CountElts++; 9987 } 9988 CountInits++; 9989 } 9990 return Success(Elements, E); 9991 } 9992 9993 bool 9994 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 9995 const auto *VT = E->getType()->castAs<VectorType>(); 9996 QualType EltTy = VT->getElementType(); 9997 APValue ZeroElement; 9998 if (EltTy->isIntegerType()) 9999 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10000 else 10001 ZeroElement = 10002 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10003 10004 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10005 return Success(Elements, E); 10006 } 10007 10008 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10009 VisitIgnoredValue(E->getSubExpr()); 10010 return ZeroInitialization(E); 10011 } 10012 10013 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10014 BinaryOperatorKind Op = E->getOpcode(); 10015 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10016 "Operation not supported on vector types"); 10017 10018 if (Op == BO_Comma) 10019 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10020 10021 Expr *LHS = E->getLHS(); 10022 Expr *RHS = E->getRHS(); 10023 10024 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10025 "Must both be vector types"); 10026 // Checking JUST the types are the same would be fine, except shifts don't 10027 // need to have their types be the same (since you always shift by an int). 10028 assert(LHS->getType()->getAs<VectorType>()->getNumElements() == 10029 E->getType()->getAs<VectorType>()->getNumElements() && 10030 RHS->getType()->getAs<VectorType>()->getNumElements() == 10031 E->getType()->getAs<VectorType>()->getNumElements() && 10032 "All operands must be the same size."); 10033 10034 APValue LHSValue; 10035 APValue RHSValue; 10036 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10037 if (!LHSOK && !Info.noteFailure()) 10038 return false; 10039 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10040 return false; 10041 10042 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10043 return false; 10044 10045 return Success(LHSValue, E); 10046 } 10047 10048 //===----------------------------------------------------------------------===// 10049 // Array Evaluation 10050 //===----------------------------------------------------------------------===// 10051 10052 namespace { 10053 class ArrayExprEvaluator 10054 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10055 const LValue &This; 10056 APValue &Result; 10057 public: 10058 10059 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10060 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10061 10062 bool Success(const APValue &V, const Expr *E) { 10063 assert(V.isArray() && "expected array"); 10064 Result = V; 10065 return true; 10066 } 10067 10068 bool ZeroInitialization(const Expr *E) { 10069 const ConstantArrayType *CAT = 10070 Info.Ctx.getAsConstantArrayType(E->getType()); 10071 if (!CAT) { 10072 if (E->getType()->isIncompleteArrayType()) { 10073 // We can be asked to zero-initialize a flexible array member; this 10074 // is represented as an ImplicitValueInitExpr of incomplete array 10075 // type. In this case, the array has zero elements. 10076 Result = APValue(APValue::UninitArray(), 0, 0); 10077 return true; 10078 } 10079 // FIXME: We could handle VLAs here. 10080 return Error(E); 10081 } 10082 10083 Result = APValue(APValue::UninitArray(), 0, 10084 CAT->getSize().getZExtValue()); 10085 if (!Result.hasArrayFiller()) return true; 10086 10087 // Zero-initialize all elements. 10088 LValue Subobject = This; 10089 Subobject.addArray(Info, E, CAT); 10090 ImplicitValueInitExpr VIE(CAT->getElementType()); 10091 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10092 } 10093 10094 bool VisitCallExpr(const CallExpr *E) { 10095 return handleCallExpr(E, Result, &This); 10096 } 10097 bool VisitInitListExpr(const InitListExpr *E, 10098 QualType AllocType = QualType()); 10099 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10100 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10101 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10102 const LValue &Subobject, 10103 APValue *Value, QualType Type); 10104 bool VisitStringLiteral(const StringLiteral *E, 10105 QualType AllocType = QualType()) { 10106 expandStringLiteral(Info, E, Result, AllocType); 10107 return true; 10108 } 10109 }; 10110 } // end anonymous namespace 10111 10112 static bool EvaluateArray(const Expr *E, const LValue &This, 10113 APValue &Result, EvalInfo &Info) { 10114 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 10115 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10116 } 10117 10118 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10119 APValue &Result, const InitListExpr *ILE, 10120 QualType AllocType) { 10121 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 10122 "not an array rvalue"); 10123 return ArrayExprEvaluator(Info, This, Result) 10124 .VisitInitListExpr(ILE, AllocType); 10125 } 10126 10127 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10128 APValue &Result, 10129 const CXXConstructExpr *CCE, 10130 QualType AllocType) { 10131 assert(CCE->isRValue() && CCE->getType()->isArrayType() && 10132 "not an array rvalue"); 10133 return ArrayExprEvaluator(Info, This, Result) 10134 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10135 } 10136 10137 // Return true iff the given array filler may depend on the element index. 10138 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10139 // For now, just allow non-class value-initialization and initialization 10140 // lists comprised of them. 10141 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10142 return false; 10143 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10144 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10145 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10146 return true; 10147 } 10148 return false; 10149 } 10150 return true; 10151 } 10152 10153 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10154 QualType AllocType) { 10155 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10156 AllocType.isNull() ? E->getType() : AllocType); 10157 if (!CAT) 10158 return Error(E); 10159 10160 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10161 // an appropriately-typed string literal enclosed in braces. 10162 if (E->isStringLiteralInit()) { 10163 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 10164 // FIXME: Support ObjCEncodeExpr here once we support it in 10165 // ArrayExprEvaluator generally. 10166 if (!SL) 10167 return Error(E); 10168 return VisitStringLiteral(SL, AllocType); 10169 } 10170 10171 bool Success = true; 10172 10173 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10174 "zero-initialized array shouldn't have any initialized elts"); 10175 APValue Filler; 10176 if (Result.isArray() && Result.hasArrayFiller()) 10177 Filler = Result.getArrayFiller(); 10178 10179 unsigned NumEltsToInit = E->getNumInits(); 10180 unsigned NumElts = CAT->getSize().getZExtValue(); 10181 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10182 10183 // If the initializer might depend on the array index, run it for each 10184 // array element. 10185 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10186 NumEltsToInit = NumElts; 10187 10188 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10189 << NumEltsToInit << ".\n"); 10190 10191 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10192 10193 // If the array was previously zero-initialized, preserve the 10194 // zero-initialized values. 10195 if (Filler.hasValue()) { 10196 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10197 Result.getArrayInitializedElt(I) = Filler; 10198 if (Result.hasArrayFiller()) 10199 Result.getArrayFiller() = Filler; 10200 } 10201 10202 LValue Subobject = This; 10203 Subobject.addArray(Info, E, CAT); 10204 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10205 const Expr *Init = 10206 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10207 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10208 Info, Subobject, Init) || 10209 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10210 CAT->getElementType(), 1)) { 10211 if (!Info.noteFailure()) 10212 return false; 10213 Success = false; 10214 } 10215 } 10216 10217 if (!Result.hasArrayFiller()) 10218 return Success; 10219 10220 // If we get here, we have a trivial filler, which we can just evaluate 10221 // once and splat over the rest of the array elements. 10222 assert(FillerExpr && "no array filler for incomplete init list"); 10223 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10224 FillerExpr) && Success; 10225 } 10226 10227 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10228 LValue CommonLV; 10229 if (E->getCommonExpr() && 10230 !Evaluate(Info.CurrentCall->createTemporary( 10231 E->getCommonExpr(), 10232 getStorageType(Info.Ctx, E->getCommonExpr()), false, 10233 CommonLV), 10234 Info, E->getCommonExpr()->getSourceExpr())) 10235 return false; 10236 10237 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10238 10239 uint64_t Elements = CAT->getSize().getZExtValue(); 10240 Result = APValue(APValue::UninitArray(), Elements, Elements); 10241 10242 LValue Subobject = This; 10243 Subobject.addArray(Info, E, CAT); 10244 10245 bool Success = true; 10246 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10247 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10248 Info, Subobject, E->getSubExpr()) || 10249 !HandleLValueArrayAdjustment(Info, E, Subobject, 10250 CAT->getElementType(), 1)) { 10251 if (!Info.noteFailure()) 10252 return false; 10253 Success = false; 10254 } 10255 } 10256 10257 return Success; 10258 } 10259 10260 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10261 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10262 } 10263 10264 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10265 const LValue &Subobject, 10266 APValue *Value, 10267 QualType Type) { 10268 bool HadZeroInit = Value->hasValue(); 10269 10270 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10271 unsigned N = CAT->getSize().getZExtValue(); 10272 10273 // Preserve the array filler if we had prior zero-initialization. 10274 APValue Filler = 10275 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10276 : APValue(); 10277 10278 *Value = APValue(APValue::UninitArray(), N, N); 10279 10280 if (HadZeroInit) 10281 for (unsigned I = 0; I != N; ++I) 10282 Value->getArrayInitializedElt(I) = Filler; 10283 10284 // Initialize the elements. 10285 LValue ArrayElt = Subobject; 10286 ArrayElt.addArray(Info, E, CAT); 10287 for (unsigned I = 0; I != N; ++I) 10288 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10289 CAT->getElementType()) || 10290 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10291 CAT->getElementType(), 1)) 10292 return false; 10293 10294 return true; 10295 } 10296 10297 if (!Type->isRecordType()) 10298 return Error(E); 10299 10300 return RecordExprEvaluator(Info, Subobject, *Value) 10301 .VisitCXXConstructExpr(E, Type); 10302 } 10303 10304 //===----------------------------------------------------------------------===// 10305 // Integer Evaluation 10306 // 10307 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10308 // types and back in constant folding. Integer values are thus represented 10309 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10310 //===----------------------------------------------------------------------===// 10311 10312 namespace { 10313 class IntExprEvaluator 10314 : public ExprEvaluatorBase<IntExprEvaluator> { 10315 APValue &Result; 10316 public: 10317 IntExprEvaluator(EvalInfo &info, APValue &result) 10318 : ExprEvaluatorBaseTy(info), Result(result) {} 10319 10320 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10321 assert(E->getType()->isIntegralOrEnumerationType() && 10322 "Invalid evaluation result."); 10323 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10324 "Invalid evaluation result."); 10325 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10326 "Invalid evaluation result."); 10327 Result = APValue(SI); 10328 return true; 10329 } 10330 bool Success(const llvm::APSInt &SI, const Expr *E) { 10331 return Success(SI, E, Result); 10332 } 10333 10334 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10335 assert(E->getType()->isIntegralOrEnumerationType() && 10336 "Invalid evaluation result."); 10337 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10338 "Invalid evaluation result."); 10339 Result = APValue(APSInt(I)); 10340 Result.getInt().setIsUnsigned( 10341 E->getType()->isUnsignedIntegerOrEnumerationType()); 10342 return true; 10343 } 10344 bool Success(const llvm::APInt &I, const Expr *E) { 10345 return Success(I, E, Result); 10346 } 10347 10348 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10349 assert(E->getType()->isIntegralOrEnumerationType() && 10350 "Invalid evaluation result."); 10351 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10352 return true; 10353 } 10354 bool Success(uint64_t Value, const Expr *E) { 10355 return Success(Value, E, Result); 10356 } 10357 10358 bool Success(CharUnits Size, const Expr *E) { 10359 return Success(Size.getQuantity(), E); 10360 } 10361 10362 bool Success(const APValue &V, const Expr *E) { 10363 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10364 Result = V; 10365 return true; 10366 } 10367 return Success(V.getInt(), E); 10368 } 10369 10370 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10371 10372 //===--------------------------------------------------------------------===// 10373 // Visitor Methods 10374 //===--------------------------------------------------------------------===// 10375 10376 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10377 return Success(E->getValue(), E); 10378 } 10379 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10380 return Success(E->getValue(), E); 10381 } 10382 10383 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10384 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10385 if (CheckReferencedDecl(E, E->getDecl())) 10386 return true; 10387 10388 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10389 } 10390 bool VisitMemberExpr(const MemberExpr *E) { 10391 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10392 VisitIgnoredBaseExpression(E->getBase()); 10393 return true; 10394 } 10395 10396 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10397 } 10398 10399 bool VisitCallExpr(const CallExpr *E); 10400 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10401 bool VisitBinaryOperator(const BinaryOperator *E); 10402 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10403 bool VisitUnaryOperator(const UnaryOperator *E); 10404 10405 bool VisitCastExpr(const CastExpr* E); 10406 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10407 10408 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10409 return Success(E->getValue(), E); 10410 } 10411 10412 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10413 return Success(E->getValue(), E); 10414 } 10415 10416 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10417 if (Info.ArrayInitIndex == uint64_t(-1)) { 10418 // We were asked to evaluate this subexpression independent of the 10419 // enclosing ArrayInitLoopExpr. We can't do that. 10420 Info.FFDiag(E); 10421 return false; 10422 } 10423 return Success(Info.ArrayInitIndex, E); 10424 } 10425 10426 // Note, GNU defines __null as an integer, not a pointer. 10427 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10428 return ZeroInitialization(E); 10429 } 10430 10431 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10432 return Success(E->getValue(), E); 10433 } 10434 10435 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10436 return Success(E->getValue(), E); 10437 } 10438 10439 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10440 return Success(E->getValue(), E); 10441 } 10442 10443 bool VisitUnaryReal(const UnaryOperator *E); 10444 bool VisitUnaryImag(const UnaryOperator *E); 10445 10446 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10447 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10448 bool VisitSourceLocExpr(const SourceLocExpr *E); 10449 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10450 bool VisitRequiresExpr(const RequiresExpr *E); 10451 // FIXME: Missing: array subscript of vector, member of vector 10452 }; 10453 10454 class FixedPointExprEvaluator 10455 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10456 APValue &Result; 10457 10458 public: 10459 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10460 : ExprEvaluatorBaseTy(info), Result(result) {} 10461 10462 bool Success(const llvm::APInt &I, const Expr *E) { 10463 return Success( 10464 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10465 } 10466 10467 bool Success(uint64_t Value, const Expr *E) { 10468 return Success( 10469 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10470 } 10471 10472 bool Success(const APValue &V, const Expr *E) { 10473 return Success(V.getFixedPoint(), E); 10474 } 10475 10476 bool Success(const APFixedPoint &V, const Expr *E) { 10477 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10478 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10479 "Invalid evaluation result."); 10480 Result = APValue(V); 10481 return true; 10482 } 10483 10484 //===--------------------------------------------------------------------===// 10485 // Visitor Methods 10486 //===--------------------------------------------------------------------===// 10487 10488 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10489 return Success(E->getValue(), E); 10490 } 10491 10492 bool VisitCastExpr(const CastExpr *E); 10493 bool VisitUnaryOperator(const UnaryOperator *E); 10494 bool VisitBinaryOperator(const BinaryOperator *E); 10495 }; 10496 } // end anonymous namespace 10497 10498 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10499 /// produce either the integer value or a pointer. 10500 /// 10501 /// GCC has a heinous extension which folds casts between pointer types and 10502 /// pointer-sized integral types. We support this by allowing the evaluation of 10503 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10504 /// Some simple arithmetic on such values is supported (they are treated much 10505 /// like char*). 10506 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10507 EvalInfo &Info) { 10508 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10509 return IntExprEvaluator(Info, Result).Visit(E); 10510 } 10511 10512 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10513 APValue Val; 10514 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10515 return false; 10516 if (!Val.isInt()) { 10517 // FIXME: It would be better to produce the diagnostic for casting 10518 // a pointer to an integer. 10519 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10520 return false; 10521 } 10522 Result = Val.getInt(); 10523 return true; 10524 } 10525 10526 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10527 APValue Evaluated = E->EvaluateInContext( 10528 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10529 return Success(Evaluated, E); 10530 } 10531 10532 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10533 EvalInfo &Info) { 10534 if (E->getType()->isFixedPointType()) { 10535 APValue Val; 10536 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10537 return false; 10538 if (!Val.isFixedPoint()) 10539 return false; 10540 10541 Result = Val.getFixedPoint(); 10542 return true; 10543 } 10544 return false; 10545 } 10546 10547 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10548 EvalInfo &Info) { 10549 if (E->getType()->isIntegerType()) { 10550 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10551 APSInt Val; 10552 if (!EvaluateInteger(E, Val, Info)) 10553 return false; 10554 Result = APFixedPoint(Val, FXSema); 10555 return true; 10556 } else if (E->getType()->isFixedPointType()) { 10557 return EvaluateFixedPoint(E, Result, Info); 10558 } 10559 return false; 10560 } 10561 10562 /// Check whether the given declaration can be directly converted to an integral 10563 /// rvalue. If not, no diagnostic is produced; there are other things we can 10564 /// try. 10565 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10566 // Enums are integer constant exprs. 10567 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10568 // Check for signedness/width mismatches between E type and ECD value. 10569 bool SameSign = (ECD->getInitVal().isSigned() 10570 == E->getType()->isSignedIntegerOrEnumerationType()); 10571 bool SameWidth = (ECD->getInitVal().getBitWidth() 10572 == Info.Ctx.getIntWidth(E->getType())); 10573 if (SameSign && SameWidth) 10574 return Success(ECD->getInitVal(), E); 10575 else { 10576 // Get rid of mismatch (otherwise Success assertions will fail) 10577 // by computing a new value matching the type of E. 10578 llvm::APSInt Val = ECD->getInitVal(); 10579 if (!SameSign) 10580 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10581 if (!SameWidth) 10582 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10583 return Success(Val, E); 10584 } 10585 } 10586 return false; 10587 } 10588 10589 /// Values returned by __builtin_classify_type, chosen to match the values 10590 /// produced by GCC's builtin. 10591 enum class GCCTypeClass { 10592 None = -1, 10593 Void = 0, 10594 Integer = 1, 10595 // GCC reserves 2 for character types, but instead classifies them as 10596 // integers. 10597 Enum = 3, 10598 Bool = 4, 10599 Pointer = 5, 10600 // GCC reserves 6 for references, but appears to never use it (because 10601 // expressions never have reference type, presumably). 10602 PointerToDataMember = 7, 10603 RealFloat = 8, 10604 Complex = 9, 10605 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10606 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10607 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10608 // uses 12 for that purpose, same as for a class or struct. Maybe it 10609 // internally implements a pointer to member as a struct? Who knows. 10610 PointerToMemberFunction = 12, // Not a bug, see above. 10611 ClassOrStruct = 12, 10612 Union = 13, 10613 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10614 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10615 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10616 // literals. 10617 }; 10618 10619 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10620 /// as GCC. 10621 static GCCTypeClass 10622 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10623 assert(!T->isDependentType() && "unexpected dependent type"); 10624 10625 QualType CanTy = T.getCanonicalType(); 10626 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10627 10628 switch (CanTy->getTypeClass()) { 10629 #define TYPE(ID, BASE) 10630 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10631 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10632 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10633 #include "clang/AST/TypeNodes.inc" 10634 case Type::Auto: 10635 case Type::DeducedTemplateSpecialization: 10636 llvm_unreachable("unexpected non-canonical or dependent type"); 10637 10638 case Type::Builtin: 10639 switch (BT->getKind()) { 10640 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10641 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10642 case BuiltinType::ID: return GCCTypeClass::Integer; 10643 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10644 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10645 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10646 case BuiltinType::ID: break; 10647 #include "clang/AST/BuiltinTypes.def" 10648 case BuiltinType::Void: 10649 return GCCTypeClass::Void; 10650 10651 case BuiltinType::Bool: 10652 return GCCTypeClass::Bool; 10653 10654 case BuiltinType::Char_U: 10655 case BuiltinType::UChar: 10656 case BuiltinType::WChar_U: 10657 case BuiltinType::Char8: 10658 case BuiltinType::Char16: 10659 case BuiltinType::Char32: 10660 case BuiltinType::UShort: 10661 case BuiltinType::UInt: 10662 case BuiltinType::ULong: 10663 case BuiltinType::ULongLong: 10664 case BuiltinType::UInt128: 10665 return GCCTypeClass::Integer; 10666 10667 case BuiltinType::UShortAccum: 10668 case BuiltinType::UAccum: 10669 case BuiltinType::ULongAccum: 10670 case BuiltinType::UShortFract: 10671 case BuiltinType::UFract: 10672 case BuiltinType::ULongFract: 10673 case BuiltinType::SatUShortAccum: 10674 case BuiltinType::SatUAccum: 10675 case BuiltinType::SatULongAccum: 10676 case BuiltinType::SatUShortFract: 10677 case BuiltinType::SatUFract: 10678 case BuiltinType::SatULongFract: 10679 return GCCTypeClass::None; 10680 10681 case BuiltinType::NullPtr: 10682 10683 case BuiltinType::ObjCId: 10684 case BuiltinType::ObjCClass: 10685 case BuiltinType::ObjCSel: 10686 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10687 case BuiltinType::Id: 10688 #include "clang/Basic/OpenCLImageTypes.def" 10689 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10690 case BuiltinType::Id: 10691 #include "clang/Basic/OpenCLExtensionTypes.def" 10692 case BuiltinType::OCLSampler: 10693 case BuiltinType::OCLEvent: 10694 case BuiltinType::OCLClkEvent: 10695 case BuiltinType::OCLQueue: 10696 case BuiltinType::OCLReserveID: 10697 #define SVE_TYPE(Name, Id, SingletonId) \ 10698 case BuiltinType::Id: 10699 #include "clang/Basic/AArch64SVEACLETypes.def" 10700 return GCCTypeClass::None; 10701 10702 case BuiltinType::Dependent: 10703 llvm_unreachable("unexpected dependent type"); 10704 }; 10705 llvm_unreachable("unexpected placeholder type"); 10706 10707 case Type::Enum: 10708 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 10709 10710 case Type::Pointer: 10711 case Type::ConstantArray: 10712 case Type::VariableArray: 10713 case Type::IncompleteArray: 10714 case Type::FunctionNoProto: 10715 case Type::FunctionProto: 10716 return GCCTypeClass::Pointer; 10717 10718 case Type::MemberPointer: 10719 return CanTy->isMemberDataPointerType() 10720 ? GCCTypeClass::PointerToDataMember 10721 : GCCTypeClass::PointerToMemberFunction; 10722 10723 case Type::Complex: 10724 return GCCTypeClass::Complex; 10725 10726 case Type::Record: 10727 return CanTy->isUnionType() ? GCCTypeClass::Union 10728 : GCCTypeClass::ClassOrStruct; 10729 10730 case Type::Atomic: 10731 // GCC classifies _Atomic T the same as T. 10732 return EvaluateBuiltinClassifyType( 10733 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 10734 10735 case Type::BlockPointer: 10736 case Type::Vector: 10737 case Type::ExtVector: 10738 case Type::ConstantMatrix: 10739 case Type::ObjCObject: 10740 case Type::ObjCInterface: 10741 case Type::ObjCObjectPointer: 10742 case Type::Pipe: 10743 case Type::ExtInt: 10744 // GCC classifies vectors as None. We follow its lead and classify all 10745 // other types that don't fit into the regular classification the same way. 10746 return GCCTypeClass::None; 10747 10748 case Type::LValueReference: 10749 case Type::RValueReference: 10750 llvm_unreachable("invalid type for expression"); 10751 } 10752 10753 llvm_unreachable("unexpected type class"); 10754 } 10755 10756 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10757 /// as GCC. 10758 static GCCTypeClass 10759 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 10760 // If no argument was supplied, default to None. This isn't 10761 // ideal, however it is what gcc does. 10762 if (E->getNumArgs() == 0) 10763 return GCCTypeClass::None; 10764 10765 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 10766 // being an ICE, but still folds it to a constant using the type of the first 10767 // argument. 10768 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 10769 } 10770 10771 /// EvaluateBuiltinConstantPForLValue - Determine the result of 10772 /// __builtin_constant_p when applied to the given pointer. 10773 /// 10774 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 10775 /// or it points to the first character of a string literal. 10776 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 10777 APValue::LValueBase Base = LV.getLValueBase(); 10778 if (Base.isNull()) { 10779 // A null base is acceptable. 10780 return true; 10781 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 10782 if (!isa<StringLiteral>(E)) 10783 return false; 10784 return LV.getLValueOffset().isZero(); 10785 } else if (Base.is<TypeInfoLValue>()) { 10786 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 10787 // evaluate to true. 10788 return true; 10789 } else { 10790 // Any other base is not constant enough for GCC. 10791 return false; 10792 } 10793 } 10794 10795 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 10796 /// GCC as we can manage. 10797 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 10798 // This evaluation is not permitted to have side-effects, so evaluate it in 10799 // a speculative evaluation context. 10800 SpeculativeEvaluationRAII SpeculativeEval(Info); 10801 10802 // Constant-folding is always enabled for the operand of __builtin_constant_p 10803 // (even when the enclosing evaluation context otherwise requires a strict 10804 // language-specific constant expression). 10805 FoldConstant Fold(Info, true); 10806 10807 QualType ArgType = Arg->getType(); 10808 10809 // __builtin_constant_p always has one operand. The rules which gcc follows 10810 // are not precisely documented, but are as follows: 10811 // 10812 // - If the operand is of integral, floating, complex or enumeration type, 10813 // and can be folded to a known value of that type, it returns 1. 10814 // - If the operand can be folded to a pointer to the first character 10815 // of a string literal (or such a pointer cast to an integral type) 10816 // or to a null pointer or an integer cast to a pointer, it returns 1. 10817 // 10818 // Otherwise, it returns 0. 10819 // 10820 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 10821 // its support for this did not work prior to GCC 9 and is not yet well 10822 // understood. 10823 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 10824 ArgType->isAnyComplexType() || ArgType->isPointerType() || 10825 ArgType->isNullPtrType()) { 10826 APValue V; 10827 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 10828 Fold.keepDiagnostics(); 10829 return false; 10830 } 10831 10832 // For a pointer (possibly cast to integer), there are special rules. 10833 if (V.getKind() == APValue::LValue) 10834 return EvaluateBuiltinConstantPForLValue(V); 10835 10836 // Otherwise, any constant value is good enough. 10837 return V.hasValue(); 10838 } 10839 10840 // Anything else isn't considered to be sufficiently constant. 10841 return false; 10842 } 10843 10844 /// Retrieves the "underlying object type" of the given expression, 10845 /// as used by __builtin_object_size. 10846 static QualType getObjectType(APValue::LValueBase B) { 10847 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 10848 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 10849 return VD->getType(); 10850 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 10851 if (isa<CompoundLiteralExpr>(E)) 10852 return E->getType(); 10853 } else if (B.is<TypeInfoLValue>()) { 10854 return B.getTypeInfoType(); 10855 } else if (B.is<DynamicAllocLValue>()) { 10856 return B.getDynamicAllocType(); 10857 } 10858 10859 return QualType(); 10860 } 10861 10862 /// A more selective version of E->IgnoreParenCasts for 10863 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 10864 /// to change the type of E. 10865 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 10866 /// 10867 /// Always returns an RValue with a pointer representation. 10868 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 10869 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 10870 10871 auto *NoParens = E->IgnoreParens(); 10872 auto *Cast = dyn_cast<CastExpr>(NoParens); 10873 if (Cast == nullptr) 10874 return NoParens; 10875 10876 // We only conservatively allow a few kinds of casts, because this code is 10877 // inherently a simple solution that seeks to support the common case. 10878 auto CastKind = Cast->getCastKind(); 10879 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 10880 CastKind != CK_AddressSpaceConversion) 10881 return NoParens; 10882 10883 auto *SubExpr = Cast->getSubExpr(); 10884 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 10885 return NoParens; 10886 return ignorePointerCastsAndParens(SubExpr); 10887 } 10888 10889 /// Checks to see if the given LValue's Designator is at the end of the LValue's 10890 /// record layout. e.g. 10891 /// struct { struct { int a, b; } fst, snd; } obj; 10892 /// obj.fst // no 10893 /// obj.snd // yes 10894 /// obj.fst.a // no 10895 /// obj.fst.b // no 10896 /// obj.snd.a // no 10897 /// obj.snd.b // yes 10898 /// 10899 /// Please note: this function is specialized for how __builtin_object_size 10900 /// views "objects". 10901 /// 10902 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 10903 /// correct result, it will always return true. 10904 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 10905 assert(!LVal.Designator.Invalid); 10906 10907 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 10908 const RecordDecl *Parent = FD->getParent(); 10909 Invalid = Parent->isInvalidDecl(); 10910 if (Invalid || Parent->isUnion()) 10911 return true; 10912 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 10913 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 10914 }; 10915 10916 auto &Base = LVal.getLValueBase(); 10917 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 10918 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 10919 bool Invalid; 10920 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10921 return Invalid; 10922 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 10923 for (auto *FD : IFD->chain()) { 10924 bool Invalid; 10925 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 10926 return Invalid; 10927 } 10928 } 10929 } 10930 10931 unsigned I = 0; 10932 QualType BaseType = getType(Base); 10933 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 10934 // If we don't know the array bound, conservatively assume we're looking at 10935 // the final array element. 10936 ++I; 10937 if (BaseType->isIncompleteArrayType()) 10938 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 10939 else 10940 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 10941 } 10942 10943 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 10944 const auto &Entry = LVal.Designator.Entries[I]; 10945 if (BaseType->isArrayType()) { 10946 // Because __builtin_object_size treats arrays as objects, we can ignore 10947 // the index iff this is the last array in the Designator. 10948 if (I + 1 == E) 10949 return true; 10950 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 10951 uint64_t Index = Entry.getAsArrayIndex(); 10952 if (Index + 1 != CAT->getSize()) 10953 return false; 10954 BaseType = CAT->getElementType(); 10955 } else if (BaseType->isAnyComplexType()) { 10956 const auto *CT = BaseType->castAs<ComplexType>(); 10957 uint64_t Index = Entry.getAsArrayIndex(); 10958 if (Index != 1) 10959 return false; 10960 BaseType = CT->getElementType(); 10961 } else if (auto *FD = getAsField(Entry)) { 10962 bool Invalid; 10963 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10964 return Invalid; 10965 BaseType = FD->getType(); 10966 } else { 10967 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 10968 return false; 10969 } 10970 } 10971 return true; 10972 } 10973 10974 /// Tests to see if the LValue has a user-specified designator (that isn't 10975 /// necessarily valid). Note that this always returns 'true' if the LValue has 10976 /// an unsized array as its first designator entry, because there's currently no 10977 /// way to tell if the user typed *foo or foo[0]. 10978 static bool refersToCompleteObject(const LValue &LVal) { 10979 if (LVal.Designator.Invalid) 10980 return false; 10981 10982 if (!LVal.Designator.Entries.empty()) 10983 return LVal.Designator.isMostDerivedAnUnsizedArray(); 10984 10985 if (!LVal.InvalidBase) 10986 return true; 10987 10988 // If `E` is a MemberExpr, then the first part of the designator is hiding in 10989 // the LValueBase. 10990 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 10991 return !E || !isa<MemberExpr>(E); 10992 } 10993 10994 /// Attempts to detect a user writing into a piece of memory that's impossible 10995 /// to figure out the size of by just using types. 10996 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 10997 const SubobjectDesignator &Designator = LVal.Designator; 10998 // Notes: 10999 // - Users can only write off of the end when we have an invalid base. Invalid 11000 // bases imply we don't know where the memory came from. 11001 // - We used to be a bit more aggressive here; we'd only be conservative if 11002 // the array at the end was flexible, or if it had 0 or 1 elements. This 11003 // broke some common standard library extensions (PR30346), but was 11004 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11005 // with some sort of list. OTOH, it seems that GCC is always 11006 // conservative with the last element in structs (if it's an array), so our 11007 // current behavior is more compatible than an explicit list approach would 11008 // be. 11009 return LVal.InvalidBase && 11010 Designator.Entries.size() == Designator.MostDerivedPathLength && 11011 Designator.MostDerivedIsArrayElement && 11012 isDesignatorAtObjectEnd(Ctx, LVal); 11013 } 11014 11015 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11016 /// Fails if the conversion would cause loss of precision. 11017 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11018 CharUnits &Result) { 11019 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11020 if (Int.ugt(CharUnitsMax)) 11021 return false; 11022 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11023 return true; 11024 } 11025 11026 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11027 /// determine how many bytes exist from the beginning of the object to either 11028 /// the end of the current subobject, or the end of the object itself, depending 11029 /// on what the LValue looks like + the value of Type. 11030 /// 11031 /// If this returns false, the value of Result is undefined. 11032 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11033 unsigned Type, const LValue &LVal, 11034 CharUnits &EndOffset) { 11035 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11036 11037 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11038 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11039 return false; 11040 return HandleSizeof(Info, ExprLoc, Ty, Result); 11041 }; 11042 11043 // We want to evaluate the size of the entire object. This is a valid fallback 11044 // for when Type=1 and the designator is invalid, because we're asked for an 11045 // upper-bound. 11046 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11047 // Type=3 wants a lower bound, so we can't fall back to this. 11048 if (Type == 3 && !DetermineForCompleteObject) 11049 return false; 11050 11051 llvm::APInt APEndOffset; 11052 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11053 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11054 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11055 11056 if (LVal.InvalidBase) 11057 return false; 11058 11059 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11060 return CheckedHandleSizeof(BaseTy, EndOffset); 11061 } 11062 11063 // We want to evaluate the size of a subobject. 11064 const SubobjectDesignator &Designator = LVal.Designator; 11065 11066 // The following is a moderately common idiom in C: 11067 // 11068 // struct Foo { int a; char c[1]; }; 11069 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11070 // strcpy(&F->c[0], Bar); 11071 // 11072 // In order to not break too much legacy code, we need to support it. 11073 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11074 // If we can resolve this to an alloc_size call, we can hand that back, 11075 // because we know for certain how many bytes there are to write to. 11076 llvm::APInt APEndOffset; 11077 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11078 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11079 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11080 11081 // If we cannot determine the size of the initial allocation, then we can't 11082 // given an accurate upper-bound. However, we are still able to give 11083 // conservative lower-bounds for Type=3. 11084 if (Type == 1) 11085 return false; 11086 } 11087 11088 CharUnits BytesPerElem; 11089 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11090 return false; 11091 11092 // According to the GCC documentation, we want the size of the subobject 11093 // denoted by the pointer. But that's not quite right -- what we actually 11094 // want is the size of the immediately-enclosing array, if there is one. 11095 int64_t ElemsRemaining; 11096 if (Designator.MostDerivedIsArrayElement && 11097 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11098 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11099 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11100 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11101 } else { 11102 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11103 } 11104 11105 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11106 return true; 11107 } 11108 11109 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11110 /// returns true and stores the result in @p Size. 11111 /// 11112 /// If @p WasError is non-null, this will report whether the failure to evaluate 11113 /// is to be treated as an Error in IntExprEvaluator. 11114 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11115 EvalInfo &Info, uint64_t &Size) { 11116 // Determine the denoted object. 11117 LValue LVal; 11118 { 11119 // The operand of __builtin_object_size is never evaluated for side-effects. 11120 // If there are any, but we can determine the pointed-to object anyway, then 11121 // ignore the side-effects. 11122 SpeculativeEvaluationRAII SpeculativeEval(Info); 11123 IgnoreSideEffectsRAII Fold(Info); 11124 11125 if (E->isGLValue()) { 11126 // It's possible for us to be given GLValues if we're called via 11127 // Expr::tryEvaluateObjectSize. 11128 APValue RVal; 11129 if (!EvaluateAsRValue(Info, E, RVal)) 11130 return false; 11131 LVal.setFrom(Info.Ctx, RVal); 11132 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11133 /*InvalidBaseOK=*/true)) 11134 return false; 11135 } 11136 11137 // If we point to before the start of the object, there are no accessible 11138 // bytes. 11139 if (LVal.getLValueOffset().isNegative()) { 11140 Size = 0; 11141 return true; 11142 } 11143 11144 CharUnits EndOffset; 11145 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11146 return false; 11147 11148 // If we've fallen outside of the end offset, just pretend there's nothing to 11149 // write to/read from. 11150 if (EndOffset <= LVal.getLValueOffset()) 11151 Size = 0; 11152 else 11153 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11154 return true; 11155 } 11156 11157 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11158 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11159 return VisitBuiltinCallExpr(E, BuiltinOp); 11160 11161 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11162 } 11163 11164 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11165 APValue &Val, APSInt &Alignment) { 11166 QualType SrcTy = E->getArg(0)->getType(); 11167 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11168 return false; 11169 // Even though we are evaluating integer expressions we could get a pointer 11170 // argument for the __builtin_is_aligned() case. 11171 if (SrcTy->isPointerType()) { 11172 LValue Ptr; 11173 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11174 return false; 11175 Ptr.moveInto(Val); 11176 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11177 Info.FFDiag(E->getArg(0)); 11178 return false; 11179 } else { 11180 APSInt SrcInt; 11181 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11182 return false; 11183 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11184 "Bit widths must be the same"); 11185 Val = APValue(SrcInt); 11186 } 11187 assert(Val.hasValue()); 11188 return true; 11189 } 11190 11191 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11192 unsigned BuiltinOp) { 11193 switch (BuiltinOp) { 11194 default: 11195 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11196 11197 case Builtin::BI__builtin_dynamic_object_size: 11198 case Builtin::BI__builtin_object_size: { 11199 // The type was checked when we built the expression. 11200 unsigned Type = 11201 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11202 assert(Type <= 3 && "unexpected type"); 11203 11204 uint64_t Size; 11205 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11206 return Success(Size, E); 11207 11208 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11209 return Success((Type & 2) ? 0 : -1, E); 11210 11211 // Expression had no side effects, but we couldn't statically determine the 11212 // size of the referenced object. 11213 switch (Info.EvalMode) { 11214 case EvalInfo::EM_ConstantExpression: 11215 case EvalInfo::EM_ConstantFold: 11216 case EvalInfo::EM_IgnoreSideEffects: 11217 // Leave it to IR generation. 11218 return Error(E); 11219 case EvalInfo::EM_ConstantExpressionUnevaluated: 11220 // Reduce it to a constant now. 11221 return Success((Type & 2) ? 0 : -1, E); 11222 } 11223 11224 llvm_unreachable("unexpected EvalMode"); 11225 } 11226 11227 case Builtin::BI__builtin_os_log_format_buffer_size: { 11228 analyze_os_log::OSLogBufferLayout Layout; 11229 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11230 return Success(Layout.size().getQuantity(), E); 11231 } 11232 11233 case Builtin::BI__builtin_is_aligned: { 11234 APValue Src; 11235 APSInt Alignment; 11236 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11237 return false; 11238 if (Src.isLValue()) { 11239 // If we evaluated a pointer, check the minimum known alignment. 11240 LValue Ptr; 11241 Ptr.setFrom(Info.Ctx, Src); 11242 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11243 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11244 // We can return true if the known alignment at the computed offset is 11245 // greater than the requested alignment. 11246 assert(PtrAlign.isPowerOfTwo()); 11247 assert(Alignment.isPowerOf2()); 11248 if (PtrAlign.getQuantity() >= Alignment) 11249 return Success(1, E); 11250 // If the alignment is not known to be sufficient, some cases could still 11251 // be aligned at run time. However, if the requested alignment is less or 11252 // equal to the base alignment and the offset is not aligned, we know that 11253 // the run-time value can never be aligned. 11254 if (BaseAlignment.getQuantity() >= Alignment && 11255 PtrAlign.getQuantity() < Alignment) 11256 return Success(0, E); 11257 // Otherwise we can't infer whether the value is sufficiently aligned. 11258 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11259 // in cases where we can't fully evaluate the pointer. 11260 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11261 << Alignment; 11262 return false; 11263 } 11264 assert(Src.isInt()); 11265 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11266 } 11267 case Builtin::BI__builtin_align_up: { 11268 APValue Src; 11269 APSInt Alignment; 11270 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11271 return false; 11272 if (!Src.isInt()) 11273 return Error(E); 11274 APSInt AlignedVal = 11275 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11276 Src.getInt().isUnsigned()); 11277 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11278 return Success(AlignedVal, E); 11279 } 11280 case Builtin::BI__builtin_align_down: { 11281 APValue Src; 11282 APSInt Alignment; 11283 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11284 return false; 11285 if (!Src.isInt()) 11286 return Error(E); 11287 APSInt AlignedVal = 11288 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11289 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11290 return Success(AlignedVal, E); 11291 } 11292 11293 case Builtin::BI__builtin_bitreverse8: 11294 case Builtin::BI__builtin_bitreverse16: 11295 case Builtin::BI__builtin_bitreverse32: 11296 case Builtin::BI__builtin_bitreverse64: { 11297 APSInt Val; 11298 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11299 return false; 11300 11301 return Success(Val.reverseBits(), E); 11302 } 11303 11304 case Builtin::BI__builtin_bswap16: 11305 case Builtin::BI__builtin_bswap32: 11306 case Builtin::BI__builtin_bswap64: { 11307 APSInt Val; 11308 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11309 return false; 11310 11311 return Success(Val.byteSwap(), E); 11312 } 11313 11314 case Builtin::BI__builtin_classify_type: 11315 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11316 11317 case Builtin::BI__builtin_clrsb: 11318 case Builtin::BI__builtin_clrsbl: 11319 case Builtin::BI__builtin_clrsbll: { 11320 APSInt Val; 11321 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11322 return false; 11323 11324 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11325 } 11326 11327 case Builtin::BI__builtin_clz: 11328 case Builtin::BI__builtin_clzl: 11329 case Builtin::BI__builtin_clzll: 11330 case Builtin::BI__builtin_clzs: { 11331 APSInt Val; 11332 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11333 return false; 11334 if (!Val) 11335 return Error(E); 11336 11337 return Success(Val.countLeadingZeros(), E); 11338 } 11339 11340 case Builtin::BI__builtin_constant_p: { 11341 const Expr *Arg = E->getArg(0); 11342 if (EvaluateBuiltinConstantP(Info, Arg)) 11343 return Success(true, E); 11344 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11345 // Outside a constant context, eagerly evaluate to false in the presence 11346 // of side-effects in order to avoid -Wunsequenced false-positives in 11347 // a branch on __builtin_constant_p(expr). 11348 return Success(false, E); 11349 } 11350 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11351 return false; 11352 } 11353 11354 case Builtin::BI__builtin_is_constant_evaluated: { 11355 const auto *Callee = Info.CurrentCall->getCallee(); 11356 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11357 (Info.CallStackDepth == 1 || 11358 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11359 Callee->getIdentifier() && 11360 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11361 // FIXME: Find a better way to avoid duplicated diagnostics. 11362 if (Info.EvalStatus.Diag) 11363 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11364 : Info.CurrentCall->CallLoc, 11365 diag::warn_is_constant_evaluated_always_true_constexpr) 11366 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11367 : "std::is_constant_evaluated"); 11368 } 11369 11370 return Success(Info.InConstantContext, E); 11371 } 11372 11373 case Builtin::BI__builtin_ctz: 11374 case Builtin::BI__builtin_ctzl: 11375 case Builtin::BI__builtin_ctzll: 11376 case Builtin::BI__builtin_ctzs: { 11377 APSInt Val; 11378 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11379 return false; 11380 if (!Val) 11381 return Error(E); 11382 11383 return Success(Val.countTrailingZeros(), E); 11384 } 11385 11386 case Builtin::BI__builtin_eh_return_data_regno: { 11387 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11388 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11389 return Success(Operand, E); 11390 } 11391 11392 case Builtin::BI__builtin_expect: 11393 case Builtin::BI__builtin_expect_with_probability: 11394 return Visit(E->getArg(0)); 11395 11396 case Builtin::BI__builtin_ffs: 11397 case Builtin::BI__builtin_ffsl: 11398 case Builtin::BI__builtin_ffsll: { 11399 APSInt Val; 11400 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11401 return false; 11402 11403 unsigned N = Val.countTrailingZeros(); 11404 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11405 } 11406 11407 case Builtin::BI__builtin_fpclassify: { 11408 APFloat Val(0.0); 11409 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11410 return false; 11411 unsigned Arg; 11412 switch (Val.getCategory()) { 11413 case APFloat::fcNaN: Arg = 0; break; 11414 case APFloat::fcInfinity: Arg = 1; break; 11415 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11416 case APFloat::fcZero: Arg = 4; break; 11417 } 11418 return Visit(E->getArg(Arg)); 11419 } 11420 11421 case Builtin::BI__builtin_isinf_sign: { 11422 APFloat Val(0.0); 11423 return EvaluateFloat(E->getArg(0), Val, Info) && 11424 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11425 } 11426 11427 case Builtin::BI__builtin_isinf: { 11428 APFloat Val(0.0); 11429 return EvaluateFloat(E->getArg(0), Val, Info) && 11430 Success(Val.isInfinity() ? 1 : 0, E); 11431 } 11432 11433 case Builtin::BI__builtin_isfinite: { 11434 APFloat Val(0.0); 11435 return EvaluateFloat(E->getArg(0), Val, Info) && 11436 Success(Val.isFinite() ? 1 : 0, E); 11437 } 11438 11439 case Builtin::BI__builtin_isnan: { 11440 APFloat Val(0.0); 11441 return EvaluateFloat(E->getArg(0), Val, Info) && 11442 Success(Val.isNaN() ? 1 : 0, E); 11443 } 11444 11445 case Builtin::BI__builtin_isnormal: { 11446 APFloat Val(0.0); 11447 return EvaluateFloat(E->getArg(0), Val, Info) && 11448 Success(Val.isNormal() ? 1 : 0, E); 11449 } 11450 11451 case Builtin::BI__builtin_parity: 11452 case Builtin::BI__builtin_parityl: 11453 case Builtin::BI__builtin_parityll: { 11454 APSInt Val; 11455 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11456 return false; 11457 11458 return Success(Val.countPopulation() % 2, E); 11459 } 11460 11461 case Builtin::BI__builtin_popcount: 11462 case Builtin::BI__builtin_popcountl: 11463 case Builtin::BI__builtin_popcountll: { 11464 APSInt Val; 11465 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11466 return false; 11467 11468 return Success(Val.countPopulation(), E); 11469 } 11470 11471 case Builtin::BI__builtin_rotateleft8: 11472 case Builtin::BI__builtin_rotateleft16: 11473 case Builtin::BI__builtin_rotateleft32: 11474 case Builtin::BI__builtin_rotateleft64: 11475 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11476 case Builtin::BI_rotl16: 11477 case Builtin::BI_rotl: 11478 case Builtin::BI_lrotl: 11479 case Builtin::BI_rotl64: { 11480 APSInt Val, Amt; 11481 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11482 !EvaluateInteger(E->getArg(1), Amt, Info)) 11483 return false; 11484 11485 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11486 } 11487 11488 case Builtin::BI__builtin_rotateright8: 11489 case Builtin::BI__builtin_rotateright16: 11490 case Builtin::BI__builtin_rotateright32: 11491 case Builtin::BI__builtin_rotateright64: 11492 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11493 case Builtin::BI_rotr16: 11494 case Builtin::BI_rotr: 11495 case Builtin::BI_lrotr: 11496 case Builtin::BI_rotr64: { 11497 APSInt Val, Amt; 11498 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11499 !EvaluateInteger(E->getArg(1), Amt, Info)) 11500 return false; 11501 11502 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11503 } 11504 11505 case Builtin::BIstrlen: 11506 case Builtin::BIwcslen: 11507 // A call to strlen is not a constant expression. 11508 if (Info.getLangOpts().CPlusPlus11) 11509 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11510 << /*isConstexpr*/0 << /*isConstructor*/0 11511 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11512 else 11513 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11514 LLVM_FALLTHROUGH; 11515 case Builtin::BI__builtin_strlen: 11516 case Builtin::BI__builtin_wcslen: { 11517 // As an extension, we support __builtin_strlen() as a constant expression, 11518 // and support folding strlen() to a constant. 11519 LValue String; 11520 if (!EvaluatePointer(E->getArg(0), String, Info)) 11521 return false; 11522 11523 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11524 11525 // Fast path: if it's a string literal, search the string value. 11526 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11527 String.getLValueBase().dyn_cast<const Expr *>())) { 11528 // The string literal may have embedded null characters. Find the first 11529 // one and truncate there. 11530 StringRef Str = S->getBytes(); 11531 int64_t Off = String.Offset.getQuantity(); 11532 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11533 S->getCharByteWidth() == 1 && 11534 // FIXME: Add fast-path for wchar_t too. 11535 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11536 Str = Str.substr(Off); 11537 11538 StringRef::size_type Pos = Str.find(0); 11539 if (Pos != StringRef::npos) 11540 Str = Str.substr(0, Pos); 11541 11542 return Success(Str.size(), E); 11543 } 11544 11545 // Fall through to slow path to issue appropriate diagnostic. 11546 } 11547 11548 // Slow path: scan the bytes of the string looking for the terminating 0. 11549 for (uint64_t Strlen = 0; /**/; ++Strlen) { 11550 APValue Char; 11551 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11552 !Char.isInt()) 11553 return false; 11554 if (!Char.getInt()) 11555 return Success(Strlen, E); 11556 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11557 return false; 11558 } 11559 } 11560 11561 case Builtin::BIstrcmp: 11562 case Builtin::BIwcscmp: 11563 case Builtin::BIstrncmp: 11564 case Builtin::BIwcsncmp: 11565 case Builtin::BImemcmp: 11566 case Builtin::BIbcmp: 11567 case Builtin::BIwmemcmp: 11568 // A call to strlen is not a constant expression. 11569 if (Info.getLangOpts().CPlusPlus11) 11570 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11571 << /*isConstexpr*/0 << /*isConstructor*/0 11572 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11573 else 11574 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11575 LLVM_FALLTHROUGH; 11576 case Builtin::BI__builtin_strcmp: 11577 case Builtin::BI__builtin_wcscmp: 11578 case Builtin::BI__builtin_strncmp: 11579 case Builtin::BI__builtin_wcsncmp: 11580 case Builtin::BI__builtin_memcmp: 11581 case Builtin::BI__builtin_bcmp: 11582 case Builtin::BI__builtin_wmemcmp: { 11583 LValue String1, String2; 11584 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11585 !EvaluatePointer(E->getArg(1), String2, Info)) 11586 return false; 11587 11588 uint64_t MaxLength = uint64_t(-1); 11589 if (BuiltinOp != Builtin::BIstrcmp && 11590 BuiltinOp != Builtin::BIwcscmp && 11591 BuiltinOp != Builtin::BI__builtin_strcmp && 11592 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11593 APSInt N; 11594 if (!EvaluateInteger(E->getArg(2), N, Info)) 11595 return false; 11596 MaxLength = N.getExtValue(); 11597 } 11598 11599 // Empty substrings compare equal by definition. 11600 if (MaxLength == 0u) 11601 return Success(0, E); 11602 11603 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11604 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11605 String1.Designator.Invalid || String2.Designator.Invalid) 11606 return false; 11607 11608 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11609 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11610 11611 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11612 BuiltinOp == Builtin::BIbcmp || 11613 BuiltinOp == Builtin::BI__builtin_memcmp || 11614 BuiltinOp == Builtin::BI__builtin_bcmp; 11615 11616 assert(IsRawByte || 11617 (Info.Ctx.hasSameUnqualifiedType( 11618 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11619 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11620 11621 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11622 // 'char8_t', but no other types. 11623 if (IsRawByte && 11624 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11625 // FIXME: Consider using our bit_cast implementation to support this. 11626 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11627 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11628 << CharTy1 << CharTy2; 11629 return false; 11630 } 11631 11632 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11633 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11634 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11635 Char1.isInt() && Char2.isInt(); 11636 }; 11637 const auto &AdvanceElems = [&] { 11638 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11639 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11640 }; 11641 11642 bool StopAtNull = 11643 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11644 BuiltinOp != Builtin::BIwmemcmp && 11645 BuiltinOp != Builtin::BI__builtin_memcmp && 11646 BuiltinOp != Builtin::BI__builtin_bcmp && 11647 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11648 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11649 BuiltinOp == Builtin::BIwcsncmp || 11650 BuiltinOp == Builtin::BIwmemcmp || 11651 BuiltinOp == Builtin::BI__builtin_wcscmp || 11652 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11653 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11654 11655 for (; MaxLength; --MaxLength) { 11656 APValue Char1, Char2; 11657 if (!ReadCurElems(Char1, Char2)) 11658 return false; 11659 if (Char1.getInt().ne(Char2.getInt())) { 11660 if (IsWide) // wmemcmp compares with wchar_t signedness. 11661 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11662 // memcmp always compares unsigned chars. 11663 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11664 } 11665 if (StopAtNull && !Char1.getInt()) 11666 return Success(0, E); 11667 assert(!(StopAtNull && !Char2.getInt())); 11668 if (!AdvanceElems()) 11669 return false; 11670 } 11671 // We hit the strncmp / memcmp limit. 11672 return Success(0, E); 11673 } 11674 11675 case Builtin::BI__atomic_always_lock_free: 11676 case Builtin::BI__atomic_is_lock_free: 11677 case Builtin::BI__c11_atomic_is_lock_free: { 11678 APSInt SizeVal; 11679 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11680 return false; 11681 11682 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11683 // of two less than or equal to the maximum inline atomic width, we know it 11684 // is lock-free. If the size isn't a power of two, or greater than the 11685 // maximum alignment where we promote atomics, we know it is not lock-free 11686 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11687 // the answer can only be determined at runtime; for example, 16-byte 11688 // atomics have lock-free implementations on some, but not all, 11689 // x86-64 processors. 11690 11691 // Check power-of-two. 11692 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11693 if (Size.isPowerOfTwo()) { 11694 // Check against inlining width. 11695 unsigned InlineWidthBits = 11696 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11697 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11698 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11699 Size == CharUnits::One() || 11700 E->getArg(1)->isNullPointerConstant(Info.Ctx, 11701 Expr::NPC_NeverValueDependent)) 11702 // OK, we will inline appropriately-aligned operations of this size, 11703 // and _Atomic(T) is appropriately-aligned. 11704 return Success(1, E); 11705 11706 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 11707 castAs<PointerType>()->getPointeeType(); 11708 if (!PointeeType->isIncompleteType() && 11709 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 11710 // OK, we will inline operations on this object. 11711 return Success(1, E); 11712 } 11713 } 11714 } 11715 11716 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 11717 Success(0, E) : Error(E); 11718 } 11719 case Builtin::BIomp_is_initial_device: 11720 // We can decide statically which value the runtime would return if called. 11721 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 11722 case Builtin::BI__builtin_add_overflow: 11723 case Builtin::BI__builtin_sub_overflow: 11724 case Builtin::BI__builtin_mul_overflow: 11725 case Builtin::BI__builtin_sadd_overflow: 11726 case Builtin::BI__builtin_uadd_overflow: 11727 case Builtin::BI__builtin_uaddl_overflow: 11728 case Builtin::BI__builtin_uaddll_overflow: 11729 case Builtin::BI__builtin_usub_overflow: 11730 case Builtin::BI__builtin_usubl_overflow: 11731 case Builtin::BI__builtin_usubll_overflow: 11732 case Builtin::BI__builtin_umul_overflow: 11733 case Builtin::BI__builtin_umull_overflow: 11734 case Builtin::BI__builtin_umulll_overflow: 11735 case Builtin::BI__builtin_saddl_overflow: 11736 case Builtin::BI__builtin_saddll_overflow: 11737 case Builtin::BI__builtin_ssub_overflow: 11738 case Builtin::BI__builtin_ssubl_overflow: 11739 case Builtin::BI__builtin_ssubll_overflow: 11740 case Builtin::BI__builtin_smul_overflow: 11741 case Builtin::BI__builtin_smull_overflow: 11742 case Builtin::BI__builtin_smulll_overflow: { 11743 LValue ResultLValue; 11744 APSInt LHS, RHS; 11745 11746 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 11747 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 11748 !EvaluateInteger(E->getArg(1), RHS, Info) || 11749 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 11750 return false; 11751 11752 APSInt Result; 11753 bool DidOverflow = false; 11754 11755 // If the types don't have to match, enlarge all 3 to the largest of them. 11756 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11757 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11758 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11759 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 11760 ResultType->isSignedIntegerOrEnumerationType(); 11761 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 11762 ResultType->isSignedIntegerOrEnumerationType(); 11763 uint64_t LHSSize = LHS.getBitWidth(); 11764 uint64_t RHSSize = RHS.getBitWidth(); 11765 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 11766 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 11767 11768 // Add an additional bit if the signedness isn't uniformly agreed to. We 11769 // could do this ONLY if there is a signed and an unsigned that both have 11770 // MaxBits, but the code to check that is pretty nasty. The issue will be 11771 // caught in the shrink-to-result later anyway. 11772 if (IsSigned && !AllSigned) 11773 ++MaxBits; 11774 11775 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 11776 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 11777 Result = APSInt(MaxBits, !IsSigned); 11778 } 11779 11780 // Find largest int. 11781 switch (BuiltinOp) { 11782 default: 11783 llvm_unreachable("Invalid value for BuiltinOp"); 11784 case Builtin::BI__builtin_add_overflow: 11785 case Builtin::BI__builtin_sadd_overflow: 11786 case Builtin::BI__builtin_saddl_overflow: 11787 case Builtin::BI__builtin_saddll_overflow: 11788 case Builtin::BI__builtin_uadd_overflow: 11789 case Builtin::BI__builtin_uaddl_overflow: 11790 case Builtin::BI__builtin_uaddll_overflow: 11791 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 11792 : LHS.uadd_ov(RHS, DidOverflow); 11793 break; 11794 case Builtin::BI__builtin_sub_overflow: 11795 case Builtin::BI__builtin_ssub_overflow: 11796 case Builtin::BI__builtin_ssubl_overflow: 11797 case Builtin::BI__builtin_ssubll_overflow: 11798 case Builtin::BI__builtin_usub_overflow: 11799 case Builtin::BI__builtin_usubl_overflow: 11800 case Builtin::BI__builtin_usubll_overflow: 11801 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 11802 : LHS.usub_ov(RHS, DidOverflow); 11803 break; 11804 case Builtin::BI__builtin_mul_overflow: 11805 case Builtin::BI__builtin_smul_overflow: 11806 case Builtin::BI__builtin_smull_overflow: 11807 case Builtin::BI__builtin_smulll_overflow: 11808 case Builtin::BI__builtin_umul_overflow: 11809 case Builtin::BI__builtin_umull_overflow: 11810 case Builtin::BI__builtin_umulll_overflow: 11811 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 11812 : LHS.umul_ov(RHS, DidOverflow); 11813 break; 11814 } 11815 11816 // In the case where multiple sizes are allowed, truncate and see if 11817 // the values are the same. 11818 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11819 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11820 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11821 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 11822 // since it will give us the behavior of a TruncOrSelf in the case where 11823 // its parameter <= its size. We previously set Result to be at least the 11824 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 11825 // will work exactly like TruncOrSelf. 11826 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 11827 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 11828 11829 if (!APSInt::isSameValue(Temp, Result)) 11830 DidOverflow = true; 11831 Result = Temp; 11832 } 11833 11834 APValue APV{Result}; 11835 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 11836 return false; 11837 return Success(DidOverflow, E); 11838 } 11839 } 11840 } 11841 11842 /// Determine whether this is a pointer past the end of the complete 11843 /// object referred to by the lvalue. 11844 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 11845 const LValue &LV) { 11846 // A null pointer can be viewed as being "past the end" but we don't 11847 // choose to look at it that way here. 11848 if (!LV.getLValueBase()) 11849 return false; 11850 11851 // If the designator is valid and refers to a subobject, we're not pointing 11852 // past the end. 11853 if (!LV.getLValueDesignator().Invalid && 11854 !LV.getLValueDesignator().isOnePastTheEnd()) 11855 return false; 11856 11857 // A pointer to an incomplete type might be past-the-end if the type's size is 11858 // zero. We cannot tell because the type is incomplete. 11859 QualType Ty = getType(LV.getLValueBase()); 11860 if (Ty->isIncompleteType()) 11861 return true; 11862 11863 // We're a past-the-end pointer if we point to the byte after the object, 11864 // no matter what our type or path is. 11865 auto Size = Ctx.getTypeSizeInChars(Ty); 11866 return LV.getLValueOffset() == Size; 11867 } 11868 11869 namespace { 11870 11871 /// Data recursive integer evaluator of certain binary operators. 11872 /// 11873 /// We use a data recursive algorithm for binary operators so that we are able 11874 /// to handle extreme cases of chained binary operators without causing stack 11875 /// overflow. 11876 class DataRecursiveIntBinOpEvaluator { 11877 struct EvalResult { 11878 APValue Val; 11879 bool Failed; 11880 11881 EvalResult() : Failed(false) { } 11882 11883 void swap(EvalResult &RHS) { 11884 Val.swap(RHS.Val); 11885 Failed = RHS.Failed; 11886 RHS.Failed = false; 11887 } 11888 }; 11889 11890 struct Job { 11891 const Expr *E; 11892 EvalResult LHSResult; // meaningful only for binary operator expression. 11893 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 11894 11895 Job() = default; 11896 Job(Job &&) = default; 11897 11898 void startSpeculativeEval(EvalInfo &Info) { 11899 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 11900 } 11901 11902 private: 11903 SpeculativeEvaluationRAII SpecEvalRAII; 11904 }; 11905 11906 SmallVector<Job, 16> Queue; 11907 11908 IntExprEvaluator &IntEval; 11909 EvalInfo &Info; 11910 APValue &FinalResult; 11911 11912 public: 11913 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 11914 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 11915 11916 /// True if \param E is a binary operator that we are going to handle 11917 /// data recursively. 11918 /// We handle binary operators that are comma, logical, or that have operands 11919 /// with integral or enumeration type. 11920 static bool shouldEnqueue(const BinaryOperator *E) { 11921 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 11922 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 11923 E->getLHS()->getType()->isIntegralOrEnumerationType() && 11924 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11925 } 11926 11927 bool Traverse(const BinaryOperator *E) { 11928 enqueue(E); 11929 EvalResult PrevResult; 11930 while (!Queue.empty()) 11931 process(PrevResult); 11932 11933 if (PrevResult.Failed) return false; 11934 11935 FinalResult.swap(PrevResult.Val); 11936 return true; 11937 } 11938 11939 private: 11940 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 11941 return IntEval.Success(Value, E, Result); 11942 } 11943 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 11944 return IntEval.Success(Value, E, Result); 11945 } 11946 bool Error(const Expr *E) { 11947 return IntEval.Error(E); 11948 } 11949 bool Error(const Expr *E, diag::kind D) { 11950 return IntEval.Error(E, D); 11951 } 11952 11953 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 11954 return Info.CCEDiag(E, D); 11955 } 11956 11957 // Returns true if visiting the RHS is necessary, false otherwise. 11958 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11959 bool &SuppressRHSDiags); 11960 11961 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 11962 const BinaryOperator *E, APValue &Result); 11963 11964 void EvaluateExpr(const Expr *E, EvalResult &Result) { 11965 Result.Failed = !Evaluate(Result.Val, Info, E); 11966 if (Result.Failed) 11967 Result.Val = APValue(); 11968 } 11969 11970 void process(EvalResult &Result); 11971 11972 void enqueue(const Expr *E) { 11973 E = E->IgnoreParens(); 11974 Queue.resize(Queue.size()+1); 11975 Queue.back().E = E; 11976 Queue.back().Kind = Job::AnyExprKind; 11977 } 11978 }; 11979 11980 } 11981 11982 bool DataRecursiveIntBinOpEvaluator:: 11983 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11984 bool &SuppressRHSDiags) { 11985 if (E->getOpcode() == BO_Comma) { 11986 // Ignore LHS but note if we could not evaluate it. 11987 if (LHSResult.Failed) 11988 return Info.noteSideEffect(); 11989 return true; 11990 } 11991 11992 if (E->isLogicalOp()) { 11993 bool LHSAsBool; 11994 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 11995 // We were able to evaluate the LHS, see if we can get away with not 11996 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 11997 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 11998 Success(LHSAsBool, E, LHSResult.Val); 11999 return false; // Ignore RHS 12000 } 12001 } else { 12002 LHSResult.Failed = true; 12003 12004 // Since we weren't able to evaluate the left hand side, it 12005 // might have had side effects. 12006 if (!Info.noteSideEffect()) 12007 return false; 12008 12009 // We can't evaluate the LHS; however, sometimes the result 12010 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12011 // Don't ignore RHS and suppress diagnostics from this arm. 12012 SuppressRHSDiags = true; 12013 } 12014 12015 return true; 12016 } 12017 12018 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12019 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12020 12021 if (LHSResult.Failed && !Info.noteFailure()) 12022 return false; // Ignore RHS; 12023 12024 return true; 12025 } 12026 12027 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12028 bool IsSub) { 12029 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12030 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12031 // offsets. 12032 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12033 CharUnits &Offset = LVal.getLValueOffset(); 12034 uint64_t Offset64 = Offset.getQuantity(); 12035 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12036 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12037 : Offset64 + Index64); 12038 } 12039 12040 bool DataRecursiveIntBinOpEvaluator:: 12041 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12042 const BinaryOperator *E, APValue &Result) { 12043 if (E->getOpcode() == BO_Comma) { 12044 if (RHSResult.Failed) 12045 return false; 12046 Result = RHSResult.Val; 12047 return true; 12048 } 12049 12050 if (E->isLogicalOp()) { 12051 bool lhsResult, rhsResult; 12052 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12053 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12054 12055 if (LHSIsOK) { 12056 if (RHSIsOK) { 12057 if (E->getOpcode() == BO_LOr) 12058 return Success(lhsResult || rhsResult, E, Result); 12059 else 12060 return Success(lhsResult && rhsResult, E, Result); 12061 } 12062 } else { 12063 if (RHSIsOK) { 12064 // We can't evaluate the LHS; however, sometimes the result 12065 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12066 if (rhsResult == (E->getOpcode() == BO_LOr)) 12067 return Success(rhsResult, E, Result); 12068 } 12069 } 12070 12071 return false; 12072 } 12073 12074 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12075 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12076 12077 if (LHSResult.Failed || RHSResult.Failed) 12078 return false; 12079 12080 const APValue &LHSVal = LHSResult.Val; 12081 const APValue &RHSVal = RHSResult.Val; 12082 12083 // Handle cases like (unsigned long)&a + 4. 12084 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12085 Result = LHSVal; 12086 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12087 return true; 12088 } 12089 12090 // Handle cases like 4 + (unsigned long)&a 12091 if (E->getOpcode() == BO_Add && 12092 RHSVal.isLValue() && LHSVal.isInt()) { 12093 Result = RHSVal; 12094 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12095 return true; 12096 } 12097 12098 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12099 // Handle (intptr_t)&&A - (intptr_t)&&B. 12100 if (!LHSVal.getLValueOffset().isZero() || 12101 !RHSVal.getLValueOffset().isZero()) 12102 return false; 12103 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12104 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12105 if (!LHSExpr || !RHSExpr) 12106 return false; 12107 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12108 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12109 if (!LHSAddrExpr || !RHSAddrExpr) 12110 return false; 12111 // Make sure both labels come from the same function. 12112 if (LHSAddrExpr->getLabel()->getDeclContext() != 12113 RHSAddrExpr->getLabel()->getDeclContext()) 12114 return false; 12115 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12116 return true; 12117 } 12118 12119 // All the remaining cases expect both operands to be an integer 12120 if (!LHSVal.isInt() || !RHSVal.isInt()) 12121 return Error(E); 12122 12123 // Set up the width and signedness manually, in case it can't be deduced 12124 // from the operation we're performing. 12125 // FIXME: Don't do this in the cases where we can deduce it. 12126 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12127 E->getType()->isUnsignedIntegerOrEnumerationType()); 12128 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12129 RHSVal.getInt(), Value)) 12130 return false; 12131 return Success(Value, E, Result); 12132 } 12133 12134 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12135 Job &job = Queue.back(); 12136 12137 switch (job.Kind) { 12138 case Job::AnyExprKind: { 12139 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12140 if (shouldEnqueue(Bop)) { 12141 job.Kind = Job::BinOpKind; 12142 enqueue(Bop->getLHS()); 12143 return; 12144 } 12145 } 12146 12147 EvaluateExpr(job.E, Result); 12148 Queue.pop_back(); 12149 return; 12150 } 12151 12152 case Job::BinOpKind: { 12153 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12154 bool SuppressRHSDiags = false; 12155 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12156 Queue.pop_back(); 12157 return; 12158 } 12159 if (SuppressRHSDiags) 12160 job.startSpeculativeEval(Info); 12161 job.LHSResult.swap(Result); 12162 job.Kind = Job::BinOpVisitedLHSKind; 12163 enqueue(Bop->getRHS()); 12164 return; 12165 } 12166 12167 case Job::BinOpVisitedLHSKind: { 12168 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12169 EvalResult RHS; 12170 RHS.swap(Result); 12171 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12172 Queue.pop_back(); 12173 return; 12174 } 12175 } 12176 12177 llvm_unreachable("Invalid Job::Kind!"); 12178 } 12179 12180 namespace { 12181 /// Used when we determine that we should fail, but can keep evaluating prior to 12182 /// noting that we had a failure. 12183 class DelayedNoteFailureRAII { 12184 EvalInfo &Info; 12185 bool NoteFailure; 12186 12187 public: 12188 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 12189 : Info(Info), NoteFailure(NoteFailure) {} 12190 ~DelayedNoteFailureRAII() { 12191 if (NoteFailure) { 12192 bool ContinueAfterFailure = Info.noteFailure(); 12193 (void)ContinueAfterFailure; 12194 assert(ContinueAfterFailure && 12195 "Shouldn't have kept evaluating on failure."); 12196 } 12197 } 12198 }; 12199 12200 enum class CmpResult { 12201 Unequal, 12202 Less, 12203 Equal, 12204 Greater, 12205 Unordered, 12206 }; 12207 } 12208 12209 template <class SuccessCB, class AfterCB> 12210 static bool 12211 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12212 SuccessCB &&Success, AfterCB &&DoAfter) { 12213 assert(E->isComparisonOp() && "expected comparison operator"); 12214 assert((E->getOpcode() == BO_Cmp || 12215 E->getType()->isIntegralOrEnumerationType()) && 12216 "unsupported binary expression evaluation"); 12217 auto Error = [&](const Expr *E) { 12218 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12219 return false; 12220 }; 12221 12222 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12223 bool IsEquality = E->isEqualityOp(); 12224 12225 QualType LHSTy = E->getLHS()->getType(); 12226 QualType RHSTy = E->getRHS()->getType(); 12227 12228 if (LHSTy->isIntegralOrEnumerationType() && 12229 RHSTy->isIntegralOrEnumerationType()) { 12230 APSInt LHS, RHS; 12231 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12232 if (!LHSOK && !Info.noteFailure()) 12233 return false; 12234 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12235 return false; 12236 if (LHS < RHS) 12237 return Success(CmpResult::Less, E); 12238 if (LHS > RHS) 12239 return Success(CmpResult::Greater, E); 12240 return Success(CmpResult::Equal, E); 12241 } 12242 12243 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12244 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12245 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12246 12247 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12248 if (!LHSOK && !Info.noteFailure()) 12249 return false; 12250 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12251 return false; 12252 if (LHSFX < RHSFX) 12253 return Success(CmpResult::Less, E); 12254 if (LHSFX > RHSFX) 12255 return Success(CmpResult::Greater, E); 12256 return Success(CmpResult::Equal, E); 12257 } 12258 12259 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12260 ComplexValue LHS, RHS; 12261 bool LHSOK; 12262 if (E->isAssignmentOp()) { 12263 LValue LV; 12264 EvaluateLValue(E->getLHS(), LV, Info); 12265 LHSOK = false; 12266 } else if (LHSTy->isRealFloatingType()) { 12267 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12268 if (LHSOK) { 12269 LHS.makeComplexFloat(); 12270 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12271 } 12272 } else { 12273 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12274 } 12275 if (!LHSOK && !Info.noteFailure()) 12276 return false; 12277 12278 if (E->getRHS()->getType()->isRealFloatingType()) { 12279 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12280 return false; 12281 RHS.makeComplexFloat(); 12282 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12283 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12284 return false; 12285 12286 if (LHS.isComplexFloat()) { 12287 APFloat::cmpResult CR_r = 12288 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12289 APFloat::cmpResult CR_i = 12290 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12291 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12292 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12293 } else { 12294 assert(IsEquality && "invalid complex comparison"); 12295 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12296 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12297 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12298 } 12299 } 12300 12301 if (LHSTy->isRealFloatingType() && 12302 RHSTy->isRealFloatingType()) { 12303 APFloat RHS(0.0), LHS(0.0); 12304 12305 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12306 if (!LHSOK && !Info.noteFailure()) 12307 return false; 12308 12309 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12310 return false; 12311 12312 assert(E->isComparisonOp() && "Invalid binary operator!"); 12313 auto GetCmpRes = [&]() { 12314 switch (LHS.compare(RHS)) { 12315 case APFloat::cmpEqual: 12316 return CmpResult::Equal; 12317 case APFloat::cmpLessThan: 12318 return CmpResult::Less; 12319 case APFloat::cmpGreaterThan: 12320 return CmpResult::Greater; 12321 case APFloat::cmpUnordered: 12322 return CmpResult::Unordered; 12323 } 12324 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12325 }; 12326 return Success(GetCmpRes(), E); 12327 } 12328 12329 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12330 LValue LHSValue, RHSValue; 12331 12332 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12333 if (!LHSOK && !Info.noteFailure()) 12334 return false; 12335 12336 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12337 return false; 12338 12339 // Reject differing bases from the normal codepath; we special-case 12340 // comparisons to null. 12341 if (!HasSameBase(LHSValue, RHSValue)) { 12342 // Inequalities and subtractions between unrelated pointers have 12343 // unspecified or undefined behavior. 12344 if (!IsEquality) { 12345 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12346 return false; 12347 } 12348 // A constant address may compare equal to the address of a symbol. 12349 // The one exception is that address of an object cannot compare equal 12350 // to a null pointer constant. 12351 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12352 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12353 return Error(E); 12354 // It's implementation-defined whether distinct literals will have 12355 // distinct addresses. In clang, the result of such a comparison is 12356 // unspecified, so it is not a constant expression. However, we do know 12357 // that the address of a literal will be non-null. 12358 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12359 LHSValue.Base && RHSValue.Base) 12360 return Error(E); 12361 // We can't tell whether weak symbols will end up pointing to the same 12362 // object. 12363 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12364 return Error(E); 12365 // We can't compare the address of the start of one object with the 12366 // past-the-end address of another object, per C++ DR1652. 12367 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12368 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12369 (RHSValue.Base && RHSValue.Offset.isZero() && 12370 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12371 return Error(E); 12372 // We can't tell whether an object is at the same address as another 12373 // zero sized object. 12374 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12375 (LHSValue.Base && isZeroSized(RHSValue))) 12376 return Error(E); 12377 return Success(CmpResult::Unequal, E); 12378 } 12379 12380 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12381 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12382 12383 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12384 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12385 12386 // C++11 [expr.rel]p3: 12387 // Pointers to void (after pointer conversions) can be compared, with a 12388 // result defined as follows: If both pointers represent the same 12389 // address or are both the null pointer value, the result is true if the 12390 // operator is <= or >= and false otherwise; otherwise the result is 12391 // unspecified. 12392 // We interpret this as applying to pointers to *cv* void. 12393 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12394 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12395 12396 // C++11 [expr.rel]p2: 12397 // - If two pointers point to non-static data members of the same object, 12398 // or to subobjects or array elements fo such members, recursively, the 12399 // pointer to the later declared member compares greater provided the 12400 // two members have the same access control and provided their class is 12401 // not a union. 12402 // [...] 12403 // - Otherwise pointer comparisons are unspecified. 12404 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12405 bool WasArrayIndex; 12406 unsigned Mismatch = FindDesignatorMismatch( 12407 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12408 // At the point where the designators diverge, the comparison has a 12409 // specified value if: 12410 // - we are comparing array indices 12411 // - we are comparing fields of a union, or fields with the same access 12412 // Otherwise, the result is unspecified and thus the comparison is not a 12413 // constant expression. 12414 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12415 Mismatch < RHSDesignator.Entries.size()) { 12416 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12417 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12418 if (!LF && !RF) 12419 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12420 else if (!LF) 12421 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12422 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12423 << RF->getParent() << RF; 12424 else if (!RF) 12425 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12426 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12427 << LF->getParent() << LF; 12428 else if (!LF->getParent()->isUnion() && 12429 LF->getAccess() != RF->getAccess()) 12430 Info.CCEDiag(E, 12431 diag::note_constexpr_pointer_comparison_differing_access) 12432 << LF << LF->getAccess() << RF << RF->getAccess() 12433 << LF->getParent(); 12434 } 12435 } 12436 12437 // The comparison here must be unsigned, and performed with the same 12438 // width as the pointer. 12439 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12440 uint64_t CompareLHS = LHSOffset.getQuantity(); 12441 uint64_t CompareRHS = RHSOffset.getQuantity(); 12442 assert(PtrSize <= 64 && "Unexpected pointer width"); 12443 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12444 CompareLHS &= Mask; 12445 CompareRHS &= Mask; 12446 12447 // If there is a base and this is a relational operator, we can only 12448 // compare pointers within the object in question; otherwise, the result 12449 // depends on where the object is located in memory. 12450 if (!LHSValue.Base.isNull() && IsRelational) { 12451 QualType BaseTy = getType(LHSValue.Base); 12452 if (BaseTy->isIncompleteType()) 12453 return Error(E); 12454 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12455 uint64_t OffsetLimit = Size.getQuantity(); 12456 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12457 return Error(E); 12458 } 12459 12460 if (CompareLHS < CompareRHS) 12461 return Success(CmpResult::Less, E); 12462 if (CompareLHS > CompareRHS) 12463 return Success(CmpResult::Greater, E); 12464 return Success(CmpResult::Equal, E); 12465 } 12466 12467 if (LHSTy->isMemberPointerType()) { 12468 assert(IsEquality && "unexpected member pointer operation"); 12469 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12470 12471 MemberPtr LHSValue, RHSValue; 12472 12473 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12474 if (!LHSOK && !Info.noteFailure()) 12475 return false; 12476 12477 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12478 return false; 12479 12480 // C++11 [expr.eq]p2: 12481 // If both operands are null, they compare equal. Otherwise if only one is 12482 // null, they compare unequal. 12483 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12484 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12485 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12486 } 12487 12488 // Otherwise if either is a pointer to a virtual member function, the 12489 // result is unspecified. 12490 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12491 if (MD->isVirtual()) 12492 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12493 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12494 if (MD->isVirtual()) 12495 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12496 12497 // Otherwise they compare equal if and only if they would refer to the 12498 // same member of the same most derived object or the same subobject if 12499 // they were dereferenced with a hypothetical object of the associated 12500 // class type. 12501 bool Equal = LHSValue == RHSValue; 12502 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12503 } 12504 12505 if (LHSTy->isNullPtrType()) { 12506 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12507 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12508 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12509 // are compared, the result is true of the operator is <=, >= or ==, and 12510 // false otherwise. 12511 return Success(CmpResult::Equal, E); 12512 } 12513 12514 return DoAfter(); 12515 } 12516 12517 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12518 if (!CheckLiteralType(Info, E)) 12519 return false; 12520 12521 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12522 ComparisonCategoryResult CCR; 12523 switch (CR) { 12524 case CmpResult::Unequal: 12525 llvm_unreachable("should never produce Unequal for three-way comparison"); 12526 case CmpResult::Less: 12527 CCR = ComparisonCategoryResult::Less; 12528 break; 12529 case CmpResult::Equal: 12530 CCR = ComparisonCategoryResult::Equal; 12531 break; 12532 case CmpResult::Greater: 12533 CCR = ComparisonCategoryResult::Greater; 12534 break; 12535 case CmpResult::Unordered: 12536 CCR = ComparisonCategoryResult::Unordered; 12537 break; 12538 } 12539 // Evaluation succeeded. Lookup the information for the comparison category 12540 // type and fetch the VarDecl for the result. 12541 const ComparisonCategoryInfo &CmpInfo = 12542 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12543 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12544 // Check and evaluate the result as a constant expression. 12545 LValue LV; 12546 LV.set(VD); 12547 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12548 return false; 12549 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 12550 }; 12551 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12552 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12553 }); 12554 } 12555 12556 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12557 // We don't call noteFailure immediately because the assignment happens after 12558 // we evaluate LHS and RHS. 12559 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 12560 return Error(E); 12561 12562 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 12563 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12564 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12565 12566 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12567 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12568 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12569 12570 if (E->isComparisonOp()) { 12571 // Evaluate builtin binary comparisons by evaluating them as three-way 12572 // comparisons and then translating the result. 12573 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12574 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12575 "should only produce Unequal for equality comparisons"); 12576 bool IsEqual = CR == CmpResult::Equal, 12577 IsLess = CR == CmpResult::Less, 12578 IsGreater = CR == CmpResult::Greater; 12579 auto Op = E->getOpcode(); 12580 switch (Op) { 12581 default: 12582 llvm_unreachable("unsupported binary operator"); 12583 case BO_EQ: 12584 case BO_NE: 12585 return Success(IsEqual == (Op == BO_EQ), E); 12586 case BO_LT: 12587 return Success(IsLess, E); 12588 case BO_GT: 12589 return Success(IsGreater, E); 12590 case BO_LE: 12591 return Success(IsEqual || IsLess, E); 12592 case BO_GE: 12593 return Success(IsEqual || IsGreater, E); 12594 } 12595 }; 12596 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12597 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12598 }); 12599 } 12600 12601 QualType LHSTy = E->getLHS()->getType(); 12602 QualType RHSTy = E->getRHS()->getType(); 12603 12604 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12605 E->getOpcode() == BO_Sub) { 12606 LValue LHSValue, RHSValue; 12607 12608 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12609 if (!LHSOK && !Info.noteFailure()) 12610 return false; 12611 12612 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12613 return false; 12614 12615 // Reject differing bases from the normal codepath; we special-case 12616 // comparisons to null. 12617 if (!HasSameBase(LHSValue, RHSValue)) { 12618 // Handle &&A - &&B. 12619 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12620 return Error(E); 12621 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12622 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12623 if (!LHSExpr || !RHSExpr) 12624 return Error(E); 12625 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12626 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12627 if (!LHSAddrExpr || !RHSAddrExpr) 12628 return Error(E); 12629 // Make sure both labels come from the same function. 12630 if (LHSAddrExpr->getLabel()->getDeclContext() != 12631 RHSAddrExpr->getLabel()->getDeclContext()) 12632 return Error(E); 12633 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12634 } 12635 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12636 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12637 12638 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12639 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12640 12641 // C++11 [expr.add]p6: 12642 // Unless both pointers point to elements of the same array object, or 12643 // one past the last element of the array object, the behavior is 12644 // undefined. 12645 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12646 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12647 RHSDesignator)) 12648 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12649 12650 QualType Type = E->getLHS()->getType(); 12651 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12652 12653 CharUnits ElementSize; 12654 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12655 return false; 12656 12657 // As an extension, a type may have zero size (empty struct or union in 12658 // C, array of zero length). Pointer subtraction in such cases has 12659 // undefined behavior, so is not constant. 12660 if (ElementSize.isZero()) { 12661 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12662 << ElementType; 12663 return false; 12664 } 12665 12666 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12667 // and produce incorrect results when it overflows. Such behavior 12668 // appears to be non-conforming, but is common, so perhaps we should 12669 // assume the standard intended for such cases to be undefined behavior 12670 // and check for them. 12671 12672 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12673 // overflow in the final conversion to ptrdiff_t. 12674 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12675 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12676 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12677 false); 12678 APSInt TrueResult = (LHS - RHS) / ElemSize; 12679 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12680 12681 if (Result.extend(65) != TrueResult && 12682 !HandleOverflow(Info, E, TrueResult, E->getType())) 12683 return false; 12684 return Success(Result, E); 12685 } 12686 12687 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12688 } 12689 12690 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12691 /// a result as the expression's type. 12692 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12693 const UnaryExprOrTypeTraitExpr *E) { 12694 switch(E->getKind()) { 12695 case UETT_PreferredAlignOf: 12696 case UETT_AlignOf: { 12697 if (E->isArgumentType()) 12698 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 12699 E); 12700 else 12701 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 12702 E); 12703 } 12704 12705 case UETT_VecStep: { 12706 QualType Ty = E->getTypeOfArgument(); 12707 12708 if (Ty->isVectorType()) { 12709 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 12710 12711 // The vec_step built-in functions that take a 3-component 12712 // vector return 4. (OpenCL 1.1 spec 6.11.12) 12713 if (n == 3) 12714 n = 4; 12715 12716 return Success(n, E); 12717 } else 12718 return Success(1, E); 12719 } 12720 12721 case UETT_SizeOf: { 12722 QualType SrcTy = E->getTypeOfArgument(); 12723 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 12724 // the result is the size of the referenced type." 12725 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 12726 SrcTy = Ref->getPointeeType(); 12727 12728 CharUnits Sizeof; 12729 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 12730 return false; 12731 return Success(Sizeof, E); 12732 } 12733 case UETT_OpenMPRequiredSimdAlign: 12734 assert(E->isArgumentType()); 12735 return Success( 12736 Info.Ctx.toCharUnitsFromBits( 12737 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 12738 .getQuantity(), 12739 E); 12740 } 12741 12742 llvm_unreachable("unknown expr/type trait"); 12743 } 12744 12745 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 12746 CharUnits Result; 12747 unsigned n = OOE->getNumComponents(); 12748 if (n == 0) 12749 return Error(OOE); 12750 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 12751 for (unsigned i = 0; i != n; ++i) { 12752 OffsetOfNode ON = OOE->getComponent(i); 12753 switch (ON.getKind()) { 12754 case OffsetOfNode::Array: { 12755 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 12756 APSInt IdxResult; 12757 if (!EvaluateInteger(Idx, IdxResult, Info)) 12758 return false; 12759 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 12760 if (!AT) 12761 return Error(OOE); 12762 CurrentType = AT->getElementType(); 12763 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 12764 Result += IdxResult.getSExtValue() * ElementSize; 12765 break; 12766 } 12767 12768 case OffsetOfNode::Field: { 12769 FieldDecl *MemberDecl = ON.getField(); 12770 const RecordType *RT = CurrentType->getAs<RecordType>(); 12771 if (!RT) 12772 return Error(OOE); 12773 RecordDecl *RD = RT->getDecl(); 12774 if (RD->isInvalidDecl()) return false; 12775 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12776 unsigned i = MemberDecl->getFieldIndex(); 12777 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 12778 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 12779 CurrentType = MemberDecl->getType().getNonReferenceType(); 12780 break; 12781 } 12782 12783 case OffsetOfNode::Identifier: 12784 llvm_unreachable("dependent __builtin_offsetof"); 12785 12786 case OffsetOfNode::Base: { 12787 CXXBaseSpecifier *BaseSpec = ON.getBase(); 12788 if (BaseSpec->isVirtual()) 12789 return Error(OOE); 12790 12791 // Find the layout of the class whose base we are looking into. 12792 const RecordType *RT = CurrentType->getAs<RecordType>(); 12793 if (!RT) 12794 return Error(OOE); 12795 RecordDecl *RD = RT->getDecl(); 12796 if (RD->isInvalidDecl()) return false; 12797 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12798 12799 // Find the base class itself. 12800 CurrentType = BaseSpec->getType(); 12801 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 12802 if (!BaseRT) 12803 return Error(OOE); 12804 12805 // Add the offset to the base. 12806 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 12807 break; 12808 } 12809 } 12810 } 12811 return Success(Result, OOE); 12812 } 12813 12814 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12815 switch (E->getOpcode()) { 12816 default: 12817 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 12818 // See C99 6.6p3. 12819 return Error(E); 12820 case UO_Extension: 12821 // FIXME: Should extension allow i-c-e extension expressions in its scope? 12822 // If so, we could clear the diagnostic ID. 12823 return Visit(E->getSubExpr()); 12824 case UO_Plus: 12825 // The result is just the value. 12826 return Visit(E->getSubExpr()); 12827 case UO_Minus: { 12828 if (!Visit(E->getSubExpr())) 12829 return false; 12830 if (!Result.isInt()) return Error(E); 12831 const APSInt &Value = Result.getInt(); 12832 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 12833 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 12834 E->getType())) 12835 return false; 12836 return Success(-Value, E); 12837 } 12838 case UO_Not: { 12839 if (!Visit(E->getSubExpr())) 12840 return false; 12841 if (!Result.isInt()) return Error(E); 12842 return Success(~Result.getInt(), E); 12843 } 12844 case UO_LNot: { 12845 bool bres; 12846 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 12847 return false; 12848 return Success(!bres, E); 12849 } 12850 } 12851 } 12852 12853 /// HandleCast - This is used to evaluate implicit or explicit casts where the 12854 /// result type is integer. 12855 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 12856 const Expr *SubExpr = E->getSubExpr(); 12857 QualType DestType = E->getType(); 12858 QualType SrcType = SubExpr->getType(); 12859 12860 switch (E->getCastKind()) { 12861 case CK_BaseToDerived: 12862 case CK_DerivedToBase: 12863 case CK_UncheckedDerivedToBase: 12864 case CK_Dynamic: 12865 case CK_ToUnion: 12866 case CK_ArrayToPointerDecay: 12867 case CK_FunctionToPointerDecay: 12868 case CK_NullToPointer: 12869 case CK_NullToMemberPointer: 12870 case CK_BaseToDerivedMemberPointer: 12871 case CK_DerivedToBaseMemberPointer: 12872 case CK_ReinterpretMemberPointer: 12873 case CK_ConstructorConversion: 12874 case CK_IntegralToPointer: 12875 case CK_ToVoid: 12876 case CK_VectorSplat: 12877 case CK_IntegralToFloating: 12878 case CK_FloatingCast: 12879 case CK_CPointerToObjCPointerCast: 12880 case CK_BlockPointerToObjCPointerCast: 12881 case CK_AnyPointerToBlockPointerCast: 12882 case CK_ObjCObjectLValueCast: 12883 case CK_FloatingRealToComplex: 12884 case CK_FloatingComplexToReal: 12885 case CK_FloatingComplexCast: 12886 case CK_FloatingComplexToIntegralComplex: 12887 case CK_IntegralRealToComplex: 12888 case CK_IntegralComplexCast: 12889 case CK_IntegralComplexToFloatingComplex: 12890 case CK_BuiltinFnToFnPtr: 12891 case CK_ZeroToOCLOpaqueType: 12892 case CK_NonAtomicToAtomic: 12893 case CK_AddressSpaceConversion: 12894 case CK_IntToOCLSampler: 12895 case CK_FixedPointCast: 12896 case CK_IntegralToFixedPoint: 12897 llvm_unreachable("invalid cast kind for integral value"); 12898 12899 case CK_BitCast: 12900 case CK_Dependent: 12901 case CK_LValueBitCast: 12902 case CK_ARCProduceObject: 12903 case CK_ARCConsumeObject: 12904 case CK_ARCReclaimReturnedObject: 12905 case CK_ARCExtendBlockObject: 12906 case CK_CopyAndAutoreleaseBlockObject: 12907 return Error(E); 12908 12909 case CK_UserDefinedConversion: 12910 case CK_LValueToRValue: 12911 case CK_AtomicToNonAtomic: 12912 case CK_NoOp: 12913 case CK_LValueToRValueBitCast: 12914 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12915 12916 case CK_MemberPointerToBoolean: 12917 case CK_PointerToBoolean: 12918 case CK_IntegralToBoolean: 12919 case CK_FloatingToBoolean: 12920 case CK_BooleanToSignedIntegral: 12921 case CK_FloatingComplexToBoolean: 12922 case CK_IntegralComplexToBoolean: { 12923 bool BoolResult; 12924 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 12925 return false; 12926 uint64_t IntResult = BoolResult; 12927 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 12928 IntResult = (uint64_t)-1; 12929 return Success(IntResult, E); 12930 } 12931 12932 case CK_FixedPointToIntegral: { 12933 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 12934 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 12935 return false; 12936 bool Overflowed; 12937 llvm::APSInt Result = Src.convertToInt( 12938 Info.Ctx.getIntWidth(DestType), 12939 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 12940 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 12941 return false; 12942 return Success(Result, E); 12943 } 12944 12945 case CK_FixedPointToBoolean: { 12946 // Unsigned padding does not affect this. 12947 APValue Val; 12948 if (!Evaluate(Val, Info, SubExpr)) 12949 return false; 12950 return Success(Val.getFixedPoint().getBoolValue(), E); 12951 } 12952 12953 case CK_IntegralCast: { 12954 if (!Visit(SubExpr)) 12955 return false; 12956 12957 if (!Result.isInt()) { 12958 // Allow casts of address-of-label differences if they are no-ops 12959 // or narrowing. (The narrowing case isn't actually guaranteed to 12960 // be constant-evaluatable except in some narrow cases which are hard 12961 // to detect here. We let it through on the assumption the user knows 12962 // what they are doing.) 12963 if (Result.isAddrLabelDiff()) 12964 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 12965 // Only allow casts of lvalues if they are lossless. 12966 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 12967 } 12968 12969 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 12970 Result.getInt()), E); 12971 } 12972 12973 case CK_PointerToIntegral: { 12974 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 12975 12976 LValue LV; 12977 if (!EvaluatePointer(SubExpr, LV, Info)) 12978 return false; 12979 12980 if (LV.getLValueBase()) { 12981 // Only allow based lvalue casts if they are lossless. 12982 // FIXME: Allow a larger integer size than the pointer size, and allow 12983 // narrowing back down to pointer width in subsequent integral casts. 12984 // FIXME: Check integer type's active bits, not its type size. 12985 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 12986 return Error(E); 12987 12988 LV.Designator.setInvalid(); 12989 LV.moveInto(Result); 12990 return true; 12991 } 12992 12993 APSInt AsInt; 12994 APValue V; 12995 LV.moveInto(V); 12996 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 12997 llvm_unreachable("Can't cast this!"); 12998 12999 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13000 } 13001 13002 case CK_IntegralComplexToReal: { 13003 ComplexValue C; 13004 if (!EvaluateComplex(SubExpr, C, Info)) 13005 return false; 13006 return Success(C.getComplexIntReal(), E); 13007 } 13008 13009 case CK_FloatingToIntegral: { 13010 APFloat F(0.0); 13011 if (!EvaluateFloat(SubExpr, F, Info)) 13012 return false; 13013 13014 APSInt Value; 13015 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13016 return false; 13017 return Success(Value, E); 13018 } 13019 } 13020 13021 llvm_unreachable("unknown cast resulting in integral value"); 13022 } 13023 13024 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13025 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13026 ComplexValue LV; 13027 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13028 return false; 13029 if (!LV.isComplexInt()) 13030 return Error(E); 13031 return Success(LV.getComplexIntReal(), E); 13032 } 13033 13034 return Visit(E->getSubExpr()); 13035 } 13036 13037 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13038 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13039 ComplexValue LV; 13040 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13041 return false; 13042 if (!LV.isComplexInt()) 13043 return Error(E); 13044 return Success(LV.getComplexIntImag(), E); 13045 } 13046 13047 VisitIgnoredValue(E->getSubExpr()); 13048 return Success(0, E); 13049 } 13050 13051 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13052 return Success(E->getPackLength(), E); 13053 } 13054 13055 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13056 return Success(E->getValue(), E); 13057 } 13058 13059 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13060 const ConceptSpecializationExpr *E) { 13061 return Success(E->isSatisfied(), E); 13062 } 13063 13064 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13065 return Success(E->isSatisfied(), E); 13066 } 13067 13068 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13069 switch (E->getOpcode()) { 13070 default: 13071 // Invalid unary operators 13072 return Error(E); 13073 case UO_Plus: 13074 // The result is just the value. 13075 return Visit(E->getSubExpr()); 13076 case UO_Minus: { 13077 if (!Visit(E->getSubExpr())) return false; 13078 if (!Result.isFixedPoint()) 13079 return Error(E); 13080 bool Overflowed; 13081 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13082 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13083 return false; 13084 return Success(Negated, E); 13085 } 13086 case UO_LNot: { 13087 bool bres; 13088 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13089 return false; 13090 return Success(!bres, E); 13091 } 13092 } 13093 } 13094 13095 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13096 const Expr *SubExpr = E->getSubExpr(); 13097 QualType DestType = E->getType(); 13098 assert(DestType->isFixedPointType() && 13099 "Expected destination type to be a fixed point type"); 13100 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13101 13102 switch (E->getCastKind()) { 13103 case CK_FixedPointCast: { 13104 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13105 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13106 return false; 13107 bool Overflowed; 13108 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13109 if (Overflowed) { 13110 if (Info.checkingForUndefinedBehavior()) 13111 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13112 diag::warn_fixedpoint_constant_overflow) 13113 << Result.toString() << E->getType(); 13114 else if (!HandleOverflow(Info, E, Result, E->getType())) 13115 return false; 13116 } 13117 return Success(Result, E); 13118 } 13119 case CK_IntegralToFixedPoint: { 13120 APSInt Src; 13121 if (!EvaluateInteger(SubExpr, Src, Info)) 13122 return false; 13123 13124 bool Overflowed; 13125 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13126 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13127 13128 if (Overflowed) { 13129 if (Info.checkingForUndefinedBehavior()) 13130 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13131 diag::warn_fixedpoint_constant_overflow) 13132 << IntResult.toString() << E->getType(); 13133 else if (!HandleOverflow(Info, E, IntResult, E->getType())) 13134 return false; 13135 } 13136 13137 return Success(IntResult, E); 13138 } 13139 case CK_NoOp: 13140 case CK_LValueToRValue: 13141 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13142 default: 13143 return Error(E); 13144 } 13145 } 13146 13147 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13148 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13149 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13150 13151 const Expr *LHS = E->getLHS(); 13152 const Expr *RHS = E->getRHS(); 13153 FixedPointSemantics ResultFXSema = 13154 Info.Ctx.getFixedPointSemantics(E->getType()); 13155 13156 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13157 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13158 return false; 13159 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13160 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13161 return false; 13162 13163 bool OpOverflow = false, ConversionOverflow = false; 13164 APFixedPoint Result(LHSFX.getSemantics()); 13165 switch (E->getOpcode()) { 13166 case BO_Add: { 13167 Result = LHSFX.add(RHSFX, &OpOverflow) 13168 .convert(ResultFXSema, &ConversionOverflow); 13169 break; 13170 } 13171 case BO_Sub: { 13172 Result = LHSFX.sub(RHSFX, &OpOverflow) 13173 .convert(ResultFXSema, &ConversionOverflow); 13174 break; 13175 } 13176 case BO_Mul: { 13177 Result = LHSFX.mul(RHSFX, &OpOverflow) 13178 .convert(ResultFXSema, &ConversionOverflow); 13179 break; 13180 } 13181 case BO_Div: { 13182 if (RHSFX.getValue() == 0) { 13183 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13184 return false; 13185 } 13186 Result = LHSFX.div(RHSFX, &OpOverflow) 13187 .convert(ResultFXSema, &ConversionOverflow); 13188 break; 13189 } 13190 case BO_Shl: 13191 case BO_Shr: { 13192 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13193 llvm::APSInt RHSVal = RHSFX.getValue(); 13194 13195 unsigned ShiftBW = 13196 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13197 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13198 // Embedded-C 4.1.6.2.2: 13199 // The right operand must be nonnegative and less than the total number 13200 // of (nonpadding) bits of the fixed-point operand ... 13201 if (RHSVal.isNegative()) 13202 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13203 else if (Amt != RHSVal) 13204 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13205 << RHSVal << E->getType() << ShiftBW; 13206 13207 if (E->getOpcode() == BO_Shl) 13208 Result = LHSFX.shl(Amt, &OpOverflow); 13209 else 13210 Result = LHSFX.shr(Amt, &OpOverflow); 13211 break; 13212 } 13213 default: 13214 return false; 13215 } 13216 if (OpOverflow || ConversionOverflow) { 13217 if (Info.checkingForUndefinedBehavior()) 13218 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13219 diag::warn_fixedpoint_constant_overflow) 13220 << Result.toString() << E->getType(); 13221 else if (!HandleOverflow(Info, E, Result, E->getType())) 13222 return false; 13223 } 13224 return Success(Result, E); 13225 } 13226 13227 //===----------------------------------------------------------------------===// 13228 // Float Evaluation 13229 //===----------------------------------------------------------------------===// 13230 13231 namespace { 13232 class FloatExprEvaluator 13233 : public ExprEvaluatorBase<FloatExprEvaluator> { 13234 APFloat &Result; 13235 public: 13236 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13237 : ExprEvaluatorBaseTy(info), Result(result) {} 13238 13239 bool Success(const APValue &V, const Expr *e) { 13240 Result = V.getFloat(); 13241 return true; 13242 } 13243 13244 bool ZeroInitialization(const Expr *E) { 13245 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13246 return true; 13247 } 13248 13249 bool VisitCallExpr(const CallExpr *E); 13250 13251 bool VisitUnaryOperator(const UnaryOperator *E); 13252 bool VisitBinaryOperator(const BinaryOperator *E); 13253 bool VisitFloatingLiteral(const FloatingLiteral *E); 13254 bool VisitCastExpr(const CastExpr *E); 13255 13256 bool VisitUnaryReal(const UnaryOperator *E); 13257 bool VisitUnaryImag(const UnaryOperator *E); 13258 13259 // FIXME: Missing: array subscript of vector, member of vector 13260 }; 13261 } // end anonymous namespace 13262 13263 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13264 assert(E->isRValue() && E->getType()->isRealFloatingType()); 13265 return FloatExprEvaluator(Info, Result).Visit(E); 13266 } 13267 13268 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13269 QualType ResultTy, 13270 const Expr *Arg, 13271 bool SNaN, 13272 llvm::APFloat &Result) { 13273 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13274 if (!S) return false; 13275 13276 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13277 13278 llvm::APInt fill; 13279 13280 // Treat empty strings as if they were zero. 13281 if (S->getString().empty()) 13282 fill = llvm::APInt(32, 0); 13283 else if (S->getString().getAsInteger(0, fill)) 13284 return false; 13285 13286 if (Context.getTargetInfo().isNan2008()) { 13287 if (SNaN) 13288 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13289 else 13290 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13291 } else { 13292 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13293 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13294 // a different encoding to what became a standard in 2008, and for pre- 13295 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13296 // sNaN. This is now known as "legacy NaN" encoding. 13297 if (SNaN) 13298 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13299 else 13300 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13301 } 13302 13303 return true; 13304 } 13305 13306 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13307 switch (E->getBuiltinCallee()) { 13308 default: 13309 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13310 13311 case Builtin::BI__builtin_huge_val: 13312 case Builtin::BI__builtin_huge_valf: 13313 case Builtin::BI__builtin_huge_vall: 13314 case Builtin::BI__builtin_huge_valf128: 13315 case Builtin::BI__builtin_inf: 13316 case Builtin::BI__builtin_inff: 13317 case Builtin::BI__builtin_infl: 13318 case Builtin::BI__builtin_inff128: { 13319 const llvm::fltSemantics &Sem = 13320 Info.Ctx.getFloatTypeSemantics(E->getType()); 13321 Result = llvm::APFloat::getInf(Sem); 13322 return true; 13323 } 13324 13325 case Builtin::BI__builtin_nans: 13326 case Builtin::BI__builtin_nansf: 13327 case Builtin::BI__builtin_nansl: 13328 case Builtin::BI__builtin_nansf128: 13329 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13330 true, Result)) 13331 return Error(E); 13332 return true; 13333 13334 case Builtin::BI__builtin_nan: 13335 case Builtin::BI__builtin_nanf: 13336 case Builtin::BI__builtin_nanl: 13337 case Builtin::BI__builtin_nanf128: 13338 // If this is __builtin_nan() turn this into a nan, otherwise we 13339 // can't constant fold it. 13340 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13341 false, Result)) 13342 return Error(E); 13343 return true; 13344 13345 case Builtin::BI__builtin_fabs: 13346 case Builtin::BI__builtin_fabsf: 13347 case Builtin::BI__builtin_fabsl: 13348 case Builtin::BI__builtin_fabsf128: 13349 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13350 return false; 13351 13352 if (Result.isNegative()) 13353 Result.changeSign(); 13354 return true; 13355 13356 // FIXME: Builtin::BI__builtin_powi 13357 // FIXME: Builtin::BI__builtin_powif 13358 // FIXME: Builtin::BI__builtin_powil 13359 13360 case Builtin::BI__builtin_copysign: 13361 case Builtin::BI__builtin_copysignf: 13362 case Builtin::BI__builtin_copysignl: 13363 case Builtin::BI__builtin_copysignf128: { 13364 APFloat RHS(0.); 13365 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13366 !EvaluateFloat(E->getArg(1), RHS, Info)) 13367 return false; 13368 Result.copySign(RHS); 13369 return true; 13370 } 13371 } 13372 } 13373 13374 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13375 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13376 ComplexValue CV; 13377 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13378 return false; 13379 Result = CV.FloatReal; 13380 return true; 13381 } 13382 13383 return Visit(E->getSubExpr()); 13384 } 13385 13386 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13387 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13388 ComplexValue CV; 13389 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13390 return false; 13391 Result = CV.FloatImag; 13392 return true; 13393 } 13394 13395 VisitIgnoredValue(E->getSubExpr()); 13396 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13397 Result = llvm::APFloat::getZero(Sem); 13398 return true; 13399 } 13400 13401 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13402 switch (E->getOpcode()) { 13403 default: return Error(E); 13404 case UO_Plus: 13405 return EvaluateFloat(E->getSubExpr(), Result, Info); 13406 case UO_Minus: 13407 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13408 return false; 13409 Result.changeSign(); 13410 return true; 13411 } 13412 } 13413 13414 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13415 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13416 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13417 13418 APFloat RHS(0.0); 13419 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13420 if (!LHSOK && !Info.noteFailure()) 13421 return false; 13422 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13423 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13424 } 13425 13426 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13427 Result = E->getValue(); 13428 return true; 13429 } 13430 13431 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13432 const Expr* SubExpr = E->getSubExpr(); 13433 13434 switch (E->getCastKind()) { 13435 default: 13436 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13437 13438 case CK_IntegralToFloating: { 13439 APSInt IntResult; 13440 return EvaluateInteger(SubExpr, IntResult, Info) && 13441 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 13442 E->getType(), Result); 13443 } 13444 13445 case CK_FloatingCast: { 13446 if (!Visit(SubExpr)) 13447 return false; 13448 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13449 Result); 13450 } 13451 13452 case CK_FloatingComplexToReal: { 13453 ComplexValue V; 13454 if (!EvaluateComplex(SubExpr, V, Info)) 13455 return false; 13456 Result = V.getComplexFloatReal(); 13457 return true; 13458 } 13459 } 13460 } 13461 13462 //===----------------------------------------------------------------------===// 13463 // Complex Evaluation (for float and integer) 13464 //===----------------------------------------------------------------------===// 13465 13466 namespace { 13467 class ComplexExprEvaluator 13468 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13469 ComplexValue &Result; 13470 13471 public: 13472 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13473 : ExprEvaluatorBaseTy(info), Result(Result) {} 13474 13475 bool Success(const APValue &V, const Expr *e) { 13476 Result.setFrom(V); 13477 return true; 13478 } 13479 13480 bool ZeroInitialization(const Expr *E); 13481 13482 //===--------------------------------------------------------------------===// 13483 // Visitor Methods 13484 //===--------------------------------------------------------------------===// 13485 13486 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13487 bool VisitCastExpr(const CastExpr *E); 13488 bool VisitBinaryOperator(const BinaryOperator *E); 13489 bool VisitUnaryOperator(const UnaryOperator *E); 13490 bool VisitInitListExpr(const InitListExpr *E); 13491 bool VisitCallExpr(const CallExpr *E); 13492 }; 13493 } // end anonymous namespace 13494 13495 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13496 EvalInfo &Info) { 13497 assert(E->isRValue() && E->getType()->isAnyComplexType()); 13498 return ComplexExprEvaluator(Info, Result).Visit(E); 13499 } 13500 13501 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13502 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13503 if (ElemTy->isRealFloatingType()) { 13504 Result.makeComplexFloat(); 13505 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13506 Result.FloatReal = Zero; 13507 Result.FloatImag = Zero; 13508 } else { 13509 Result.makeComplexInt(); 13510 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13511 Result.IntReal = Zero; 13512 Result.IntImag = Zero; 13513 } 13514 return true; 13515 } 13516 13517 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13518 const Expr* SubExpr = E->getSubExpr(); 13519 13520 if (SubExpr->getType()->isRealFloatingType()) { 13521 Result.makeComplexFloat(); 13522 APFloat &Imag = Result.FloatImag; 13523 if (!EvaluateFloat(SubExpr, Imag, Info)) 13524 return false; 13525 13526 Result.FloatReal = APFloat(Imag.getSemantics()); 13527 return true; 13528 } else { 13529 assert(SubExpr->getType()->isIntegerType() && 13530 "Unexpected imaginary literal."); 13531 13532 Result.makeComplexInt(); 13533 APSInt &Imag = Result.IntImag; 13534 if (!EvaluateInteger(SubExpr, Imag, Info)) 13535 return false; 13536 13537 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13538 return true; 13539 } 13540 } 13541 13542 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13543 13544 switch (E->getCastKind()) { 13545 case CK_BitCast: 13546 case CK_BaseToDerived: 13547 case CK_DerivedToBase: 13548 case CK_UncheckedDerivedToBase: 13549 case CK_Dynamic: 13550 case CK_ToUnion: 13551 case CK_ArrayToPointerDecay: 13552 case CK_FunctionToPointerDecay: 13553 case CK_NullToPointer: 13554 case CK_NullToMemberPointer: 13555 case CK_BaseToDerivedMemberPointer: 13556 case CK_DerivedToBaseMemberPointer: 13557 case CK_MemberPointerToBoolean: 13558 case CK_ReinterpretMemberPointer: 13559 case CK_ConstructorConversion: 13560 case CK_IntegralToPointer: 13561 case CK_PointerToIntegral: 13562 case CK_PointerToBoolean: 13563 case CK_ToVoid: 13564 case CK_VectorSplat: 13565 case CK_IntegralCast: 13566 case CK_BooleanToSignedIntegral: 13567 case CK_IntegralToBoolean: 13568 case CK_IntegralToFloating: 13569 case CK_FloatingToIntegral: 13570 case CK_FloatingToBoolean: 13571 case CK_FloatingCast: 13572 case CK_CPointerToObjCPointerCast: 13573 case CK_BlockPointerToObjCPointerCast: 13574 case CK_AnyPointerToBlockPointerCast: 13575 case CK_ObjCObjectLValueCast: 13576 case CK_FloatingComplexToReal: 13577 case CK_FloatingComplexToBoolean: 13578 case CK_IntegralComplexToReal: 13579 case CK_IntegralComplexToBoolean: 13580 case CK_ARCProduceObject: 13581 case CK_ARCConsumeObject: 13582 case CK_ARCReclaimReturnedObject: 13583 case CK_ARCExtendBlockObject: 13584 case CK_CopyAndAutoreleaseBlockObject: 13585 case CK_BuiltinFnToFnPtr: 13586 case CK_ZeroToOCLOpaqueType: 13587 case CK_NonAtomicToAtomic: 13588 case CK_AddressSpaceConversion: 13589 case CK_IntToOCLSampler: 13590 case CK_FixedPointCast: 13591 case CK_FixedPointToBoolean: 13592 case CK_FixedPointToIntegral: 13593 case CK_IntegralToFixedPoint: 13594 llvm_unreachable("invalid cast kind for complex value"); 13595 13596 case CK_LValueToRValue: 13597 case CK_AtomicToNonAtomic: 13598 case CK_NoOp: 13599 case CK_LValueToRValueBitCast: 13600 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13601 13602 case CK_Dependent: 13603 case CK_LValueBitCast: 13604 case CK_UserDefinedConversion: 13605 return Error(E); 13606 13607 case CK_FloatingRealToComplex: { 13608 APFloat &Real = Result.FloatReal; 13609 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13610 return false; 13611 13612 Result.makeComplexFloat(); 13613 Result.FloatImag = APFloat(Real.getSemantics()); 13614 return true; 13615 } 13616 13617 case CK_FloatingComplexCast: { 13618 if (!Visit(E->getSubExpr())) 13619 return false; 13620 13621 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13622 QualType From 13623 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13624 13625 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13626 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13627 } 13628 13629 case CK_FloatingComplexToIntegralComplex: { 13630 if (!Visit(E->getSubExpr())) 13631 return false; 13632 13633 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13634 QualType From 13635 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13636 Result.makeComplexInt(); 13637 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13638 To, Result.IntReal) && 13639 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13640 To, Result.IntImag); 13641 } 13642 13643 case CK_IntegralRealToComplex: { 13644 APSInt &Real = Result.IntReal; 13645 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13646 return false; 13647 13648 Result.makeComplexInt(); 13649 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13650 return true; 13651 } 13652 13653 case CK_IntegralComplexCast: { 13654 if (!Visit(E->getSubExpr())) 13655 return false; 13656 13657 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13658 QualType From 13659 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13660 13661 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 13662 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 13663 return true; 13664 } 13665 13666 case CK_IntegralComplexToFloatingComplex: { 13667 if (!Visit(E->getSubExpr())) 13668 return false; 13669 13670 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13671 QualType From 13672 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13673 Result.makeComplexFloat(); 13674 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 13675 To, Result.FloatReal) && 13676 HandleIntToFloatCast(Info, E, From, Result.IntImag, 13677 To, Result.FloatImag); 13678 } 13679 } 13680 13681 llvm_unreachable("unknown cast resulting in complex value"); 13682 } 13683 13684 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13685 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13686 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13687 13688 // Track whether the LHS or RHS is real at the type system level. When this is 13689 // the case we can simplify our evaluation strategy. 13690 bool LHSReal = false, RHSReal = false; 13691 13692 bool LHSOK; 13693 if (E->getLHS()->getType()->isRealFloatingType()) { 13694 LHSReal = true; 13695 APFloat &Real = Result.FloatReal; 13696 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 13697 if (LHSOK) { 13698 Result.makeComplexFloat(); 13699 Result.FloatImag = APFloat(Real.getSemantics()); 13700 } 13701 } else { 13702 LHSOK = Visit(E->getLHS()); 13703 } 13704 if (!LHSOK && !Info.noteFailure()) 13705 return false; 13706 13707 ComplexValue RHS; 13708 if (E->getRHS()->getType()->isRealFloatingType()) { 13709 RHSReal = true; 13710 APFloat &Real = RHS.FloatReal; 13711 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 13712 return false; 13713 RHS.makeComplexFloat(); 13714 RHS.FloatImag = APFloat(Real.getSemantics()); 13715 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 13716 return false; 13717 13718 assert(!(LHSReal && RHSReal) && 13719 "Cannot have both operands of a complex operation be real."); 13720 switch (E->getOpcode()) { 13721 default: return Error(E); 13722 case BO_Add: 13723 if (Result.isComplexFloat()) { 13724 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 13725 APFloat::rmNearestTiesToEven); 13726 if (LHSReal) 13727 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13728 else if (!RHSReal) 13729 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 13730 APFloat::rmNearestTiesToEven); 13731 } else { 13732 Result.getComplexIntReal() += RHS.getComplexIntReal(); 13733 Result.getComplexIntImag() += RHS.getComplexIntImag(); 13734 } 13735 break; 13736 case BO_Sub: 13737 if (Result.isComplexFloat()) { 13738 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 13739 APFloat::rmNearestTiesToEven); 13740 if (LHSReal) { 13741 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13742 Result.getComplexFloatImag().changeSign(); 13743 } else if (!RHSReal) { 13744 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 13745 APFloat::rmNearestTiesToEven); 13746 } 13747 } else { 13748 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 13749 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 13750 } 13751 break; 13752 case BO_Mul: 13753 if (Result.isComplexFloat()) { 13754 // This is an implementation of complex multiplication according to the 13755 // constraints laid out in C11 Annex G. The implementation uses the 13756 // following naming scheme: 13757 // (a + ib) * (c + id) 13758 ComplexValue LHS = Result; 13759 APFloat &A = LHS.getComplexFloatReal(); 13760 APFloat &B = LHS.getComplexFloatImag(); 13761 APFloat &C = RHS.getComplexFloatReal(); 13762 APFloat &D = RHS.getComplexFloatImag(); 13763 APFloat &ResR = Result.getComplexFloatReal(); 13764 APFloat &ResI = Result.getComplexFloatImag(); 13765 if (LHSReal) { 13766 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 13767 ResR = A * C; 13768 ResI = A * D; 13769 } else if (RHSReal) { 13770 ResR = C * A; 13771 ResI = C * B; 13772 } else { 13773 // In the fully general case, we need to handle NaNs and infinities 13774 // robustly. 13775 APFloat AC = A * C; 13776 APFloat BD = B * D; 13777 APFloat AD = A * D; 13778 APFloat BC = B * C; 13779 ResR = AC - BD; 13780 ResI = AD + BC; 13781 if (ResR.isNaN() && ResI.isNaN()) { 13782 bool Recalc = false; 13783 if (A.isInfinity() || B.isInfinity()) { 13784 A = APFloat::copySign( 13785 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13786 B = APFloat::copySign( 13787 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13788 if (C.isNaN()) 13789 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13790 if (D.isNaN()) 13791 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13792 Recalc = true; 13793 } 13794 if (C.isInfinity() || D.isInfinity()) { 13795 C = APFloat::copySign( 13796 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13797 D = APFloat::copySign( 13798 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13799 if (A.isNaN()) 13800 A = APFloat::copySign(APFloat(A.getSemantics()), A); 13801 if (B.isNaN()) 13802 B = APFloat::copySign(APFloat(B.getSemantics()), B); 13803 Recalc = true; 13804 } 13805 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 13806 AD.isInfinity() || BC.isInfinity())) { 13807 if (A.isNaN()) 13808 A = APFloat::copySign(APFloat(A.getSemantics()), A); 13809 if (B.isNaN()) 13810 B = APFloat::copySign(APFloat(B.getSemantics()), B); 13811 if (C.isNaN()) 13812 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13813 if (D.isNaN()) 13814 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13815 Recalc = true; 13816 } 13817 if (Recalc) { 13818 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 13819 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 13820 } 13821 } 13822 } 13823 } else { 13824 ComplexValue LHS = Result; 13825 Result.getComplexIntReal() = 13826 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 13827 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 13828 Result.getComplexIntImag() = 13829 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 13830 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 13831 } 13832 break; 13833 case BO_Div: 13834 if (Result.isComplexFloat()) { 13835 // This is an implementation of complex division according to the 13836 // constraints laid out in C11 Annex G. The implementation uses the 13837 // following naming scheme: 13838 // (a + ib) / (c + id) 13839 ComplexValue LHS = Result; 13840 APFloat &A = LHS.getComplexFloatReal(); 13841 APFloat &B = LHS.getComplexFloatImag(); 13842 APFloat &C = RHS.getComplexFloatReal(); 13843 APFloat &D = RHS.getComplexFloatImag(); 13844 APFloat &ResR = Result.getComplexFloatReal(); 13845 APFloat &ResI = Result.getComplexFloatImag(); 13846 if (RHSReal) { 13847 ResR = A / C; 13848 ResI = B / C; 13849 } else { 13850 if (LHSReal) { 13851 // No real optimizations we can do here, stub out with zero. 13852 B = APFloat::getZero(A.getSemantics()); 13853 } 13854 int DenomLogB = 0; 13855 APFloat MaxCD = maxnum(abs(C), abs(D)); 13856 if (MaxCD.isFinite()) { 13857 DenomLogB = ilogb(MaxCD); 13858 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 13859 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 13860 } 13861 APFloat Denom = C * C + D * D; 13862 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 13863 APFloat::rmNearestTiesToEven); 13864 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 13865 APFloat::rmNearestTiesToEven); 13866 if (ResR.isNaN() && ResI.isNaN()) { 13867 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 13868 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 13869 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 13870 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 13871 D.isFinite()) { 13872 A = APFloat::copySign( 13873 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13874 B = APFloat::copySign( 13875 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13876 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 13877 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 13878 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 13879 C = APFloat::copySign( 13880 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13881 D = APFloat::copySign( 13882 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13883 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 13884 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 13885 } 13886 } 13887 } 13888 } else { 13889 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 13890 return Error(E, diag::note_expr_divide_by_zero); 13891 13892 ComplexValue LHS = Result; 13893 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 13894 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 13895 Result.getComplexIntReal() = 13896 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 13897 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 13898 Result.getComplexIntImag() = 13899 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 13900 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 13901 } 13902 break; 13903 } 13904 13905 return true; 13906 } 13907 13908 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13909 // Get the operand value into 'Result'. 13910 if (!Visit(E->getSubExpr())) 13911 return false; 13912 13913 switch (E->getOpcode()) { 13914 default: 13915 return Error(E); 13916 case UO_Extension: 13917 return true; 13918 case UO_Plus: 13919 // The result is always just the subexpr. 13920 return true; 13921 case UO_Minus: 13922 if (Result.isComplexFloat()) { 13923 Result.getComplexFloatReal().changeSign(); 13924 Result.getComplexFloatImag().changeSign(); 13925 } 13926 else { 13927 Result.getComplexIntReal() = -Result.getComplexIntReal(); 13928 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13929 } 13930 return true; 13931 case UO_Not: 13932 if (Result.isComplexFloat()) 13933 Result.getComplexFloatImag().changeSign(); 13934 else 13935 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13936 return true; 13937 } 13938 } 13939 13940 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 13941 if (E->getNumInits() == 2) { 13942 if (E->getType()->isComplexType()) { 13943 Result.makeComplexFloat(); 13944 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 13945 return false; 13946 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 13947 return false; 13948 } else { 13949 Result.makeComplexInt(); 13950 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 13951 return false; 13952 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 13953 return false; 13954 } 13955 return true; 13956 } 13957 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 13958 } 13959 13960 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 13961 switch (E->getBuiltinCallee()) { 13962 case Builtin::BI__builtin_complex: 13963 Result.makeComplexFloat(); 13964 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 13965 return false; 13966 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 13967 return false; 13968 return true; 13969 13970 default: 13971 break; 13972 } 13973 13974 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13975 } 13976 13977 //===----------------------------------------------------------------------===// 13978 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 13979 // implicit conversion. 13980 //===----------------------------------------------------------------------===// 13981 13982 namespace { 13983 class AtomicExprEvaluator : 13984 public ExprEvaluatorBase<AtomicExprEvaluator> { 13985 const LValue *This; 13986 APValue &Result; 13987 public: 13988 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 13989 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 13990 13991 bool Success(const APValue &V, const Expr *E) { 13992 Result = V; 13993 return true; 13994 } 13995 13996 bool ZeroInitialization(const Expr *E) { 13997 ImplicitValueInitExpr VIE( 13998 E->getType()->castAs<AtomicType>()->getValueType()); 13999 // For atomic-qualified class (and array) types in C++, initialize the 14000 // _Atomic-wrapped subobject directly, in-place. 14001 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14002 : Evaluate(Result, Info, &VIE); 14003 } 14004 14005 bool VisitCastExpr(const CastExpr *E) { 14006 switch (E->getCastKind()) { 14007 default: 14008 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14009 case CK_NonAtomicToAtomic: 14010 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14011 : Evaluate(Result, Info, E->getSubExpr()); 14012 } 14013 } 14014 }; 14015 } // end anonymous namespace 14016 14017 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14018 EvalInfo &Info) { 14019 assert(E->isRValue() && E->getType()->isAtomicType()); 14020 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14021 } 14022 14023 //===----------------------------------------------------------------------===// 14024 // Void expression evaluation, primarily for a cast to void on the LHS of a 14025 // comma operator 14026 //===----------------------------------------------------------------------===// 14027 14028 namespace { 14029 class VoidExprEvaluator 14030 : public ExprEvaluatorBase<VoidExprEvaluator> { 14031 public: 14032 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14033 14034 bool Success(const APValue &V, const Expr *e) { return true; } 14035 14036 bool ZeroInitialization(const Expr *E) { return true; } 14037 14038 bool VisitCastExpr(const CastExpr *E) { 14039 switch (E->getCastKind()) { 14040 default: 14041 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14042 case CK_ToVoid: 14043 VisitIgnoredValue(E->getSubExpr()); 14044 return true; 14045 } 14046 } 14047 14048 bool VisitCallExpr(const CallExpr *E) { 14049 switch (E->getBuiltinCallee()) { 14050 case Builtin::BI__assume: 14051 case Builtin::BI__builtin_assume: 14052 // The argument is not evaluated! 14053 return true; 14054 14055 case Builtin::BI__builtin_operator_delete: 14056 return HandleOperatorDeleteCall(Info, E); 14057 14058 default: 14059 break; 14060 } 14061 14062 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14063 } 14064 14065 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14066 }; 14067 } // end anonymous namespace 14068 14069 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14070 // We cannot speculatively evaluate a delete expression. 14071 if (Info.SpeculativeEvaluationDepth) 14072 return false; 14073 14074 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14075 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14076 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14077 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14078 return false; 14079 } 14080 14081 const Expr *Arg = E->getArgument(); 14082 14083 LValue Pointer; 14084 if (!EvaluatePointer(Arg, Pointer, Info)) 14085 return false; 14086 if (Pointer.Designator.Invalid) 14087 return false; 14088 14089 // Deleting a null pointer has no effect. 14090 if (Pointer.isNullPointer()) { 14091 // This is the only case where we need to produce an extension warning: 14092 // the only other way we can succeed is if we find a dynamic allocation, 14093 // and we will have warned when we allocated it in that case. 14094 if (!Info.getLangOpts().CPlusPlus20) 14095 Info.CCEDiag(E, diag::note_constexpr_new); 14096 return true; 14097 } 14098 14099 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14100 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14101 if (!Alloc) 14102 return false; 14103 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14104 14105 // For the non-array case, the designator must be empty if the static type 14106 // does not have a virtual destructor. 14107 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14108 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14109 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14110 << Arg->getType()->getPointeeType() << AllocType; 14111 return false; 14112 } 14113 14114 // For a class type with a virtual destructor, the selected operator delete 14115 // is the one looked up when building the destructor. 14116 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14117 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14118 if (VirtualDelete && 14119 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14120 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14121 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14122 return false; 14123 } 14124 } 14125 14126 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14127 (*Alloc)->Value, AllocType)) 14128 return false; 14129 14130 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14131 // The element was already erased. This means the destructor call also 14132 // deleted the object. 14133 // FIXME: This probably results in undefined behavior before we get this 14134 // far, and should be diagnosed elsewhere first. 14135 Info.FFDiag(E, diag::note_constexpr_double_delete); 14136 return false; 14137 } 14138 14139 return true; 14140 } 14141 14142 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14143 assert(E->isRValue() && E->getType()->isVoidType()); 14144 return VoidExprEvaluator(Info).Visit(E); 14145 } 14146 14147 //===----------------------------------------------------------------------===// 14148 // Top level Expr::EvaluateAsRValue method. 14149 //===----------------------------------------------------------------------===// 14150 14151 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14152 // In C, function designators are not lvalues, but we evaluate them as if they 14153 // are. 14154 QualType T = E->getType(); 14155 if (E->isGLValue() || T->isFunctionType()) { 14156 LValue LV; 14157 if (!EvaluateLValue(E, LV, Info)) 14158 return false; 14159 LV.moveInto(Result); 14160 } else if (T->isVectorType()) { 14161 if (!EvaluateVector(E, Result, Info)) 14162 return false; 14163 } else if (T->isIntegralOrEnumerationType()) { 14164 if (!IntExprEvaluator(Info, Result).Visit(E)) 14165 return false; 14166 } else if (T->hasPointerRepresentation()) { 14167 LValue LV; 14168 if (!EvaluatePointer(E, LV, Info)) 14169 return false; 14170 LV.moveInto(Result); 14171 } else if (T->isRealFloatingType()) { 14172 llvm::APFloat F(0.0); 14173 if (!EvaluateFloat(E, F, Info)) 14174 return false; 14175 Result = APValue(F); 14176 } else if (T->isAnyComplexType()) { 14177 ComplexValue C; 14178 if (!EvaluateComplex(E, C, Info)) 14179 return false; 14180 C.moveInto(Result); 14181 } else if (T->isFixedPointType()) { 14182 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14183 } else if (T->isMemberPointerType()) { 14184 MemberPtr P; 14185 if (!EvaluateMemberPointer(E, P, Info)) 14186 return false; 14187 P.moveInto(Result); 14188 return true; 14189 } else if (T->isArrayType()) { 14190 LValue LV; 14191 APValue &Value = 14192 Info.CurrentCall->createTemporary(E, T, false, LV); 14193 if (!EvaluateArray(E, LV, Value, Info)) 14194 return false; 14195 Result = Value; 14196 } else if (T->isRecordType()) { 14197 LValue LV; 14198 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV); 14199 if (!EvaluateRecord(E, LV, Value, Info)) 14200 return false; 14201 Result = Value; 14202 } else if (T->isVoidType()) { 14203 if (!Info.getLangOpts().CPlusPlus11) 14204 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14205 << E->getType(); 14206 if (!EvaluateVoid(E, Info)) 14207 return false; 14208 } else if (T->isAtomicType()) { 14209 QualType Unqual = T.getAtomicUnqualifiedType(); 14210 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14211 LValue LV; 14212 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV); 14213 if (!EvaluateAtomic(E, &LV, Value, Info)) 14214 return false; 14215 } else { 14216 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14217 return false; 14218 } 14219 } else if (Info.getLangOpts().CPlusPlus11) { 14220 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14221 return false; 14222 } else { 14223 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14224 return false; 14225 } 14226 14227 return true; 14228 } 14229 14230 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14231 /// cases, the in-place evaluation is essential, since later initializers for 14232 /// an object can indirectly refer to subobjects which were initialized earlier. 14233 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14234 const Expr *E, bool AllowNonLiteralTypes) { 14235 assert(!E->isValueDependent()); 14236 14237 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14238 return false; 14239 14240 if (E->isRValue()) { 14241 // Evaluate arrays and record types in-place, so that later initializers can 14242 // refer to earlier-initialized members of the object. 14243 QualType T = E->getType(); 14244 if (T->isArrayType()) 14245 return EvaluateArray(E, This, Result, Info); 14246 else if (T->isRecordType()) 14247 return EvaluateRecord(E, This, Result, Info); 14248 else if (T->isAtomicType()) { 14249 QualType Unqual = T.getAtomicUnqualifiedType(); 14250 if (Unqual->isArrayType() || Unqual->isRecordType()) 14251 return EvaluateAtomic(E, &This, Result, Info); 14252 } 14253 } 14254 14255 // For any other type, in-place evaluation is unimportant. 14256 return Evaluate(Result, Info, E); 14257 } 14258 14259 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14260 /// lvalue-to-rvalue cast if it is an lvalue. 14261 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14262 if (Info.EnableNewConstInterp) { 14263 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14264 return false; 14265 } else { 14266 if (E->getType().isNull()) 14267 return false; 14268 14269 if (!CheckLiteralType(Info, E)) 14270 return false; 14271 14272 if (!::Evaluate(Result, Info, E)) 14273 return false; 14274 14275 if (E->isGLValue()) { 14276 LValue LV; 14277 LV.setFrom(Info.Ctx, Result); 14278 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14279 return false; 14280 } 14281 } 14282 14283 // Check this core constant expression is a constant expression. 14284 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) && 14285 CheckMemoryLeaks(Info); 14286 } 14287 14288 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14289 const ASTContext &Ctx, bool &IsConst) { 14290 // Fast-path evaluations of integer literals, since we sometimes see files 14291 // containing vast quantities of these. 14292 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14293 Result.Val = APValue(APSInt(L->getValue(), 14294 L->getType()->isUnsignedIntegerType())); 14295 IsConst = true; 14296 return true; 14297 } 14298 14299 // This case should be rare, but we need to check it before we check on 14300 // the type below. 14301 if (Exp->getType().isNull()) { 14302 IsConst = false; 14303 return true; 14304 } 14305 14306 // FIXME: Evaluating values of large array and record types can cause 14307 // performance problems. Only do so in C++11 for now. 14308 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 14309 Exp->getType()->isRecordType()) && 14310 !Ctx.getLangOpts().CPlusPlus11) { 14311 IsConst = false; 14312 return true; 14313 } 14314 return false; 14315 } 14316 14317 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14318 Expr::SideEffectsKind SEK) { 14319 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14320 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14321 } 14322 14323 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14324 const ASTContext &Ctx, EvalInfo &Info) { 14325 bool IsConst; 14326 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14327 return IsConst; 14328 14329 return EvaluateAsRValue(Info, E, Result.Val); 14330 } 14331 14332 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14333 const ASTContext &Ctx, 14334 Expr::SideEffectsKind AllowSideEffects, 14335 EvalInfo &Info) { 14336 if (!E->getType()->isIntegralOrEnumerationType()) 14337 return false; 14338 14339 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14340 !ExprResult.Val.isInt() || 14341 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14342 return false; 14343 14344 return true; 14345 } 14346 14347 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14348 const ASTContext &Ctx, 14349 Expr::SideEffectsKind AllowSideEffects, 14350 EvalInfo &Info) { 14351 if (!E->getType()->isFixedPointType()) 14352 return false; 14353 14354 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14355 return false; 14356 14357 if (!ExprResult.Val.isFixedPoint() || 14358 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14359 return false; 14360 14361 return true; 14362 } 14363 14364 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14365 /// any crazy technique (that has nothing to do with language standards) that 14366 /// we want to. If this function returns true, it returns the folded constant 14367 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14368 /// will be applied to the result. 14369 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14370 bool InConstantContext) const { 14371 assert(!isValueDependent() && 14372 "Expression evaluator can't be called on a dependent expression."); 14373 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14374 Info.InConstantContext = InConstantContext; 14375 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14376 } 14377 14378 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14379 bool InConstantContext) const { 14380 assert(!isValueDependent() && 14381 "Expression evaluator can't be called on a dependent expression."); 14382 EvalResult Scratch; 14383 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14384 HandleConversionToBool(Scratch.Val, Result); 14385 } 14386 14387 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14388 SideEffectsKind AllowSideEffects, 14389 bool InConstantContext) const { 14390 assert(!isValueDependent() && 14391 "Expression evaluator can't be called on a dependent expression."); 14392 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14393 Info.InConstantContext = InConstantContext; 14394 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14395 } 14396 14397 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14398 SideEffectsKind AllowSideEffects, 14399 bool InConstantContext) const { 14400 assert(!isValueDependent() && 14401 "Expression evaluator can't be called on a dependent expression."); 14402 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14403 Info.InConstantContext = InConstantContext; 14404 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14405 } 14406 14407 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14408 SideEffectsKind AllowSideEffects, 14409 bool InConstantContext) const { 14410 assert(!isValueDependent() && 14411 "Expression evaluator can't be called on a dependent expression."); 14412 14413 if (!getType()->isRealFloatingType()) 14414 return false; 14415 14416 EvalResult ExprResult; 14417 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14418 !ExprResult.Val.isFloat() || 14419 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14420 return false; 14421 14422 Result = ExprResult.Val.getFloat(); 14423 return true; 14424 } 14425 14426 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14427 bool InConstantContext) const { 14428 assert(!isValueDependent() && 14429 "Expression evaluator can't be called on a dependent expression."); 14430 14431 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14432 Info.InConstantContext = InConstantContext; 14433 LValue LV; 14434 CheckedTemporaries CheckedTemps; 14435 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14436 Result.HasSideEffects || 14437 !CheckLValueConstantExpression(Info, getExprLoc(), 14438 Ctx.getLValueReferenceType(getType()), LV, 14439 Expr::EvaluateForCodeGen, CheckedTemps)) 14440 return false; 14441 14442 LV.moveInto(Result.Val); 14443 return true; 14444 } 14445 14446 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 14447 const ASTContext &Ctx, bool InPlace) const { 14448 assert(!isValueDependent() && 14449 "Expression evaluator can't be called on a dependent expression."); 14450 14451 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14452 EvalInfo Info(Ctx, Result, EM); 14453 Info.InConstantContext = true; 14454 14455 if (InPlace) { 14456 Info.setEvaluatingDecl(this, Result.Val); 14457 LValue LVal; 14458 LVal.set(this); 14459 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || 14460 Result.HasSideEffects) 14461 return false; 14462 } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects) 14463 return false; 14464 14465 if (!Info.discardCleanups()) 14466 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14467 14468 return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14469 Result.Val, Usage) && 14470 CheckMemoryLeaks(Info); 14471 } 14472 14473 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14474 const VarDecl *VD, 14475 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14476 assert(!isValueDependent() && 14477 "Expression evaluator can't be called on a dependent expression."); 14478 14479 // FIXME: Evaluating initializers for large array and record types can cause 14480 // performance problems. Only do so in C++11 for now. 14481 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14482 !Ctx.getLangOpts().CPlusPlus11) 14483 return false; 14484 14485 Expr::EvalStatus EStatus; 14486 EStatus.Diag = &Notes; 14487 14488 EvalInfo Info(Ctx, EStatus, VD->isConstexpr() 14489 ? EvalInfo::EM_ConstantExpression 14490 : EvalInfo::EM_ConstantFold); 14491 Info.setEvaluatingDecl(VD, Value); 14492 Info.InConstantContext = true; 14493 14494 SourceLocation DeclLoc = VD->getLocation(); 14495 QualType DeclTy = VD->getType(); 14496 14497 if (Info.EnableNewConstInterp) { 14498 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14499 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14500 return false; 14501 } else { 14502 LValue LVal; 14503 LVal.set(VD); 14504 14505 if (!EvaluateInPlace(Value, Info, LVal, this, 14506 /*AllowNonLiteralTypes=*/true) || 14507 EStatus.HasSideEffects) 14508 return false; 14509 14510 // At this point, any lifetime-extended temporaries are completely 14511 // initialized. 14512 Info.performLifetimeExtension(); 14513 14514 if (!Info.discardCleanups()) 14515 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14516 } 14517 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) && 14518 CheckMemoryLeaks(Info); 14519 } 14520 14521 bool VarDecl::evaluateDestruction( 14522 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14523 Expr::EvalStatus EStatus; 14524 EStatus.Diag = &Notes; 14525 14526 // Make a copy of the value for the destructor to mutate, if we know it. 14527 // Otherwise, treat the value as default-initialized; if the destructor works 14528 // anyway, then the destruction is constant (and must be essentially empty). 14529 APValue DestroyedValue; 14530 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14531 DestroyedValue = *getEvaluatedValue(); 14532 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14533 return false; 14534 14535 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression); 14536 Info.setEvaluatingDecl(this, DestroyedValue, 14537 EvalInfo::EvaluatingDeclKind::Dtor); 14538 Info.InConstantContext = true; 14539 14540 SourceLocation DeclLoc = getLocation(); 14541 QualType DeclTy = getType(); 14542 14543 LValue LVal; 14544 LVal.set(this); 14545 14546 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) || 14547 EStatus.HasSideEffects) 14548 return false; 14549 14550 if (!Info.discardCleanups()) 14551 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14552 14553 ensureEvaluatedStmt()->HasConstantDestruction = true; 14554 return true; 14555 } 14556 14557 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14558 /// constant folded, but discard the result. 14559 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14560 assert(!isValueDependent() && 14561 "Expression evaluator can't be called on a dependent expression."); 14562 14563 EvalResult Result; 14564 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14565 !hasUnacceptableSideEffect(Result, SEK); 14566 } 14567 14568 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14569 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14570 assert(!isValueDependent() && 14571 "Expression evaluator can't be called on a dependent expression."); 14572 14573 EvalResult EVResult; 14574 EVResult.Diag = Diag; 14575 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14576 Info.InConstantContext = true; 14577 14578 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14579 (void)Result; 14580 assert(Result && "Could not evaluate expression"); 14581 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14582 14583 return EVResult.Val.getInt(); 14584 } 14585 14586 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14587 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14588 assert(!isValueDependent() && 14589 "Expression evaluator can't be called on a dependent expression."); 14590 14591 EvalResult EVResult; 14592 EVResult.Diag = Diag; 14593 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14594 Info.InConstantContext = true; 14595 Info.CheckingForUndefinedBehavior = true; 14596 14597 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 14598 (void)Result; 14599 assert(Result && "Could not evaluate expression"); 14600 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14601 14602 return EVResult.Val.getInt(); 14603 } 14604 14605 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 14606 assert(!isValueDependent() && 14607 "Expression evaluator can't be called on a dependent expression."); 14608 14609 bool IsConst; 14610 EvalResult EVResult; 14611 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 14612 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14613 Info.CheckingForUndefinedBehavior = true; 14614 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 14615 } 14616 } 14617 14618 bool Expr::EvalResult::isGlobalLValue() const { 14619 assert(Val.isLValue()); 14620 return IsGlobalLValue(Val.getLValueBase()); 14621 } 14622 14623 14624 /// isIntegerConstantExpr - this recursive routine will test if an expression is 14625 /// an integer constant expression. 14626 14627 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 14628 /// comma, etc 14629 14630 // CheckICE - This function does the fundamental ICE checking: the returned 14631 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 14632 // and a (possibly null) SourceLocation indicating the location of the problem. 14633 // 14634 // Note that to reduce code duplication, this helper does no evaluation 14635 // itself; the caller checks whether the expression is evaluatable, and 14636 // in the rare cases where CheckICE actually cares about the evaluated 14637 // value, it calls into Evaluate. 14638 14639 namespace { 14640 14641 enum ICEKind { 14642 /// This expression is an ICE. 14643 IK_ICE, 14644 /// This expression is not an ICE, but if it isn't evaluated, it's 14645 /// a legal subexpression for an ICE. This return value is used to handle 14646 /// the comma operator in C99 mode, and non-constant subexpressions. 14647 IK_ICEIfUnevaluated, 14648 /// This expression is not an ICE, and is not a legal subexpression for one. 14649 IK_NotICE 14650 }; 14651 14652 struct ICEDiag { 14653 ICEKind Kind; 14654 SourceLocation Loc; 14655 14656 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 14657 }; 14658 14659 } 14660 14661 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 14662 14663 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 14664 14665 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 14666 Expr::EvalResult EVResult; 14667 Expr::EvalStatus Status; 14668 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 14669 14670 Info.InConstantContext = true; 14671 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 14672 !EVResult.Val.isInt()) 14673 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14674 14675 return NoDiag(); 14676 } 14677 14678 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 14679 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 14680 if (!E->getType()->isIntegralOrEnumerationType()) 14681 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14682 14683 switch (E->getStmtClass()) { 14684 #define ABSTRACT_STMT(Node) 14685 #define STMT(Node, Base) case Expr::Node##Class: 14686 #define EXPR(Node, Base) 14687 #include "clang/AST/StmtNodes.inc" 14688 case Expr::PredefinedExprClass: 14689 case Expr::FloatingLiteralClass: 14690 case Expr::ImaginaryLiteralClass: 14691 case Expr::StringLiteralClass: 14692 case Expr::ArraySubscriptExprClass: 14693 case Expr::MatrixSubscriptExprClass: 14694 case Expr::OMPArraySectionExprClass: 14695 case Expr::OMPArrayShapingExprClass: 14696 case Expr::OMPIteratorExprClass: 14697 case Expr::MemberExprClass: 14698 case Expr::CompoundAssignOperatorClass: 14699 case Expr::CompoundLiteralExprClass: 14700 case Expr::ExtVectorElementExprClass: 14701 case Expr::DesignatedInitExprClass: 14702 case Expr::ArrayInitLoopExprClass: 14703 case Expr::ArrayInitIndexExprClass: 14704 case Expr::NoInitExprClass: 14705 case Expr::DesignatedInitUpdateExprClass: 14706 case Expr::ImplicitValueInitExprClass: 14707 case Expr::ParenListExprClass: 14708 case Expr::VAArgExprClass: 14709 case Expr::AddrLabelExprClass: 14710 case Expr::StmtExprClass: 14711 case Expr::CXXMemberCallExprClass: 14712 case Expr::CUDAKernelCallExprClass: 14713 case Expr::CXXAddrspaceCastExprClass: 14714 case Expr::CXXDynamicCastExprClass: 14715 case Expr::CXXTypeidExprClass: 14716 case Expr::CXXUuidofExprClass: 14717 case Expr::MSPropertyRefExprClass: 14718 case Expr::MSPropertySubscriptExprClass: 14719 case Expr::CXXNullPtrLiteralExprClass: 14720 case Expr::UserDefinedLiteralClass: 14721 case Expr::CXXThisExprClass: 14722 case Expr::CXXThrowExprClass: 14723 case Expr::CXXNewExprClass: 14724 case Expr::CXXDeleteExprClass: 14725 case Expr::CXXPseudoDestructorExprClass: 14726 case Expr::UnresolvedLookupExprClass: 14727 case Expr::TypoExprClass: 14728 case Expr::RecoveryExprClass: 14729 case Expr::DependentScopeDeclRefExprClass: 14730 case Expr::CXXConstructExprClass: 14731 case Expr::CXXInheritedCtorInitExprClass: 14732 case Expr::CXXStdInitializerListExprClass: 14733 case Expr::CXXBindTemporaryExprClass: 14734 case Expr::ExprWithCleanupsClass: 14735 case Expr::CXXTemporaryObjectExprClass: 14736 case Expr::CXXUnresolvedConstructExprClass: 14737 case Expr::CXXDependentScopeMemberExprClass: 14738 case Expr::UnresolvedMemberExprClass: 14739 case Expr::ObjCStringLiteralClass: 14740 case Expr::ObjCBoxedExprClass: 14741 case Expr::ObjCArrayLiteralClass: 14742 case Expr::ObjCDictionaryLiteralClass: 14743 case Expr::ObjCEncodeExprClass: 14744 case Expr::ObjCMessageExprClass: 14745 case Expr::ObjCSelectorExprClass: 14746 case Expr::ObjCProtocolExprClass: 14747 case Expr::ObjCIvarRefExprClass: 14748 case Expr::ObjCPropertyRefExprClass: 14749 case Expr::ObjCSubscriptRefExprClass: 14750 case Expr::ObjCIsaExprClass: 14751 case Expr::ObjCAvailabilityCheckExprClass: 14752 case Expr::ShuffleVectorExprClass: 14753 case Expr::ConvertVectorExprClass: 14754 case Expr::BlockExprClass: 14755 case Expr::NoStmtClass: 14756 case Expr::OpaqueValueExprClass: 14757 case Expr::PackExpansionExprClass: 14758 case Expr::SubstNonTypeTemplateParmPackExprClass: 14759 case Expr::FunctionParmPackExprClass: 14760 case Expr::AsTypeExprClass: 14761 case Expr::ObjCIndirectCopyRestoreExprClass: 14762 case Expr::MaterializeTemporaryExprClass: 14763 case Expr::PseudoObjectExprClass: 14764 case Expr::AtomicExprClass: 14765 case Expr::LambdaExprClass: 14766 case Expr::CXXFoldExprClass: 14767 case Expr::CoawaitExprClass: 14768 case Expr::DependentCoawaitExprClass: 14769 case Expr::CoyieldExprClass: 14770 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14771 14772 case Expr::InitListExprClass: { 14773 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 14774 // form "T x = { a };" is equivalent to "T x = a;". 14775 // Unless we're initializing a reference, T is a scalar as it is known to be 14776 // of integral or enumeration type. 14777 if (E->isRValue()) 14778 if (cast<InitListExpr>(E)->getNumInits() == 1) 14779 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 14780 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14781 } 14782 14783 case Expr::SizeOfPackExprClass: 14784 case Expr::GNUNullExprClass: 14785 case Expr::SourceLocExprClass: 14786 return NoDiag(); 14787 14788 case Expr::SubstNonTypeTemplateParmExprClass: 14789 return 14790 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 14791 14792 case Expr::ConstantExprClass: 14793 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 14794 14795 case Expr::ParenExprClass: 14796 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 14797 case Expr::GenericSelectionExprClass: 14798 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 14799 case Expr::IntegerLiteralClass: 14800 case Expr::FixedPointLiteralClass: 14801 case Expr::CharacterLiteralClass: 14802 case Expr::ObjCBoolLiteralExprClass: 14803 case Expr::CXXBoolLiteralExprClass: 14804 case Expr::CXXScalarValueInitExprClass: 14805 case Expr::TypeTraitExprClass: 14806 case Expr::ConceptSpecializationExprClass: 14807 case Expr::RequiresExprClass: 14808 case Expr::ArrayTypeTraitExprClass: 14809 case Expr::ExpressionTraitExprClass: 14810 case Expr::CXXNoexceptExprClass: 14811 return NoDiag(); 14812 case Expr::CallExprClass: 14813 case Expr::CXXOperatorCallExprClass: { 14814 // C99 6.6/3 allows function calls within unevaluated subexpressions of 14815 // constant expressions, but they can never be ICEs because an ICE cannot 14816 // contain an operand of (pointer to) function type. 14817 const CallExpr *CE = cast<CallExpr>(E); 14818 if (CE->getBuiltinCallee()) 14819 return CheckEvalInICE(E, Ctx); 14820 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14821 } 14822 case Expr::CXXRewrittenBinaryOperatorClass: 14823 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 14824 Ctx); 14825 case Expr::DeclRefExprClass: { 14826 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 14827 return NoDiag(); 14828 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 14829 if (Ctx.getLangOpts().CPlusPlus && 14830 D && IsConstNonVolatile(D->getType())) { 14831 // Parameter variables are never constants. Without this check, 14832 // getAnyInitializer() can find a default argument, which leads 14833 // to chaos. 14834 if (isa<ParmVarDecl>(D)) 14835 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14836 14837 // C++ 7.1.5.1p2 14838 // A variable of non-volatile const-qualified integral or enumeration 14839 // type initialized by an ICE can be used in ICEs. 14840 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 14841 if (!Dcl->getType()->isIntegralOrEnumerationType()) 14842 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14843 14844 const VarDecl *VD; 14845 // Look for a declaration of this variable that has an initializer, and 14846 // check whether it is an ICE. 14847 if (Dcl->getAnyInitializer(VD) && !VD->isWeak() && VD->checkInitIsICE()) 14848 return NoDiag(); 14849 else 14850 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14851 } 14852 } 14853 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14854 } 14855 case Expr::UnaryOperatorClass: { 14856 const UnaryOperator *Exp = cast<UnaryOperator>(E); 14857 switch (Exp->getOpcode()) { 14858 case UO_PostInc: 14859 case UO_PostDec: 14860 case UO_PreInc: 14861 case UO_PreDec: 14862 case UO_AddrOf: 14863 case UO_Deref: 14864 case UO_Coawait: 14865 // C99 6.6/3 allows increment and decrement within unevaluated 14866 // subexpressions of constant expressions, but they can never be ICEs 14867 // because an ICE cannot contain an lvalue operand. 14868 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14869 case UO_Extension: 14870 case UO_LNot: 14871 case UO_Plus: 14872 case UO_Minus: 14873 case UO_Not: 14874 case UO_Real: 14875 case UO_Imag: 14876 return CheckICE(Exp->getSubExpr(), Ctx); 14877 } 14878 llvm_unreachable("invalid unary operator class"); 14879 } 14880 case Expr::OffsetOfExprClass: { 14881 // Note that per C99, offsetof must be an ICE. And AFAIK, using 14882 // EvaluateAsRValue matches the proposed gcc behavior for cases like 14883 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 14884 // compliance: we should warn earlier for offsetof expressions with 14885 // array subscripts that aren't ICEs, and if the array subscripts 14886 // are ICEs, the value of the offsetof must be an integer constant. 14887 return CheckEvalInICE(E, Ctx); 14888 } 14889 case Expr::UnaryExprOrTypeTraitExprClass: { 14890 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 14891 if ((Exp->getKind() == UETT_SizeOf) && 14892 Exp->getTypeOfArgument()->isVariableArrayType()) 14893 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14894 return NoDiag(); 14895 } 14896 case Expr::BinaryOperatorClass: { 14897 const BinaryOperator *Exp = cast<BinaryOperator>(E); 14898 switch (Exp->getOpcode()) { 14899 case BO_PtrMemD: 14900 case BO_PtrMemI: 14901 case BO_Assign: 14902 case BO_MulAssign: 14903 case BO_DivAssign: 14904 case BO_RemAssign: 14905 case BO_AddAssign: 14906 case BO_SubAssign: 14907 case BO_ShlAssign: 14908 case BO_ShrAssign: 14909 case BO_AndAssign: 14910 case BO_XorAssign: 14911 case BO_OrAssign: 14912 // C99 6.6/3 allows assignments within unevaluated subexpressions of 14913 // constant expressions, but they can never be ICEs because an ICE cannot 14914 // contain an lvalue operand. 14915 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14916 14917 case BO_Mul: 14918 case BO_Div: 14919 case BO_Rem: 14920 case BO_Add: 14921 case BO_Sub: 14922 case BO_Shl: 14923 case BO_Shr: 14924 case BO_LT: 14925 case BO_GT: 14926 case BO_LE: 14927 case BO_GE: 14928 case BO_EQ: 14929 case BO_NE: 14930 case BO_And: 14931 case BO_Xor: 14932 case BO_Or: 14933 case BO_Comma: 14934 case BO_Cmp: { 14935 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14936 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14937 if (Exp->getOpcode() == BO_Div || 14938 Exp->getOpcode() == BO_Rem) { 14939 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 14940 // we don't evaluate one. 14941 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 14942 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 14943 if (REval == 0) 14944 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14945 if (REval.isSigned() && REval.isAllOnesValue()) { 14946 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 14947 if (LEval.isMinSignedValue()) 14948 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14949 } 14950 } 14951 } 14952 if (Exp->getOpcode() == BO_Comma) { 14953 if (Ctx.getLangOpts().C99) { 14954 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 14955 // if it isn't evaluated. 14956 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 14957 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14958 } else { 14959 // In both C89 and C++, commas in ICEs are illegal. 14960 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14961 } 14962 } 14963 return Worst(LHSResult, RHSResult); 14964 } 14965 case BO_LAnd: 14966 case BO_LOr: { 14967 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14968 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14969 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 14970 // Rare case where the RHS has a comma "side-effect"; we need 14971 // to actually check the condition to see whether the side 14972 // with the comma is evaluated. 14973 if ((Exp->getOpcode() == BO_LAnd) != 14974 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 14975 return RHSResult; 14976 return NoDiag(); 14977 } 14978 14979 return Worst(LHSResult, RHSResult); 14980 } 14981 } 14982 llvm_unreachable("invalid binary operator kind"); 14983 } 14984 case Expr::ImplicitCastExprClass: 14985 case Expr::CStyleCastExprClass: 14986 case Expr::CXXFunctionalCastExprClass: 14987 case Expr::CXXStaticCastExprClass: 14988 case Expr::CXXReinterpretCastExprClass: 14989 case Expr::CXXConstCastExprClass: 14990 case Expr::ObjCBridgedCastExprClass: { 14991 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 14992 if (isa<ExplicitCastExpr>(E)) { 14993 if (const FloatingLiteral *FL 14994 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 14995 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 14996 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 14997 APSInt IgnoredVal(DestWidth, !DestSigned); 14998 bool Ignored; 14999 // If the value does not fit in the destination type, the behavior is 15000 // undefined, so we are not required to treat it as a constant 15001 // expression. 15002 if (FL->getValue().convertToInteger(IgnoredVal, 15003 llvm::APFloat::rmTowardZero, 15004 &Ignored) & APFloat::opInvalidOp) 15005 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15006 return NoDiag(); 15007 } 15008 } 15009 switch (cast<CastExpr>(E)->getCastKind()) { 15010 case CK_LValueToRValue: 15011 case CK_AtomicToNonAtomic: 15012 case CK_NonAtomicToAtomic: 15013 case CK_NoOp: 15014 case CK_IntegralToBoolean: 15015 case CK_IntegralCast: 15016 return CheckICE(SubExpr, Ctx); 15017 default: 15018 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15019 } 15020 } 15021 case Expr::BinaryConditionalOperatorClass: { 15022 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15023 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15024 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15025 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15026 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15027 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15028 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15029 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15030 return FalseResult; 15031 } 15032 case Expr::ConditionalOperatorClass: { 15033 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15034 // If the condition (ignoring parens) is a __builtin_constant_p call, 15035 // then only the true side is actually considered in an integer constant 15036 // expression, and it is fully evaluated. This is an important GNU 15037 // extension. See GCC PR38377 for discussion. 15038 if (const CallExpr *CallCE 15039 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15040 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15041 return CheckEvalInICE(E, Ctx); 15042 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15043 if (CondResult.Kind == IK_NotICE) 15044 return CondResult; 15045 15046 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15047 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15048 15049 if (TrueResult.Kind == IK_NotICE) 15050 return TrueResult; 15051 if (FalseResult.Kind == IK_NotICE) 15052 return FalseResult; 15053 if (CondResult.Kind == IK_ICEIfUnevaluated) 15054 return CondResult; 15055 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15056 return NoDiag(); 15057 // Rare case where the diagnostics depend on which side is evaluated 15058 // Note that if we get here, CondResult is 0, and at least one of 15059 // TrueResult and FalseResult is non-zero. 15060 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15061 return FalseResult; 15062 return TrueResult; 15063 } 15064 case Expr::CXXDefaultArgExprClass: 15065 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15066 case Expr::CXXDefaultInitExprClass: 15067 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15068 case Expr::ChooseExprClass: { 15069 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15070 } 15071 case Expr::BuiltinBitCastExprClass: { 15072 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15073 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15074 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15075 } 15076 } 15077 15078 llvm_unreachable("Invalid StmtClass!"); 15079 } 15080 15081 /// Evaluate an expression as a C++11 integral constant expression. 15082 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15083 const Expr *E, 15084 llvm::APSInt *Value, 15085 SourceLocation *Loc) { 15086 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15087 if (Loc) *Loc = E->getExprLoc(); 15088 return false; 15089 } 15090 15091 APValue Result; 15092 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15093 return false; 15094 15095 if (!Result.isInt()) { 15096 if (Loc) *Loc = E->getExprLoc(); 15097 return false; 15098 } 15099 15100 if (Value) *Value = Result.getInt(); 15101 return true; 15102 } 15103 15104 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15105 SourceLocation *Loc) const { 15106 assert(!isValueDependent() && 15107 "Expression evaluator can't be called on a dependent expression."); 15108 15109 if (Ctx.getLangOpts().CPlusPlus11) 15110 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15111 15112 ICEDiag D = CheckICE(this, Ctx); 15113 if (D.Kind != IK_ICE) { 15114 if (Loc) *Loc = D.Loc; 15115 return false; 15116 } 15117 return true; 15118 } 15119 15120 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15121 SourceLocation *Loc, 15122 bool isEvaluated) const { 15123 assert(!isValueDependent() && 15124 "Expression evaluator can't be called on a dependent expression."); 15125 15126 APSInt Value; 15127 15128 if (Ctx.getLangOpts().CPlusPlus11) { 15129 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15130 return Value; 15131 return None; 15132 } 15133 15134 if (!isIntegerConstantExpr(Ctx, Loc)) 15135 return None; 15136 15137 // The only possible side-effects here are due to UB discovered in the 15138 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15139 // required to treat the expression as an ICE, so we produce the folded 15140 // value. 15141 EvalResult ExprResult; 15142 Expr::EvalStatus Status; 15143 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15144 Info.InConstantContext = true; 15145 15146 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15147 llvm_unreachable("ICE cannot be evaluated!"); 15148 15149 return ExprResult.Val.getInt(); 15150 } 15151 15152 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15153 assert(!isValueDependent() && 15154 "Expression evaluator can't be called on a dependent expression."); 15155 15156 return CheckICE(this, Ctx).Kind == IK_ICE; 15157 } 15158 15159 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15160 SourceLocation *Loc) const { 15161 assert(!isValueDependent() && 15162 "Expression evaluator can't be called on a dependent expression."); 15163 15164 // We support this checking in C++98 mode in order to diagnose compatibility 15165 // issues. 15166 assert(Ctx.getLangOpts().CPlusPlus); 15167 15168 // Build evaluation settings. 15169 Expr::EvalStatus Status; 15170 SmallVector<PartialDiagnosticAt, 8> Diags; 15171 Status.Diag = &Diags; 15172 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15173 15174 APValue Scratch; 15175 bool IsConstExpr = 15176 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15177 // FIXME: We don't produce a diagnostic for this, but the callers that 15178 // call us on arbitrary full-expressions should generally not care. 15179 Info.discardCleanups() && !Status.HasSideEffects; 15180 15181 if (!Diags.empty()) { 15182 IsConstExpr = false; 15183 if (Loc) *Loc = Diags[0].first; 15184 } else if (!IsConstExpr) { 15185 // FIXME: This shouldn't happen. 15186 if (Loc) *Loc = getExprLoc(); 15187 } 15188 15189 return IsConstExpr; 15190 } 15191 15192 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15193 const FunctionDecl *Callee, 15194 ArrayRef<const Expr*> Args, 15195 const Expr *This) const { 15196 assert(!isValueDependent() && 15197 "Expression evaluator can't be called on a dependent expression."); 15198 15199 Expr::EvalStatus Status; 15200 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15201 Info.InConstantContext = true; 15202 15203 LValue ThisVal; 15204 const LValue *ThisPtr = nullptr; 15205 if (This) { 15206 #ifndef NDEBUG 15207 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15208 assert(MD && "Don't provide `this` for non-methods."); 15209 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15210 #endif 15211 if (!This->isValueDependent() && 15212 EvaluateObjectArgument(Info, This, ThisVal) && 15213 !Info.EvalStatus.HasSideEffects) 15214 ThisPtr = &ThisVal; 15215 15216 // Ignore any side-effects from a failed evaluation. This is safe because 15217 // they can't interfere with any other argument evaluation. 15218 Info.EvalStatus.HasSideEffects = false; 15219 } 15220 15221 ArgVector ArgValues(Args.size()); 15222 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15223 I != E; ++I) { 15224 if ((*I)->isValueDependent() || 15225 !Evaluate(ArgValues[I - Args.begin()], Info, *I) || 15226 Info.EvalStatus.HasSideEffects) 15227 // If evaluation fails, throw away the argument entirely. 15228 ArgValues[I - Args.begin()] = APValue(); 15229 15230 // Ignore any side-effects from a failed evaluation. This is safe because 15231 // they can't interfere with any other argument evaluation. 15232 Info.EvalStatus.HasSideEffects = false; 15233 } 15234 15235 // Parameter cleanups happen in the caller and are not part of this 15236 // evaluation. 15237 Info.discardCleanups(); 15238 Info.EvalStatus.HasSideEffects = false; 15239 15240 // Build fake call to Callee. 15241 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 15242 ArgValues.data()); 15243 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15244 FullExpressionRAII Scope(Info); 15245 return Evaluate(Value, Info, this) && Scope.destroy() && 15246 !Info.EvalStatus.HasSideEffects; 15247 } 15248 15249 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15250 SmallVectorImpl< 15251 PartialDiagnosticAt> &Diags) { 15252 // FIXME: It would be useful to check constexpr function templates, but at the 15253 // moment the constant expression evaluator cannot cope with the non-rigorous 15254 // ASTs which we build for dependent expressions. 15255 if (FD->isDependentContext()) 15256 return true; 15257 15258 // Bail out if a constexpr constructor has an initializer that contains an 15259 // error. We deliberately don't produce a diagnostic, as we have produced a 15260 // relevant diagnostic when parsing the error initializer. 15261 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 15262 for (const auto *InitExpr : Ctor->inits()) { 15263 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 15264 return false; 15265 } 15266 } 15267 Expr::EvalStatus Status; 15268 Status.Diag = &Diags; 15269 15270 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15271 Info.InConstantContext = true; 15272 Info.CheckingPotentialConstantExpression = true; 15273 15274 // The constexpr VM attempts to compile all methods to bytecode here. 15275 if (Info.EnableNewConstInterp) { 15276 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15277 return Diags.empty(); 15278 } 15279 15280 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15281 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15282 15283 // Fabricate an arbitrary expression on the stack and pretend that it 15284 // is a temporary being used as the 'this' pointer. 15285 LValue This; 15286 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15287 This.set({&VIE, Info.CurrentCall->Index}); 15288 15289 ArrayRef<const Expr*> Args; 15290 15291 APValue Scratch; 15292 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15293 // Evaluate the call as a constant initializer, to allow the construction 15294 // of objects of non-literal types. 15295 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15296 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15297 } else { 15298 SourceLocation Loc = FD->getLocation(); 15299 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15300 Args, /*ArgValues*/ nullptr, FD->getBody(), Info, 15301 Scratch, nullptr); 15302 } 15303 15304 return Diags.empty(); 15305 } 15306 15307 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15308 const FunctionDecl *FD, 15309 SmallVectorImpl< 15310 PartialDiagnosticAt> &Diags) { 15311 assert(!E->isValueDependent() && 15312 "Expression evaluator can't be called on a dependent expression."); 15313 15314 Expr::EvalStatus Status; 15315 Status.Diag = &Diags; 15316 15317 EvalInfo Info(FD->getASTContext(), Status, 15318 EvalInfo::EM_ConstantExpressionUnevaluated); 15319 Info.InConstantContext = true; 15320 Info.CheckingPotentialConstantExpression = true; 15321 15322 // Fabricate a call stack frame to give the arguments a plausible cover story. 15323 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, 15324 /*ArgValues*/ nullptr); 15325 15326 APValue ResultScratch; 15327 Evaluate(ResultScratch, Info, E); 15328 return Diags.empty(); 15329 } 15330 15331 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15332 unsigned Type) const { 15333 if (!getType()->isPointerType()) 15334 return false; 15335 15336 Expr::EvalStatus Status; 15337 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15338 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15339 } 15340