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 "clang/AST/APValue.h" 36 #include "clang/AST/ASTContext.h" 37 #include "clang/AST/ASTDiagnostic.h" 38 #include "clang/AST/ASTLambda.h" 39 #include "clang/AST/CharUnits.h" 40 #include "clang/AST/CurrentSourceLocExprScope.h" 41 #include "clang/AST/CXXInheritance.h" 42 #include "clang/AST/Expr.h" 43 #include "clang/AST/OSLog.h" 44 #include "clang/AST/RecordLayout.h" 45 #include "clang/AST/StmtVisitor.h" 46 #include "clang/AST/TypeLoc.h" 47 #include "clang/Basic/Builtins.h" 48 #include "clang/Basic/FixedPoint.h" 49 #include "clang/Basic/TargetInfo.h" 50 #include "llvm/ADT/SmallBitVector.h" 51 #include "llvm/Support/SaveAndRestore.h" 52 #include "llvm/Support/raw_ostream.h" 53 #include <cstring> 54 #include <functional> 55 56 #define DEBUG_TYPE "exprconstant" 57 58 using namespace clang; 59 using llvm::APSInt; 60 using llvm::APFloat; 61 62 static bool IsGlobalLValue(APValue::LValueBase B); 63 64 namespace { 65 struct LValue; 66 struct CallStackFrame; 67 struct EvalInfo; 68 69 using SourceLocExprScopeGuard = 70 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 71 72 static QualType getType(APValue::LValueBase B) { 73 if (!B) return QualType(); 74 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 75 // FIXME: It's unclear where we're supposed to take the type from, and 76 // this actually matters for arrays of unknown bound. Eg: 77 // 78 // extern int arr[]; void f() { extern int arr[3]; }; 79 // constexpr int *p = &arr[1]; // valid? 80 // 81 // For now, we take the array bound from the most recent declaration. 82 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 83 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 84 QualType T = Redecl->getType(); 85 if (!T->isIncompleteArrayType()) 86 return T; 87 } 88 return D->getType(); 89 } 90 91 if (B.is<TypeInfoLValue>()) 92 return B.getTypeInfoType(); 93 94 const Expr *Base = B.get<const Expr*>(); 95 96 // For a materialized temporary, the type of the temporary we materialized 97 // may not be the type of the expression. 98 if (const MaterializeTemporaryExpr *MTE = 99 dyn_cast<MaterializeTemporaryExpr>(Base)) { 100 SmallVector<const Expr *, 2> CommaLHSs; 101 SmallVector<SubobjectAdjustment, 2> Adjustments; 102 const Expr *Temp = MTE->GetTemporaryExpr(); 103 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 104 Adjustments); 105 // Keep any cv-qualifiers from the reference if we generated a temporary 106 // for it directly. Otherwise use the type after adjustment. 107 if (!Adjustments.empty()) 108 return Inner->getType(); 109 } 110 111 return Base->getType(); 112 } 113 114 /// Get an LValue path entry, which is known to not be an array index, as a 115 /// field declaration. 116 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 117 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 118 } 119 /// Get an LValue path entry, which is known to not be an array index, as a 120 /// base class declaration. 121 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 122 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 123 } 124 /// Determine whether this LValue path entry for a base class names a virtual 125 /// base class. 126 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 127 return E.getAsBaseOrMember().getInt(); 128 } 129 130 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 131 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 132 const FunctionDecl *Callee = CE->getDirectCallee(); 133 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 134 } 135 136 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 137 /// This will look through a single cast. 138 /// 139 /// Returns null if we couldn't unwrap a function with alloc_size. 140 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 141 if (!E->getType()->isPointerType()) 142 return nullptr; 143 144 E = E->IgnoreParens(); 145 // If we're doing a variable assignment from e.g. malloc(N), there will 146 // probably be a cast of some kind. In exotic cases, we might also see a 147 // top-level ExprWithCleanups. Ignore them either way. 148 if (const auto *FE = dyn_cast<FullExpr>(E)) 149 E = FE->getSubExpr()->IgnoreParens(); 150 151 if (const auto *Cast = dyn_cast<CastExpr>(E)) 152 E = Cast->getSubExpr()->IgnoreParens(); 153 154 if (const auto *CE = dyn_cast<CallExpr>(E)) 155 return getAllocSizeAttr(CE) ? CE : nullptr; 156 return nullptr; 157 } 158 159 /// Determines whether or not the given Base contains a call to a function 160 /// with the alloc_size attribute. 161 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 162 const auto *E = Base.dyn_cast<const Expr *>(); 163 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 164 } 165 166 /// The bound to claim that an array of unknown bound has. 167 /// The value in MostDerivedArraySize is undefined in this case. So, set it 168 /// to an arbitrary value that's likely to loudly break things if it's used. 169 static const uint64_t AssumedSizeForUnsizedArray = 170 std::numeric_limits<uint64_t>::max() / 2; 171 172 /// Determines if an LValue with the given LValueBase will have an unsized 173 /// array in its designator. 174 /// Find the path length and type of the most-derived subobject in the given 175 /// path, and find the size of the containing array, if any. 176 static unsigned 177 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 178 ArrayRef<APValue::LValuePathEntry> Path, 179 uint64_t &ArraySize, QualType &Type, bool &IsArray, 180 bool &FirstEntryIsUnsizedArray) { 181 // This only accepts LValueBases from APValues, and APValues don't support 182 // arrays that lack size info. 183 assert(!isBaseAnAllocSizeCall(Base) && 184 "Unsized arrays shouldn't appear here"); 185 unsigned MostDerivedLength = 0; 186 Type = getType(Base); 187 188 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 189 if (Type->isArrayType()) { 190 const ArrayType *AT = Ctx.getAsArrayType(Type); 191 Type = AT->getElementType(); 192 MostDerivedLength = I + 1; 193 IsArray = true; 194 195 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 196 ArraySize = CAT->getSize().getZExtValue(); 197 } else { 198 assert(I == 0 && "unexpected unsized array designator"); 199 FirstEntryIsUnsizedArray = true; 200 ArraySize = AssumedSizeForUnsizedArray; 201 } 202 } else if (Type->isAnyComplexType()) { 203 const ComplexType *CT = Type->castAs<ComplexType>(); 204 Type = CT->getElementType(); 205 ArraySize = 2; 206 MostDerivedLength = I + 1; 207 IsArray = true; 208 } else if (const FieldDecl *FD = getAsField(Path[I])) { 209 Type = FD->getType(); 210 ArraySize = 0; 211 MostDerivedLength = I + 1; 212 IsArray = false; 213 } else { 214 // Path[I] describes a base class. 215 ArraySize = 0; 216 IsArray = false; 217 } 218 } 219 return MostDerivedLength; 220 } 221 222 // The order of this enum is important for diagnostics. 223 enum CheckSubobjectKind { 224 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex, 225 CSK_Real, CSK_Imag 226 }; 227 228 /// A path from a glvalue to a subobject of that glvalue. 229 struct SubobjectDesignator { 230 /// True if the subobject was named in a manner not supported by C++11. Such 231 /// lvalues can still be folded, but they are not core constant expressions 232 /// and we cannot perform lvalue-to-rvalue conversions on them. 233 unsigned Invalid : 1; 234 235 /// Is this a pointer one past the end of an object? 236 unsigned IsOnePastTheEnd : 1; 237 238 /// Indicator of whether the first entry is an unsized array. 239 unsigned FirstEntryIsAnUnsizedArray : 1; 240 241 /// Indicator of whether the most-derived object is an array element. 242 unsigned MostDerivedIsArrayElement : 1; 243 244 /// The length of the path to the most-derived object of which this is a 245 /// subobject. 246 unsigned MostDerivedPathLength : 28; 247 248 /// The size of the array of which the most-derived object is an element. 249 /// This will always be 0 if the most-derived object is not an array 250 /// element. 0 is not an indicator of whether or not the most-derived object 251 /// is an array, however, because 0-length arrays are allowed. 252 /// 253 /// If the current array is an unsized array, the value of this is 254 /// undefined. 255 uint64_t MostDerivedArraySize; 256 257 /// The type of the most derived object referred to by this address. 258 QualType MostDerivedType; 259 260 typedef APValue::LValuePathEntry PathEntry; 261 262 /// The entries on the path from the glvalue to the designated subobject. 263 SmallVector<PathEntry, 8> Entries; 264 265 SubobjectDesignator() : Invalid(true) {} 266 267 explicit SubobjectDesignator(QualType T) 268 : Invalid(false), IsOnePastTheEnd(false), 269 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 270 MostDerivedPathLength(0), MostDerivedArraySize(0), 271 MostDerivedType(T) {} 272 273 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 274 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 275 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 276 MostDerivedPathLength(0), MostDerivedArraySize(0) { 277 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 278 if (!Invalid) { 279 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 280 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 281 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 282 if (V.getLValueBase()) { 283 bool IsArray = false; 284 bool FirstIsUnsizedArray = false; 285 MostDerivedPathLength = findMostDerivedSubobject( 286 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 287 MostDerivedType, IsArray, FirstIsUnsizedArray); 288 MostDerivedIsArrayElement = IsArray; 289 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 290 } 291 } 292 } 293 294 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 295 unsigned NewLength) { 296 if (Invalid) 297 return; 298 299 assert(Base && "cannot truncate path for null pointer"); 300 assert(NewLength <= Entries.size() && "not a truncation"); 301 302 if (NewLength == Entries.size()) 303 return; 304 Entries.resize(NewLength); 305 306 bool IsArray = false; 307 bool FirstIsUnsizedArray = false; 308 MostDerivedPathLength = findMostDerivedSubobject( 309 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 310 FirstIsUnsizedArray); 311 MostDerivedIsArrayElement = IsArray; 312 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 313 } 314 315 void setInvalid() { 316 Invalid = true; 317 Entries.clear(); 318 } 319 320 /// Determine whether the most derived subobject is an array without a 321 /// known bound. 322 bool isMostDerivedAnUnsizedArray() const { 323 assert(!Invalid && "Calling this makes no sense on invalid designators"); 324 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 325 } 326 327 /// Determine what the most derived array's size is. Results in an assertion 328 /// failure if the most derived array lacks a size. 329 uint64_t getMostDerivedArraySize() const { 330 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 331 return MostDerivedArraySize; 332 } 333 334 /// Determine whether this is a one-past-the-end pointer. 335 bool isOnePastTheEnd() const { 336 assert(!Invalid); 337 if (IsOnePastTheEnd) 338 return true; 339 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 340 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 341 MostDerivedArraySize) 342 return true; 343 return false; 344 } 345 346 /// Get the range of valid index adjustments in the form 347 /// {maximum value that can be subtracted from this pointer, 348 /// maximum value that can be added to this pointer} 349 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 350 if (Invalid || isMostDerivedAnUnsizedArray()) 351 return {0, 0}; 352 353 // [expr.add]p4: For the purposes of these operators, a pointer to a 354 // nonarray object behaves the same as a pointer to the first element of 355 // an array of length one with the type of the object as its element type. 356 bool IsArray = MostDerivedPathLength == Entries.size() && 357 MostDerivedIsArrayElement; 358 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 359 : (uint64_t)IsOnePastTheEnd; 360 uint64_t ArraySize = 361 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 362 return {ArrayIndex, ArraySize - ArrayIndex}; 363 } 364 365 /// Check that this refers to a valid subobject. 366 bool isValidSubobject() const { 367 if (Invalid) 368 return false; 369 return !isOnePastTheEnd(); 370 } 371 /// Check that this refers to a valid subobject, and if not, produce a 372 /// relevant diagnostic and set the designator as invalid. 373 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 374 375 /// Get the type of the designated object. 376 QualType getType(ASTContext &Ctx) const { 377 assert(!Invalid && "invalid designator has no subobject type"); 378 return MostDerivedPathLength == Entries.size() 379 ? MostDerivedType 380 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 381 } 382 383 /// Update this designator to refer to the first element within this array. 384 void addArrayUnchecked(const ConstantArrayType *CAT) { 385 Entries.push_back(PathEntry::ArrayIndex(0)); 386 387 // This is a most-derived object. 388 MostDerivedType = CAT->getElementType(); 389 MostDerivedIsArrayElement = true; 390 MostDerivedArraySize = CAT->getSize().getZExtValue(); 391 MostDerivedPathLength = Entries.size(); 392 } 393 /// Update this designator to refer to the first element within the array of 394 /// elements of type T. This is an array of unknown size. 395 void addUnsizedArrayUnchecked(QualType ElemTy) { 396 Entries.push_back(PathEntry::ArrayIndex(0)); 397 398 MostDerivedType = ElemTy; 399 MostDerivedIsArrayElement = true; 400 // The value in MostDerivedArraySize is undefined in this case. So, set it 401 // to an arbitrary value that's likely to loudly break things if it's 402 // used. 403 MostDerivedArraySize = AssumedSizeForUnsizedArray; 404 MostDerivedPathLength = Entries.size(); 405 } 406 /// Update this designator to refer to the given base or member of this 407 /// object. 408 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 409 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 410 411 // If this isn't a base class, it's a new most-derived object. 412 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 413 MostDerivedType = FD->getType(); 414 MostDerivedIsArrayElement = false; 415 MostDerivedArraySize = 0; 416 MostDerivedPathLength = Entries.size(); 417 } 418 } 419 /// Update this designator to refer to the given complex component. 420 void addComplexUnchecked(QualType EltTy, bool Imag) { 421 Entries.push_back(PathEntry::ArrayIndex(Imag)); 422 423 // This is technically a most-derived object, though in practice this 424 // is unlikely to matter. 425 MostDerivedType = EltTy; 426 MostDerivedIsArrayElement = true; 427 MostDerivedArraySize = 2; 428 MostDerivedPathLength = Entries.size(); 429 } 430 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 431 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 432 const APSInt &N); 433 /// Add N to the address of this subobject. 434 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 435 if (Invalid || !N) return; 436 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 437 if (isMostDerivedAnUnsizedArray()) { 438 diagnoseUnsizedArrayPointerArithmetic(Info, E); 439 // Can't verify -- trust that the user is doing the right thing (or if 440 // not, trust that the caller will catch the bad behavior). 441 // FIXME: Should we reject if this overflows, at least? 442 Entries.back() = PathEntry::ArrayIndex( 443 Entries.back().getAsArrayIndex() + TruncatedN); 444 return; 445 } 446 447 // [expr.add]p4: For the purposes of these operators, a pointer to a 448 // nonarray object behaves the same as a pointer to the first element of 449 // an array of length one with the type of the object as its element type. 450 bool IsArray = MostDerivedPathLength == Entries.size() && 451 MostDerivedIsArrayElement; 452 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 453 : (uint64_t)IsOnePastTheEnd; 454 uint64_t ArraySize = 455 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 456 457 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 458 // Calculate the actual index in a wide enough type, so we can include 459 // it in the note. 460 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 461 (llvm::APInt&)N += ArrayIndex; 462 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 463 diagnosePointerArithmetic(Info, E, N); 464 setInvalid(); 465 return; 466 } 467 468 ArrayIndex += TruncatedN; 469 assert(ArrayIndex <= ArraySize && 470 "bounds check succeeded for out-of-bounds index"); 471 472 if (IsArray) 473 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 474 else 475 IsOnePastTheEnd = (ArrayIndex != 0); 476 } 477 }; 478 479 /// A stack frame in the constexpr call stack. 480 struct CallStackFrame { 481 EvalInfo &Info; 482 483 /// Parent - The caller of this stack frame. 484 CallStackFrame *Caller; 485 486 /// Callee - The function which was called. 487 const FunctionDecl *Callee; 488 489 /// This - The binding for the this pointer in this call, if any. 490 const LValue *This; 491 492 /// Arguments - Parameter bindings for this function call, indexed by 493 /// parameters' function scope indices. 494 APValue *Arguments; 495 496 /// Source location information about the default argument or default 497 /// initializer expression we're evaluating, if any. 498 CurrentSourceLocExprScope CurSourceLocExprScope; 499 500 // Note that we intentionally use std::map here so that references to 501 // values are stable. 502 typedef std::pair<const void *, unsigned> MapKeyTy; 503 typedef std::map<MapKeyTy, APValue> MapTy; 504 /// Temporaries - Temporary lvalues materialized within this stack frame. 505 MapTy Temporaries; 506 507 /// CallLoc - The location of the call expression for this call. 508 SourceLocation CallLoc; 509 510 /// Index - The call index of this call. 511 unsigned Index; 512 513 /// The stack of integers for tracking version numbers for temporaries. 514 SmallVector<unsigned, 2> TempVersionStack = {1}; 515 unsigned CurTempVersion = TempVersionStack.back(); 516 517 unsigned getTempVersion() const { return TempVersionStack.back(); } 518 519 void pushTempVersion() { 520 TempVersionStack.push_back(++CurTempVersion); 521 } 522 523 void popTempVersion() { 524 TempVersionStack.pop_back(); 525 } 526 527 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 528 // on the overall stack usage of deeply-recursing constexpr evaluations. 529 // (We should cache this map rather than recomputing it repeatedly.) 530 // But let's try this and see how it goes; we can look into caching the map 531 // as a later change. 532 533 /// LambdaCaptureFields - Mapping from captured variables/this to 534 /// corresponding data members in the closure class. 535 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 536 FieldDecl *LambdaThisCaptureField; 537 538 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 539 const FunctionDecl *Callee, const LValue *This, 540 APValue *Arguments); 541 ~CallStackFrame(); 542 543 // Return the temporary for Key whose version number is Version. 544 APValue *getTemporary(const void *Key, unsigned Version) { 545 MapKeyTy KV(Key, Version); 546 auto LB = Temporaries.lower_bound(KV); 547 if (LB != Temporaries.end() && LB->first == KV) 548 return &LB->second; 549 // Pair (Key,Version) wasn't found in the map. Check that no elements 550 // in the map have 'Key' as their key. 551 assert((LB == Temporaries.end() || LB->first.first != Key) && 552 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 553 "Element with key 'Key' found in map"); 554 return nullptr; 555 } 556 557 // Return the current temporary for Key in the map. 558 APValue *getCurrentTemporary(const void *Key) { 559 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 560 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 561 return &std::prev(UB)->second; 562 return nullptr; 563 } 564 565 // Return the version number of the current temporary for Key. 566 unsigned getCurrentTemporaryVersion(const void *Key) const { 567 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 568 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 569 return std::prev(UB)->first.second; 570 return 0; 571 } 572 573 APValue &createTemporary(const void *Key, bool IsLifetimeExtended); 574 }; 575 576 /// Temporarily override 'this'. 577 class ThisOverrideRAII { 578 public: 579 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 580 : Frame(Frame), OldThis(Frame.This) { 581 if (Enable) 582 Frame.This = NewThis; 583 } 584 ~ThisOverrideRAII() { 585 Frame.This = OldThis; 586 } 587 private: 588 CallStackFrame &Frame; 589 const LValue *OldThis; 590 }; 591 592 /// A partial diagnostic which we might know in advance that we are not going 593 /// to emit. 594 class OptionalDiagnostic { 595 PartialDiagnostic *Diag; 596 597 public: 598 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr) 599 : Diag(Diag) {} 600 601 template<typename T> 602 OptionalDiagnostic &operator<<(const T &v) { 603 if (Diag) 604 *Diag << v; 605 return *this; 606 } 607 608 OptionalDiagnostic &operator<<(const APSInt &I) { 609 if (Diag) { 610 SmallVector<char, 32> Buffer; 611 I.toString(Buffer); 612 *Diag << StringRef(Buffer.data(), Buffer.size()); 613 } 614 return *this; 615 } 616 617 OptionalDiagnostic &operator<<(const APFloat &F) { 618 if (Diag) { 619 // FIXME: Force the precision of the source value down so we don't 620 // print digits which are usually useless (we don't really care here if 621 // we truncate a digit by accident in edge cases). Ideally, 622 // APFloat::toString would automatically print the shortest 623 // representation which rounds to the correct value, but it's a bit 624 // tricky to implement. 625 unsigned precision = 626 llvm::APFloat::semanticsPrecision(F.getSemantics()); 627 precision = (precision * 59 + 195) / 196; 628 SmallVector<char, 32> Buffer; 629 F.toString(Buffer, precision); 630 *Diag << StringRef(Buffer.data(), Buffer.size()); 631 } 632 return *this; 633 } 634 635 OptionalDiagnostic &operator<<(const APFixedPoint &FX) { 636 if (Diag) { 637 SmallVector<char, 32> Buffer; 638 FX.toString(Buffer); 639 *Diag << StringRef(Buffer.data(), Buffer.size()); 640 } 641 return *this; 642 } 643 }; 644 645 /// A cleanup, and a flag indicating whether it is lifetime-extended. 646 class Cleanup { 647 llvm::PointerIntPair<APValue*, 1, bool> Value; 648 649 public: 650 Cleanup(APValue *Val, bool IsLifetimeExtended) 651 : Value(Val, IsLifetimeExtended) {} 652 653 bool isLifetimeExtended() const { return Value.getInt(); } 654 void endLifetime() { 655 *Value.getPointer() = APValue(); 656 } 657 }; 658 659 /// A reference to an object whose construction we are currently evaluating. 660 struct ObjectUnderConstruction { 661 APValue::LValueBase Base; 662 ArrayRef<APValue::LValuePathEntry> Path; 663 friend bool operator==(const ObjectUnderConstruction &LHS, 664 const ObjectUnderConstruction &RHS) { 665 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 666 } 667 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 668 return llvm::hash_combine(Obj.Base, Obj.Path); 669 } 670 }; 671 enum class ConstructionPhase { None, Bases, AfterBases }; 672 } 673 674 namespace llvm { 675 template<> struct DenseMapInfo<ObjectUnderConstruction> { 676 using Base = DenseMapInfo<APValue::LValueBase>; 677 static ObjectUnderConstruction getEmptyKey() { 678 return {Base::getEmptyKey(), {}}; } 679 static ObjectUnderConstruction getTombstoneKey() { 680 return {Base::getTombstoneKey(), {}}; 681 } 682 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 683 return hash_value(Object); 684 } 685 static bool isEqual(const ObjectUnderConstruction &LHS, 686 const ObjectUnderConstruction &RHS) { 687 return LHS == RHS; 688 } 689 }; 690 } 691 692 namespace { 693 /// EvalInfo - This is a private struct used by the evaluator to capture 694 /// information about a subexpression as it is folded. It retains information 695 /// about the AST context, but also maintains information about the folded 696 /// expression. 697 /// 698 /// If an expression could be evaluated, it is still possible it is not a C 699 /// "integer constant expression" or constant expression. If not, this struct 700 /// captures information about how and why not. 701 /// 702 /// One bit of information passed *into* the request for constant folding 703 /// indicates whether the subexpression is "evaluated" or not according to C 704 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 705 /// evaluate the expression regardless of what the RHS is, but C only allows 706 /// certain things in certain situations. 707 struct EvalInfo { 708 ASTContext &Ctx; 709 710 /// EvalStatus - Contains information about the evaluation. 711 Expr::EvalStatus &EvalStatus; 712 713 /// CurrentCall - The top of the constexpr call stack. 714 CallStackFrame *CurrentCall; 715 716 /// CallStackDepth - The number of calls in the call stack right now. 717 unsigned CallStackDepth; 718 719 /// NextCallIndex - The next call index to assign. 720 unsigned NextCallIndex; 721 722 /// StepsLeft - The remaining number of evaluation steps we're permitted 723 /// to perform. This is essentially a limit for the number of statements 724 /// we will evaluate. 725 unsigned StepsLeft; 726 727 /// BottomFrame - The frame in which evaluation started. This must be 728 /// initialized after CurrentCall and CallStackDepth. 729 CallStackFrame BottomFrame; 730 731 /// A stack of values whose lifetimes end at the end of some surrounding 732 /// evaluation frame. 733 llvm::SmallVector<Cleanup, 16> CleanupStack; 734 735 /// EvaluatingDecl - This is the declaration whose initializer is being 736 /// evaluated, if any. 737 APValue::LValueBase EvaluatingDecl; 738 739 /// EvaluatingDeclValue - This is the value being constructed for the 740 /// declaration whose initializer is being evaluated, if any. 741 APValue *EvaluatingDeclValue; 742 743 /// Set of objects that are currently being constructed. 744 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 745 ObjectsUnderConstruction; 746 747 struct EvaluatingConstructorRAII { 748 EvalInfo &EI; 749 ObjectUnderConstruction Object; 750 bool DidInsert; 751 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 752 bool HasBases) 753 : EI(EI), Object(Object) { 754 DidInsert = 755 EI.ObjectsUnderConstruction 756 .insert({Object, HasBases ? ConstructionPhase::Bases 757 : ConstructionPhase::AfterBases}) 758 .second; 759 } 760 void finishedConstructingBases() { 761 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 762 } 763 ~EvaluatingConstructorRAII() { 764 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 765 } 766 }; 767 768 ConstructionPhase 769 isEvaluatingConstructor(APValue::LValueBase Base, 770 ArrayRef<APValue::LValuePathEntry> Path) { 771 return ObjectsUnderConstruction.lookup({Base, Path}); 772 } 773 774 /// If we're currently speculatively evaluating, the outermost call stack 775 /// depth at which we can mutate state, otherwise 0. 776 unsigned SpeculativeEvaluationDepth = 0; 777 778 /// The current array initialization index, if we're performing array 779 /// initialization. 780 uint64_t ArrayInitIndex = -1; 781 782 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 783 /// notes attached to it will also be stored, otherwise they will not be. 784 bool HasActiveDiagnostic; 785 786 /// Have we emitted a diagnostic explaining why we couldn't constant 787 /// fold (not just why it's not strictly a constant expression)? 788 bool HasFoldFailureDiagnostic; 789 790 /// Whether or not we're in a context where the front end requires a 791 /// constant value. 792 bool InConstantContext; 793 794 enum EvaluationMode { 795 /// Evaluate as a constant expression. Stop if we find that the expression 796 /// is not a constant expression. 797 EM_ConstantExpression, 798 799 /// Evaluate as a potential constant expression. Keep going if we hit a 800 /// construct that we can't evaluate yet (because we don't yet know the 801 /// value of something) but stop if we hit something that could never be 802 /// a constant expression. 803 EM_PotentialConstantExpression, 804 805 /// Fold the expression to a constant. Stop if we hit a side-effect that 806 /// we can't model. 807 EM_ConstantFold, 808 809 /// Evaluate the expression looking for integer overflow and similar 810 /// issues. Don't worry about side-effects, and try to visit all 811 /// subexpressions. 812 EM_EvaluateForOverflow, 813 814 /// Evaluate in any way we know how. Don't worry about side-effects that 815 /// can't be modeled. 816 EM_IgnoreSideEffects, 817 818 /// Evaluate as a constant expression. Stop if we find that the expression 819 /// is not a constant expression. Some expressions can be retried in the 820 /// optimizer if we don't constant fold them here, but in an unevaluated 821 /// context we try to fold them immediately since the optimizer never 822 /// gets a chance to look at it. 823 EM_ConstantExpressionUnevaluated, 824 825 /// Evaluate as a potential constant expression. Keep going if we hit a 826 /// construct that we can't evaluate yet (because we don't yet know the 827 /// value of something) but stop if we hit something that could never be 828 /// a constant expression. Some expressions can be retried in the 829 /// optimizer if we don't constant fold them here, but in an unevaluated 830 /// context we try to fold them immediately since the optimizer never 831 /// gets a chance to look at it. 832 EM_PotentialConstantExpressionUnevaluated, 833 } EvalMode; 834 835 /// Are we checking whether the expression is a potential constant 836 /// expression? 837 bool checkingPotentialConstantExpression() const { 838 return EvalMode == EM_PotentialConstantExpression || 839 EvalMode == EM_PotentialConstantExpressionUnevaluated; 840 } 841 842 /// Are we checking an expression for overflow? 843 // FIXME: We should check for any kind of undefined or suspicious behavior 844 // in such constructs, not just overflow. 845 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; } 846 847 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 848 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 849 CallStackDepth(0), NextCallIndex(1), 850 StepsLeft(getLangOpts().ConstexprStepLimit), 851 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 852 EvaluatingDecl((const ValueDecl *)nullptr), 853 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 854 HasFoldFailureDiagnostic(false), 855 InConstantContext(false), EvalMode(Mode) {} 856 857 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) { 858 EvaluatingDecl = Base; 859 EvaluatingDeclValue = &Value; 860 } 861 862 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); } 863 864 bool CheckCallLimit(SourceLocation Loc) { 865 // Don't perform any constexpr calls (other than the call we're checking) 866 // when checking a potential constant expression. 867 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 868 return false; 869 if (NextCallIndex == 0) { 870 // NextCallIndex has wrapped around. 871 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 872 return false; 873 } 874 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 875 return true; 876 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 877 << getLangOpts().ConstexprCallDepth; 878 return false; 879 } 880 881 std::pair<CallStackFrame *, unsigned> 882 getCallFrameAndDepth(unsigned CallIndex) { 883 assert(CallIndex && "no call index in getCallFrameAndDepth"); 884 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 885 // be null in this loop. 886 unsigned Depth = CallStackDepth; 887 CallStackFrame *Frame = CurrentCall; 888 while (Frame->Index > CallIndex) { 889 Frame = Frame->Caller; 890 --Depth; 891 } 892 if (Frame->Index == CallIndex) 893 return {Frame, Depth}; 894 return {nullptr, 0}; 895 } 896 897 bool nextStep(const Stmt *S) { 898 if (!StepsLeft) { 899 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 900 return false; 901 } 902 --StepsLeft; 903 return true; 904 } 905 906 private: 907 /// Add a diagnostic to the diagnostics list. 908 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) { 909 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator()); 910 EvalStatus.Diag->push_back(std::make_pair(Loc, PD)); 911 return EvalStatus.Diag->back().second; 912 } 913 914 /// Add notes containing a call stack to the current point of evaluation. 915 void addCallStack(unsigned Limit); 916 917 private: 918 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId, 919 unsigned ExtraNotes, bool IsCCEDiag) { 920 921 if (EvalStatus.Diag) { 922 // If we have a prior diagnostic, it will be noting that the expression 923 // isn't a constant expression. This diagnostic is more important, 924 // unless we require this evaluation to produce a constant expression. 925 // 926 // FIXME: We might want to show both diagnostics to the user in 927 // EM_ConstantFold mode. 928 if (!EvalStatus.Diag->empty()) { 929 switch (EvalMode) { 930 case EM_ConstantFold: 931 case EM_IgnoreSideEffects: 932 case EM_EvaluateForOverflow: 933 if (!HasFoldFailureDiagnostic) 934 break; 935 // We've already failed to fold something. Keep that diagnostic. 936 LLVM_FALLTHROUGH; 937 case EM_ConstantExpression: 938 case EM_PotentialConstantExpression: 939 case EM_ConstantExpressionUnevaluated: 940 case EM_PotentialConstantExpressionUnevaluated: 941 HasActiveDiagnostic = false; 942 return OptionalDiagnostic(); 943 } 944 } 945 946 unsigned CallStackNotes = CallStackDepth - 1; 947 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit(); 948 if (Limit) 949 CallStackNotes = std::min(CallStackNotes, Limit + 1); 950 if (checkingPotentialConstantExpression()) 951 CallStackNotes = 0; 952 953 HasActiveDiagnostic = true; 954 HasFoldFailureDiagnostic = !IsCCEDiag; 955 EvalStatus.Diag->clear(); 956 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes); 957 addDiag(Loc, DiagId); 958 if (!checkingPotentialConstantExpression()) 959 addCallStack(Limit); 960 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second); 961 } 962 HasActiveDiagnostic = false; 963 return OptionalDiagnostic(); 964 } 965 public: 966 // Diagnose that the evaluation could not be folded (FF => FoldFailure) 967 OptionalDiagnostic 968 FFDiag(SourceLocation Loc, 969 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr, 970 unsigned ExtraNotes = 0) { 971 return Diag(Loc, DiagId, ExtraNotes, false); 972 } 973 974 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId 975 = diag::note_invalid_subexpr_in_const_expr, 976 unsigned ExtraNotes = 0) { 977 if (EvalStatus.Diag) 978 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false); 979 HasActiveDiagnostic = false; 980 return OptionalDiagnostic(); 981 } 982 983 /// Diagnose that the evaluation does not produce a C++11 core constant 984 /// expression. 985 /// 986 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or 987 /// EM_PotentialConstantExpression mode and we produce one of these. 988 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId 989 = diag::note_invalid_subexpr_in_const_expr, 990 unsigned ExtraNotes = 0) { 991 // Don't override a previous diagnostic. Don't bother collecting 992 // diagnostics if we're evaluating for overflow. 993 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) { 994 HasActiveDiagnostic = false; 995 return OptionalDiagnostic(); 996 } 997 return Diag(Loc, DiagId, ExtraNotes, true); 998 } 999 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId 1000 = diag::note_invalid_subexpr_in_const_expr, 1001 unsigned ExtraNotes = 0) { 1002 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes); 1003 } 1004 /// Add a note to a prior diagnostic. 1005 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) { 1006 if (!HasActiveDiagnostic) 1007 return OptionalDiagnostic(); 1008 return OptionalDiagnostic(&addDiag(Loc, DiagId)); 1009 } 1010 1011 /// Add a stack of notes to a prior diagnostic. 1012 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) { 1013 if (HasActiveDiagnostic) { 1014 EvalStatus.Diag->insert(EvalStatus.Diag->end(), 1015 Diags.begin(), Diags.end()); 1016 } 1017 } 1018 1019 /// Should we continue evaluation after encountering a side-effect that we 1020 /// couldn't model? 1021 bool keepEvaluatingAfterSideEffect() { 1022 switch (EvalMode) { 1023 case EM_PotentialConstantExpression: 1024 case EM_PotentialConstantExpressionUnevaluated: 1025 case EM_EvaluateForOverflow: 1026 case EM_IgnoreSideEffects: 1027 return true; 1028 1029 case EM_ConstantExpression: 1030 case EM_ConstantExpressionUnevaluated: 1031 case EM_ConstantFold: 1032 return false; 1033 } 1034 llvm_unreachable("Missed EvalMode case"); 1035 } 1036 1037 /// Note that we have had a side-effect, and determine whether we should 1038 /// keep evaluating. 1039 bool noteSideEffect() { 1040 EvalStatus.HasSideEffects = true; 1041 return keepEvaluatingAfterSideEffect(); 1042 } 1043 1044 /// Should we continue evaluation after encountering undefined behavior? 1045 bool keepEvaluatingAfterUndefinedBehavior() { 1046 switch (EvalMode) { 1047 case EM_EvaluateForOverflow: 1048 case EM_IgnoreSideEffects: 1049 case EM_ConstantFold: 1050 return true; 1051 1052 case EM_PotentialConstantExpression: 1053 case EM_PotentialConstantExpressionUnevaluated: 1054 case EM_ConstantExpression: 1055 case EM_ConstantExpressionUnevaluated: 1056 return false; 1057 } 1058 llvm_unreachable("Missed EvalMode case"); 1059 } 1060 1061 /// Note that we hit something that was technically undefined behavior, but 1062 /// that we can evaluate past it (such as signed overflow or floating-point 1063 /// division by zero.) 1064 bool noteUndefinedBehavior() { 1065 EvalStatus.HasUndefinedBehavior = true; 1066 return keepEvaluatingAfterUndefinedBehavior(); 1067 } 1068 1069 /// Should we continue evaluation as much as possible after encountering a 1070 /// construct which can't be reduced to a value? 1071 bool keepEvaluatingAfterFailure() { 1072 if (!StepsLeft) 1073 return false; 1074 1075 switch (EvalMode) { 1076 case EM_PotentialConstantExpression: 1077 case EM_PotentialConstantExpressionUnevaluated: 1078 case EM_EvaluateForOverflow: 1079 return true; 1080 1081 case EM_ConstantExpression: 1082 case EM_ConstantExpressionUnevaluated: 1083 case EM_ConstantFold: 1084 case EM_IgnoreSideEffects: 1085 return false; 1086 } 1087 llvm_unreachable("Missed EvalMode case"); 1088 } 1089 1090 /// Notes that we failed to evaluate an expression that other expressions 1091 /// directly depend on, and determine if we should keep evaluating. This 1092 /// should only be called if we actually intend to keep evaluating. 1093 /// 1094 /// Call noteSideEffect() instead if we may be able to ignore the value that 1095 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1096 /// 1097 /// (Foo(), 1) // use noteSideEffect 1098 /// (Foo() || true) // use noteSideEffect 1099 /// Foo() + 1 // use noteFailure 1100 LLVM_NODISCARD bool noteFailure() { 1101 // Failure when evaluating some expression often means there is some 1102 // subexpression whose evaluation was skipped. Therefore, (because we 1103 // don't track whether we skipped an expression when unwinding after an 1104 // evaluation failure) every evaluation failure that bubbles up from a 1105 // subexpression implies that a side-effect has potentially happened. We 1106 // skip setting the HasSideEffects flag to true until we decide to 1107 // continue evaluating after that point, which happens here. 1108 bool KeepGoing = keepEvaluatingAfterFailure(); 1109 EvalStatus.HasSideEffects |= KeepGoing; 1110 return KeepGoing; 1111 } 1112 1113 class ArrayInitLoopIndex { 1114 EvalInfo &Info; 1115 uint64_t OuterIndex; 1116 1117 public: 1118 ArrayInitLoopIndex(EvalInfo &Info) 1119 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1120 Info.ArrayInitIndex = 0; 1121 } 1122 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1123 1124 operator uint64_t&() { return Info.ArrayInitIndex; } 1125 }; 1126 }; 1127 1128 /// Object used to treat all foldable expressions as constant expressions. 1129 struct FoldConstant { 1130 EvalInfo &Info; 1131 bool Enabled; 1132 bool HadNoPriorDiags; 1133 EvalInfo::EvaluationMode OldMode; 1134 1135 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1136 : Info(Info), 1137 Enabled(Enabled), 1138 HadNoPriorDiags(Info.EvalStatus.Diag && 1139 Info.EvalStatus.Diag->empty() && 1140 !Info.EvalStatus.HasSideEffects), 1141 OldMode(Info.EvalMode) { 1142 if (Enabled && 1143 (Info.EvalMode == EvalInfo::EM_ConstantExpression || 1144 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated)) 1145 Info.EvalMode = EvalInfo::EM_ConstantFold; 1146 } 1147 void keepDiagnostics() { Enabled = false; } 1148 ~FoldConstant() { 1149 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1150 !Info.EvalStatus.HasSideEffects) 1151 Info.EvalStatus.Diag->clear(); 1152 Info.EvalMode = OldMode; 1153 } 1154 }; 1155 1156 /// RAII object used to set the current evaluation mode to ignore 1157 /// side-effects. 1158 struct IgnoreSideEffectsRAII { 1159 EvalInfo &Info; 1160 EvalInfo::EvaluationMode OldMode; 1161 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1162 : Info(Info), OldMode(Info.EvalMode) { 1163 if (!Info.checkingPotentialConstantExpression()) 1164 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1165 } 1166 1167 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1168 }; 1169 1170 /// RAII object used to optionally suppress diagnostics and side-effects from 1171 /// a speculative evaluation. 1172 class SpeculativeEvaluationRAII { 1173 EvalInfo *Info = nullptr; 1174 Expr::EvalStatus OldStatus; 1175 unsigned OldSpeculativeEvaluationDepth; 1176 1177 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1178 Info = Other.Info; 1179 OldStatus = Other.OldStatus; 1180 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1181 Other.Info = nullptr; 1182 } 1183 1184 void maybeRestoreState() { 1185 if (!Info) 1186 return; 1187 1188 Info->EvalStatus = OldStatus; 1189 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1190 } 1191 1192 public: 1193 SpeculativeEvaluationRAII() = default; 1194 1195 SpeculativeEvaluationRAII( 1196 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1197 : Info(&Info), OldStatus(Info.EvalStatus), 1198 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1199 Info.EvalStatus.Diag = NewDiag; 1200 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1201 } 1202 1203 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1204 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1205 moveFromAndCancel(std::move(Other)); 1206 } 1207 1208 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1209 maybeRestoreState(); 1210 moveFromAndCancel(std::move(Other)); 1211 return *this; 1212 } 1213 1214 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1215 }; 1216 1217 /// RAII object wrapping a full-expression or block scope, and handling 1218 /// the ending of the lifetime of temporaries created within it. 1219 template<bool IsFullExpression> 1220 class ScopeRAII { 1221 EvalInfo &Info; 1222 unsigned OldStackSize; 1223 public: 1224 ScopeRAII(EvalInfo &Info) 1225 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1226 // Push a new temporary version. This is needed to distinguish between 1227 // temporaries created in different iterations of a loop. 1228 Info.CurrentCall->pushTempVersion(); 1229 } 1230 ~ScopeRAII() { 1231 // Body moved to a static method to encourage the compiler to inline away 1232 // instances of this class. 1233 cleanup(Info, OldStackSize); 1234 Info.CurrentCall->popTempVersion(); 1235 } 1236 private: 1237 static void cleanup(EvalInfo &Info, unsigned OldStackSize) { 1238 unsigned NewEnd = OldStackSize; 1239 for (unsigned I = OldStackSize, N = Info.CleanupStack.size(); 1240 I != N; ++I) { 1241 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) { 1242 // Full-expression cleanup of a lifetime-extended temporary: nothing 1243 // to do, just move this cleanup to the right place in the stack. 1244 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]); 1245 ++NewEnd; 1246 } else { 1247 // End the lifetime of the object. 1248 Info.CleanupStack[I].endLifetime(); 1249 } 1250 } 1251 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd, 1252 Info.CleanupStack.end()); 1253 } 1254 }; 1255 typedef ScopeRAII<false> BlockScopeRAII; 1256 typedef ScopeRAII<true> FullExpressionRAII; 1257 } 1258 1259 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1260 CheckSubobjectKind CSK) { 1261 if (Invalid) 1262 return false; 1263 if (isOnePastTheEnd()) { 1264 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1265 << CSK; 1266 setInvalid(); 1267 return false; 1268 } 1269 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1270 // must actually be at least one array element; even a VLA cannot have a 1271 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1272 return true; 1273 } 1274 1275 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1276 const Expr *E) { 1277 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1278 // Do not set the designator as invalid: we can represent this situation, 1279 // and correct handling of __builtin_object_size requires us to do so. 1280 } 1281 1282 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1283 const Expr *E, 1284 const APSInt &N) { 1285 // If we're complaining, we must be able to statically determine the size of 1286 // the most derived array. 1287 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1288 Info.CCEDiag(E, diag::note_constexpr_array_index) 1289 << N << /*array*/ 0 1290 << static_cast<unsigned>(getMostDerivedArraySize()); 1291 else 1292 Info.CCEDiag(E, diag::note_constexpr_array_index) 1293 << N << /*non-array*/ 1; 1294 setInvalid(); 1295 } 1296 1297 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1298 const FunctionDecl *Callee, const LValue *This, 1299 APValue *Arguments) 1300 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1301 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1302 Info.CurrentCall = this; 1303 ++Info.CallStackDepth; 1304 } 1305 1306 CallStackFrame::~CallStackFrame() { 1307 assert(Info.CurrentCall == this && "calls retired out of order"); 1308 --Info.CallStackDepth; 1309 Info.CurrentCall = Caller; 1310 } 1311 1312 APValue &CallStackFrame::createTemporary(const void *Key, 1313 bool IsLifetimeExtended) { 1314 unsigned Version = Info.CurrentCall->getTempVersion(); 1315 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1316 assert(Result.isAbsent() && "temporary created multiple times"); 1317 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended)); 1318 return Result; 1319 } 1320 1321 static void describeCall(CallStackFrame *Frame, raw_ostream &Out); 1322 1323 void EvalInfo::addCallStack(unsigned Limit) { 1324 // Determine which calls to skip, if any. 1325 unsigned ActiveCalls = CallStackDepth - 1; 1326 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart; 1327 if (Limit && Limit < ActiveCalls) { 1328 SkipStart = Limit / 2 + Limit % 2; 1329 SkipEnd = ActiveCalls - Limit / 2; 1330 } 1331 1332 // Walk the call stack and add the diagnostics. 1333 unsigned CallIdx = 0; 1334 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame; 1335 Frame = Frame->Caller, ++CallIdx) { 1336 // Skip this call? 1337 if (CallIdx >= SkipStart && CallIdx < SkipEnd) { 1338 if (CallIdx == SkipStart) { 1339 // Note that we're skipping calls. 1340 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed) 1341 << unsigned(ActiveCalls - Limit); 1342 } 1343 continue; 1344 } 1345 1346 // Use a different note for an inheriting constructor, because from the 1347 // user's perspective it's not really a function at all. 1348 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) { 1349 if (CD->isInheritingConstructor()) { 1350 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here) 1351 << CD->getParent(); 1352 continue; 1353 } 1354 } 1355 1356 SmallVector<char, 128> Buffer; 1357 llvm::raw_svector_ostream Out(Buffer); 1358 describeCall(Frame, Out); 1359 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str(); 1360 } 1361 } 1362 1363 /// Kinds of access we can perform on an object, for diagnostics. Note that 1364 /// we consider a member function call to be a kind of access, even though 1365 /// it is not formally an access of the object, because it has (largely) the 1366 /// same set of semantic restrictions. 1367 enum AccessKinds { 1368 AK_Read, 1369 AK_Assign, 1370 AK_Increment, 1371 AK_Decrement, 1372 AK_MemberCall, 1373 AK_DynamicCast, 1374 AK_TypeId, 1375 }; 1376 1377 static bool isModification(AccessKinds AK) { 1378 switch (AK) { 1379 case AK_Read: 1380 case AK_MemberCall: 1381 case AK_DynamicCast: 1382 case AK_TypeId: 1383 return false; 1384 case AK_Assign: 1385 case AK_Increment: 1386 case AK_Decrement: 1387 return true; 1388 } 1389 llvm_unreachable("unknown access kind"); 1390 } 1391 1392 /// Is this an access per the C++ definition? 1393 static bool isFormalAccess(AccessKinds AK) { 1394 return AK == AK_Read || isModification(AK); 1395 } 1396 1397 namespace { 1398 struct ComplexValue { 1399 private: 1400 bool IsInt; 1401 1402 public: 1403 APSInt IntReal, IntImag; 1404 APFloat FloatReal, FloatImag; 1405 1406 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1407 1408 void makeComplexFloat() { IsInt = false; } 1409 bool isComplexFloat() const { return !IsInt; } 1410 APFloat &getComplexFloatReal() { return FloatReal; } 1411 APFloat &getComplexFloatImag() { return FloatImag; } 1412 1413 void makeComplexInt() { IsInt = true; } 1414 bool isComplexInt() const { return IsInt; } 1415 APSInt &getComplexIntReal() { return IntReal; } 1416 APSInt &getComplexIntImag() { return IntImag; } 1417 1418 void moveInto(APValue &v) const { 1419 if (isComplexFloat()) 1420 v = APValue(FloatReal, FloatImag); 1421 else 1422 v = APValue(IntReal, IntImag); 1423 } 1424 void setFrom(const APValue &v) { 1425 assert(v.isComplexFloat() || v.isComplexInt()); 1426 if (v.isComplexFloat()) { 1427 makeComplexFloat(); 1428 FloatReal = v.getComplexFloatReal(); 1429 FloatImag = v.getComplexFloatImag(); 1430 } else { 1431 makeComplexInt(); 1432 IntReal = v.getComplexIntReal(); 1433 IntImag = v.getComplexIntImag(); 1434 } 1435 } 1436 }; 1437 1438 struct LValue { 1439 APValue::LValueBase Base; 1440 CharUnits Offset; 1441 SubobjectDesignator Designator; 1442 bool IsNullPtr : 1; 1443 bool InvalidBase : 1; 1444 1445 const APValue::LValueBase getLValueBase() const { return Base; } 1446 CharUnits &getLValueOffset() { return Offset; } 1447 const CharUnits &getLValueOffset() const { return Offset; } 1448 SubobjectDesignator &getLValueDesignator() { return Designator; } 1449 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1450 bool isNullPointer() const { return IsNullPtr;} 1451 1452 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1453 unsigned getLValueVersion() const { return Base.getVersion(); } 1454 1455 void moveInto(APValue &V) const { 1456 if (Designator.Invalid) 1457 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1458 else { 1459 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1460 V = APValue(Base, Offset, Designator.Entries, 1461 Designator.IsOnePastTheEnd, IsNullPtr); 1462 } 1463 } 1464 void setFrom(ASTContext &Ctx, const APValue &V) { 1465 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1466 Base = V.getLValueBase(); 1467 Offset = V.getLValueOffset(); 1468 InvalidBase = false; 1469 Designator = SubobjectDesignator(Ctx, V); 1470 IsNullPtr = V.isNullPointer(); 1471 } 1472 1473 void set(APValue::LValueBase B, bool BInvalid = false) { 1474 #ifndef NDEBUG 1475 // We only allow a few types of invalid bases. Enforce that here. 1476 if (BInvalid) { 1477 const auto *E = B.get<const Expr *>(); 1478 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1479 "Unexpected type of invalid base"); 1480 } 1481 #endif 1482 1483 Base = B; 1484 Offset = CharUnits::fromQuantity(0); 1485 InvalidBase = BInvalid; 1486 Designator = SubobjectDesignator(getType(B)); 1487 IsNullPtr = false; 1488 } 1489 1490 void setNull(QualType PointerTy, uint64_t TargetVal) { 1491 Base = (Expr *)nullptr; 1492 Offset = CharUnits::fromQuantity(TargetVal); 1493 InvalidBase = false; 1494 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1495 IsNullPtr = true; 1496 } 1497 1498 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1499 set(B, true); 1500 } 1501 1502 private: 1503 // Check that this LValue is not based on a null pointer. If it is, produce 1504 // a diagnostic and mark the designator as invalid. 1505 template <typename GenDiagType> 1506 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1507 if (Designator.Invalid) 1508 return false; 1509 if (IsNullPtr) { 1510 GenDiag(); 1511 Designator.setInvalid(); 1512 return false; 1513 } 1514 return true; 1515 } 1516 1517 public: 1518 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1519 CheckSubobjectKind CSK) { 1520 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1521 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1522 }); 1523 } 1524 1525 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1526 AccessKinds AK) { 1527 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1528 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1529 }); 1530 } 1531 1532 // Check this LValue refers to an object. If not, set the designator to be 1533 // invalid and emit a diagnostic. 1534 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1535 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1536 Designator.checkSubobject(Info, E, CSK); 1537 } 1538 1539 void addDecl(EvalInfo &Info, const Expr *E, 1540 const Decl *D, bool Virtual = false) { 1541 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1542 Designator.addDeclUnchecked(D, Virtual); 1543 } 1544 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1545 if (!Designator.Entries.empty()) { 1546 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1547 Designator.setInvalid(); 1548 return; 1549 } 1550 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1551 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1552 Designator.FirstEntryIsAnUnsizedArray = true; 1553 Designator.addUnsizedArrayUnchecked(ElemTy); 1554 } 1555 } 1556 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1557 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1558 Designator.addArrayUnchecked(CAT); 1559 } 1560 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1561 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1562 Designator.addComplexUnchecked(EltTy, Imag); 1563 } 1564 void clearIsNullPointer() { 1565 IsNullPtr = false; 1566 } 1567 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1568 const APSInt &Index, CharUnits ElementSize) { 1569 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1570 // but we're not required to diagnose it and it's valid in C++.) 1571 if (!Index) 1572 return; 1573 1574 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1575 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1576 // offsets. 1577 uint64_t Offset64 = Offset.getQuantity(); 1578 uint64_t ElemSize64 = ElementSize.getQuantity(); 1579 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1580 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1581 1582 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1583 Designator.adjustIndex(Info, E, Index); 1584 clearIsNullPointer(); 1585 } 1586 void adjustOffset(CharUnits N) { 1587 Offset += N; 1588 if (N.getQuantity()) 1589 clearIsNullPointer(); 1590 } 1591 }; 1592 1593 struct MemberPtr { 1594 MemberPtr() {} 1595 explicit MemberPtr(const ValueDecl *Decl) : 1596 DeclAndIsDerivedMember(Decl, false), Path() {} 1597 1598 /// The member or (direct or indirect) field referred to by this member 1599 /// pointer, or 0 if this is a null member pointer. 1600 const ValueDecl *getDecl() const { 1601 return DeclAndIsDerivedMember.getPointer(); 1602 } 1603 /// Is this actually a member of some type derived from the relevant class? 1604 bool isDerivedMember() const { 1605 return DeclAndIsDerivedMember.getInt(); 1606 } 1607 /// Get the class which the declaration actually lives in. 1608 const CXXRecordDecl *getContainingRecord() const { 1609 return cast<CXXRecordDecl>( 1610 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1611 } 1612 1613 void moveInto(APValue &V) const { 1614 V = APValue(getDecl(), isDerivedMember(), Path); 1615 } 1616 void setFrom(const APValue &V) { 1617 assert(V.isMemberPointer()); 1618 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1619 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1620 Path.clear(); 1621 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1622 Path.insert(Path.end(), P.begin(), P.end()); 1623 } 1624 1625 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1626 /// whether the member is a member of some class derived from the class type 1627 /// of the member pointer. 1628 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1629 /// Path - The path of base/derived classes from the member declaration's 1630 /// class (exclusive) to the class type of the member pointer (inclusive). 1631 SmallVector<const CXXRecordDecl*, 4> Path; 1632 1633 /// Perform a cast towards the class of the Decl (either up or down the 1634 /// hierarchy). 1635 bool castBack(const CXXRecordDecl *Class) { 1636 assert(!Path.empty()); 1637 const CXXRecordDecl *Expected; 1638 if (Path.size() >= 2) 1639 Expected = Path[Path.size() - 2]; 1640 else 1641 Expected = getContainingRecord(); 1642 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1643 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1644 // if B does not contain the original member and is not a base or 1645 // derived class of the class containing the original member, the result 1646 // of the cast is undefined. 1647 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1648 // (D::*). We consider that to be a language defect. 1649 return false; 1650 } 1651 Path.pop_back(); 1652 return true; 1653 } 1654 /// Perform a base-to-derived member pointer cast. 1655 bool castToDerived(const CXXRecordDecl *Derived) { 1656 if (!getDecl()) 1657 return true; 1658 if (!isDerivedMember()) { 1659 Path.push_back(Derived); 1660 return true; 1661 } 1662 if (!castBack(Derived)) 1663 return false; 1664 if (Path.empty()) 1665 DeclAndIsDerivedMember.setInt(false); 1666 return true; 1667 } 1668 /// Perform a derived-to-base member pointer cast. 1669 bool castToBase(const CXXRecordDecl *Base) { 1670 if (!getDecl()) 1671 return true; 1672 if (Path.empty()) 1673 DeclAndIsDerivedMember.setInt(true); 1674 if (isDerivedMember()) { 1675 Path.push_back(Base); 1676 return true; 1677 } 1678 return castBack(Base); 1679 } 1680 }; 1681 1682 /// Compare two member pointers, which are assumed to be of the same type. 1683 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1684 if (!LHS.getDecl() || !RHS.getDecl()) 1685 return !LHS.getDecl() && !RHS.getDecl(); 1686 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1687 return false; 1688 return LHS.Path == RHS.Path; 1689 } 1690 } 1691 1692 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1693 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1694 const LValue &This, const Expr *E, 1695 bool AllowNonLiteralTypes = false); 1696 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1697 bool InvalidBaseOK = false); 1698 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1699 bool InvalidBaseOK = false); 1700 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1701 EvalInfo &Info); 1702 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1703 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1704 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1705 EvalInfo &Info); 1706 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1707 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1708 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1709 EvalInfo &Info); 1710 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1711 1712 /// Evaluate an integer or fixed point expression into an APResult. 1713 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1714 EvalInfo &Info); 1715 1716 /// Evaluate only a fixed point expression into an APResult. 1717 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1718 EvalInfo &Info); 1719 1720 //===----------------------------------------------------------------------===// 1721 // Misc utilities 1722 //===----------------------------------------------------------------------===// 1723 1724 /// A helper function to create a temporary and set an LValue. 1725 template <class KeyTy> 1726 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended, 1727 LValue &LV, CallStackFrame &Frame) { 1728 LV.set({Key, Frame.Info.CurrentCall->Index, 1729 Frame.Info.CurrentCall->getTempVersion()}); 1730 return Frame.createTemporary(Key, IsLifetimeExtended); 1731 } 1732 1733 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1734 /// preserving its value (by extending by up to one bit as needed). 1735 static void negateAsSigned(APSInt &Int) { 1736 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1737 Int = Int.extend(Int.getBitWidth() + 1); 1738 Int.setIsSigned(true); 1739 } 1740 Int = -Int; 1741 } 1742 1743 /// Produce a string describing the given constexpr call. 1744 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) { 1745 unsigned ArgIndex = 0; 1746 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) && 1747 !isa<CXXConstructorDecl>(Frame->Callee) && 1748 cast<CXXMethodDecl>(Frame->Callee)->isInstance(); 1749 1750 if (!IsMemberCall) 1751 Out << *Frame->Callee << '('; 1752 1753 if (Frame->This && IsMemberCall) { 1754 APValue Val; 1755 Frame->This->moveInto(Val); 1756 Val.printPretty(Out, Frame->Info.Ctx, 1757 Frame->This->Designator.MostDerivedType); 1758 // FIXME: Add parens around Val if needed. 1759 Out << "->" << *Frame->Callee << '('; 1760 IsMemberCall = false; 1761 } 1762 1763 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(), 1764 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) { 1765 if (ArgIndex > (unsigned)IsMemberCall) 1766 Out << ", "; 1767 1768 const ParmVarDecl *Param = *I; 1769 const APValue &Arg = Frame->Arguments[ArgIndex]; 1770 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType()); 1771 1772 if (ArgIndex == 0 && IsMemberCall) 1773 Out << "->" << *Frame->Callee << '('; 1774 } 1775 1776 Out << ')'; 1777 } 1778 1779 /// Evaluate an expression to see if it had side-effects, and discard its 1780 /// result. 1781 /// \return \c true if the caller should keep evaluating. 1782 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1783 APValue Scratch; 1784 if (!Evaluate(Scratch, Info, E)) 1785 // We don't need the value, but we might have skipped a side effect here. 1786 return Info.noteSideEffect(); 1787 return true; 1788 } 1789 1790 /// Should this call expression be treated as a string literal? 1791 static bool IsStringLiteralCall(const CallExpr *E) { 1792 unsigned Builtin = E->getBuiltinCallee(); 1793 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1794 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1795 } 1796 1797 static bool IsGlobalLValue(APValue::LValueBase B) { 1798 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1799 // constant expression of pointer type that evaluates to... 1800 1801 // ... a null pointer value, or a prvalue core constant expression of type 1802 // std::nullptr_t. 1803 if (!B) return true; 1804 1805 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1806 // ... the address of an object with static storage duration, 1807 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1808 return VD->hasGlobalStorage(); 1809 // ... the address of a function, 1810 return isa<FunctionDecl>(D); 1811 } 1812 1813 if (B.is<TypeInfoLValue>()) 1814 return true; 1815 1816 const Expr *E = B.get<const Expr*>(); 1817 switch (E->getStmtClass()) { 1818 default: 1819 return false; 1820 case Expr::CompoundLiteralExprClass: { 1821 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1822 return CLE->isFileScope() && CLE->isLValue(); 1823 } 1824 case Expr::MaterializeTemporaryExprClass: 1825 // A materialized temporary might have been lifetime-extended to static 1826 // storage duration. 1827 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1828 // A string literal has static storage duration. 1829 case Expr::StringLiteralClass: 1830 case Expr::PredefinedExprClass: 1831 case Expr::ObjCStringLiteralClass: 1832 case Expr::ObjCEncodeExprClass: 1833 case Expr::CXXUuidofExprClass: 1834 return true; 1835 case Expr::ObjCBoxedExprClass: 1836 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 1837 case Expr::CallExprClass: 1838 return IsStringLiteralCall(cast<CallExpr>(E)); 1839 // For GCC compatibility, &&label has static storage duration. 1840 case Expr::AddrLabelExprClass: 1841 return true; 1842 // A Block literal expression may be used as the initialization value for 1843 // Block variables at global or local static scope. 1844 case Expr::BlockExprClass: 1845 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1846 case Expr::ImplicitValueInitExprClass: 1847 // FIXME: 1848 // We can never form an lvalue with an implicit value initialization as its 1849 // base through expression evaluation, so these only appear in one case: the 1850 // implicit variable declaration we invent when checking whether a constexpr 1851 // constructor can produce a constant expression. We must assume that such 1852 // an expression might be a global lvalue. 1853 return true; 1854 } 1855 } 1856 1857 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1858 return LVal.Base.dyn_cast<const ValueDecl*>(); 1859 } 1860 1861 static bool IsLiteralLValue(const LValue &Value) { 1862 if (Value.getLValueCallIndex()) 1863 return false; 1864 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1865 return E && !isa<MaterializeTemporaryExpr>(E); 1866 } 1867 1868 static bool IsWeakLValue(const LValue &Value) { 1869 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1870 return Decl && Decl->isWeak(); 1871 } 1872 1873 static bool isZeroSized(const LValue &Value) { 1874 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1875 if (Decl && isa<VarDecl>(Decl)) { 1876 QualType Ty = Decl->getType(); 1877 if (Ty->isArrayType()) 1878 return Ty->isIncompleteType() || 1879 Decl->getASTContext().getTypeSize(Ty) == 0; 1880 } 1881 return false; 1882 } 1883 1884 static bool HasSameBase(const LValue &A, const LValue &B) { 1885 if (!A.getLValueBase()) 1886 return !B.getLValueBase(); 1887 if (!B.getLValueBase()) 1888 return false; 1889 1890 if (A.getLValueBase().getOpaqueValue() != 1891 B.getLValueBase().getOpaqueValue()) { 1892 const Decl *ADecl = GetLValueBaseDecl(A); 1893 if (!ADecl) 1894 return false; 1895 const Decl *BDecl = GetLValueBaseDecl(B); 1896 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 1897 return false; 1898 } 1899 1900 return IsGlobalLValue(A.getLValueBase()) || 1901 (A.getLValueCallIndex() == B.getLValueCallIndex() && 1902 A.getLValueVersion() == B.getLValueVersion()); 1903 } 1904 1905 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1906 assert(Base && "no location for a null lvalue"); 1907 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1908 if (VD) 1909 Info.Note(VD->getLocation(), diag::note_declared_at); 1910 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 1911 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 1912 // We have no information to show for a typeid(T) object. 1913 } 1914 1915 /// Check that this reference or pointer core constant expression is a valid 1916 /// value for an address or reference constant expression. Return true if we 1917 /// can fold this expression, whether or not it's a constant expression. 1918 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 1919 QualType Type, const LValue &LVal, 1920 Expr::ConstExprUsage Usage) { 1921 bool IsReferenceType = Type->isReferenceType(); 1922 1923 APValue::LValueBase Base = LVal.getLValueBase(); 1924 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 1925 1926 // Check that the object is a global. Note that the fake 'this' object we 1927 // manufacture when checking potential constant expressions is conservatively 1928 // assumed to be global here. 1929 if (!IsGlobalLValue(Base)) { 1930 if (Info.getLangOpts().CPlusPlus11) { 1931 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1932 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 1933 << IsReferenceType << !Designator.Entries.empty() 1934 << !!VD << VD; 1935 NoteLValueLocation(Info, Base); 1936 } else { 1937 Info.FFDiag(Loc); 1938 } 1939 // Don't allow references to temporaries to escape. 1940 return false; 1941 } 1942 assert((Info.checkingPotentialConstantExpression() || 1943 LVal.getLValueCallIndex() == 0) && 1944 "have call index for global lvalue"); 1945 1946 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 1947 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 1948 // Check if this is a thread-local variable. 1949 if (Var->getTLSKind()) 1950 return false; 1951 1952 // A dllimport variable never acts like a constant. 1953 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 1954 return false; 1955 } 1956 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 1957 // __declspec(dllimport) must be handled very carefully: 1958 // We must never initialize an expression with the thunk in C++. 1959 // Doing otherwise would allow the same id-expression to yield 1960 // different addresses for the same function in different translation 1961 // units. However, this means that we must dynamically initialize the 1962 // expression with the contents of the import address table at runtime. 1963 // 1964 // The C language has no notion of ODR; furthermore, it has no notion of 1965 // dynamic initialization. This means that we are permitted to 1966 // perform initialization with the address of the thunk. 1967 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 1968 FD->hasAttr<DLLImportAttr>()) 1969 return false; 1970 } 1971 } 1972 1973 // Allow address constant expressions to be past-the-end pointers. This is 1974 // an extension: the standard requires them to point to an object. 1975 if (!IsReferenceType) 1976 return true; 1977 1978 // A reference constant expression must refer to an object. 1979 if (!Base) { 1980 // FIXME: diagnostic 1981 Info.CCEDiag(Loc); 1982 return true; 1983 } 1984 1985 // Does this refer one past the end of some object? 1986 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 1987 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1988 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 1989 << !Designator.Entries.empty() << !!VD << VD; 1990 NoteLValueLocation(Info, Base); 1991 } 1992 1993 return true; 1994 } 1995 1996 /// Member pointers are constant expressions unless they point to a 1997 /// non-virtual dllimport member function. 1998 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 1999 SourceLocation Loc, 2000 QualType Type, 2001 const APValue &Value, 2002 Expr::ConstExprUsage Usage) { 2003 const ValueDecl *Member = Value.getMemberPointerDecl(); 2004 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2005 if (!FD) 2006 return true; 2007 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 2008 !FD->hasAttr<DLLImportAttr>(); 2009 } 2010 2011 /// Check that this core constant expression is of literal type, and if not, 2012 /// produce an appropriate diagnostic. 2013 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2014 const LValue *This = nullptr) { 2015 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2016 return true; 2017 2018 // C++1y: A constant initializer for an object o [...] may also invoke 2019 // constexpr constructors for o and its subobjects even if those objects 2020 // are of non-literal class types. 2021 // 2022 // C++11 missed this detail for aggregates, so classes like this: 2023 // struct foo_t { union { int i; volatile int j; } u; }; 2024 // are not (obviously) initializable like so: 2025 // __attribute__((__require_constant_initialization__)) 2026 // static const foo_t x = {{0}}; 2027 // because "i" is a subobject with non-literal initialization (due to the 2028 // volatile member of the union). See: 2029 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2030 // Therefore, we use the C++1y behavior. 2031 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2032 return true; 2033 2034 // Prvalue constant expressions must be of literal types. 2035 if (Info.getLangOpts().CPlusPlus11) 2036 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2037 << E->getType(); 2038 else 2039 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2040 return false; 2041 } 2042 2043 /// Check that this core constant expression value is a valid value for a 2044 /// constant expression. If not, report an appropriate diagnostic. Does not 2045 /// check that the expression is of literal type. 2046 static bool 2047 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 2048 const APValue &Value, 2049 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen, 2050 SourceLocation SubobjectLoc = SourceLocation()) { 2051 if (!Value.hasValue()) { 2052 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2053 << true << Type; 2054 if (SubobjectLoc.isValid()) 2055 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2056 return false; 2057 } 2058 2059 // We allow _Atomic(T) to be initialized from anything that T can be 2060 // initialized from. 2061 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2062 Type = AT->getValueType(); 2063 2064 // Core issue 1454: For a literal constant expression of array or class type, 2065 // each subobject of its value shall have been initialized by a constant 2066 // expression. 2067 if (Value.isArray()) { 2068 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2069 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2070 if (!CheckConstantExpression(Info, DiagLoc, EltTy, 2071 Value.getArrayInitializedElt(I), Usage, 2072 SubobjectLoc)) 2073 return false; 2074 } 2075 if (!Value.hasArrayFiller()) 2076 return true; 2077 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(), 2078 Usage, SubobjectLoc); 2079 } 2080 if (Value.isUnion() && Value.getUnionField()) { 2081 return CheckConstantExpression(Info, DiagLoc, 2082 Value.getUnionField()->getType(), 2083 Value.getUnionValue(), Usage, 2084 Value.getUnionField()->getLocation()); 2085 } 2086 if (Value.isStruct()) { 2087 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2088 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2089 unsigned BaseIndex = 0; 2090 for (const CXXBaseSpecifier &BS : CD->bases()) { 2091 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(), 2092 Value.getStructBase(BaseIndex), Usage, 2093 BS.getBeginLoc())) 2094 return false; 2095 ++BaseIndex; 2096 } 2097 } 2098 for (const auto *I : RD->fields()) { 2099 if (I->isUnnamedBitfield()) 2100 continue; 2101 2102 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 2103 Value.getStructField(I->getFieldIndex()), 2104 Usage, I->getLocation())) 2105 return false; 2106 } 2107 } 2108 2109 if (Value.isLValue()) { 2110 LValue LVal; 2111 LVal.setFrom(Info.Ctx, Value); 2112 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage); 2113 } 2114 2115 if (Value.isMemberPointer()) 2116 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 2117 2118 // Everything else is fine. 2119 return true; 2120 } 2121 2122 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2123 // A null base expression indicates a null pointer. These are always 2124 // evaluatable, and they are false unless the offset is zero. 2125 if (!Value.getLValueBase()) { 2126 Result = !Value.getLValueOffset().isZero(); 2127 return true; 2128 } 2129 2130 // We have a non-null base. These are generally known to be true, but if it's 2131 // a weak declaration it can be null at runtime. 2132 Result = true; 2133 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2134 return !Decl || !Decl->isWeak(); 2135 } 2136 2137 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2138 switch (Val.getKind()) { 2139 case APValue::None: 2140 case APValue::Indeterminate: 2141 return false; 2142 case APValue::Int: 2143 Result = Val.getInt().getBoolValue(); 2144 return true; 2145 case APValue::FixedPoint: 2146 Result = Val.getFixedPoint().getBoolValue(); 2147 return true; 2148 case APValue::Float: 2149 Result = !Val.getFloat().isZero(); 2150 return true; 2151 case APValue::ComplexInt: 2152 Result = Val.getComplexIntReal().getBoolValue() || 2153 Val.getComplexIntImag().getBoolValue(); 2154 return true; 2155 case APValue::ComplexFloat: 2156 Result = !Val.getComplexFloatReal().isZero() || 2157 !Val.getComplexFloatImag().isZero(); 2158 return true; 2159 case APValue::LValue: 2160 return EvalPointerValueAsBool(Val, Result); 2161 case APValue::MemberPointer: 2162 Result = Val.getMemberPointerDecl(); 2163 return true; 2164 case APValue::Vector: 2165 case APValue::Array: 2166 case APValue::Struct: 2167 case APValue::Union: 2168 case APValue::AddrLabelDiff: 2169 return false; 2170 } 2171 2172 llvm_unreachable("unknown APValue kind"); 2173 } 2174 2175 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2176 EvalInfo &Info) { 2177 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2178 APValue Val; 2179 if (!Evaluate(Val, Info, E)) 2180 return false; 2181 return HandleConversionToBool(Val, Result); 2182 } 2183 2184 template<typename T> 2185 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2186 const T &SrcValue, QualType DestType) { 2187 Info.CCEDiag(E, diag::note_constexpr_overflow) 2188 << SrcValue << DestType; 2189 return Info.noteUndefinedBehavior(); 2190 } 2191 2192 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2193 QualType SrcType, const APFloat &Value, 2194 QualType DestType, APSInt &Result) { 2195 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2196 // Determine whether we are converting to unsigned or signed. 2197 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2198 2199 Result = APSInt(DestWidth, !DestSigned); 2200 bool ignored; 2201 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2202 & APFloat::opInvalidOp) 2203 return HandleOverflow(Info, E, Value, DestType); 2204 return true; 2205 } 2206 2207 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2208 QualType SrcType, QualType DestType, 2209 APFloat &Result) { 2210 APFloat Value = Result; 2211 bool ignored; 2212 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 2213 APFloat::rmNearestTiesToEven, &ignored) 2214 & APFloat::opOverflow) 2215 return HandleOverflow(Info, E, Value, DestType); 2216 return true; 2217 } 2218 2219 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2220 QualType DestType, QualType SrcType, 2221 const APSInt &Value) { 2222 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2223 // Figure out if this is a truncate, extend or noop cast. 2224 // If the input is signed, do a sign extend, noop, or truncate. 2225 APSInt Result = Value.extOrTrunc(DestWidth); 2226 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2227 if (DestType->isBooleanType()) 2228 Result = Value.getBoolValue(); 2229 return Result; 2230 } 2231 2232 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2233 QualType SrcType, const APSInt &Value, 2234 QualType DestType, APFloat &Result) { 2235 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2236 if (Result.convertFromAPInt(Value, Value.isSigned(), 2237 APFloat::rmNearestTiesToEven) 2238 & APFloat::opOverflow) 2239 return HandleOverflow(Info, E, Value, DestType); 2240 return true; 2241 } 2242 2243 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2244 APValue &Value, const FieldDecl *FD) { 2245 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2246 2247 if (!Value.isInt()) { 2248 // Trying to store a pointer-cast-to-integer into a bitfield. 2249 // FIXME: In this case, we should provide the diagnostic for casting 2250 // a pointer to an integer. 2251 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2252 Info.FFDiag(E); 2253 return false; 2254 } 2255 2256 APSInt &Int = Value.getInt(); 2257 unsigned OldBitWidth = Int.getBitWidth(); 2258 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2259 if (NewBitWidth < OldBitWidth) 2260 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2261 return true; 2262 } 2263 2264 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2265 llvm::APInt &Res) { 2266 APValue SVal; 2267 if (!Evaluate(SVal, Info, E)) 2268 return false; 2269 if (SVal.isInt()) { 2270 Res = SVal.getInt(); 2271 return true; 2272 } 2273 if (SVal.isFloat()) { 2274 Res = SVal.getFloat().bitcastToAPInt(); 2275 return true; 2276 } 2277 if (SVal.isVector()) { 2278 QualType VecTy = E->getType(); 2279 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2280 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2281 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2282 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2283 Res = llvm::APInt::getNullValue(VecSize); 2284 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2285 APValue &Elt = SVal.getVectorElt(i); 2286 llvm::APInt EltAsInt; 2287 if (Elt.isInt()) { 2288 EltAsInt = Elt.getInt(); 2289 } else if (Elt.isFloat()) { 2290 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2291 } else { 2292 // Don't try to handle vectors of anything other than int or float 2293 // (not sure if it's possible to hit this case). 2294 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2295 return false; 2296 } 2297 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2298 if (BigEndian) 2299 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2300 else 2301 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2302 } 2303 return true; 2304 } 2305 // Give up if the input isn't an int, float, or vector. For example, we 2306 // reject "(v4i16)(intptr_t)&a". 2307 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2308 return false; 2309 } 2310 2311 /// Perform the given integer operation, which is known to need at most BitWidth 2312 /// bits, and check for overflow in the original type (if that type was not an 2313 /// unsigned type). 2314 template<typename Operation> 2315 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2316 const APSInt &LHS, const APSInt &RHS, 2317 unsigned BitWidth, Operation Op, 2318 APSInt &Result) { 2319 if (LHS.isUnsigned()) { 2320 Result = Op(LHS, RHS); 2321 return true; 2322 } 2323 2324 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2325 Result = Value.trunc(LHS.getBitWidth()); 2326 if (Result.extend(BitWidth) != Value) { 2327 if (Info.checkingForOverflow()) 2328 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2329 diag::warn_integer_constant_overflow) 2330 << Result.toString(10) << E->getType(); 2331 else 2332 return HandleOverflow(Info, E, Value, E->getType()); 2333 } 2334 return true; 2335 } 2336 2337 /// Perform the given binary integer operation. 2338 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2339 BinaryOperatorKind Opcode, APSInt RHS, 2340 APSInt &Result) { 2341 switch (Opcode) { 2342 default: 2343 Info.FFDiag(E); 2344 return false; 2345 case BO_Mul: 2346 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2347 std::multiplies<APSInt>(), Result); 2348 case BO_Add: 2349 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2350 std::plus<APSInt>(), Result); 2351 case BO_Sub: 2352 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2353 std::minus<APSInt>(), Result); 2354 case BO_And: Result = LHS & RHS; return true; 2355 case BO_Xor: Result = LHS ^ RHS; return true; 2356 case BO_Or: Result = LHS | RHS; return true; 2357 case BO_Div: 2358 case BO_Rem: 2359 if (RHS == 0) { 2360 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2361 return false; 2362 } 2363 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2364 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2365 // this operation and gives the two's complement result. 2366 if (RHS.isNegative() && RHS.isAllOnesValue() && 2367 LHS.isSigned() && LHS.isMinSignedValue()) 2368 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2369 E->getType()); 2370 return true; 2371 case BO_Shl: { 2372 if (Info.getLangOpts().OpenCL) 2373 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2374 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2375 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2376 RHS.isUnsigned()); 2377 else if (RHS.isSigned() && RHS.isNegative()) { 2378 // During constant-folding, a negative shift is an opposite shift. Such 2379 // a shift is not a constant expression. 2380 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2381 RHS = -RHS; 2382 goto shift_right; 2383 } 2384 shift_left: 2385 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2386 // the shifted type. 2387 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2388 if (SA != RHS) { 2389 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2390 << RHS << E->getType() << LHS.getBitWidth(); 2391 } else if (LHS.isSigned()) { 2392 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2393 // operand, and must not overflow the corresponding unsigned type. 2394 if (LHS.isNegative()) 2395 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2396 else if (LHS.countLeadingZeros() < SA) 2397 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2398 } 2399 Result = LHS << SA; 2400 return true; 2401 } 2402 case BO_Shr: { 2403 if (Info.getLangOpts().OpenCL) 2404 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2405 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2406 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2407 RHS.isUnsigned()); 2408 else if (RHS.isSigned() && RHS.isNegative()) { 2409 // During constant-folding, a negative shift is an opposite shift. Such a 2410 // shift is not a constant expression. 2411 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2412 RHS = -RHS; 2413 goto shift_left; 2414 } 2415 shift_right: 2416 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2417 // shifted type. 2418 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2419 if (SA != RHS) 2420 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2421 << RHS << E->getType() << LHS.getBitWidth(); 2422 Result = LHS >> SA; 2423 return true; 2424 } 2425 2426 case BO_LT: Result = LHS < RHS; return true; 2427 case BO_GT: Result = LHS > RHS; return true; 2428 case BO_LE: Result = LHS <= RHS; return true; 2429 case BO_GE: Result = LHS >= RHS; return true; 2430 case BO_EQ: Result = LHS == RHS; return true; 2431 case BO_NE: Result = LHS != RHS; return true; 2432 case BO_Cmp: 2433 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2434 } 2435 } 2436 2437 /// Perform the given binary floating-point operation, in-place, on LHS. 2438 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2439 APFloat &LHS, BinaryOperatorKind Opcode, 2440 const APFloat &RHS) { 2441 switch (Opcode) { 2442 default: 2443 Info.FFDiag(E); 2444 return false; 2445 case BO_Mul: 2446 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2447 break; 2448 case BO_Add: 2449 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2450 break; 2451 case BO_Sub: 2452 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2453 break; 2454 case BO_Div: 2455 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2456 break; 2457 } 2458 2459 if (LHS.isInfinity() || LHS.isNaN()) { 2460 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2461 return Info.noteUndefinedBehavior(); 2462 } 2463 return true; 2464 } 2465 2466 /// Cast an lvalue referring to a base subobject to a derived class, by 2467 /// truncating the lvalue's path to the given length. 2468 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2469 const RecordDecl *TruncatedType, 2470 unsigned TruncatedElements) { 2471 SubobjectDesignator &D = Result.Designator; 2472 2473 // Check we actually point to a derived class object. 2474 if (TruncatedElements == D.Entries.size()) 2475 return true; 2476 assert(TruncatedElements >= D.MostDerivedPathLength && 2477 "not casting to a derived class"); 2478 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2479 return false; 2480 2481 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2482 const RecordDecl *RD = TruncatedType; 2483 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2484 if (RD->isInvalidDecl()) return false; 2485 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2486 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2487 if (isVirtualBaseClass(D.Entries[I])) 2488 Result.Offset -= Layout.getVBaseClassOffset(Base); 2489 else 2490 Result.Offset -= Layout.getBaseClassOffset(Base); 2491 RD = Base; 2492 } 2493 D.Entries.resize(TruncatedElements); 2494 return true; 2495 } 2496 2497 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2498 const CXXRecordDecl *Derived, 2499 const CXXRecordDecl *Base, 2500 const ASTRecordLayout *RL = nullptr) { 2501 if (!RL) { 2502 if (Derived->isInvalidDecl()) return false; 2503 RL = &Info.Ctx.getASTRecordLayout(Derived); 2504 } 2505 2506 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2507 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2508 return true; 2509 } 2510 2511 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2512 const CXXRecordDecl *DerivedDecl, 2513 const CXXBaseSpecifier *Base) { 2514 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2515 2516 if (!Base->isVirtual()) 2517 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2518 2519 SubobjectDesignator &D = Obj.Designator; 2520 if (D.Invalid) 2521 return false; 2522 2523 // Extract most-derived object and corresponding type. 2524 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2525 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2526 return false; 2527 2528 // Find the virtual base class. 2529 if (DerivedDecl->isInvalidDecl()) return false; 2530 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2531 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2532 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2533 return true; 2534 } 2535 2536 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2537 QualType Type, LValue &Result) { 2538 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2539 PathE = E->path_end(); 2540 PathI != PathE; ++PathI) { 2541 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2542 *PathI)) 2543 return false; 2544 Type = (*PathI)->getType(); 2545 } 2546 return true; 2547 } 2548 2549 /// Cast an lvalue referring to a derived class to a known base subobject. 2550 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 2551 const CXXRecordDecl *DerivedRD, 2552 const CXXRecordDecl *BaseRD) { 2553 CXXBasePaths Paths(/*FindAmbiguities=*/false, 2554 /*RecordPaths=*/true, /*DetectVirtual=*/false); 2555 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 2556 llvm_unreachable("Class must be derived from the passed in base class!"); 2557 2558 for (CXXBasePathElement &Elem : Paths.front()) 2559 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 2560 return false; 2561 return true; 2562 } 2563 2564 /// Update LVal to refer to the given field, which must be a member of the type 2565 /// currently described by LVal. 2566 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2567 const FieldDecl *FD, 2568 const ASTRecordLayout *RL = nullptr) { 2569 if (!RL) { 2570 if (FD->getParent()->isInvalidDecl()) return false; 2571 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2572 } 2573 2574 unsigned I = FD->getFieldIndex(); 2575 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2576 LVal.addDecl(Info, E, FD); 2577 return true; 2578 } 2579 2580 /// Update LVal to refer to the given indirect field. 2581 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2582 LValue &LVal, 2583 const IndirectFieldDecl *IFD) { 2584 for (const auto *C : IFD->chain()) 2585 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2586 return false; 2587 return true; 2588 } 2589 2590 /// Get the size of the given type in char units. 2591 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2592 QualType Type, CharUnits &Size) { 2593 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2594 // extension. 2595 if (Type->isVoidType() || Type->isFunctionType()) { 2596 Size = CharUnits::One(); 2597 return true; 2598 } 2599 2600 if (Type->isDependentType()) { 2601 Info.FFDiag(Loc); 2602 return false; 2603 } 2604 2605 if (!Type->isConstantSizeType()) { 2606 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2607 // FIXME: Better diagnostic. 2608 Info.FFDiag(Loc); 2609 return false; 2610 } 2611 2612 Size = Info.Ctx.getTypeSizeInChars(Type); 2613 return true; 2614 } 2615 2616 /// Update a pointer value to model pointer arithmetic. 2617 /// \param Info - Information about the ongoing evaluation. 2618 /// \param E - The expression being evaluated, for diagnostic purposes. 2619 /// \param LVal - The pointer value to be updated. 2620 /// \param EltTy - The pointee type represented by LVal. 2621 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2622 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2623 LValue &LVal, QualType EltTy, 2624 APSInt Adjustment) { 2625 CharUnits SizeOfPointee; 2626 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2627 return false; 2628 2629 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2630 return true; 2631 } 2632 2633 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2634 LValue &LVal, QualType EltTy, 2635 int64_t Adjustment) { 2636 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 2637 APSInt::get(Adjustment)); 2638 } 2639 2640 /// Update an lvalue to refer to a component of a complex number. 2641 /// \param Info - Information about the ongoing evaluation. 2642 /// \param LVal - The lvalue to be updated. 2643 /// \param EltTy - The complex number's component type. 2644 /// \param Imag - False for the real component, true for the imaginary. 2645 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 2646 LValue &LVal, QualType EltTy, 2647 bool Imag) { 2648 if (Imag) { 2649 CharUnits SizeOfComponent; 2650 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 2651 return false; 2652 LVal.Offset += SizeOfComponent; 2653 } 2654 LVal.addComplex(Info, E, EltTy, Imag); 2655 return true; 2656 } 2657 2658 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 2659 QualType Type, const LValue &LVal, 2660 APValue &RVal); 2661 2662 /// Try to evaluate the initializer for a variable declaration. 2663 /// 2664 /// \param Info Information about the ongoing evaluation. 2665 /// \param E An expression to be used when printing diagnostics. 2666 /// \param VD The variable whose initializer should be obtained. 2667 /// \param Frame The frame in which the variable was created. Must be null 2668 /// if this variable is not local to the evaluation. 2669 /// \param Result Filled in with a pointer to the value of the variable. 2670 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 2671 const VarDecl *VD, CallStackFrame *Frame, 2672 APValue *&Result, const LValue *LVal) { 2673 2674 // If this is a parameter to an active constexpr function call, perform 2675 // argument substitution. 2676 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 2677 // Assume arguments of a potential constant expression are unknown 2678 // constant expressions. 2679 if (Info.checkingPotentialConstantExpression()) 2680 return false; 2681 if (!Frame || !Frame->Arguments) { 2682 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2683 return false; 2684 } 2685 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 2686 return true; 2687 } 2688 2689 // If this is a local variable, dig out its value. 2690 if (Frame) { 2691 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 2692 : Frame->getCurrentTemporary(VD); 2693 if (!Result) { 2694 // Assume variables referenced within a lambda's call operator that were 2695 // not declared within the call operator are captures and during checking 2696 // of a potential constant expression, assume they are unknown constant 2697 // expressions. 2698 assert(isLambdaCallOperator(Frame->Callee) && 2699 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 2700 "missing value for local variable"); 2701 if (Info.checkingPotentialConstantExpression()) 2702 return false; 2703 // FIXME: implement capture evaluation during constant expr evaluation. 2704 Info.FFDiag(E->getBeginLoc(), 2705 diag::note_unimplemented_constexpr_lambda_feature_ast) 2706 << "captures not currently allowed"; 2707 return false; 2708 } 2709 return true; 2710 } 2711 2712 // Dig out the initializer, and use the declaration which it's attached to. 2713 const Expr *Init = VD->getAnyInitializer(VD); 2714 if (!Init || Init->isValueDependent()) { 2715 // If we're checking a potential constant expression, the variable could be 2716 // initialized later. 2717 if (!Info.checkingPotentialConstantExpression()) 2718 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2719 return false; 2720 } 2721 2722 // If we're currently evaluating the initializer of this declaration, use that 2723 // in-flight value. 2724 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 2725 Result = Info.EvaluatingDeclValue; 2726 return true; 2727 } 2728 2729 // Never evaluate the initializer of a weak variable. We can't be sure that 2730 // this is the definition which will be used. 2731 if (VD->isWeak()) { 2732 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2733 return false; 2734 } 2735 2736 // Check that we can fold the initializer. In C++, we will have already done 2737 // this in the cases where it matters for conformance. 2738 SmallVector<PartialDiagnosticAt, 8> Notes; 2739 if (!VD->evaluateValue(Notes)) { 2740 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 2741 Notes.size() + 1) << VD; 2742 Info.Note(VD->getLocation(), diag::note_declared_at); 2743 Info.addNotes(Notes); 2744 return false; 2745 } else if (!VD->checkInitIsICE()) { 2746 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 2747 Notes.size() + 1) << VD; 2748 Info.Note(VD->getLocation(), diag::note_declared_at); 2749 Info.addNotes(Notes); 2750 } 2751 2752 Result = VD->getEvaluatedValue(); 2753 return true; 2754 } 2755 2756 static bool IsConstNonVolatile(QualType T) { 2757 Qualifiers Quals = T.getQualifiers(); 2758 return Quals.hasConst() && !Quals.hasVolatile(); 2759 } 2760 2761 /// Get the base index of the given base class within an APValue representing 2762 /// the given derived class. 2763 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 2764 const CXXRecordDecl *Base) { 2765 Base = Base->getCanonicalDecl(); 2766 unsigned Index = 0; 2767 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 2768 E = Derived->bases_end(); I != E; ++I, ++Index) { 2769 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 2770 return Index; 2771 } 2772 2773 llvm_unreachable("base class missing from derived class's bases list"); 2774 } 2775 2776 /// Extract the value of a character from a string literal. 2777 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 2778 uint64_t Index) { 2779 assert(!isa<SourceLocExpr>(Lit) && 2780 "SourceLocExpr should have already been converted to a StringLiteral"); 2781 2782 // FIXME: Support MakeStringConstant 2783 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 2784 std::string Str; 2785 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 2786 assert(Index <= Str.size() && "Index too large"); 2787 return APSInt::getUnsigned(Str.c_str()[Index]); 2788 } 2789 2790 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 2791 Lit = PE->getFunctionName(); 2792 const StringLiteral *S = cast<StringLiteral>(Lit); 2793 const ConstantArrayType *CAT = 2794 Info.Ctx.getAsConstantArrayType(S->getType()); 2795 assert(CAT && "string literal isn't an array"); 2796 QualType CharType = CAT->getElementType(); 2797 assert(CharType->isIntegerType() && "unexpected character type"); 2798 2799 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2800 CharType->isUnsignedIntegerType()); 2801 if (Index < S->getLength()) 2802 Value = S->getCodeUnit(Index); 2803 return Value; 2804 } 2805 2806 // Expand a string literal into an array of characters. 2807 // 2808 // FIXME: This is inefficient; we should probably introduce something similar 2809 // to the LLVM ConstantDataArray to make this cheaper. 2810 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 2811 APValue &Result) { 2812 const ConstantArrayType *CAT = 2813 Info.Ctx.getAsConstantArrayType(S->getType()); 2814 assert(CAT && "string literal isn't an array"); 2815 QualType CharType = CAT->getElementType(); 2816 assert(CharType->isIntegerType() && "unexpected character type"); 2817 2818 unsigned Elts = CAT->getSize().getZExtValue(); 2819 Result = APValue(APValue::UninitArray(), 2820 std::min(S->getLength(), Elts), Elts); 2821 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2822 CharType->isUnsignedIntegerType()); 2823 if (Result.hasArrayFiller()) 2824 Result.getArrayFiller() = APValue(Value); 2825 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 2826 Value = S->getCodeUnit(I); 2827 Result.getArrayInitializedElt(I) = APValue(Value); 2828 } 2829 } 2830 2831 // Expand an array so that it has more than Index filled elements. 2832 static void expandArray(APValue &Array, unsigned Index) { 2833 unsigned Size = Array.getArraySize(); 2834 assert(Index < Size); 2835 2836 // Always at least double the number of elements for which we store a value. 2837 unsigned OldElts = Array.getArrayInitializedElts(); 2838 unsigned NewElts = std::max(Index+1, OldElts * 2); 2839 NewElts = std::min(Size, std::max(NewElts, 8u)); 2840 2841 // Copy the data across. 2842 APValue NewValue(APValue::UninitArray(), NewElts, Size); 2843 for (unsigned I = 0; I != OldElts; ++I) 2844 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 2845 for (unsigned I = OldElts; I != NewElts; ++I) 2846 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 2847 if (NewValue.hasArrayFiller()) 2848 NewValue.getArrayFiller() = Array.getArrayFiller(); 2849 Array.swap(NewValue); 2850 } 2851 2852 /// Determine whether a type would actually be read by an lvalue-to-rvalue 2853 /// conversion. If it's of class type, we may assume that the copy operation 2854 /// is trivial. Note that this is never true for a union type with fields 2855 /// (because the copy always "reads" the active member) and always true for 2856 /// a non-class type. 2857 static bool isReadByLvalueToRvalueConversion(QualType T) { 2858 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2859 if (!RD || (RD->isUnion() && !RD->field_empty())) 2860 return true; 2861 if (RD->isEmpty()) 2862 return false; 2863 2864 for (auto *Field : RD->fields()) 2865 if (isReadByLvalueToRvalueConversion(Field->getType())) 2866 return true; 2867 2868 for (auto &BaseSpec : RD->bases()) 2869 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 2870 return true; 2871 2872 return false; 2873 } 2874 2875 /// Diagnose an attempt to read from any unreadable field within the specified 2876 /// type, which might be a class type. 2877 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E, 2878 QualType T) { 2879 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2880 if (!RD) 2881 return false; 2882 2883 if (!RD->hasMutableFields()) 2884 return false; 2885 2886 for (auto *Field : RD->fields()) { 2887 // If we're actually going to read this field in some way, then it can't 2888 // be mutable. If we're in a union, then assigning to a mutable field 2889 // (even an empty one) can change the active member, so that's not OK. 2890 // FIXME: Add core issue number for the union case. 2891 if (Field->isMutable() && 2892 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 2893 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field; 2894 Info.Note(Field->getLocation(), diag::note_declared_at); 2895 return true; 2896 } 2897 2898 if (diagnoseUnreadableFields(Info, E, Field->getType())) 2899 return true; 2900 } 2901 2902 for (auto &BaseSpec : RD->bases()) 2903 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType())) 2904 return true; 2905 2906 // All mutable fields were empty, and thus not actually read. 2907 return false; 2908 } 2909 2910 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 2911 APValue::LValueBase Base) { 2912 // A temporary we created. 2913 if (Base.getCallIndex()) 2914 return true; 2915 2916 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 2917 if (!Evaluating) 2918 return false; 2919 2920 // The variable whose initializer we're evaluating. 2921 if (auto *BaseD = Base.dyn_cast<const ValueDecl*>()) 2922 if (declaresSameEntity(Evaluating, BaseD)) 2923 return true; 2924 2925 // A temporary lifetime-extended by the variable whose initializer we're 2926 // evaluating. 2927 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 2928 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 2929 if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating)) 2930 return true; 2931 2932 return false; 2933 } 2934 2935 namespace { 2936 /// A handle to a complete object (an object that is not a subobject of 2937 /// another object). 2938 struct CompleteObject { 2939 /// The identity of the object. 2940 APValue::LValueBase Base; 2941 /// The value of the complete object. 2942 APValue *Value; 2943 /// The type of the complete object. 2944 QualType Type; 2945 2946 CompleteObject() : Value(nullptr) {} 2947 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 2948 : Base(Base), Value(Value), Type(Type) {} 2949 2950 bool mayReadMutableMembers(EvalInfo &Info) const { 2951 // In C++14 onwards, it is permitted to read a mutable member whose 2952 // lifetime began within the evaluation. 2953 // FIXME: Should we also allow this in C++11? 2954 if (!Info.getLangOpts().CPlusPlus14) 2955 return false; 2956 return lifetimeStartedInEvaluation(Info, Base); 2957 } 2958 2959 explicit operator bool() const { return !Type.isNull(); } 2960 }; 2961 } // end anonymous namespace 2962 2963 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 2964 bool IsMutable = false) { 2965 // C++ [basic.type.qualifier]p1: 2966 // - A const object is an object of type const T or a non-mutable subobject 2967 // of a const object. 2968 if (ObjType.isConstQualified() && !IsMutable) 2969 SubobjType.addConst(); 2970 // - A volatile object is an object of type const T or a subobject of a 2971 // volatile object. 2972 if (ObjType.isVolatileQualified()) 2973 SubobjType.addVolatile(); 2974 return SubobjType; 2975 } 2976 2977 /// Find the designated sub-object of an rvalue. 2978 template<typename SubobjectHandler> 2979 typename SubobjectHandler::result_type 2980 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 2981 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 2982 if (Sub.Invalid) 2983 // A diagnostic will have already been produced. 2984 return handler.failed(); 2985 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 2986 if (Info.getLangOpts().CPlusPlus11) 2987 Info.FFDiag(E, Sub.isOnePastTheEnd() 2988 ? diag::note_constexpr_access_past_end 2989 : diag::note_constexpr_access_unsized_array) 2990 << handler.AccessKind; 2991 else 2992 Info.FFDiag(E); 2993 return handler.failed(); 2994 } 2995 2996 APValue *O = Obj.Value; 2997 QualType ObjType = Obj.Type; 2998 const FieldDecl *LastField = nullptr; 2999 const FieldDecl *VolatileField = nullptr; 3000 3001 // Walk the designator's path to find the subobject. 3002 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3003 // Reading an indeterminate value is undefined, but assigning over one is OK. 3004 if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) { 3005 if (!Info.checkingPotentialConstantExpression()) 3006 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3007 << handler.AccessKind << O->isIndeterminate(); 3008 return handler.failed(); 3009 } 3010 3011 // C++ [class.ctor]p5: 3012 // const and volatile semantics are not applied on an object under 3013 // construction. 3014 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3015 ObjType->isRecordType() && 3016 Info.isEvaluatingConstructor( 3017 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3018 Sub.Entries.begin() + I)) != 3019 ConstructionPhase::None) { 3020 ObjType = Info.Ctx.getCanonicalType(ObjType); 3021 ObjType.removeLocalConst(); 3022 ObjType.removeLocalVolatile(); 3023 } 3024 3025 // If this is our last pass, check that the final object type is OK. 3026 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3027 // Accesses to volatile objects are prohibited. 3028 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3029 if (Info.getLangOpts().CPlusPlus) { 3030 int DiagKind; 3031 SourceLocation Loc; 3032 const NamedDecl *Decl = nullptr; 3033 if (VolatileField) { 3034 DiagKind = 2; 3035 Loc = VolatileField->getLocation(); 3036 Decl = VolatileField; 3037 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3038 DiagKind = 1; 3039 Loc = VD->getLocation(); 3040 Decl = VD; 3041 } else { 3042 DiagKind = 0; 3043 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3044 Loc = E->getExprLoc(); 3045 } 3046 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3047 << handler.AccessKind << DiagKind << Decl; 3048 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3049 } else { 3050 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3051 } 3052 return handler.failed(); 3053 } 3054 3055 // If we are reading an object of class type, there may still be more 3056 // things we need to check: if there are any mutable subobjects, we 3057 // cannot perform this read. (This only happens when performing a trivial 3058 // copy or assignment.) 3059 if (ObjType->isRecordType() && handler.AccessKind == AK_Read && 3060 !Obj.mayReadMutableMembers(Info) && 3061 diagnoseUnreadableFields(Info, E, ObjType)) 3062 return handler.failed(); 3063 } 3064 3065 if (I == N) { 3066 if (!handler.found(*O, ObjType)) 3067 return false; 3068 3069 // If we modified a bit-field, truncate it to the right width. 3070 if (isModification(handler.AccessKind) && 3071 LastField && LastField->isBitField() && 3072 !truncateBitfieldValue(Info, E, *O, LastField)) 3073 return false; 3074 3075 return true; 3076 } 3077 3078 LastField = nullptr; 3079 if (ObjType->isArrayType()) { 3080 // Next subobject is an array element. 3081 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3082 assert(CAT && "vla in literal type?"); 3083 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3084 if (CAT->getSize().ule(Index)) { 3085 // Note, it should not be possible to form a pointer with a valid 3086 // designator which points more than one past the end of the array. 3087 if (Info.getLangOpts().CPlusPlus11) 3088 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3089 << handler.AccessKind; 3090 else 3091 Info.FFDiag(E); 3092 return handler.failed(); 3093 } 3094 3095 ObjType = CAT->getElementType(); 3096 3097 if (O->getArrayInitializedElts() > Index) 3098 O = &O->getArrayInitializedElt(Index); 3099 else if (handler.AccessKind != AK_Read) { 3100 expandArray(*O, Index); 3101 O = &O->getArrayInitializedElt(Index); 3102 } else 3103 O = &O->getArrayFiller(); 3104 } else if (ObjType->isAnyComplexType()) { 3105 // Next subobject is a complex number. 3106 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3107 if (Index > 1) { 3108 if (Info.getLangOpts().CPlusPlus11) 3109 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3110 << handler.AccessKind; 3111 else 3112 Info.FFDiag(E); 3113 return handler.failed(); 3114 } 3115 3116 ObjType = getSubobjectType( 3117 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3118 3119 assert(I == N - 1 && "extracting subobject of scalar?"); 3120 if (O->isComplexInt()) { 3121 return handler.found(Index ? O->getComplexIntImag() 3122 : O->getComplexIntReal(), ObjType); 3123 } else { 3124 assert(O->isComplexFloat()); 3125 return handler.found(Index ? O->getComplexFloatImag() 3126 : O->getComplexFloatReal(), ObjType); 3127 } 3128 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3129 if (Field->isMutable() && handler.AccessKind == AK_Read && 3130 !Obj.mayReadMutableMembers(Info)) { 3131 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) 3132 << Field; 3133 Info.Note(Field->getLocation(), diag::note_declared_at); 3134 return handler.failed(); 3135 } 3136 3137 // Next subobject is a class, struct or union field. 3138 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3139 if (RD->isUnion()) { 3140 const FieldDecl *UnionField = O->getUnionField(); 3141 if (!UnionField || 3142 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3143 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3144 << handler.AccessKind << Field << !UnionField << UnionField; 3145 return handler.failed(); 3146 } 3147 O = &O->getUnionValue(); 3148 } else 3149 O = &O->getStructField(Field->getFieldIndex()); 3150 3151 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3152 LastField = Field; 3153 if (Field->getType().isVolatileQualified()) 3154 VolatileField = Field; 3155 } else { 3156 // Next subobject is a base class. 3157 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3158 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3159 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3160 3161 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3162 } 3163 } 3164 } 3165 3166 namespace { 3167 struct ExtractSubobjectHandler { 3168 EvalInfo &Info; 3169 APValue &Result; 3170 3171 static const AccessKinds AccessKind = AK_Read; 3172 3173 typedef bool result_type; 3174 bool failed() { return false; } 3175 bool found(APValue &Subobj, QualType SubobjType) { 3176 Result = Subobj; 3177 return true; 3178 } 3179 bool found(APSInt &Value, QualType SubobjType) { 3180 Result = APValue(Value); 3181 return true; 3182 } 3183 bool found(APFloat &Value, QualType SubobjType) { 3184 Result = APValue(Value); 3185 return true; 3186 } 3187 }; 3188 } // end anonymous namespace 3189 3190 const AccessKinds ExtractSubobjectHandler::AccessKind; 3191 3192 /// Extract the designated sub-object of an rvalue. 3193 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3194 const CompleteObject &Obj, 3195 const SubobjectDesignator &Sub, 3196 APValue &Result) { 3197 ExtractSubobjectHandler Handler = { Info, Result }; 3198 return findSubobject(Info, E, Obj, Sub, Handler); 3199 } 3200 3201 namespace { 3202 struct ModifySubobjectHandler { 3203 EvalInfo &Info; 3204 APValue &NewVal; 3205 const Expr *E; 3206 3207 typedef bool result_type; 3208 static const AccessKinds AccessKind = AK_Assign; 3209 3210 bool checkConst(QualType QT) { 3211 // Assigning to a const object has undefined behavior. 3212 if (QT.isConstQualified()) { 3213 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3214 return false; 3215 } 3216 return true; 3217 } 3218 3219 bool failed() { return false; } 3220 bool found(APValue &Subobj, QualType SubobjType) { 3221 if (!checkConst(SubobjType)) 3222 return false; 3223 // We've been given ownership of NewVal, so just swap it in. 3224 Subobj.swap(NewVal); 3225 return true; 3226 } 3227 bool found(APSInt &Value, QualType SubobjType) { 3228 if (!checkConst(SubobjType)) 3229 return false; 3230 if (!NewVal.isInt()) { 3231 // Maybe trying to write a cast pointer value into a complex? 3232 Info.FFDiag(E); 3233 return false; 3234 } 3235 Value = NewVal.getInt(); 3236 return true; 3237 } 3238 bool found(APFloat &Value, QualType SubobjType) { 3239 if (!checkConst(SubobjType)) 3240 return false; 3241 Value = NewVal.getFloat(); 3242 return true; 3243 } 3244 }; 3245 } // end anonymous namespace 3246 3247 const AccessKinds ModifySubobjectHandler::AccessKind; 3248 3249 /// Update the designated sub-object of an rvalue to the given value. 3250 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3251 const CompleteObject &Obj, 3252 const SubobjectDesignator &Sub, 3253 APValue &NewVal) { 3254 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3255 return findSubobject(Info, E, Obj, Sub, Handler); 3256 } 3257 3258 /// Find the position where two subobject designators diverge, or equivalently 3259 /// the length of the common initial subsequence. 3260 static unsigned FindDesignatorMismatch(QualType ObjType, 3261 const SubobjectDesignator &A, 3262 const SubobjectDesignator &B, 3263 bool &WasArrayIndex) { 3264 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3265 for (/**/; I != N; ++I) { 3266 if (!ObjType.isNull() && 3267 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3268 // Next subobject is an array element. 3269 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3270 WasArrayIndex = true; 3271 return I; 3272 } 3273 if (ObjType->isAnyComplexType()) 3274 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3275 else 3276 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3277 } else { 3278 if (A.Entries[I].getAsBaseOrMember() != 3279 B.Entries[I].getAsBaseOrMember()) { 3280 WasArrayIndex = false; 3281 return I; 3282 } 3283 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3284 // Next subobject is a field. 3285 ObjType = FD->getType(); 3286 else 3287 // Next subobject is a base class. 3288 ObjType = QualType(); 3289 } 3290 } 3291 WasArrayIndex = false; 3292 return I; 3293 } 3294 3295 /// Determine whether the given subobject designators refer to elements of the 3296 /// same array object. 3297 static bool AreElementsOfSameArray(QualType ObjType, 3298 const SubobjectDesignator &A, 3299 const SubobjectDesignator &B) { 3300 if (A.Entries.size() != B.Entries.size()) 3301 return false; 3302 3303 bool IsArray = A.MostDerivedIsArrayElement; 3304 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3305 // A is a subobject of the array element. 3306 return false; 3307 3308 // If A (and B) designates an array element, the last entry will be the array 3309 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3310 // of length 1' case, and the entire path must match. 3311 bool WasArrayIndex; 3312 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3313 return CommonLength >= A.Entries.size() - IsArray; 3314 } 3315 3316 /// Find the complete object to which an LValue refers. 3317 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3318 AccessKinds AK, const LValue &LVal, 3319 QualType LValType) { 3320 if (LVal.InvalidBase) { 3321 Info.FFDiag(E); 3322 return CompleteObject(); 3323 } 3324 3325 if (!LVal.Base) { 3326 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3327 return CompleteObject(); 3328 } 3329 3330 CallStackFrame *Frame = nullptr; 3331 unsigned Depth = 0; 3332 if (LVal.getLValueCallIndex()) { 3333 std::tie(Frame, Depth) = 3334 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3335 if (!Frame) { 3336 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3337 << AK << LVal.Base.is<const ValueDecl*>(); 3338 NoteLValueLocation(Info, LVal.Base); 3339 return CompleteObject(); 3340 } 3341 } 3342 3343 bool IsAccess = isFormalAccess(AK); 3344 3345 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3346 // is not a constant expression (even if the object is non-volatile). We also 3347 // apply this rule to C++98, in order to conform to the expected 'volatile' 3348 // semantics. 3349 if (IsAccess && LValType.isVolatileQualified()) { 3350 if (Info.getLangOpts().CPlusPlus) 3351 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3352 << AK << LValType; 3353 else 3354 Info.FFDiag(E); 3355 return CompleteObject(); 3356 } 3357 3358 // Compute value storage location and type of base object. 3359 APValue *BaseVal = nullptr; 3360 QualType BaseType = getType(LVal.Base); 3361 3362 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 3363 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3364 // In C++11, constexpr, non-volatile variables initialized with constant 3365 // expressions are constant expressions too. Inside constexpr functions, 3366 // parameters are constant expressions even if they're non-const. 3367 // In C++1y, objects local to a constant expression (those with a Frame) are 3368 // both readable and writable inside constant expressions. 3369 // In C, such things can also be folded, although they are not ICEs. 3370 const VarDecl *VD = dyn_cast<VarDecl>(D); 3371 if (VD) { 3372 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3373 VD = VDef; 3374 } 3375 if (!VD || VD->isInvalidDecl()) { 3376 Info.FFDiag(E); 3377 return CompleteObject(); 3378 } 3379 3380 // Unless we're looking at a local variable or argument in a constexpr call, 3381 // the variable we're reading must be const. 3382 if (!Frame) { 3383 if (Info.getLangOpts().CPlusPlus14 && 3384 declaresSameEntity( 3385 VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) { 3386 // OK, we can read and modify an object if we're in the process of 3387 // evaluating its initializer, because its lifetime began in this 3388 // evaluation. 3389 } else if (isModification(AK)) { 3390 // All the remaining cases do not permit modification of the object. 3391 Info.FFDiag(E, diag::note_constexpr_modify_global); 3392 return CompleteObject(); 3393 } else if (VD->isConstexpr()) { 3394 // OK, we can read this variable. 3395 } else if (BaseType->isIntegralOrEnumerationType()) { 3396 // In OpenCL if a variable is in constant address space it is a const 3397 // value. 3398 if (!(BaseType.isConstQualified() || 3399 (Info.getLangOpts().OpenCL && 3400 BaseType.getAddressSpace() == LangAS::opencl_constant))) { 3401 if (!IsAccess) 3402 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3403 if (Info.getLangOpts().CPlusPlus) { 3404 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3405 Info.Note(VD->getLocation(), diag::note_declared_at); 3406 } else { 3407 Info.FFDiag(E); 3408 } 3409 return CompleteObject(); 3410 } 3411 } else if (!IsAccess) { 3412 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3413 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { 3414 // We support folding of const floating-point types, in order to make 3415 // static const data members of such types (supported as an extension) 3416 // more useful. 3417 if (Info.getLangOpts().CPlusPlus11) { 3418 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3419 Info.Note(VD->getLocation(), diag::note_declared_at); 3420 } else { 3421 Info.CCEDiag(E); 3422 } 3423 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { 3424 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; 3425 // Keep evaluating to see what we can do. 3426 } else { 3427 // FIXME: Allow folding of values of any literal type in all languages. 3428 if (Info.checkingPotentialConstantExpression() && 3429 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { 3430 // The definition of this variable could be constexpr. We can't 3431 // access it right now, but may be able to in future. 3432 } else if (Info.getLangOpts().CPlusPlus11) { 3433 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3434 Info.Note(VD->getLocation(), diag::note_declared_at); 3435 } else { 3436 Info.FFDiag(E); 3437 } 3438 return CompleteObject(); 3439 } 3440 } 3441 3442 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3443 return CompleteObject(); 3444 } else { 3445 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3446 3447 if (!Frame) { 3448 if (const MaterializeTemporaryExpr *MTE = 3449 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 3450 assert(MTE->getStorageDuration() == SD_Static && 3451 "should have a frame for a non-global materialized temporary"); 3452 3453 // Per C++1y [expr.const]p2: 3454 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3455 // - a [...] glvalue of integral or enumeration type that refers to 3456 // a non-volatile const object [...] 3457 // [...] 3458 // - a [...] glvalue of literal type that refers to a non-volatile 3459 // object whose lifetime began within the evaluation of e. 3460 // 3461 // C++11 misses the 'began within the evaluation of e' check and 3462 // instead allows all temporaries, including things like: 3463 // int &&r = 1; 3464 // int x = ++r; 3465 // constexpr int k = r; 3466 // Therefore we use the C++14 rules in C++11 too. 3467 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3468 const ValueDecl *ED = MTE->getExtendingDecl(); 3469 if (!(BaseType.isConstQualified() && 3470 BaseType->isIntegralOrEnumerationType()) && 3471 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) { 3472 if (!IsAccess) 3473 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3474 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3475 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3476 return CompleteObject(); 3477 } 3478 3479 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false); 3480 assert(BaseVal && "got reference to unevaluated temporary"); 3481 } else { 3482 if (!IsAccess) 3483 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3484 APValue Val; 3485 LVal.moveInto(Val); 3486 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 3487 << AK 3488 << Val.getAsString(Info.Ctx, 3489 Info.Ctx.getLValueReferenceType(LValType)); 3490 NoteLValueLocation(Info, LVal.Base); 3491 return CompleteObject(); 3492 } 3493 } else { 3494 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 3495 assert(BaseVal && "missing value for temporary"); 3496 } 3497 } 3498 3499 // In C++14, we can't safely access any mutable state when we might be 3500 // evaluating after an unmodeled side effect. 3501 // 3502 // FIXME: Not all local state is mutable. Allow local constant subobjects 3503 // to be read here (but take care with 'mutable' fields). 3504 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3505 Info.EvalStatus.HasSideEffects) || 3506 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth)) 3507 return CompleteObject(); 3508 3509 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 3510 } 3511 3512 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 3513 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3514 /// glvalue referred to by an entity of reference type. 3515 /// 3516 /// \param Info - Information about the ongoing evaluation. 3517 /// \param Conv - The expression for which we are performing the conversion. 3518 /// Used for diagnostics. 3519 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 3520 /// case of a non-class type). 3521 /// \param LVal - The glvalue on which we are attempting to perform this action. 3522 /// \param RVal - The produced value will be placed here. 3523 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 3524 QualType Type, 3525 const LValue &LVal, APValue &RVal) { 3526 if (LVal.Designator.Invalid) 3527 return false; 3528 3529 // Check for special cases where there is no existing APValue to look at. 3530 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3531 3532 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 3533 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 3534 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 3535 // initializer until now for such expressions. Such an expression can't be 3536 // an ICE in C, so this only matters for fold. 3537 if (Type.isVolatileQualified()) { 3538 Info.FFDiag(Conv); 3539 return false; 3540 } 3541 APValue Lit; 3542 if (!Evaluate(Lit, Info, CLE->getInitializer())) 3543 return false; 3544 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 3545 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal); 3546 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 3547 // Special-case character extraction so we don't have to construct an 3548 // APValue for the whole string. 3549 assert(LVal.Designator.Entries.size() <= 1 && 3550 "Can only read characters from string literals"); 3551 if (LVal.Designator.Entries.empty()) { 3552 // Fail for now for LValue to RValue conversion of an array. 3553 // (This shouldn't show up in C/C++, but it could be triggered by a 3554 // weird EvaluateAsRValue call from a tool.) 3555 Info.FFDiag(Conv); 3556 return false; 3557 } 3558 if (LVal.Designator.isOnePastTheEnd()) { 3559 if (Info.getLangOpts().CPlusPlus11) 3560 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read; 3561 else 3562 Info.FFDiag(Conv); 3563 return false; 3564 } 3565 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 3566 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 3567 return true; 3568 } 3569 } 3570 3571 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type); 3572 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal); 3573 } 3574 3575 /// Perform an assignment of Val to LVal. Takes ownership of Val. 3576 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 3577 QualType LValType, APValue &Val) { 3578 if (LVal.Designator.Invalid) 3579 return false; 3580 3581 if (!Info.getLangOpts().CPlusPlus14) { 3582 Info.FFDiag(E); 3583 return false; 3584 } 3585 3586 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3587 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 3588 } 3589 3590 namespace { 3591 struct CompoundAssignSubobjectHandler { 3592 EvalInfo &Info; 3593 const Expr *E; 3594 QualType PromotedLHSType; 3595 BinaryOperatorKind Opcode; 3596 const APValue &RHS; 3597 3598 static const AccessKinds AccessKind = AK_Assign; 3599 3600 typedef bool result_type; 3601 3602 bool checkConst(QualType QT) { 3603 // Assigning to a const object has undefined behavior. 3604 if (QT.isConstQualified()) { 3605 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3606 return false; 3607 } 3608 return true; 3609 } 3610 3611 bool failed() { return false; } 3612 bool found(APValue &Subobj, QualType SubobjType) { 3613 switch (Subobj.getKind()) { 3614 case APValue::Int: 3615 return found(Subobj.getInt(), SubobjType); 3616 case APValue::Float: 3617 return found(Subobj.getFloat(), SubobjType); 3618 case APValue::ComplexInt: 3619 case APValue::ComplexFloat: 3620 // FIXME: Implement complex compound assignment. 3621 Info.FFDiag(E); 3622 return false; 3623 case APValue::LValue: 3624 return foundPointer(Subobj, SubobjType); 3625 default: 3626 // FIXME: can this happen? 3627 Info.FFDiag(E); 3628 return false; 3629 } 3630 } 3631 bool found(APSInt &Value, QualType SubobjType) { 3632 if (!checkConst(SubobjType)) 3633 return false; 3634 3635 if (!SubobjType->isIntegerType()) { 3636 // We don't support compound assignment on integer-cast-to-pointer 3637 // values. 3638 Info.FFDiag(E); 3639 return false; 3640 } 3641 3642 if (RHS.isInt()) { 3643 APSInt LHS = 3644 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 3645 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 3646 return false; 3647 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 3648 return true; 3649 } else if (RHS.isFloat()) { 3650 APFloat FValue(0.0); 3651 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, 3652 FValue) && 3653 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 3654 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 3655 Value); 3656 } 3657 3658 Info.FFDiag(E); 3659 return false; 3660 } 3661 bool found(APFloat &Value, QualType SubobjType) { 3662 return checkConst(SubobjType) && 3663 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 3664 Value) && 3665 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 3666 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 3667 } 3668 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3669 if (!checkConst(SubobjType)) 3670 return false; 3671 3672 QualType PointeeType; 3673 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3674 PointeeType = PT->getPointeeType(); 3675 3676 if (PointeeType.isNull() || !RHS.isInt() || 3677 (Opcode != BO_Add && Opcode != BO_Sub)) { 3678 Info.FFDiag(E); 3679 return false; 3680 } 3681 3682 APSInt Offset = RHS.getInt(); 3683 if (Opcode == BO_Sub) 3684 negateAsSigned(Offset); 3685 3686 LValue LVal; 3687 LVal.setFrom(Info.Ctx, Subobj); 3688 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 3689 return false; 3690 LVal.moveInto(Subobj); 3691 return true; 3692 } 3693 }; 3694 } // end anonymous namespace 3695 3696 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 3697 3698 /// Perform a compound assignment of LVal <op>= RVal. 3699 static bool handleCompoundAssignment( 3700 EvalInfo &Info, const Expr *E, 3701 const LValue &LVal, QualType LValType, QualType PromotedLValType, 3702 BinaryOperatorKind Opcode, const APValue &RVal) { 3703 if (LVal.Designator.Invalid) 3704 return false; 3705 3706 if (!Info.getLangOpts().CPlusPlus14) { 3707 Info.FFDiag(E); 3708 return false; 3709 } 3710 3711 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3712 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 3713 RVal }; 3714 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3715 } 3716 3717 namespace { 3718 struct IncDecSubobjectHandler { 3719 EvalInfo &Info; 3720 const UnaryOperator *E; 3721 AccessKinds AccessKind; 3722 APValue *Old; 3723 3724 typedef bool result_type; 3725 3726 bool checkConst(QualType QT) { 3727 // Assigning to a const object has undefined behavior. 3728 if (QT.isConstQualified()) { 3729 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3730 return false; 3731 } 3732 return true; 3733 } 3734 3735 bool failed() { return false; } 3736 bool found(APValue &Subobj, QualType SubobjType) { 3737 // Stash the old value. Also clear Old, so we don't clobber it later 3738 // if we're post-incrementing a complex. 3739 if (Old) { 3740 *Old = Subobj; 3741 Old = nullptr; 3742 } 3743 3744 switch (Subobj.getKind()) { 3745 case APValue::Int: 3746 return found(Subobj.getInt(), SubobjType); 3747 case APValue::Float: 3748 return found(Subobj.getFloat(), SubobjType); 3749 case APValue::ComplexInt: 3750 return found(Subobj.getComplexIntReal(), 3751 SubobjType->castAs<ComplexType>()->getElementType() 3752 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3753 case APValue::ComplexFloat: 3754 return found(Subobj.getComplexFloatReal(), 3755 SubobjType->castAs<ComplexType>()->getElementType() 3756 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3757 case APValue::LValue: 3758 return foundPointer(Subobj, SubobjType); 3759 default: 3760 // FIXME: can this happen? 3761 Info.FFDiag(E); 3762 return false; 3763 } 3764 } 3765 bool found(APSInt &Value, QualType SubobjType) { 3766 if (!checkConst(SubobjType)) 3767 return false; 3768 3769 if (!SubobjType->isIntegerType()) { 3770 // We don't support increment / decrement on integer-cast-to-pointer 3771 // values. 3772 Info.FFDiag(E); 3773 return false; 3774 } 3775 3776 if (Old) *Old = APValue(Value); 3777 3778 // bool arithmetic promotes to int, and the conversion back to bool 3779 // doesn't reduce mod 2^n, so special-case it. 3780 if (SubobjType->isBooleanType()) { 3781 if (AccessKind == AK_Increment) 3782 Value = 1; 3783 else 3784 Value = !Value; 3785 return true; 3786 } 3787 3788 bool WasNegative = Value.isNegative(); 3789 if (AccessKind == AK_Increment) { 3790 ++Value; 3791 3792 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 3793 APSInt ActualValue(Value, /*IsUnsigned*/true); 3794 return HandleOverflow(Info, E, ActualValue, SubobjType); 3795 } 3796 } else { 3797 --Value; 3798 3799 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 3800 unsigned BitWidth = Value.getBitWidth(); 3801 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 3802 ActualValue.setBit(BitWidth); 3803 return HandleOverflow(Info, E, ActualValue, SubobjType); 3804 } 3805 } 3806 return true; 3807 } 3808 bool found(APFloat &Value, QualType SubobjType) { 3809 if (!checkConst(SubobjType)) 3810 return false; 3811 3812 if (Old) *Old = APValue(Value); 3813 3814 APFloat One(Value.getSemantics(), 1); 3815 if (AccessKind == AK_Increment) 3816 Value.add(One, APFloat::rmNearestTiesToEven); 3817 else 3818 Value.subtract(One, APFloat::rmNearestTiesToEven); 3819 return true; 3820 } 3821 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3822 if (!checkConst(SubobjType)) 3823 return false; 3824 3825 QualType PointeeType; 3826 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3827 PointeeType = PT->getPointeeType(); 3828 else { 3829 Info.FFDiag(E); 3830 return false; 3831 } 3832 3833 LValue LVal; 3834 LVal.setFrom(Info.Ctx, Subobj); 3835 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 3836 AccessKind == AK_Increment ? 1 : -1)) 3837 return false; 3838 LVal.moveInto(Subobj); 3839 return true; 3840 } 3841 }; 3842 } // end anonymous namespace 3843 3844 /// Perform an increment or decrement on LVal. 3845 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 3846 QualType LValType, bool IsIncrement, APValue *Old) { 3847 if (LVal.Designator.Invalid) 3848 return false; 3849 3850 if (!Info.getLangOpts().CPlusPlus14) { 3851 Info.FFDiag(E); 3852 return false; 3853 } 3854 3855 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 3856 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 3857 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 3858 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3859 } 3860 3861 /// Build an lvalue for the object argument of a member function call. 3862 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 3863 LValue &This) { 3864 if (Object->getType()->isPointerType()) 3865 return EvaluatePointer(Object, This, Info); 3866 3867 if (Object->isGLValue()) 3868 return EvaluateLValue(Object, This, Info); 3869 3870 if (Object->getType()->isLiteralType(Info.Ctx)) 3871 return EvaluateTemporary(Object, This, Info); 3872 3873 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 3874 return false; 3875 } 3876 3877 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 3878 /// lvalue referring to the result. 3879 /// 3880 /// \param Info - Information about the ongoing evaluation. 3881 /// \param LV - An lvalue referring to the base of the member pointer. 3882 /// \param RHS - The member pointer expression. 3883 /// \param IncludeMember - Specifies whether the member itself is included in 3884 /// the resulting LValue subobject designator. This is not possible when 3885 /// creating a bound member function. 3886 /// \return The field or method declaration to which the member pointer refers, 3887 /// or 0 if evaluation fails. 3888 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3889 QualType LVType, 3890 LValue &LV, 3891 const Expr *RHS, 3892 bool IncludeMember = true) { 3893 MemberPtr MemPtr; 3894 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 3895 return nullptr; 3896 3897 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 3898 // member value, the behavior is undefined. 3899 if (!MemPtr.getDecl()) { 3900 // FIXME: Specific diagnostic. 3901 Info.FFDiag(RHS); 3902 return nullptr; 3903 } 3904 3905 if (MemPtr.isDerivedMember()) { 3906 // This is a member of some derived class. Truncate LV appropriately. 3907 // The end of the derived-to-base path for the base object must match the 3908 // derived-to-base path for the member pointer. 3909 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 3910 LV.Designator.Entries.size()) { 3911 Info.FFDiag(RHS); 3912 return nullptr; 3913 } 3914 unsigned PathLengthToMember = 3915 LV.Designator.Entries.size() - MemPtr.Path.size(); 3916 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 3917 const CXXRecordDecl *LVDecl = getAsBaseClass( 3918 LV.Designator.Entries[PathLengthToMember + I]); 3919 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 3920 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 3921 Info.FFDiag(RHS); 3922 return nullptr; 3923 } 3924 } 3925 3926 // Truncate the lvalue to the appropriate derived class. 3927 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 3928 PathLengthToMember)) 3929 return nullptr; 3930 } else if (!MemPtr.Path.empty()) { 3931 // Extend the LValue path with the member pointer's path. 3932 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 3933 MemPtr.Path.size() + IncludeMember); 3934 3935 // Walk down to the appropriate base class. 3936 if (const PointerType *PT = LVType->getAs<PointerType>()) 3937 LVType = PT->getPointeeType(); 3938 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 3939 assert(RD && "member pointer access on non-class-type expression"); 3940 // The first class in the path is that of the lvalue. 3941 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 3942 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 3943 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 3944 return nullptr; 3945 RD = Base; 3946 } 3947 // Finally cast to the class containing the member. 3948 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 3949 MemPtr.getContainingRecord())) 3950 return nullptr; 3951 } 3952 3953 // Add the member. Note that we cannot build bound member functions here. 3954 if (IncludeMember) { 3955 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 3956 if (!HandleLValueMember(Info, RHS, LV, FD)) 3957 return nullptr; 3958 } else if (const IndirectFieldDecl *IFD = 3959 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 3960 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 3961 return nullptr; 3962 } else { 3963 llvm_unreachable("can't construct reference to bound member function"); 3964 } 3965 } 3966 3967 return MemPtr.getDecl(); 3968 } 3969 3970 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3971 const BinaryOperator *BO, 3972 LValue &LV, 3973 bool IncludeMember = true) { 3974 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 3975 3976 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 3977 if (Info.noteFailure()) { 3978 MemberPtr MemPtr; 3979 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 3980 } 3981 return nullptr; 3982 } 3983 3984 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 3985 BO->getRHS(), IncludeMember); 3986 } 3987 3988 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 3989 /// the provided lvalue, which currently refers to the base object. 3990 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 3991 LValue &Result) { 3992 SubobjectDesignator &D = Result.Designator; 3993 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 3994 return false; 3995 3996 QualType TargetQT = E->getType(); 3997 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 3998 TargetQT = PT->getPointeeType(); 3999 4000 // Check this cast lands within the final derived-to-base subobject path. 4001 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4002 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4003 << D.MostDerivedType << TargetQT; 4004 return false; 4005 } 4006 4007 // Check the type of the final cast. We don't need to check the path, 4008 // since a cast can only be formed if the path is unique. 4009 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4010 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4011 const CXXRecordDecl *FinalType; 4012 if (NewEntriesSize == D.MostDerivedPathLength) 4013 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4014 else 4015 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4016 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4017 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4018 << D.MostDerivedType << TargetQT; 4019 return false; 4020 } 4021 4022 // Truncate the lvalue to the appropriate derived class. 4023 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4024 } 4025 4026 namespace { 4027 enum EvalStmtResult { 4028 /// Evaluation failed. 4029 ESR_Failed, 4030 /// Hit a 'return' statement. 4031 ESR_Returned, 4032 /// Evaluation succeeded. 4033 ESR_Succeeded, 4034 /// Hit a 'continue' statement. 4035 ESR_Continue, 4036 /// Hit a 'break' statement. 4037 ESR_Break, 4038 /// Still scanning for 'case' or 'default' statement. 4039 ESR_CaseNotFound 4040 }; 4041 } 4042 4043 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4044 // We don't need to evaluate the initializer for a static local. 4045 if (!VD->hasLocalStorage()) 4046 return true; 4047 4048 LValue Result; 4049 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall); 4050 4051 const Expr *InitE = VD->getInit(); 4052 if (!InitE) { 4053 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized) 4054 << false << VD->getType(); 4055 Val = APValue(); 4056 return false; 4057 } 4058 4059 if (InitE->isValueDependent()) 4060 return false; 4061 4062 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4063 // Wipe out any partially-computed value, to allow tracking that this 4064 // evaluation failed. 4065 Val = APValue(); 4066 return false; 4067 } 4068 4069 return true; 4070 } 4071 4072 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4073 bool OK = true; 4074 4075 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4076 OK &= EvaluateVarDecl(Info, VD); 4077 4078 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4079 for (auto *BD : DD->bindings()) 4080 if (auto *VD = BD->getHoldingVar()) 4081 OK &= EvaluateDecl(Info, VD); 4082 4083 return OK; 4084 } 4085 4086 4087 /// Evaluate a condition (either a variable declaration or an expression). 4088 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4089 const Expr *Cond, bool &Result) { 4090 FullExpressionRAII Scope(Info); 4091 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4092 return false; 4093 return EvaluateAsBooleanCondition(Cond, Result, Info); 4094 } 4095 4096 namespace { 4097 /// A location where the result (returned value) of evaluating a 4098 /// statement should be stored. 4099 struct StmtResult { 4100 /// The APValue that should be filled in with the returned value. 4101 APValue &Value; 4102 /// The location containing the result, if any (used to support RVO). 4103 const LValue *Slot; 4104 }; 4105 4106 struct TempVersionRAII { 4107 CallStackFrame &Frame; 4108 4109 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4110 Frame.pushTempVersion(); 4111 } 4112 4113 ~TempVersionRAII() { 4114 Frame.popTempVersion(); 4115 } 4116 }; 4117 4118 } 4119 4120 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4121 const Stmt *S, 4122 const SwitchCase *SC = nullptr); 4123 4124 /// Evaluate the body of a loop, and translate the result as appropriate. 4125 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4126 const Stmt *Body, 4127 const SwitchCase *Case = nullptr) { 4128 BlockScopeRAII Scope(Info); 4129 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) { 4130 case ESR_Break: 4131 return ESR_Succeeded; 4132 case ESR_Succeeded: 4133 case ESR_Continue: 4134 return ESR_Continue; 4135 case ESR_Failed: 4136 case ESR_Returned: 4137 case ESR_CaseNotFound: 4138 return ESR; 4139 } 4140 llvm_unreachable("Invalid EvalStmtResult!"); 4141 } 4142 4143 /// Evaluate a switch statement. 4144 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4145 const SwitchStmt *SS) { 4146 BlockScopeRAII Scope(Info); 4147 4148 // Evaluate the switch condition. 4149 APSInt Value; 4150 { 4151 FullExpressionRAII Scope(Info); 4152 if (const Stmt *Init = SS->getInit()) { 4153 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4154 if (ESR != ESR_Succeeded) 4155 return ESR; 4156 } 4157 if (SS->getConditionVariable() && 4158 !EvaluateDecl(Info, SS->getConditionVariable())) 4159 return ESR_Failed; 4160 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4161 return ESR_Failed; 4162 } 4163 4164 // Find the switch case corresponding to the value of the condition. 4165 // FIXME: Cache this lookup. 4166 const SwitchCase *Found = nullptr; 4167 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4168 SC = SC->getNextSwitchCase()) { 4169 if (isa<DefaultStmt>(SC)) { 4170 Found = SC; 4171 continue; 4172 } 4173 4174 const CaseStmt *CS = cast<CaseStmt>(SC); 4175 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4176 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4177 : LHS; 4178 if (LHS <= Value && Value <= RHS) { 4179 Found = SC; 4180 break; 4181 } 4182 } 4183 4184 if (!Found) 4185 return ESR_Succeeded; 4186 4187 // Search the switch body for the switch case and evaluate it from there. 4188 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) { 4189 case ESR_Break: 4190 return ESR_Succeeded; 4191 case ESR_Succeeded: 4192 case ESR_Continue: 4193 case ESR_Failed: 4194 case ESR_Returned: 4195 return ESR; 4196 case ESR_CaseNotFound: 4197 // This can only happen if the switch case is nested within a statement 4198 // expression. We have no intention of supporting that. 4199 Info.FFDiag(Found->getBeginLoc(), 4200 diag::note_constexpr_stmt_expr_unsupported); 4201 return ESR_Failed; 4202 } 4203 llvm_unreachable("Invalid EvalStmtResult!"); 4204 } 4205 4206 // Evaluate a statement. 4207 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4208 const Stmt *S, const SwitchCase *Case) { 4209 if (!Info.nextStep(S)) 4210 return ESR_Failed; 4211 4212 // If we're hunting down a 'case' or 'default' label, recurse through 4213 // substatements until we hit the label. 4214 if (Case) { 4215 // FIXME: We don't start the lifetime of objects whose initialization we 4216 // jump over. However, such objects must be of class type with a trivial 4217 // default constructor that initialize all subobjects, so must be empty, 4218 // so this almost never matters. 4219 switch (S->getStmtClass()) { 4220 case Stmt::CompoundStmtClass: 4221 // FIXME: Precompute which substatement of a compound statement we 4222 // would jump to, and go straight there rather than performing a 4223 // linear scan each time. 4224 case Stmt::LabelStmtClass: 4225 case Stmt::AttributedStmtClass: 4226 case Stmt::DoStmtClass: 4227 break; 4228 4229 case Stmt::CaseStmtClass: 4230 case Stmt::DefaultStmtClass: 4231 if (Case == S) 4232 Case = nullptr; 4233 break; 4234 4235 case Stmt::IfStmtClass: { 4236 // FIXME: Precompute which side of an 'if' we would jump to, and go 4237 // straight there rather than scanning both sides. 4238 const IfStmt *IS = cast<IfStmt>(S); 4239 4240 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4241 // preceded by our switch label. 4242 BlockScopeRAII Scope(Info); 4243 4244 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4245 if (ESR != ESR_CaseNotFound || !IS->getElse()) 4246 return ESR; 4247 return EvaluateStmt(Result, Info, IS->getElse(), Case); 4248 } 4249 4250 case Stmt::WhileStmtClass: { 4251 EvalStmtResult ESR = 4252 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4253 if (ESR != ESR_Continue) 4254 return ESR; 4255 break; 4256 } 4257 4258 case Stmt::ForStmtClass: { 4259 const ForStmt *FS = cast<ForStmt>(S); 4260 EvalStmtResult ESR = 4261 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4262 if (ESR != ESR_Continue) 4263 return ESR; 4264 if (FS->getInc()) { 4265 FullExpressionRAII IncScope(Info); 4266 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4267 return ESR_Failed; 4268 } 4269 break; 4270 } 4271 4272 case Stmt::DeclStmtClass: 4273 // FIXME: If the variable has initialization that can't be jumped over, 4274 // bail out of any immediately-surrounding compound-statement too. 4275 default: 4276 return ESR_CaseNotFound; 4277 } 4278 } 4279 4280 switch (S->getStmtClass()) { 4281 default: 4282 if (const Expr *E = dyn_cast<Expr>(S)) { 4283 // Don't bother evaluating beyond an expression-statement which couldn't 4284 // be evaluated. 4285 FullExpressionRAII Scope(Info); 4286 if (!EvaluateIgnoredValue(Info, E)) 4287 return ESR_Failed; 4288 return ESR_Succeeded; 4289 } 4290 4291 Info.FFDiag(S->getBeginLoc()); 4292 return ESR_Failed; 4293 4294 case Stmt::NullStmtClass: 4295 return ESR_Succeeded; 4296 4297 case Stmt::DeclStmtClass: { 4298 const DeclStmt *DS = cast<DeclStmt>(S); 4299 for (const auto *DclIt : DS->decls()) { 4300 // Each declaration initialization is its own full-expression. 4301 // FIXME: This isn't quite right; if we're performing aggregate 4302 // initialization, each braced subexpression is its own full-expression. 4303 FullExpressionRAII Scope(Info); 4304 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure()) 4305 return ESR_Failed; 4306 } 4307 return ESR_Succeeded; 4308 } 4309 4310 case Stmt::ReturnStmtClass: { 4311 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4312 FullExpressionRAII Scope(Info); 4313 if (RetExpr && 4314 !(Result.Slot 4315 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4316 : Evaluate(Result.Value, Info, RetExpr))) 4317 return ESR_Failed; 4318 return ESR_Returned; 4319 } 4320 4321 case Stmt::CompoundStmtClass: { 4322 BlockScopeRAII Scope(Info); 4323 4324 const CompoundStmt *CS = cast<CompoundStmt>(S); 4325 for (const auto *BI : CS->body()) { 4326 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4327 if (ESR == ESR_Succeeded) 4328 Case = nullptr; 4329 else if (ESR != ESR_CaseNotFound) 4330 return ESR; 4331 } 4332 return Case ? ESR_CaseNotFound : ESR_Succeeded; 4333 } 4334 4335 case Stmt::IfStmtClass: { 4336 const IfStmt *IS = cast<IfStmt>(S); 4337 4338 // Evaluate the condition, as either a var decl or as an expression. 4339 BlockScopeRAII Scope(Info); 4340 if (const Stmt *Init = IS->getInit()) { 4341 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4342 if (ESR != ESR_Succeeded) 4343 return ESR; 4344 } 4345 bool Cond; 4346 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 4347 return ESR_Failed; 4348 4349 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 4350 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 4351 if (ESR != ESR_Succeeded) 4352 return ESR; 4353 } 4354 return ESR_Succeeded; 4355 } 4356 4357 case Stmt::WhileStmtClass: { 4358 const WhileStmt *WS = cast<WhileStmt>(S); 4359 while (true) { 4360 BlockScopeRAII Scope(Info); 4361 bool Continue; 4362 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 4363 Continue)) 4364 return ESR_Failed; 4365 if (!Continue) 4366 break; 4367 4368 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 4369 if (ESR != ESR_Continue) 4370 return ESR; 4371 } 4372 return ESR_Succeeded; 4373 } 4374 4375 case Stmt::DoStmtClass: { 4376 const DoStmt *DS = cast<DoStmt>(S); 4377 bool Continue; 4378 do { 4379 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 4380 if (ESR != ESR_Continue) 4381 return ESR; 4382 Case = nullptr; 4383 4384 FullExpressionRAII CondScope(Info); 4385 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info)) 4386 return ESR_Failed; 4387 } while (Continue); 4388 return ESR_Succeeded; 4389 } 4390 4391 case Stmt::ForStmtClass: { 4392 const ForStmt *FS = cast<ForStmt>(S); 4393 BlockScopeRAII Scope(Info); 4394 if (FS->getInit()) { 4395 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4396 if (ESR != ESR_Succeeded) 4397 return ESR; 4398 } 4399 while (true) { 4400 BlockScopeRAII Scope(Info); 4401 bool Continue = true; 4402 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 4403 FS->getCond(), Continue)) 4404 return ESR_Failed; 4405 if (!Continue) 4406 break; 4407 4408 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4409 if (ESR != ESR_Continue) 4410 return ESR; 4411 4412 if (FS->getInc()) { 4413 FullExpressionRAII IncScope(Info); 4414 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4415 return ESR_Failed; 4416 } 4417 } 4418 return ESR_Succeeded; 4419 } 4420 4421 case Stmt::CXXForRangeStmtClass: { 4422 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 4423 BlockScopeRAII Scope(Info); 4424 4425 // Evaluate the init-statement if present. 4426 if (FS->getInit()) { 4427 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4428 if (ESR != ESR_Succeeded) 4429 return ESR; 4430 } 4431 4432 // Initialize the __range variable. 4433 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 4434 if (ESR != ESR_Succeeded) 4435 return ESR; 4436 4437 // Create the __begin and __end iterators. 4438 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 4439 if (ESR != ESR_Succeeded) 4440 return ESR; 4441 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 4442 if (ESR != ESR_Succeeded) 4443 return ESR; 4444 4445 while (true) { 4446 // Condition: __begin != __end. 4447 { 4448 bool Continue = true; 4449 FullExpressionRAII CondExpr(Info); 4450 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 4451 return ESR_Failed; 4452 if (!Continue) 4453 break; 4454 } 4455 4456 // User's variable declaration, initialized by *__begin. 4457 BlockScopeRAII InnerScope(Info); 4458 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 4459 if (ESR != ESR_Succeeded) 4460 return ESR; 4461 4462 // Loop body. 4463 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4464 if (ESR != ESR_Continue) 4465 return ESR; 4466 4467 // Increment: ++__begin 4468 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4469 return ESR_Failed; 4470 } 4471 4472 return ESR_Succeeded; 4473 } 4474 4475 case Stmt::SwitchStmtClass: 4476 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 4477 4478 case Stmt::ContinueStmtClass: 4479 return ESR_Continue; 4480 4481 case Stmt::BreakStmtClass: 4482 return ESR_Break; 4483 4484 case Stmt::LabelStmtClass: 4485 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 4486 4487 case Stmt::AttributedStmtClass: 4488 // As a general principle, C++11 attributes can be ignored without 4489 // any semantic impact. 4490 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 4491 Case); 4492 4493 case Stmt::CaseStmtClass: 4494 case Stmt::DefaultStmtClass: 4495 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 4496 case Stmt::CXXTryStmtClass: 4497 // Evaluate try blocks by evaluating all sub statements. 4498 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 4499 } 4500 } 4501 4502 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 4503 /// default constructor. If so, we'll fold it whether or not it's marked as 4504 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 4505 /// so we need special handling. 4506 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 4507 const CXXConstructorDecl *CD, 4508 bool IsValueInitialization) { 4509 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 4510 return false; 4511 4512 // Value-initialization does not call a trivial default constructor, so such a 4513 // call is a core constant expression whether or not the constructor is 4514 // constexpr. 4515 if (!CD->isConstexpr() && !IsValueInitialization) { 4516 if (Info.getLangOpts().CPlusPlus11) { 4517 // FIXME: If DiagDecl is an implicitly-declared special member function, 4518 // we should be much more explicit about why it's not constexpr. 4519 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 4520 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 4521 Info.Note(CD->getLocation(), diag::note_declared_at); 4522 } else { 4523 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 4524 } 4525 } 4526 return true; 4527 } 4528 4529 /// CheckConstexprFunction - Check that a function can be called in a constant 4530 /// expression. 4531 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 4532 const FunctionDecl *Declaration, 4533 const FunctionDecl *Definition, 4534 const Stmt *Body) { 4535 // Potential constant expressions can contain calls to declared, but not yet 4536 // defined, constexpr functions. 4537 if (Info.checkingPotentialConstantExpression() && !Definition && 4538 Declaration->isConstexpr()) 4539 return false; 4540 4541 // Bail out if the function declaration itself is invalid. We will 4542 // have produced a relevant diagnostic while parsing it, so just 4543 // note the problematic sub-expression. 4544 if (Declaration->isInvalidDecl()) { 4545 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4546 return false; 4547 } 4548 4549 // DR1872: An instantiated virtual constexpr function can't be called in a 4550 // constant expression (prior to C++20). We can still constant-fold such a 4551 // call. 4552 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) && 4553 cast<CXXMethodDecl>(Declaration)->isVirtual()) 4554 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 4555 4556 if (Definition && Definition->isInvalidDecl()) { 4557 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4558 return false; 4559 } 4560 4561 // Can we evaluate this function call? 4562 if (Definition && Definition->isConstexpr() && Body) 4563 return true; 4564 4565 if (Info.getLangOpts().CPlusPlus11) { 4566 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 4567 4568 // If this function is not constexpr because it is an inherited 4569 // non-constexpr constructor, diagnose that directly. 4570 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 4571 if (CD && CD->isInheritingConstructor()) { 4572 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 4573 if (!Inherited->isConstexpr()) 4574 DiagDecl = CD = Inherited; 4575 } 4576 4577 // FIXME: If DiagDecl is an implicitly-declared special member function 4578 // or an inheriting constructor, we should be much more explicit about why 4579 // it's not constexpr. 4580 if (CD && CD->isInheritingConstructor()) 4581 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 4582 << CD->getInheritedConstructor().getConstructor()->getParent(); 4583 else 4584 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 4585 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 4586 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 4587 } else { 4588 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4589 } 4590 return false; 4591 } 4592 4593 namespace { 4594 struct CheckDynamicTypeHandler { 4595 AccessKinds AccessKind; 4596 typedef bool result_type; 4597 bool failed() { return false; } 4598 bool found(APValue &Subobj, QualType SubobjType) { return true; } 4599 bool found(APSInt &Value, QualType SubobjType) { return true; } 4600 bool found(APFloat &Value, QualType SubobjType) { return true; } 4601 }; 4602 } // end anonymous namespace 4603 4604 /// Check that we can access the notional vptr of an object / determine its 4605 /// dynamic type. 4606 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 4607 AccessKinds AK, bool Polymorphic) { 4608 if (This.Designator.Invalid) 4609 return false; 4610 4611 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 4612 4613 if (!Obj) 4614 return false; 4615 4616 if (!Obj.Value) { 4617 // The object is not usable in constant expressions, so we can't inspect 4618 // its value to see if it's in-lifetime or what the active union members 4619 // are. We can still check for a one-past-the-end lvalue. 4620 if (This.Designator.isOnePastTheEnd() || 4621 This.Designator.isMostDerivedAnUnsizedArray()) { 4622 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 4623 ? diag::note_constexpr_access_past_end 4624 : diag::note_constexpr_access_unsized_array) 4625 << AK; 4626 return false; 4627 } else if (Polymorphic) { 4628 // Conservatively refuse to perform a polymorphic operation if we would 4629 // not be able to read a notional 'vptr' value. 4630 APValue Val; 4631 This.moveInto(Val); 4632 QualType StarThisType = 4633 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 4634 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 4635 << AK << Val.getAsString(Info.Ctx, StarThisType); 4636 return false; 4637 } 4638 return true; 4639 } 4640 4641 CheckDynamicTypeHandler Handler{AK}; 4642 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 4643 } 4644 4645 /// Check that the pointee of the 'this' pointer in a member function call is 4646 /// either within its lifetime or in its period of construction or destruction. 4647 static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 4648 const LValue &This) { 4649 return checkDynamicType(Info, E, This, AK_MemberCall, false); 4650 } 4651 4652 struct DynamicType { 4653 /// The dynamic class type of the object. 4654 const CXXRecordDecl *Type; 4655 /// The corresponding path length in the lvalue. 4656 unsigned PathLength; 4657 }; 4658 4659 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 4660 unsigned PathLength) { 4661 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 4662 Designator.Entries.size() && "invalid path length"); 4663 return (PathLength == Designator.MostDerivedPathLength) 4664 ? Designator.MostDerivedType->getAsCXXRecordDecl() 4665 : getAsBaseClass(Designator.Entries[PathLength - 1]); 4666 } 4667 4668 /// Determine the dynamic type of an object. 4669 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 4670 LValue &This, AccessKinds AK) { 4671 // If we don't have an lvalue denoting an object of class type, there is no 4672 // meaningful dynamic type. (We consider objects of non-class type to have no 4673 // dynamic type.) 4674 if (!checkDynamicType(Info, E, This, AK, true)) 4675 return None; 4676 4677 // Refuse to compute a dynamic type in the presence of virtual bases. This 4678 // shouldn't happen other than in constant-folding situations, since literal 4679 // types can't have virtual bases. 4680 // 4681 // Note that consumers of DynamicType assume that the type has no virtual 4682 // bases, and will need modifications if this restriction is relaxed. 4683 const CXXRecordDecl *Class = 4684 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 4685 if (!Class || Class->getNumVBases()) { 4686 Info.FFDiag(E); 4687 return None; 4688 } 4689 4690 // FIXME: For very deep class hierarchies, it might be beneficial to use a 4691 // binary search here instead. But the overwhelmingly common case is that 4692 // we're not in the middle of a constructor, so it probably doesn't matter 4693 // in practice. 4694 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 4695 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 4696 PathLength <= Path.size(); ++PathLength) { 4697 switch (Info.isEvaluatingConstructor(This.getLValueBase(), 4698 Path.slice(0, PathLength))) { 4699 case ConstructionPhase::Bases: 4700 // We're constructing a base class. This is not the dynamic type. 4701 break; 4702 4703 case ConstructionPhase::None: 4704 case ConstructionPhase::AfterBases: 4705 // We've finished constructing the base classes, so this is the dynamic 4706 // type. 4707 return DynamicType{getBaseClassType(This.Designator, PathLength), 4708 PathLength}; 4709 } 4710 } 4711 4712 // CWG issue 1517: we're constructing a base class of the object described by 4713 // 'This', so that object has not yet begun its period of construction and 4714 // any polymorphic operation on it results in undefined behavior. 4715 Info.FFDiag(E); 4716 return None; 4717 } 4718 4719 /// Perform virtual dispatch. 4720 static const CXXMethodDecl *HandleVirtualDispatch( 4721 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 4722 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 4723 Optional<DynamicType> DynType = 4724 ComputeDynamicType(Info, E, This, AK_MemberCall); 4725 if (!DynType) 4726 return nullptr; 4727 4728 // Find the final overrider. It must be declared in one of the classes on the 4729 // path from the dynamic type to the static type. 4730 // FIXME: If we ever allow literal types to have virtual base classes, that 4731 // won't be true. 4732 const CXXMethodDecl *Callee = Found; 4733 unsigned PathLength = DynType->PathLength; 4734 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 4735 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 4736 const CXXMethodDecl *Overrider = 4737 Found->getCorrespondingMethodDeclaredInClass(Class, false); 4738 if (Overrider) { 4739 Callee = Overrider; 4740 break; 4741 } 4742 } 4743 4744 // C++2a [class.abstract]p6: 4745 // the effect of making a virtual call to a pure virtual function [...] is 4746 // undefined 4747 if (Callee->isPure()) { 4748 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 4749 Info.Note(Callee->getLocation(), diag::note_declared_at); 4750 return nullptr; 4751 } 4752 4753 // If necessary, walk the rest of the path to determine the sequence of 4754 // covariant adjustment steps to apply. 4755 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 4756 Found->getReturnType())) { 4757 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 4758 for (unsigned CovariantPathLength = PathLength + 1; 4759 CovariantPathLength != This.Designator.Entries.size(); 4760 ++CovariantPathLength) { 4761 const CXXRecordDecl *NextClass = 4762 getBaseClassType(This.Designator, CovariantPathLength); 4763 const CXXMethodDecl *Next = 4764 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 4765 if (Next && !Info.Ctx.hasSameUnqualifiedType( 4766 Next->getReturnType(), CovariantAdjustmentPath.back())) 4767 CovariantAdjustmentPath.push_back(Next->getReturnType()); 4768 } 4769 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 4770 CovariantAdjustmentPath.back())) 4771 CovariantAdjustmentPath.push_back(Found->getReturnType()); 4772 } 4773 4774 // Perform 'this' adjustment. 4775 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 4776 return nullptr; 4777 4778 return Callee; 4779 } 4780 4781 /// Perform the adjustment from a value returned by a virtual function to 4782 /// a value of the statically expected type, which may be a pointer or 4783 /// reference to a base class of the returned type. 4784 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 4785 APValue &Result, 4786 ArrayRef<QualType> Path) { 4787 assert(Result.isLValue() && 4788 "unexpected kind of APValue for covariant return"); 4789 if (Result.isNullPointer()) 4790 return true; 4791 4792 LValue LVal; 4793 LVal.setFrom(Info.Ctx, Result); 4794 4795 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 4796 for (unsigned I = 1; I != Path.size(); ++I) { 4797 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 4798 assert(OldClass && NewClass && "unexpected kind of covariant return"); 4799 if (OldClass != NewClass && 4800 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 4801 return false; 4802 OldClass = NewClass; 4803 } 4804 4805 LVal.moveInto(Result); 4806 return true; 4807 } 4808 4809 /// Determine whether \p Base, which is known to be a direct base class of 4810 /// \p Derived, is a public base class. 4811 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 4812 const CXXRecordDecl *Base) { 4813 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 4814 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 4815 if (BaseClass && declaresSameEntity(BaseClass, Base)) 4816 return BaseSpec.getAccessSpecifier() == AS_public; 4817 } 4818 llvm_unreachable("Base is not a direct base of Derived"); 4819 } 4820 4821 /// Apply the given dynamic cast operation on the provided lvalue. 4822 /// 4823 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 4824 /// to find a suitable target subobject. 4825 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 4826 LValue &Ptr) { 4827 // We can't do anything with a non-symbolic pointer value. 4828 SubobjectDesignator &D = Ptr.Designator; 4829 if (D.Invalid) 4830 return false; 4831 4832 // C++ [expr.dynamic.cast]p6: 4833 // If v is a null pointer value, the result is a null pointer value. 4834 if (Ptr.isNullPointer() && !E->isGLValue()) 4835 return true; 4836 4837 // For all the other cases, we need the pointer to point to an object within 4838 // its lifetime / period of construction / destruction, and we need to know 4839 // its dynamic type. 4840 Optional<DynamicType> DynType = 4841 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 4842 if (!DynType) 4843 return false; 4844 4845 // C++ [expr.dynamic.cast]p7: 4846 // If T is "pointer to cv void", then the result is a pointer to the most 4847 // derived object 4848 if (E->getType()->isVoidPointerType()) 4849 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 4850 4851 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 4852 assert(C && "dynamic_cast target is not void pointer nor class"); 4853 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 4854 4855 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 4856 // C++ [expr.dynamic.cast]p9: 4857 if (!E->isGLValue()) { 4858 // The value of a failed cast to pointer type is the null pointer value 4859 // of the required result type. 4860 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); 4861 Ptr.setNull(E->getType(), TargetVal); 4862 return true; 4863 } 4864 4865 // A failed cast to reference type throws [...] std::bad_cast. 4866 unsigned DiagKind; 4867 if (!Paths && (declaresSameEntity(DynType->Type, C) || 4868 DynType->Type->isDerivedFrom(C))) 4869 DiagKind = 0; 4870 else if (!Paths || Paths->begin() == Paths->end()) 4871 DiagKind = 1; 4872 else if (Paths->isAmbiguous(CQT)) 4873 DiagKind = 2; 4874 else { 4875 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 4876 DiagKind = 3; 4877 } 4878 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 4879 << DiagKind << Ptr.Designator.getType(Info.Ctx) 4880 << Info.Ctx.getRecordType(DynType->Type) 4881 << E->getType().getUnqualifiedType(); 4882 return false; 4883 }; 4884 4885 // Runtime check, phase 1: 4886 // Walk from the base subobject towards the derived object looking for the 4887 // target type. 4888 for (int PathLength = Ptr.Designator.Entries.size(); 4889 PathLength >= (int)DynType->PathLength; --PathLength) { 4890 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 4891 if (declaresSameEntity(Class, C)) 4892 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 4893 // We can only walk across public inheritance edges. 4894 if (PathLength > (int)DynType->PathLength && 4895 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 4896 Class)) 4897 return RuntimeCheckFailed(nullptr); 4898 } 4899 4900 // Runtime check, phase 2: 4901 // Search the dynamic type for an unambiguous public base of type C. 4902 CXXBasePaths Paths(/*FindAmbiguities=*/true, 4903 /*RecordPaths=*/true, /*DetectVirtual=*/false); 4904 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 4905 Paths.front().Access == AS_public) { 4906 // Downcast to the dynamic type... 4907 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 4908 return false; 4909 // ... then upcast to the chosen base class subobject. 4910 for (CXXBasePathElement &Elem : Paths.front()) 4911 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 4912 return false; 4913 return true; 4914 } 4915 4916 // Otherwise, the runtime check fails. 4917 return RuntimeCheckFailed(&Paths); 4918 } 4919 4920 namespace { 4921 struct StartLifetimeOfUnionMemberHandler { 4922 const FieldDecl *Field; 4923 4924 static const AccessKinds AccessKind = AK_Assign; 4925 4926 APValue getDefaultInitValue(QualType SubobjType) { 4927 if (auto *RD = SubobjType->getAsCXXRecordDecl()) { 4928 if (RD->isUnion()) 4929 return APValue((const FieldDecl*)nullptr); 4930 4931 APValue Struct(APValue::UninitStruct(), RD->getNumBases(), 4932 std::distance(RD->field_begin(), RD->field_end())); 4933 4934 unsigned Index = 0; 4935 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4936 End = RD->bases_end(); I != End; ++I, ++Index) 4937 Struct.getStructBase(Index) = getDefaultInitValue(I->getType()); 4938 4939 for (const auto *I : RD->fields()) { 4940 if (I->isUnnamedBitfield()) 4941 continue; 4942 Struct.getStructField(I->getFieldIndex()) = 4943 getDefaultInitValue(I->getType()); 4944 } 4945 return Struct; 4946 } 4947 4948 if (auto *AT = dyn_cast_or_null<ConstantArrayType>( 4949 SubobjType->getAsArrayTypeUnsafe())) { 4950 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4951 if (Array.hasArrayFiller()) 4952 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType()); 4953 return Array; 4954 } 4955 4956 return APValue::IndeterminateValue(); 4957 } 4958 4959 typedef bool result_type; 4960 bool failed() { return false; } 4961 bool found(APValue &Subobj, QualType SubobjType) { 4962 // We are supposed to perform no initialization but begin the lifetime of 4963 // the object. We interpret that as meaning to do what default 4964 // initialization of the object would do if all constructors involved were 4965 // trivial: 4966 // * All base, non-variant member, and array element subobjects' lifetimes 4967 // begin 4968 // * No variant members' lifetimes begin 4969 // * All scalar subobjects whose lifetimes begin have indeterminate values 4970 assert(SubobjType->isUnionType()); 4971 if (!declaresSameEntity(Subobj.getUnionField(), Field)) 4972 Subobj.setUnion(Field, getDefaultInitValue(Field->getType())); 4973 return true; 4974 } 4975 bool found(APSInt &Value, QualType SubobjType) { 4976 llvm_unreachable("wrong value kind for union object"); 4977 } 4978 bool found(APFloat &Value, QualType SubobjType) { 4979 llvm_unreachable("wrong value kind for union object"); 4980 } 4981 }; 4982 } // end anonymous namespace 4983 4984 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 4985 4986 /// Handle a builtin simple-assignment or a call to a trivial assignment 4987 /// operator whose left-hand side might involve a union member access. If it 4988 /// does, implicitly start the lifetime of any accessed union elements per 4989 /// C++20 [class.union]5. 4990 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 4991 const LValue &LHS) { 4992 if (LHS.InvalidBase || LHS.Designator.Invalid) 4993 return false; 4994 4995 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 4996 // C++ [class.union]p5: 4997 // define the set S(E) of subexpressions of E as follows: 4998 unsigned PathLength = LHS.Designator.Entries.size(); 4999 for (const Expr *E = LHSExpr; E != nullptr;) { 5000 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5001 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5002 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5003 if (!FD) 5004 break; 5005 5006 // ... and also contains A.B if B names a union member 5007 if (FD->getParent()->isUnion()) 5008 UnionPathLengths.push_back({PathLength - 1, FD}); 5009 5010 E = ME->getBase(); 5011 --PathLength; 5012 assert(declaresSameEntity(FD, 5013 LHS.Designator.Entries[PathLength] 5014 .getAsBaseOrMember().getPointer())); 5015 5016 // -- If E is of the form A[B] and is interpreted as a built-in array 5017 // subscripting operator, S(E) is [S(the array operand, if any)]. 5018 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5019 // Step over an ArrayToPointerDecay implicit cast. 5020 auto *Base = ASE->getBase()->IgnoreImplicit(); 5021 if (!Base->getType()->isArrayType()) 5022 break; 5023 5024 E = Base; 5025 --PathLength; 5026 5027 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5028 // Step over a derived-to-base conversion. 5029 E = ICE->getSubExpr(); 5030 if (ICE->getCastKind() == CK_NoOp) 5031 continue; 5032 if (ICE->getCastKind() != CK_DerivedToBase && 5033 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5034 break; 5035 // Walk path backwards as we walk up from the base to the derived class. 5036 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5037 --PathLength; 5038 (void)Elt; 5039 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5040 LHS.Designator.Entries[PathLength] 5041 .getAsBaseOrMember().getPointer())); 5042 } 5043 5044 // -- Otherwise, S(E) is empty. 5045 } else { 5046 break; 5047 } 5048 } 5049 5050 // Common case: no unions' lifetimes are started. 5051 if (UnionPathLengths.empty()) 5052 return true; 5053 5054 // if modification of X [would access an inactive union member], an object 5055 // of the type of X is implicitly created 5056 CompleteObject Obj = 5057 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5058 if (!Obj) 5059 return false; 5060 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5061 llvm::reverse(UnionPathLengths)) { 5062 // Form a designator for the union object. 5063 SubobjectDesignator D = LHS.Designator; 5064 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5065 5066 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second}; 5067 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5068 return false; 5069 } 5070 5071 return true; 5072 } 5073 5074 /// Determine if a class has any fields that might need to be copied by a 5075 /// trivial copy or move operation. 5076 static bool hasFields(const CXXRecordDecl *RD) { 5077 if (!RD || RD->isEmpty()) 5078 return false; 5079 for (auto *FD : RD->fields()) { 5080 if (FD->isUnnamedBitfield()) 5081 continue; 5082 return true; 5083 } 5084 for (auto &Base : RD->bases()) 5085 if (hasFields(Base.getType()->getAsCXXRecordDecl())) 5086 return true; 5087 return false; 5088 } 5089 5090 namespace { 5091 typedef SmallVector<APValue, 8> ArgVector; 5092 } 5093 5094 /// EvaluateArgs - Evaluate the arguments to a function call. 5095 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues, 5096 EvalInfo &Info, const FunctionDecl *Callee) { 5097 bool Success = true; 5098 llvm::SmallBitVector ForbiddenNullArgs; 5099 if (Callee->hasAttr<NonNullAttr>()) { 5100 ForbiddenNullArgs.resize(Args.size()); 5101 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 5102 if (!Attr->args_size()) { 5103 ForbiddenNullArgs.set(); 5104 break; 5105 } else 5106 for (auto Idx : Attr->args()) { 5107 unsigned ASTIdx = Idx.getASTIndex(); 5108 if (ASTIdx >= Args.size()) 5109 continue; 5110 ForbiddenNullArgs[ASTIdx] = 1; 5111 } 5112 } 5113 } 5114 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 5115 I != E; ++I) { 5116 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) { 5117 // If we're checking for a potential constant expression, evaluate all 5118 // initializers even if some of them fail. 5119 if (!Info.noteFailure()) 5120 return false; 5121 Success = false; 5122 } else if (!ForbiddenNullArgs.empty() && 5123 ForbiddenNullArgs[I - Args.begin()] && 5124 ArgValues[I - Args.begin()].isNullPointer()) { 5125 Info.CCEDiag(*I, diag::note_non_null_attribute_failed); 5126 if (!Info.noteFailure()) 5127 return false; 5128 Success = false; 5129 } 5130 } 5131 return Success; 5132 } 5133 5134 /// Evaluate a function call. 5135 static bool HandleFunctionCall(SourceLocation CallLoc, 5136 const FunctionDecl *Callee, const LValue *This, 5137 ArrayRef<const Expr*> Args, const Stmt *Body, 5138 EvalInfo &Info, APValue &Result, 5139 const LValue *ResultSlot) { 5140 ArgVector ArgValues(Args.size()); 5141 if (!EvaluateArgs(Args, ArgValues, Info, Callee)) 5142 return false; 5143 5144 if (!Info.CheckCallLimit(CallLoc)) 5145 return false; 5146 5147 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 5148 5149 // For a trivial copy or move assignment, perform an APValue copy. This is 5150 // essential for unions, where the operations performed by the assignment 5151 // operator cannot be represented as statements. 5152 // 5153 // Skip this for non-union classes with no fields; in that case, the defaulted 5154 // copy/move does not actually read the object. 5155 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 5156 if (MD && MD->isDefaulted() && 5157 (MD->getParent()->isUnion() || 5158 (MD->isTrivial() && hasFields(MD->getParent())))) { 5159 assert(This && 5160 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 5161 LValue RHS; 5162 RHS.setFrom(Info.Ctx, ArgValues[0]); 5163 APValue RHSValue; 5164 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), 5165 RHS, RHSValue)) 5166 return false; 5167 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() && 5168 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 5169 return false; 5170 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 5171 RHSValue)) 5172 return false; 5173 This->moveInto(Result); 5174 return true; 5175 } else if (MD && isLambdaCallOperator(MD)) { 5176 // We're in a lambda; determine the lambda capture field maps unless we're 5177 // just constexpr checking a lambda's call operator. constexpr checking is 5178 // done before the captures have been added to the closure object (unless 5179 // we're inferring constexpr-ness), so we don't have access to them in this 5180 // case. But since we don't need the captures to constexpr check, we can 5181 // just ignore them. 5182 if (!Info.checkingPotentialConstantExpression()) 5183 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 5184 Frame.LambdaThisCaptureField); 5185 } 5186 5187 StmtResult Ret = {Result, ResultSlot}; 5188 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 5189 if (ESR == ESR_Succeeded) { 5190 if (Callee->getReturnType()->isVoidType()) 5191 return true; 5192 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 5193 } 5194 return ESR == ESR_Returned; 5195 } 5196 5197 /// Evaluate a constructor call. 5198 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5199 APValue *ArgValues, 5200 const CXXConstructorDecl *Definition, 5201 EvalInfo &Info, APValue &Result) { 5202 SourceLocation CallLoc = E->getExprLoc(); 5203 if (!Info.CheckCallLimit(CallLoc)) 5204 return false; 5205 5206 const CXXRecordDecl *RD = Definition->getParent(); 5207 if (RD->getNumVBases()) { 5208 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 5209 return false; 5210 } 5211 5212 EvalInfo::EvaluatingConstructorRAII EvalObj( 5213 Info, 5214 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 5215 RD->getNumBases()); 5216 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 5217 5218 // FIXME: Creating an APValue just to hold a nonexistent return value is 5219 // wasteful. 5220 APValue RetVal; 5221 StmtResult Ret = {RetVal, nullptr}; 5222 5223 // If it's a delegating constructor, delegate. 5224 if (Definition->isDelegatingConstructor()) { 5225 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 5226 { 5227 FullExpressionRAII InitScope(Info); 5228 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit())) 5229 return false; 5230 } 5231 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5232 } 5233 5234 // For a trivial copy or move constructor, perform an APValue copy. This is 5235 // essential for unions (or classes with anonymous union members), where the 5236 // operations performed by the constructor cannot be represented by 5237 // ctor-initializers. 5238 // 5239 // Skip this for empty non-union classes; we should not perform an 5240 // lvalue-to-rvalue conversion on them because their copy constructor does not 5241 // actually read them. 5242 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 5243 (Definition->getParent()->isUnion() || 5244 (Definition->isTrivial() && hasFields(Definition->getParent())))) { 5245 LValue RHS; 5246 RHS.setFrom(Info.Ctx, ArgValues[0]); 5247 return handleLValueToRValueConversion( 5248 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 5249 RHS, Result); 5250 } 5251 5252 // Reserve space for the struct members. 5253 if (!RD->isUnion() && !Result.hasValue()) 5254 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 5255 std::distance(RD->field_begin(), RD->field_end())); 5256 5257 if (RD->isInvalidDecl()) return false; 5258 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5259 5260 // A scope for temporaries lifetime-extended by reference members. 5261 BlockScopeRAII LifetimeExtendedScope(Info); 5262 5263 bool Success = true; 5264 unsigned BasesSeen = 0; 5265 #ifndef NDEBUG 5266 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 5267 #endif 5268 for (const auto *I : Definition->inits()) { 5269 LValue Subobject = This; 5270 LValue SubobjectParent = This; 5271 APValue *Value = &Result; 5272 5273 // Determine the subobject to initialize. 5274 FieldDecl *FD = nullptr; 5275 if (I->isBaseInitializer()) { 5276 QualType BaseType(I->getBaseClass(), 0); 5277 #ifndef NDEBUG 5278 // Non-virtual base classes are initialized in the order in the class 5279 // definition. We have already checked for virtual base classes. 5280 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 5281 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 5282 "base class initializers not in expected order"); 5283 ++BaseIt; 5284 #endif 5285 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 5286 BaseType->getAsCXXRecordDecl(), &Layout)) 5287 return false; 5288 Value = &Result.getStructBase(BasesSeen++); 5289 } else if ((FD = I->getMember())) { 5290 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 5291 return false; 5292 if (RD->isUnion()) { 5293 Result = APValue(FD); 5294 Value = &Result.getUnionValue(); 5295 } else { 5296 Value = &Result.getStructField(FD->getFieldIndex()); 5297 } 5298 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 5299 // Walk the indirect field decl's chain to find the object to initialize, 5300 // and make sure we've initialized every step along it. 5301 auto IndirectFieldChain = IFD->chain(); 5302 for (auto *C : IndirectFieldChain) { 5303 FD = cast<FieldDecl>(C); 5304 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 5305 // Switch the union field if it differs. This happens if we had 5306 // preceding zero-initialization, and we're now initializing a union 5307 // subobject other than the first. 5308 // FIXME: In this case, the values of the other subobjects are 5309 // specified, since zero-initialization sets all padding bits to zero. 5310 if (!Value->hasValue() || 5311 (Value->isUnion() && Value->getUnionField() != FD)) { 5312 if (CD->isUnion()) 5313 *Value = APValue(FD); 5314 else 5315 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(), 5316 std::distance(CD->field_begin(), CD->field_end())); 5317 } 5318 // Store Subobject as its parent before updating it for the last element 5319 // in the chain. 5320 if (C == IndirectFieldChain.back()) 5321 SubobjectParent = Subobject; 5322 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 5323 return false; 5324 if (CD->isUnion()) 5325 Value = &Value->getUnionValue(); 5326 else 5327 Value = &Value->getStructField(FD->getFieldIndex()); 5328 } 5329 } else { 5330 llvm_unreachable("unknown base initializer kind"); 5331 } 5332 5333 // Need to override This for implicit field initializers as in this case 5334 // This refers to innermost anonymous struct/union containing initializer, 5335 // not to currently constructed class. 5336 const Expr *Init = I->getInit(); 5337 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 5338 isa<CXXDefaultInitExpr>(Init)); 5339 FullExpressionRAII InitScope(Info); 5340 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 5341 (FD && FD->isBitField() && 5342 !truncateBitfieldValue(Info, Init, *Value, FD))) { 5343 // If we're checking for a potential constant expression, evaluate all 5344 // initializers even if some of them fail. 5345 if (!Info.noteFailure()) 5346 return false; 5347 Success = false; 5348 } 5349 5350 // This is the point at which the dynamic type of the object becomes this 5351 // class type. 5352 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 5353 EvalObj.finishedConstructingBases(); 5354 } 5355 5356 return Success && 5357 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5358 } 5359 5360 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5361 ArrayRef<const Expr*> Args, 5362 const CXXConstructorDecl *Definition, 5363 EvalInfo &Info, APValue &Result) { 5364 ArgVector ArgValues(Args.size()); 5365 if (!EvaluateArgs(Args, ArgValues, Info, Definition)) 5366 return false; 5367 5368 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 5369 Info, Result); 5370 } 5371 5372 //===----------------------------------------------------------------------===// 5373 // Generic Evaluation 5374 //===----------------------------------------------------------------------===// 5375 namespace { 5376 5377 template <class Derived> 5378 class ExprEvaluatorBase 5379 : public ConstStmtVisitor<Derived, bool> { 5380 private: 5381 Derived &getDerived() { return static_cast<Derived&>(*this); } 5382 bool DerivedSuccess(const APValue &V, const Expr *E) { 5383 return getDerived().Success(V, E); 5384 } 5385 bool DerivedZeroInitialization(const Expr *E) { 5386 return getDerived().ZeroInitialization(E); 5387 } 5388 5389 // Check whether a conditional operator with a non-constant condition is a 5390 // potential constant expression. If neither arm is a potential constant 5391 // expression, then the conditional operator is not either. 5392 template<typename ConditionalOperator> 5393 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 5394 assert(Info.checkingPotentialConstantExpression()); 5395 5396 // Speculatively evaluate both arms. 5397 SmallVector<PartialDiagnosticAt, 8> Diag; 5398 { 5399 SpeculativeEvaluationRAII Speculate(Info, &Diag); 5400 StmtVisitorTy::Visit(E->getFalseExpr()); 5401 if (Diag.empty()) 5402 return; 5403 } 5404 5405 { 5406 SpeculativeEvaluationRAII Speculate(Info, &Diag); 5407 Diag.clear(); 5408 StmtVisitorTy::Visit(E->getTrueExpr()); 5409 if (Diag.empty()) 5410 return; 5411 } 5412 5413 Error(E, diag::note_constexpr_conditional_never_const); 5414 } 5415 5416 5417 template<typename ConditionalOperator> 5418 bool HandleConditionalOperator(const ConditionalOperator *E) { 5419 bool BoolResult; 5420 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 5421 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 5422 CheckPotentialConstantConditional(E); 5423 return false; 5424 } 5425 if (Info.noteFailure()) { 5426 StmtVisitorTy::Visit(E->getTrueExpr()); 5427 StmtVisitorTy::Visit(E->getFalseExpr()); 5428 } 5429 return false; 5430 } 5431 5432 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 5433 return StmtVisitorTy::Visit(EvalExpr); 5434 } 5435 5436 protected: 5437 EvalInfo &Info; 5438 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 5439 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 5440 5441 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 5442 return Info.CCEDiag(E, D); 5443 } 5444 5445 bool ZeroInitialization(const Expr *E) { return Error(E); } 5446 5447 public: 5448 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 5449 5450 EvalInfo &getEvalInfo() { return Info; } 5451 5452 /// Report an evaluation error. This should only be called when an error is 5453 /// first discovered. When propagating an error, just return false. 5454 bool Error(const Expr *E, diag::kind D) { 5455 Info.FFDiag(E, D); 5456 return false; 5457 } 5458 bool Error(const Expr *E) { 5459 return Error(E, diag::note_invalid_subexpr_in_const_expr); 5460 } 5461 5462 bool VisitStmt(const Stmt *) { 5463 llvm_unreachable("Expression evaluator should not be called on stmts"); 5464 } 5465 bool VisitExpr(const Expr *E) { 5466 return Error(E); 5467 } 5468 5469 bool VisitConstantExpr(const ConstantExpr *E) 5470 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5471 bool VisitParenExpr(const ParenExpr *E) 5472 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5473 bool VisitUnaryExtension(const UnaryOperator *E) 5474 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5475 bool VisitUnaryPlus(const UnaryOperator *E) 5476 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5477 bool VisitChooseExpr(const ChooseExpr *E) 5478 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 5479 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 5480 { return StmtVisitorTy::Visit(E->getResultExpr()); } 5481 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 5482 { return StmtVisitorTy::Visit(E->getReplacement()); } 5483 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 5484 TempVersionRAII RAII(*Info.CurrentCall); 5485 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 5486 return StmtVisitorTy::Visit(E->getExpr()); 5487 } 5488 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 5489 TempVersionRAII RAII(*Info.CurrentCall); 5490 // The initializer may not have been parsed yet, or might be erroneous. 5491 if (!E->getExpr()) 5492 return Error(E); 5493 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 5494 return StmtVisitorTy::Visit(E->getExpr()); 5495 } 5496 5497 // We cannot create any objects for which cleanups are required, so there is 5498 // nothing to do here; all cleanups must come from unevaluated subexpressions. 5499 bool VisitExprWithCleanups(const ExprWithCleanups *E) 5500 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5501 5502 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 5503 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 5504 return static_cast<Derived*>(this)->VisitCastExpr(E); 5505 } 5506 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 5507 if (!Info.Ctx.getLangOpts().CPlusPlus2a) 5508 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 5509 return static_cast<Derived*>(this)->VisitCastExpr(E); 5510 } 5511 5512 bool VisitBinaryOperator(const BinaryOperator *E) { 5513 switch (E->getOpcode()) { 5514 default: 5515 return Error(E); 5516 5517 case BO_Comma: 5518 VisitIgnoredValue(E->getLHS()); 5519 return StmtVisitorTy::Visit(E->getRHS()); 5520 5521 case BO_PtrMemD: 5522 case BO_PtrMemI: { 5523 LValue Obj; 5524 if (!HandleMemberPointerAccess(Info, E, Obj)) 5525 return false; 5526 APValue Result; 5527 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 5528 return false; 5529 return DerivedSuccess(Result, E); 5530 } 5531 } 5532 } 5533 5534 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 5535 // Evaluate and cache the common expression. We treat it as a temporary, 5536 // even though it's not quite the same thing. 5537 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false), 5538 Info, E->getCommon())) 5539 return false; 5540 5541 return HandleConditionalOperator(E); 5542 } 5543 5544 bool VisitConditionalOperator(const ConditionalOperator *E) { 5545 bool IsBcpCall = false; 5546 // If the condition (ignoring parens) is a __builtin_constant_p call, 5547 // the result is a constant expression if it can be folded without 5548 // side-effects. This is an important GNU extension. See GCC PR38377 5549 // for discussion. 5550 if (const CallExpr *CallCE = 5551 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 5552 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 5553 IsBcpCall = true; 5554 5555 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 5556 // constant expression; we can't check whether it's potentially foldable. 5557 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 5558 return false; 5559 5560 FoldConstant Fold(Info, IsBcpCall); 5561 if (!HandleConditionalOperator(E)) { 5562 Fold.keepDiagnostics(); 5563 return false; 5564 } 5565 5566 return true; 5567 } 5568 5569 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 5570 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 5571 return DerivedSuccess(*Value, E); 5572 5573 const Expr *Source = E->getSourceExpr(); 5574 if (!Source) 5575 return Error(E); 5576 if (Source == E) { // sanity checking. 5577 assert(0 && "OpaqueValueExpr recursively refers to itself"); 5578 return Error(E); 5579 } 5580 return StmtVisitorTy::Visit(Source); 5581 } 5582 5583 bool VisitCallExpr(const CallExpr *E) { 5584 APValue Result; 5585 if (!handleCallExpr(E, Result, nullptr)) 5586 return false; 5587 return DerivedSuccess(Result, E); 5588 } 5589 5590 bool handleCallExpr(const CallExpr *E, APValue &Result, 5591 const LValue *ResultSlot) { 5592 const Expr *Callee = E->getCallee()->IgnoreParens(); 5593 QualType CalleeType = Callee->getType(); 5594 5595 const FunctionDecl *FD = nullptr; 5596 LValue *This = nullptr, ThisVal; 5597 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 5598 bool HasQualifier = false; 5599 5600 // Extract function decl and 'this' pointer from the callee. 5601 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 5602 const CXXMethodDecl *Member = nullptr; 5603 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 5604 // Explicit bound member calls, such as x.f() or p->g(); 5605 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 5606 return false; 5607 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 5608 if (!Member) 5609 return Error(Callee); 5610 This = &ThisVal; 5611 HasQualifier = ME->hasQualifier(); 5612 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 5613 // Indirect bound member calls ('.*' or '->*'). 5614 Member = dyn_cast_or_null<CXXMethodDecl>( 5615 HandleMemberPointerAccess(Info, BE, ThisVal, false)); 5616 if (!Member) 5617 return Error(Callee); 5618 This = &ThisVal; 5619 } else 5620 return Error(Callee); 5621 FD = Member; 5622 } else if (CalleeType->isFunctionPointerType()) { 5623 LValue Call; 5624 if (!EvaluatePointer(Callee, Call, Info)) 5625 return false; 5626 5627 if (!Call.getLValueOffset().isZero()) 5628 return Error(Callee); 5629 FD = dyn_cast_or_null<FunctionDecl>( 5630 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 5631 if (!FD) 5632 return Error(Callee); 5633 // Don't call function pointers which have been cast to some other type. 5634 // Per DR (no number yet), the caller and callee can differ in noexcept. 5635 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 5636 CalleeType->getPointeeType(), FD->getType())) { 5637 return Error(E); 5638 } 5639 5640 // Overloaded operator calls to member functions are represented as normal 5641 // calls with '*this' as the first argument. 5642 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 5643 if (MD && !MD->isStatic()) { 5644 // FIXME: When selecting an implicit conversion for an overloaded 5645 // operator delete, we sometimes try to evaluate calls to conversion 5646 // operators without a 'this' parameter! 5647 if (Args.empty()) 5648 return Error(E); 5649 5650 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 5651 return false; 5652 This = &ThisVal; 5653 Args = Args.slice(1); 5654 } else if (MD && MD->isLambdaStaticInvoker()) { 5655 // Map the static invoker for the lambda back to the call operator. 5656 // Conveniently, we don't have to slice out the 'this' argument (as is 5657 // being done for the non-static case), since a static member function 5658 // doesn't have an implicit argument passed in. 5659 const CXXRecordDecl *ClosureClass = MD->getParent(); 5660 assert( 5661 ClosureClass->captures_begin() == ClosureClass->captures_end() && 5662 "Number of captures must be zero for conversion to function-ptr"); 5663 5664 const CXXMethodDecl *LambdaCallOp = 5665 ClosureClass->getLambdaCallOperator(); 5666 5667 // Set 'FD', the function that will be called below, to the call 5668 // operator. If the closure object represents a generic lambda, find 5669 // the corresponding specialization of the call operator. 5670 5671 if (ClosureClass->isGenericLambda()) { 5672 assert(MD->isFunctionTemplateSpecialization() && 5673 "A generic lambda's static-invoker function must be a " 5674 "template specialization"); 5675 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 5676 FunctionTemplateDecl *CallOpTemplate = 5677 LambdaCallOp->getDescribedFunctionTemplate(); 5678 void *InsertPos = nullptr; 5679 FunctionDecl *CorrespondingCallOpSpecialization = 5680 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 5681 assert(CorrespondingCallOpSpecialization && 5682 "We must always have a function call operator specialization " 5683 "that corresponds to our static invoker specialization"); 5684 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 5685 } else 5686 FD = LambdaCallOp; 5687 } 5688 } else 5689 return Error(E); 5690 5691 SmallVector<QualType, 4> CovariantAdjustmentPath; 5692 if (This) { 5693 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 5694 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 5695 // Perform virtual dispatch, if necessary. 5696 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 5697 CovariantAdjustmentPath); 5698 if (!FD) 5699 return false; 5700 } else { 5701 // Check that the 'this' pointer points to an object of the right type. 5702 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This)) 5703 return false; 5704 } 5705 } 5706 5707 const FunctionDecl *Definition = nullptr; 5708 Stmt *Body = FD->getBody(Definition); 5709 5710 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 5711 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 5712 Result, ResultSlot)) 5713 return false; 5714 5715 if (!CovariantAdjustmentPath.empty() && 5716 !HandleCovariantReturnAdjustment(Info, E, Result, 5717 CovariantAdjustmentPath)) 5718 return false; 5719 5720 return true; 5721 } 5722 5723 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 5724 return StmtVisitorTy::Visit(E->getInitializer()); 5725 } 5726 bool VisitInitListExpr(const InitListExpr *E) { 5727 if (E->getNumInits() == 0) 5728 return DerivedZeroInitialization(E); 5729 if (E->getNumInits() == 1) 5730 return StmtVisitorTy::Visit(E->getInit(0)); 5731 return Error(E); 5732 } 5733 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 5734 return DerivedZeroInitialization(E); 5735 } 5736 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 5737 return DerivedZeroInitialization(E); 5738 } 5739 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 5740 return DerivedZeroInitialization(E); 5741 } 5742 5743 /// A member expression where the object is a prvalue is itself a prvalue. 5744 bool VisitMemberExpr(const MemberExpr *E) { 5745 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 5746 "missing temporary materialization conversion"); 5747 assert(!E->isArrow() && "missing call to bound member function?"); 5748 5749 APValue Val; 5750 if (!Evaluate(Val, Info, E->getBase())) 5751 return false; 5752 5753 QualType BaseTy = E->getBase()->getType(); 5754 5755 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 5756 if (!FD) return Error(E); 5757 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 5758 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 5759 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 5760 5761 // Note: there is no lvalue base here. But this case should only ever 5762 // happen in C or in C++98, where we cannot be evaluating a constexpr 5763 // constructor, which is the only case the base matters. 5764 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 5765 SubobjectDesignator Designator(BaseTy); 5766 Designator.addDeclUnchecked(FD); 5767 5768 APValue Result; 5769 return extractSubobject(Info, E, Obj, Designator, Result) && 5770 DerivedSuccess(Result, E); 5771 } 5772 5773 bool VisitCastExpr(const CastExpr *E) { 5774 switch (E->getCastKind()) { 5775 default: 5776 break; 5777 5778 case CK_AtomicToNonAtomic: { 5779 APValue AtomicVal; 5780 // This does not need to be done in place even for class/array types: 5781 // atomic-to-non-atomic conversion implies copying the object 5782 // representation. 5783 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 5784 return false; 5785 return DerivedSuccess(AtomicVal, E); 5786 } 5787 5788 case CK_NoOp: 5789 case CK_UserDefinedConversion: 5790 return StmtVisitorTy::Visit(E->getSubExpr()); 5791 5792 case CK_LValueToRValue: { 5793 LValue LVal; 5794 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 5795 return false; 5796 APValue RVal; 5797 // Note, we use the subexpression's type in order to retain cv-qualifiers. 5798 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 5799 LVal, RVal)) 5800 return false; 5801 return DerivedSuccess(RVal, E); 5802 } 5803 } 5804 5805 return Error(E); 5806 } 5807 5808 bool VisitUnaryPostInc(const UnaryOperator *UO) { 5809 return VisitUnaryPostIncDec(UO); 5810 } 5811 bool VisitUnaryPostDec(const UnaryOperator *UO) { 5812 return VisitUnaryPostIncDec(UO); 5813 } 5814 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 5815 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5816 return Error(UO); 5817 5818 LValue LVal; 5819 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 5820 return false; 5821 APValue RVal; 5822 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 5823 UO->isIncrementOp(), &RVal)) 5824 return false; 5825 return DerivedSuccess(RVal, UO); 5826 } 5827 5828 bool VisitStmtExpr(const StmtExpr *E) { 5829 // We will have checked the full-expressions inside the statement expression 5830 // when they were completed, and don't need to check them again now. 5831 if (Info.checkingForOverflow()) 5832 return Error(E); 5833 5834 BlockScopeRAII Scope(Info); 5835 const CompoundStmt *CS = E->getSubStmt(); 5836 if (CS->body_empty()) 5837 return true; 5838 5839 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 5840 BE = CS->body_end(); 5841 /**/; ++BI) { 5842 if (BI + 1 == BE) { 5843 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 5844 if (!FinalExpr) { 5845 Info.FFDiag((*BI)->getBeginLoc(), 5846 diag::note_constexpr_stmt_expr_unsupported); 5847 return false; 5848 } 5849 return this->Visit(FinalExpr); 5850 } 5851 5852 APValue ReturnValue; 5853 StmtResult Result = { ReturnValue, nullptr }; 5854 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 5855 if (ESR != ESR_Succeeded) { 5856 // FIXME: If the statement-expression terminated due to 'return', 5857 // 'break', or 'continue', it would be nice to propagate that to 5858 // the outer statement evaluation rather than bailing out. 5859 if (ESR != ESR_Failed) 5860 Info.FFDiag((*BI)->getBeginLoc(), 5861 diag::note_constexpr_stmt_expr_unsupported); 5862 return false; 5863 } 5864 } 5865 5866 llvm_unreachable("Return from function from the loop above."); 5867 } 5868 5869 /// Visit a value which is evaluated, but whose value is ignored. 5870 void VisitIgnoredValue(const Expr *E) { 5871 EvaluateIgnoredValue(Info, E); 5872 } 5873 5874 /// Potentially visit a MemberExpr's base expression. 5875 void VisitIgnoredBaseExpression(const Expr *E) { 5876 // While MSVC doesn't evaluate the base expression, it does diagnose the 5877 // presence of side-effecting behavior. 5878 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 5879 return; 5880 VisitIgnoredValue(E); 5881 } 5882 }; 5883 5884 } // namespace 5885 5886 //===----------------------------------------------------------------------===// 5887 // Common base class for lvalue and temporary evaluation. 5888 //===----------------------------------------------------------------------===// 5889 namespace { 5890 template<class Derived> 5891 class LValueExprEvaluatorBase 5892 : public ExprEvaluatorBase<Derived> { 5893 protected: 5894 LValue &Result; 5895 bool InvalidBaseOK; 5896 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 5897 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 5898 5899 bool Success(APValue::LValueBase B) { 5900 Result.set(B); 5901 return true; 5902 } 5903 5904 bool evaluatePointer(const Expr *E, LValue &Result) { 5905 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 5906 } 5907 5908 public: 5909 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 5910 : ExprEvaluatorBaseTy(Info), Result(Result), 5911 InvalidBaseOK(InvalidBaseOK) {} 5912 5913 bool Success(const APValue &V, const Expr *E) { 5914 Result.setFrom(this->Info.Ctx, V); 5915 return true; 5916 } 5917 5918 bool VisitMemberExpr(const MemberExpr *E) { 5919 // Handle non-static data members. 5920 QualType BaseTy; 5921 bool EvalOK; 5922 if (E->isArrow()) { 5923 EvalOK = evaluatePointer(E->getBase(), Result); 5924 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 5925 } else if (E->getBase()->isRValue()) { 5926 assert(E->getBase()->getType()->isRecordType()); 5927 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 5928 BaseTy = E->getBase()->getType(); 5929 } else { 5930 EvalOK = this->Visit(E->getBase()); 5931 BaseTy = E->getBase()->getType(); 5932 } 5933 if (!EvalOK) { 5934 if (!InvalidBaseOK) 5935 return false; 5936 Result.setInvalid(E); 5937 return true; 5938 } 5939 5940 const ValueDecl *MD = E->getMemberDecl(); 5941 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 5942 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 5943 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 5944 (void)BaseTy; 5945 if (!HandleLValueMember(this->Info, E, Result, FD)) 5946 return false; 5947 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 5948 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 5949 return false; 5950 } else 5951 return this->Error(E); 5952 5953 if (MD->getType()->isReferenceType()) { 5954 APValue RefValue; 5955 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 5956 RefValue)) 5957 return false; 5958 return Success(RefValue, E); 5959 } 5960 return true; 5961 } 5962 5963 bool VisitBinaryOperator(const BinaryOperator *E) { 5964 switch (E->getOpcode()) { 5965 default: 5966 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5967 5968 case BO_PtrMemD: 5969 case BO_PtrMemI: 5970 return HandleMemberPointerAccess(this->Info, E, Result); 5971 } 5972 } 5973 5974 bool VisitCastExpr(const CastExpr *E) { 5975 switch (E->getCastKind()) { 5976 default: 5977 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5978 5979 case CK_DerivedToBase: 5980 case CK_UncheckedDerivedToBase: 5981 if (!this->Visit(E->getSubExpr())) 5982 return false; 5983 5984 // Now figure out the necessary offset to add to the base LV to get from 5985 // the derived class to the base class. 5986 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 5987 Result); 5988 } 5989 } 5990 }; 5991 } 5992 5993 //===----------------------------------------------------------------------===// 5994 // LValue Evaluation 5995 // 5996 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 5997 // function designators (in C), decl references to void objects (in C), and 5998 // temporaries (if building with -Wno-address-of-temporary). 5999 // 6000 // LValue evaluation produces values comprising a base expression of one of the 6001 // following types: 6002 // - Declarations 6003 // * VarDecl 6004 // * FunctionDecl 6005 // - Literals 6006 // * CompoundLiteralExpr in C (and in global scope in C++) 6007 // * StringLiteral 6008 // * PredefinedExpr 6009 // * ObjCStringLiteralExpr 6010 // * ObjCEncodeExpr 6011 // * AddrLabelExpr 6012 // * BlockExpr 6013 // * CallExpr for a MakeStringConstant builtin 6014 // - typeid(T) expressions, as TypeInfoLValues 6015 // - Locals and temporaries 6016 // * MaterializeTemporaryExpr 6017 // * Any Expr, with a CallIndex indicating the function in which the temporary 6018 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 6019 // from the AST (FIXME). 6020 // * A MaterializeTemporaryExpr that has static storage duration, with no 6021 // CallIndex, for a lifetime-extended temporary. 6022 // plus an offset in bytes. 6023 //===----------------------------------------------------------------------===// 6024 namespace { 6025 class LValueExprEvaluator 6026 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 6027 public: 6028 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 6029 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 6030 6031 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 6032 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 6033 6034 bool VisitDeclRefExpr(const DeclRefExpr *E); 6035 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 6036 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 6037 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 6038 bool VisitMemberExpr(const MemberExpr *E); 6039 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 6040 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 6041 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 6042 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 6043 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 6044 bool VisitUnaryDeref(const UnaryOperator *E); 6045 bool VisitUnaryReal(const UnaryOperator *E); 6046 bool VisitUnaryImag(const UnaryOperator *E); 6047 bool VisitUnaryPreInc(const UnaryOperator *UO) { 6048 return VisitUnaryPreIncDec(UO); 6049 } 6050 bool VisitUnaryPreDec(const UnaryOperator *UO) { 6051 return VisitUnaryPreIncDec(UO); 6052 } 6053 bool VisitBinAssign(const BinaryOperator *BO); 6054 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 6055 6056 bool VisitCastExpr(const CastExpr *E) { 6057 switch (E->getCastKind()) { 6058 default: 6059 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 6060 6061 case CK_LValueBitCast: 6062 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 6063 if (!Visit(E->getSubExpr())) 6064 return false; 6065 Result.Designator.setInvalid(); 6066 return true; 6067 6068 case CK_BaseToDerived: 6069 if (!Visit(E->getSubExpr())) 6070 return false; 6071 return HandleBaseToDerivedCast(Info, E, Result); 6072 6073 case CK_Dynamic: 6074 if (!Visit(E->getSubExpr())) 6075 return false; 6076 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 6077 } 6078 } 6079 }; 6080 } // end anonymous namespace 6081 6082 /// Evaluate an expression as an lvalue. This can be legitimately called on 6083 /// expressions which are not glvalues, in three cases: 6084 /// * function designators in C, and 6085 /// * "extern void" objects 6086 /// * @selector() expressions in Objective-C 6087 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 6088 bool InvalidBaseOK) { 6089 assert(E->isGLValue() || E->getType()->isFunctionType() || 6090 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 6091 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 6092 } 6093 6094 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 6095 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 6096 return Success(FD); 6097 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 6098 return VisitVarDecl(E, VD); 6099 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 6100 return Visit(BD->getBinding()); 6101 return Error(E); 6102 } 6103 6104 6105 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 6106 6107 // If we are within a lambda's call operator, check whether the 'VD' referred 6108 // to within 'E' actually represents a lambda-capture that maps to a 6109 // data-member/field within the closure object, and if so, evaluate to the 6110 // field or what the field refers to. 6111 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 6112 isa<DeclRefExpr>(E) && 6113 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 6114 // We don't always have a complete capture-map when checking or inferring if 6115 // the function call operator meets the requirements of a constexpr function 6116 // - but we don't need to evaluate the captures to determine constexprness 6117 // (dcl.constexpr C++17). 6118 if (Info.checkingPotentialConstantExpression()) 6119 return false; 6120 6121 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 6122 // Start with 'Result' referring to the complete closure object... 6123 Result = *Info.CurrentCall->This; 6124 // ... then update it to refer to the field of the closure object 6125 // that represents the capture. 6126 if (!HandleLValueMember(Info, E, Result, FD)) 6127 return false; 6128 // And if the field is of reference type, update 'Result' to refer to what 6129 // the field refers to. 6130 if (FD->getType()->isReferenceType()) { 6131 APValue RVal; 6132 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 6133 RVal)) 6134 return false; 6135 Result.setFrom(Info.Ctx, RVal); 6136 } 6137 return true; 6138 } 6139 } 6140 CallStackFrame *Frame = nullptr; 6141 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 6142 // Only if a local variable was declared in the function currently being 6143 // evaluated, do we expect to be able to find its value in the current 6144 // frame. (Otherwise it was likely declared in an enclosing context and 6145 // could either have a valid evaluatable value (for e.g. a constexpr 6146 // variable) or be ill-formed (and trigger an appropriate evaluation 6147 // diagnostic)). 6148 if (Info.CurrentCall->Callee && 6149 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 6150 Frame = Info.CurrentCall; 6151 } 6152 } 6153 6154 if (!VD->getType()->isReferenceType()) { 6155 if (Frame) { 6156 Result.set({VD, Frame->Index, 6157 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 6158 return true; 6159 } 6160 return Success(VD); 6161 } 6162 6163 APValue *V; 6164 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 6165 return false; 6166 if (!V->hasValue()) { 6167 // FIXME: Is it possible for V to be indeterminate here? If so, we should 6168 // adjust the diagnostic to say that. 6169 if (!Info.checkingPotentialConstantExpression()) 6170 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 6171 return false; 6172 } 6173 return Success(*V, E); 6174 } 6175 6176 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 6177 const MaterializeTemporaryExpr *E) { 6178 // Walk through the expression to find the materialized temporary itself. 6179 SmallVector<const Expr *, 2> CommaLHSs; 6180 SmallVector<SubobjectAdjustment, 2> Adjustments; 6181 const Expr *Inner = E->GetTemporaryExpr()-> 6182 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 6183 6184 // If we passed any comma operators, evaluate their LHSs. 6185 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 6186 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 6187 return false; 6188 6189 // A materialized temporary with static storage duration can appear within the 6190 // result of a constant expression evaluation, so we need to preserve its 6191 // value for use outside this evaluation. 6192 APValue *Value; 6193 if (E->getStorageDuration() == SD_Static) { 6194 Value = Info.Ctx.getMaterializedTemporaryValue(E, true); 6195 *Value = APValue(); 6196 Result.set(E); 6197 } else { 6198 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result, 6199 *Info.CurrentCall); 6200 } 6201 6202 QualType Type = Inner->getType(); 6203 6204 // Materialize the temporary itself. 6205 if (!EvaluateInPlace(*Value, Info, Result, Inner) || 6206 (E->getStorageDuration() == SD_Static && 6207 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) { 6208 *Value = APValue(); 6209 return false; 6210 } 6211 6212 // Adjust our lvalue to refer to the desired subobject. 6213 for (unsigned I = Adjustments.size(); I != 0; /**/) { 6214 --I; 6215 switch (Adjustments[I].Kind) { 6216 case SubobjectAdjustment::DerivedToBaseAdjustment: 6217 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 6218 Type, Result)) 6219 return false; 6220 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 6221 break; 6222 6223 case SubobjectAdjustment::FieldAdjustment: 6224 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 6225 return false; 6226 Type = Adjustments[I].Field->getType(); 6227 break; 6228 6229 case SubobjectAdjustment::MemberPointerAdjustment: 6230 if (!HandleMemberPointerAccess(this->Info, Type, Result, 6231 Adjustments[I].Ptr.RHS)) 6232 return false; 6233 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 6234 break; 6235 } 6236 } 6237 6238 return true; 6239 } 6240 6241 bool 6242 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 6243 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 6244 "lvalue compound literal in c++?"); 6245 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 6246 // only see this when folding in C, so there's no standard to follow here. 6247 return Success(E); 6248 } 6249 6250 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 6251 TypeInfoLValue TypeInfo; 6252 6253 if (!E->isPotentiallyEvaluated()) { 6254 if (E->isTypeOperand()) 6255 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 6256 else 6257 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 6258 } else { 6259 if (!Info.Ctx.getLangOpts().CPlusPlus2a) { 6260 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 6261 << E->getExprOperand()->getType() 6262 << E->getExprOperand()->getSourceRange(); 6263 } 6264 6265 if (!Visit(E->getExprOperand())) 6266 return false; 6267 6268 Optional<DynamicType> DynType = 6269 ComputeDynamicType(Info, E, Result, AK_TypeId); 6270 if (!DynType) 6271 return false; 6272 6273 TypeInfo = 6274 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 6275 } 6276 6277 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 6278 } 6279 6280 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 6281 return Success(E); 6282 } 6283 6284 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 6285 // Handle static data members. 6286 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 6287 VisitIgnoredBaseExpression(E->getBase()); 6288 return VisitVarDecl(E, VD); 6289 } 6290 6291 // Handle static member functions. 6292 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 6293 if (MD->isStatic()) { 6294 VisitIgnoredBaseExpression(E->getBase()); 6295 return Success(MD); 6296 } 6297 } 6298 6299 // Handle non-static data members. 6300 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 6301 } 6302 6303 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 6304 // FIXME: Deal with vectors as array subscript bases. 6305 if (E->getBase()->getType()->isVectorType()) 6306 return Error(E); 6307 6308 bool Success = true; 6309 if (!evaluatePointer(E->getBase(), Result)) { 6310 if (!Info.noteFailure()) 6311 return false; 6312 Success = false; 6313 } 6314 6315 APSInt Index; 6316 if (!EvaluateInteger(E->getIdx(), Index, Info)) 6317 return false; 6318 6319 return Success && 6320 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 6321 } 6322 6323 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 6324 return evaluatePointer(E->getSubExpr(), Result); 6325 } 6326 6327 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 6328 if (!Visit(E->getSubExpr())) 6329 return false; 6330 // __real is a no-op on scalar lvalues. 6331 if (E->getSubExpr()->getType()->isAnyComplexType()) 6332 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 6333 return true; 6334 } 6335 6336 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 6337 assert(E->getSubExpr()->getType()->isAnyComplexType() && 6338 "lvalue __imag__ on scalar?"); 6339 if (!Visit(E->getSubExpr())) 6340 return false; 6341 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 6342 return true; 6343 } 6344 6345 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 6346 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 6347 return Error(UO); 6348 6349 if (!this->Visit(UO->getSubExpr())) 6350 return false; 6351 6352 return handleIncDec( 6353 this->Info, UO, Result, UO->getSubExpr()->getType(), 6354 UO->isIncrementOp(), nullptr); 6355 } 6356 6357 bool LValueExprEvaluator::VisitCompoundAssignOperator( 6358 const CompoundAssignOperator *CAO) { 6359 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 6360 return Error(CAO); 6361 6362 APValue RHS; 6363 6364 // The overall lvalue result is the result of evaluating the LHS. 6365 if (!this->Visit(CAO->getLHS())) { 6366 if (Info.noteFailure()) 6367 Evaluate(RHS, this->Info, CAO->getRHS()); 6368 return false; 6369 } 6370 6371 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 6372 return false; 6373 6374 return handleCompoundAssignment( 6375 this->Info, CAO, 6376 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 6377 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 6378 } 6379 6380 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 6381 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 6382 return Error(E); 6383 6384 APValue NewVal; 6385 6386 if (!this->Visit(E->getLHS())) { 6387 if (Info.noteFailure()) 6388 Evaluate(NewVal, this->Info, E->getRHS()); 6389 return false; 6390 } 6391 6392 if (!Evaluate(NewVal, this->Info, E->getRHS())) 6393 return false; 6394 6395 if (Info.getLangOpts().CPlusPlus2a && 6396 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 6397 return false; 6398 6399 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 6400 NewVal); 6401 } 6402 6403 //===----------------------------------------------------------------------===// 6404 // Pointer Evaluation 6405 //===----------------------------------------------------------------------===// 6406 6407 /// Attempts to compute the number of bytes available at the pointer 6408 /// returned by a function with the alloc_size attribute. Returns true if we 6409 /// were successful. Places an unsigned number into `Result`. 6410 /// 6411 /// This expects the given CallExpr to be a call to a function with an 6412 /// alloc_size attribute. 6413 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 6414 const CallExpr *Call, 6415 llvm::APInt &Result) { 6416 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 6417 6418 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 6419 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 6420 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 6421 if (Call->getNumArgs() <= SizeArgNo) 6422 return false; 6423 6424 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 6425 Expr::EvalResult ExprResult; 6426 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 6427 return false; 6428 Into = ExprResult.Val.getInt(); 6429 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 6430 return false; 6431 Into = Into.zextOrSelf(BitsInSizeT); 6432 return true; 6433 }; 6434 6435 APSInt SizeOfElem; 6436 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 6437 return false; 6438 6439 if (!AllocSize->getNumElemsParam().isValid()) { 6440 Result = std::move(SizeOfElem); 6441 return true; 6442 } 6443 6444 APSInt NumberOfElems; 6445 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 6446 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 6447 return false; 6448 6449 bool Overflow; 6450 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 6451 if (Overflow) 6452 return false; 6453 6454 Result = std::move(BytesAvailable); 6455 return true; 6456 } 6457 6458 /// Convenience function. LVal's base must be a call to an alloc_size 6459 /// function. 6460 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 6461 const LValue &LVal, 6462 llvm::APInt &Result) { 6463 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 6464 "Can't get the size of a non alloc_size function"); 6465 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 6466 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 6467 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 6468 } 6469 6470 /// Attempts to evaluate the given LValueBase as the result of a call to 6471 /// a function with the alloc_size attribute. If it was possible to do so, this 6472 /// function will return true, make Result's Base point to said function call, 6473 /// and mark Result's Base as invalid. 6474 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 6475 LValue &Result) { 6476 if (Base.isNull()) 6477 return false; 6478 6479 // Because we do no form of static analysis, we only support const variables. 6480 // 6481 // Additionally, we can't support parameters, nor can we support static 6482 // variables (in the latter case, use-before-assign isn't UB; in the former, 6483 // we have no clue what they'll be assigned to). 6484 const auto *VD = 6485 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 6486 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 6487 return false; 6488 6489 const Expr *Init = VD->getAnyInitializer(); 6490 if (!Init) 6491 return false; 6492 6493 const Expr *E = Init->IgnoreParens(); 6494 if (!tryUnwrapAllocSizeCall(E)) 6495 return false; 6496 6497 // Store E instead of E unwrapped so that the type of the LValue's base is 6498 // what the user wanted. 6499 Result.setInvalid(E); 6500 6501 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 6502 Result.addUnsizedArray(Info, E, Pointee); 6503 return true; 6504 } 6505 6506 namespace { 6507 class PointerExprEvaluator 6508 : public ExprEvaluatorBase<PointerExprEvaluator> { 6509 LValue &Result; 6510 bool InvalidBaseOK; 6511 6512 bool Success(const Expr *E) { 6513 Result.set(E); 6514 return true; 6515 } 6516 6517 bool evaluateLValue(const Expr *E, LValue &Result) { 6518 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 6519 } 6520 6521 bool evaluatePointer(const Expr *E, LValue &Result) { 6522 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 6523 } 6524 6525 bool visitNonBuiltinCallExpr(const CallExpr *E); 6526 public: 6527 6528 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 6529 : ExprEvaluatorBaseTy(info), Result(Result), 6530 InvalidBaseOK(InvalidBaseOK) {} 6531 6532 bool Success(const APValue &V, const Expr *E) { 6533 Result.setFrom(Info.Ctx, V); 6534 return true; 6535 } 6536 bool ZeroInitialization(const Expr *E) { 6537 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); 6538 Result.setNull(E->getType(), TargetVal); 6539 return true; 6540 } 6541 6542 bool VisitBinaryOperator(const BinaryOperator *E); 6543 bool VisitCastExpr(const CastExpr* E); 6544 bool VisitUnaryAddrOf(const UnaryOperator *E); 6545 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 6546 { return Success(E); } 6547 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 6548 if (E->isExpressibleAsConstantInitializer()) 6549 return Success(E); 6550 if (Info.noteFailure()) 6551 EvaluateIgnoredValue(Info, E->getSubExpr()); 6552 return Error(E); 6553 } 6554 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 6555 { return Success(E); } 6556 bool VisitCallExpr(const CallExpr *E); 6557 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 6558 bool VisitBlockExpr(const BlockExpr *E) { 6559 if (!E->getBlockDecl()->hasCaptures()) 6560 return Success(E); 6561 return Error(E); 6562 } 6563 bool VisitCXXThisExpr(const CXXThisExpr *E) { 6564 // Can't look at 'this' when checking a potential constant expression. 6565 if (Info.checkingPotentialConstantExpression()) 6566 return false; 6567 if (!Info.CurrentCall->This) { 6568 if (Info.getLangOpts().CPlusPlus11) 6569 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 6570 else 6571 Info.FFDiag(E); 6572 return false; 6573 } 6574 Result = *Info.CurrentCall->This; 6575 // If we are inside a lambda's call operator, the 'this' expression refers 6576 // to the enclosing '*this' object (either by value or reference) which is 6577 // either copied into the closure object's field that represents the '*this' 6578 // or refers to '*this'. 6579 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 6580 // Update 'Result' to refer to the data member/field of the closure object 6581 // that represents the '*this' capture. 6582 if (!HandleLValueMember(Info, E, Result, 6583 Info.CurrentCall->LambdaThisCaptureField)) 6584 return false; 6585 // If we captured '*this' by reference, replace the field with its referent. 6586 if (Info.CurrentCall->LambdaThisCaptureField->getType() 6587 ->isPointerType()) { 6588 APValue RVal; 6589 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 6590 RVal)) 6591 return false; 6592 6593 Result.setFrom(Info.Ctx, RVal); 6594 } 6595 } 6596 return true; 6597 } 6598 6599 bool VisitSourceLocExpr(const SourceLocExpr *E) { 6600 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 6601 APValue LValResult = E->EvaluateInContext( 6602 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 6603 Result.setFrom(Info.Ctx, LValResult); 6604 return true; 6605 } 6606 6607 // FIXME: Missing: @protocol, @selector 6608 }; 6609 } // end anonymous namespace 6610 6611 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 6612 bool InvalidBaseOK) { 6613 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 6614 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 6615 } 6616 6617 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 6618 if (E->getOpcode() != BO_Add && 6619 E->getOpcode() != BO_Sub) 6620 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 6621 6622 const Expr *PExp = E->getLHS(); 6623 const Expr *IExp = E->getRHS(); 6624 if (IExp->getType()->isPointerType()) 6625 std::swap(PExp, IExp); 6626 6627 bool EvalPtrOK = evaluatePointer(PExp, Result); 6628 if (!EvalPtrOK && !Info.noteFailure()) 6629 return false; 6630 6631 llvm::APSInt Offset; 6632 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 6633 return false; 6634 6635 if (E->getOpcode() == BO_Sub) 6636 negateAsSigned(Offset); 6637 6638 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 6639 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 6640 } 6641 6642 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 6643 return evaluateLValue(E->getSubExpr(), Result); 6644 } 6645 6646 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 6647 const Expr *SubExpr = E->getSubExpr(); 6648 6649 switch (E->getCastKind()) { 6650 default: 6651 break; 6652 6653 case CK_BitCast: 6654 case CK_CPointerToObjCPointerCast: 6655 case CK_BlockPointerToObjCPointerCast: 6656 case CK_AnyPointerToBlockPointerCast: 6657 case CK_AddressSpaceConversion: 6658 if (!Visit(SubExpr)) 6659 return false; 6660 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 6661 // permitted in constant expressions in C++11. Bitcasts from cv void* are 6662 // also static_casts, but we disallow them as a resolution to DR1312. 6663 if (!E->getType()->isVoidPointerType()) { 6664 Result.Designator.setInvalid(); 6665 if (SubExpr->getType()->isVoidPointerType()) 6666 CCEDiag(E, diag::note_constexpr_invalid_cast) 6667 << 3 << SubExpr->getType(); 6668 else 6669 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 6670 } 6671 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 6672 ZeroInitialization(E); 6673 return true; 6674 6675 case CK_DerivedToBase: 6676 case CK_UncheckedDerivedToBase: 6677 if (!evaluatePointer(E->getSubExpr(), Result)) 6678 return false; 6679 if (!Result.Base && Result.Offset.isZero()) 6680 return true; 6681 6682 // Now figure out the necessary offset to add to the base LV to get from 6683 // the derived class to the base class. 6684 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 6685 castAs<PointerType>()->getPointeeType(), 6686 Result); 6687 6688 case CK_BaseToDerived: 6689 if (!Visit(E->getSubExpr())) 6690 return false; 6691 if (!Result.Base && Result.Offset.isZero()) 6692 return true; 6693 return HandleBaseToDerivedCast(Info, E, Result); 6694 6695 case CK_Dynamic: 6696 if (!Visit(E->getSubExpr())) 6697 return false; 6698 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 6699 6700 case CK_NullToPointer: 6701 VisitIgnoredValue(E->getSubExpr()); 6702 return ZeroInitialization(E); 6703 6704 case CK_IntegralToPointer: { 6705 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 6706 6707 APValue Value; 6708 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 6709 break; 6710 6711 if (Value.isInt()) { 6712 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 6713 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 6714 Result.Base = (Expr*)nullptr; 6715 Result.InvalidBase = false; 6716 Result.Offset = CharUnits::fromQuantity(N); 6717 Result.Designator.setInvalid(); 6718 Result.IsNullPtr = false; 6719 return true; 6720 } else { 6721 // Cast is of an lvalue, no need to change value. 6722 Result.setFrom(Info.Ctx, Value); 6723 return true; 6724 } 6725 } 6726 6727 case CK_ArrayToPointerDecay: { 6728 if (SubExpr->isGLValue()) { 6729 if (!evaluateLValue(SubExpr, Result)) 6730 return false; 6731 } else { 6732 APValue &Value = createTemporary(SubExpr, false, Result, 6733 *Info.CurrentCall); 6734 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 6735 return false; 6736 } 6737 // The result is a pointer to the first element of the array. 6738 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 6739 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 6740 Result.addArray(Info, E, CAT); 6741 else 6742 Result.addUnsizedArray(Info, E, AT->getElementType()); 6743 return true; 6744 } 6745 6746 case CK_FunctionToPointerDecay: 6747 return evaluateLValue(SubExpr, Result); 6748 6749 case CK_LValueToRValue: { 6750 LValue LVal; 6751 if (!evaluateLValue(E->getSubExpr(), LVal)) 6752 return false; 6753 6754 APValue RVal; 6755 // Note, we use the subexpression's type in order to retain cv-qualifiers. 6756 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 6757 LVal, RVal)) 6758 return InvalidBaseOK && 6759 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 6760 return Success(RVal, E); 6761 } 6762 } 6763 6764 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6765 } 6766 6767 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 6768 UnaryExprOrTypeTrait ExprKind) { 6769 // C++ [expr.alignof]p3: 6770 // When alignof is applied to a reference type, the result is the 6771 // alignment of the referenced type. 6772 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 6773 T = Ref->getPointeeType(); 6774 6775 if (T.getQualifiers().hasUnaligned()) 6776 return CharUnits::One(); 6777 6778 const bool AlignOfReturnsPreferred = 6779 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 6780 6781 // __alignof is defined to return the preferred alignment. 6782 // Before 8, clang returned the preferred alignment for alignof and _Alignof 6783 // as well. 6784 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 6785 return Info.Ctx.toCharUnitsFromBits( 6786 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 6787 // alignof and _Alignof are defined to return the ABI alignment. 6788 else if (ExprKind == UETT_AlignOf) 6789 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 6790 else 6791 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 6792 } 6793 6794 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 6795 UnaryExprOrTypeTrait ExprKind) { 6796 E = E->IgnoreParens(); 6797 6798 // The kinds of expressions that we have special-case logic here for 6799 // should be kept up to date with the special checks for those 6800 // expressions in Sema. 6801 6802 // alignof decl is always accepted, even if it doesn't make sense: we default 6803 // to 1 in those cases. 6804 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 6805 return Info.Ctx.getDeclAlign(DRE->getDecl(), 6806 /*RefAsPointee*/true); 6807 6808 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 6809 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 6810 /*RefAsPointee*/true); 6811 6812 return GetAlignOfType(Info, E->getType(), ExprKind); 6813 } 6814 6815 // To be clear: this happily visits unsupported builtins. Better name welcomed. 6816 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 6817 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 6818 return true; 6819 6820 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 6821 return false; 6822 6823 Result.setInvalid(E); 6824 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 6825 Result.addUnsizedArray(Info, E, PointeeTy); 6826 return true; 6827 } 6828 6829 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 6830 if (IsStringLiteralCall(E)) 6831 return Success(E); 6832 6833 if (unsigned BuiltinOp = E->getBuiltinCallee()) 6834 return VisitBuiltinCallExpr(E, BuiltinOp); 6835 6836 return visitNonBuiltinCallExpr(E); 6837 } 6838 6839 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 6840 unsigned BuiltinOp) { 6841 switch (BuiltinOp) { 6842 case Builtin::BI__builtin_addressof: 6843 return evaluateLValue(E->getArg(0), Result); 6844 case Builtin::BI__builtin_assume_aligned: { 6845 // We need to be very careful here because: if the pointer does not have the 6846 // asserted alignment, then the behavior is undefined, and undefined 6847 // behavior is non-constant. 6848 if (!evaluatePointer(E->getArg(0), Result)) 6849 return false; 6850 6851 LValue OffsetResult(Result); 6852 APSInt Alignment; 6853 if (!EvaluateInteger(E->getArg(1), Alignment, Info)) 6854 return false; 6855 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 6856 6857 if (E->getNumArgs() > 2) { 6858 APSInt Offset; 6859 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 6860 return false; 6861 6862 int64_t AdditionalOffset = -Offset.getZExtValue(); 6863 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 6864 } 6865 6866 // If there is a base object, then it must have the correct alignment. 6867 if (OffsetResult.Base) { 6868 CharUnits BaseAlignment; 6869 if (const ValueDecl *VD = 6870 OffsetResult.Base.dyn_cast<const ValueDecl*>()) { 6871 BaseAlignment = Info.Ctx.getDeclAlign(VD); 6872 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) { 6873 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf); 6874 } else { 6875 BaseAlignment = GetAlignOfType( 6876 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf); 6877 } 6878 6879 if (BaseAlignment < Align) { 6880 Result.Designator.setInvalid(); 6881 // FIXME: Add support to Diagnostic for long / long long. 6882 CCEDiag(E->getArg(0), 6883 diag::note_constexpr_baa_insufficient_alignment) << 0 6884 << (unsigned)BaseAlignment.getQuantity() 6885 << (unsigned)Align.getQuantity(); 6886 return false; 6887 } 6888 } 6889 6890 // The offset must also have the correct alignment. 6891 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 6892 Result.Designator.setInvalid(); 6893 6894 (OffsetResult.Base 6895 ? CCEDiag(E->getArg(0), 6896 diag::note_constexpr_baa_insufficient_alignment) << 1 6897 : CCEDiag(E->getArg(0), 6898 diag::note_constexpr_baa_value_insufficient_alignment)) 6899 << (int)OffsetResult.Offset.getQuantity() 6900 << (unsigned)Align.getQuantity(); 6901 return false; 6902 } 6903 6904 return true; 6905 } 6906 case Builtin::BI__builtin_launder: 6907 return evaluatePointer(E->getArg(0), Result); 6908 case Builtin::BIstrchr: 6909 case Builtin::BIwcschr: 6910 case Builtin::BImemchr: 6911 case Builtin::BIwmemchr: 6912 if (Info.getLangOpts().CPlusPlus11) 6913 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 6914 << /*isConstexpr*/0 << /*isConstructor*/0 6915 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 6916 else 6917 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 6918 LLVM_FALLTHROUGH; 6919 case Builtin::BI__builtin_strchr: 6920 case Builtin::BI__builtin_wcschr: 6921 case Builtin::BI__builtin_memchr: 6922 case Builtin::BI__builtin_char_memchr: 6923 case Builtin::BI__builtin_wmemchr: { 6924 if (!Visit(E->getArg(0))) 6925 return false; 6926 APSInt Desired; 6927 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 6928 return false; 6929 uint64_t MaxLength = uint64_t(-1); 6930 if (BuiltinOp != Builtin::BIstrchr && 6931 BuiltinOp != Builtin::BIwcschr && 6932 BuiltinOp != Builtin::BI__builtin_strchr && 6933 BuiltinOp != Builtin::BI__builtin_wcschr) { 6934 APSInt N; 6935 if (!EvaluateInteger(E->getArg(2), N, Info)) 6936 return false; 6937 MaxLength = N.getExtValue(); 6938 } 6939 // We cannot find the value if there are no candidates to match against. 6940 if (MaxLength == 0u) 6941 return ZeroInitialization(E); 6942 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 6943 Result.Designator.Invalid) 6944 return false; 6945 QualType CharTy = Result.Designator.getType(Info.Ctx); 6946 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 6947 BuiltinOp == Builtin::BI__builtin_memchr; 6948 assert(IsRawByte || 6949 Info.Ctx.hasSameUnqualifiedType( 6950 CharTy, E->getArg(0)->getType()->getPointeeType())); 6951 // Pointers to const void may point to objects of incomplete type. 6952 if (IsRawByte && CharTy->isIncompleteType()) { 6953 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 6954 return false; 6955 } 6956 // Give up on byte-oriented matching against multibyte elements. 6957 // FIXME: We can compare the bytes in the correct order. 6958 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One()) 6959 return false; 6960 // Figure out what value we're actually looking for (after converting to 6961 // the corresponding unsigned type if necessary). 6962 uint64_t DesiredVal; 6963 bool StopAtNull = false; 6964 switch (BuiltinOp) { 6965 case Builtin::BIstrchr: 6966 case Builtin::BI__builtin_strchr: 6967 // strchr compares directly to the passed integer, and therefore 6968 // always fails if given an int that is not a char. 6969 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 6970 E->getArg(1)->getType(), 6971 Desired), 6972 Desired)) 6973 return ZeroInitialization(E); 6974 StopAtNull = true; 6975 LLVM_FALLTHROUGH; 6976 case Builtin::BImemchr: 6977 case Builtin::BI__builtin_memchr: 6978 case Builtin::BI__builtin_char_memchr: 6979 // memchr compares by converting both sides to unsigned char. That's also 6980 // correct for strchr if we get this far (to cope with plain char being 6981 // unsigned in the strchr case). 6982 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 6983 break; 6984 6985 case Builtin::BIwcschr: 6986 case Builtin::BI__builtin_wcschr: 6987 StopAtNull = true; 6988 LLVM_FALLTHROUGH; 6989 case Builtin::BIwmemchr: 6990 case Builtin::BI__builtin_wmemchr: 6991 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 6992 DesiredVal = Desired.getZExtValue(); 6993 break; 6994 } 6995 6996 for (; MaxLength; --MaxLength) { 6997 APValue Char; 6998 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 6999 !Char.isInt()) 7000 return false; 7001 if (Char.getInt().getZExtValue() == DesiredVal) 7002 return true; 7003 if (StopAtNull && !Char.getInt()) 7004 break; 7005 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 7006 return false; 7007 } 7008 // Not found: return nullptr. 7009 return ZeroInitialization(E); 7010 } 7011 7012 case Builtin::BImemcpy: 7013 case Builtin::BImemmove: 7014 case Builtin::BIwmemcpy: 7015 case Builtin::BIwmemmove: 7016 if (Info.getLangOpts().CPlusPlus11) 7017 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 7018 << /*isConstexpr*/0 << /*isConstructor*/0 7019 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 7020 else 7021 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 7022 LLVM_FALLTHROUGH; 7023 case Builtin::BI__builtin_memcpy: 7024 case Builtin::BI__builtin_memmove: 7025 case Builtin::BI__builtin_wmemcpy: 7026 case Builtin::BI__builtin_wmemmove: { 7027 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 7028 BuiltinOp == Builtin::BIwmemmove || 7029 BuiltinOp == Builtin::BI__builtin_wmemcpy || 7030 BuiltinOp == Builtin::BI__builtin_wmemmove; 7031 bool Move = BuiltinOp == Builtin::BImemmove || 7032 BuiltinOp == Builtin::BIwmemmove || 7033 BuiltinOp == Builtin::BI__builtin_memmove || 7034 BuiltinOp == Builtin::BI__builtin_wmemmove; 7035 7036 // The result of mem* is the first argument. 7037 if (!Visit(E->getArg(0))) 7038 return false; 7039 LValue Dest = Result; 7040 7041 LValue Src; 7042 if (!EvaluatePointer(E->getArg(1), Src, Info)) 7043 return false; 7044 7045 APSInt N; 7046 if (!EvaluateInteger(E->getArg(2), N, Info)) 7047 return false; 7048 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 7049 7050 // If the size is zero, we treat this as always being a valid no-op. 7051 // (Even if one of the src and dest pointers is null.) 7052 if (!N) 7053 return true; 7054 7055 // Otherwise, if either of the operands is null, we can't proceed. Don't 7056 // try to determine the type of the copied objects, because there aren't 7057 // any. 7058 if (!Src.Base || !Dest.Base) { 7059 APValue Val; 7060 (!Src.Base ? Src : Dest).moveInto(Val); 7061 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 7062 << Move << WChar << !!Src.Base 7063 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 7064 return false; 7065 } 7066 if (Src.Designator.Invalid || Dest.Designator.Invalid) 7067 return false; 7068 7069 // We require that Src and Dest are both pointers to arrays of 7070 // trivially-copyable type. (For the wide version, the designator will be 7071 // invalid if the designated object is not a wchar_t.) 7072 QualType T = Dest.Designator.getType(Info.Ctx); 7073 QualType SrcT = Src.Designator.getType(Info.Ctx); 7074 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 7075 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 7076 return false; 7077 } 7078 if (T->isIncompleteType()) { 7079 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 7080 return false; 7081 } 7082 if (!T.isTriviallyCopyableType(Info.Ctx)) { 7083 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 7084 return false; 7085 } 7086 7087 // Figure out how many T's we're copying. 7088 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 7089 if (!WChar) { 7090 uint64_t Remainder; 7091 llvm::APInt OrigN = N; 7092 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 7093 if (Remainder) { 7094 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 7095 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 7096 << (unsigned)TSize; 7097 return false; 7098 } 7099 } 7100 7101 // Check that the copying will remain within the arrays, just so that we 7102 // can give a more meaningful diagnostic. This implicitly also checks that 7103 // N fits into 64 bits. 7104 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 7105 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 7106 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 7107 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 7108 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 7109 << N.toString(10, /*Signed*/false); 7110 return false; 7111 } 7112 uint64_t NElems = N.getZExtValue(); 7113 uint64_t NBytes = NElems * TSize; 7114 7115 // Check for overlap. 7116 int Direction = 1; 7117 if (HasSameBase(Src, Dest)) { 7118 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 7119 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 7120 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 7121 // Dest is inside the source region. 7122 if (!Move) { 7123 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 7124 return false; 7125 } 7126 // For memmove and friends, copy backwards. 7127 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 7128 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 7129 return false; 7130 Direction = -1; 7131 } else if (!Move && SrcOffset >= DestOffset && 7132 SrcOffset - DestOffset < NBytes) { 7133 // Src is inside the destination region for memcpy: invalid. 7134 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 7135 return false; 7136 } 7137 } 7138 7139 while (true) { 7140 APValue Val; 7141 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 7142 !handleAssignment(Info, E, Dest, T, Val)) 7143 return false; 7144 // Do not iterate past the last element; if we're copying backwards, that 7145 // might take us off the start of the array. 7146 if (--NElems == 0) 7147 return true; 7148 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 7149 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 7150 return false; 7151 } 7152 } 7153 7154 default: 7155 return visitNonBuiltinCallExpr(E); 7156 } 7157 } 7158 7159 //===----------------------------------------------------------------------===// 7160 // Member Pointer Evaluation 7161 //===----------------------------------------------------------------------===// 7162 7163 namespace { 7164 class MemberPointerExprEvaluator 7165 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 7166 MemberPtr &Result; 7167 7168 bool Success(const ValueDecl *D) { 7169 Result = MemberPtr(D); 7170 return true; 7171 } 7172 public: 7173 7174 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 7175 : ExprEvaluatorBaseTy(Info), Result(Result) {} 7176 7177 bool Success(const APValue &V, const Expr *E) { 7178 Result.setFrom(V); 7179 return true; 7180 } 7181 bool ZeroInitialization(const Expr *E) { 7182 return Success((const ValueDecl*)nullptr); 7183 } 7184 7185 bool VisitCastExpr(const CastExpr *E); 7186 bool VisitUnaryAddrOf(const UnaryOperator *E); 7187 }; 7188 } // end anonymous namespace 7189 7190 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 7191 EvalInfo &Info) { 7192 assert(E->isRValue() && E->getType()->isMemberPointerType()); 7193 return MemberPointerExprEvaluator(Info, Result).Visit(E); 7194 } 7195 7196 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 7197 switch (E->getCastKind()) { 7198 default: 7199 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7200 7201 case CK_NullToMemberPointer: 7202 VisitIgnoredValue(E->getSubExpr()); 7203 return ZeroInitialization(E); 7204 7205 case CK_BaseToDerivedMemberPointer: { 7206 if (!Visit(E->getSubExpr())) 7207 return false; 7208 if (E->path_empty()) 7209 return true; 7210 // Base-to-derived member pointer casts store the path in derived-to-base 7211 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 7212 // the wrong end of the derived->base arc, so stagger the path by one class. 7213 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 7214 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 7215 PathI != PathE; ++PathI) { 7216 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 7217 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 7218 if (!Result.castToDerived(Derived)) 7219 return Error(E); 7220 } 7221 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 7222 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 7223 return Error(E); 7224 return true; 7225 } 7226 7227 case CK_DerivedToBaseMemberPointer: 7228 if (!Visit(E->getSubExpr())) 7229 return false; 7230 for (CastExpr::path_const_iterator PathI = E->path_begin(), 7231 PathE = E->path_end(); PathI != PathE; ++PathI) { 7232 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 7233 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 7234 if (!Result.castToBase(Base)) 7235 return Error(E); 7236 } 7237 return true; 7238 } 7239 } 7240 7241 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 7242 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 7243 // member can be formed. 7244 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 7245 } 7246 7247 //===----------------------------------------------------------------------===// 7248 // Record Evaluation 7249 //===----------------------------------------------------------------------===// 7250 7251 namespace { 7252 class RecordExprEvaluator 7253 : public ExprEvaluatorBase<RecordExprEvaluator> { 7254 const LValue &This; 7255 APValue &Result; 7256 public: 7257 7258 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 7259 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 7260 7261 bool Success(const APValue &V, const Expr *E) { 7262 Result = V; 7263 return true; 7264 } 7265 bool ZeroInitialization(const Expr *E) { 7266 return ZeroInitialization(E, E->getType()); 7267 } 7268 bool ZeroInitialization(const Expr *E, QualType T); 7269 7270 bool VisitCallExpr(const CallExpr *E) { 7271 return handleCallExpr(E, Result, &This); 7272 } 7273 bool VisitCastExpr(const CastExpr *E); 7274 bool VisitInitListExpr(const InitListExpr *E); 7275 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 7276 return VisitCXXConstructExpr(E, E->getType()); 7277 } 7278 bool VisitLambdaExpr(const LambdaExpr *E); 7279 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 7280 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 7281 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 7282 7283 bool VisitBinCmp(const BinaryOperator *E); 7284 }; 7285 } 7286 7287 /// Perform zero-initialization on an object of non-union class type. 7288 /// C++11 [dcl.init]p5: 7289 /// To zero-initialize an object or reference of type T means: 7290 /// [...] 7291 /// -- if T is a (possibly cv-qualified) non-union class type, 7292 /// each non-static data member and each base-class subobject is 7293 /// zero-initialized 7294 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 7295 const RecordDecl *RD, 7296 const LValue &This, APValue &Result) { 7297 assert(!RD->isUnion() && "Expected non-union class type"); 7298 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 7299 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 7300 std::distance(RD->field_begin(), RD->field_end())); 7301 7302 if (RD->isInvalidDecl()) return false; 7303 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7304 7305 if (CD) { 7306 unsigned Index = 0; 7307 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 7308 End = CD->bases_end(); I != End; ++I, ++Index) { 7309 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 7310 LValue Subobject = This; 7311 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 7312 return false; 7313 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 7314 Result.getStructBase(Index))) 7315 return false; 7316 } 7317 } 7318 7319 for (const auto *I : RD->fields()) { 7320 // -- if T is a reference type, no initialization is performed. 7321 if (I->getType()->isReferenceType()) 7322 continue; 7323 7324 LValue Subobject = This; 7325 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 7326 return false; 7327 7328 ImplicitValueInitExpr VIE(I->getType()); 7329 if (!EvaluateInPlace( 7330 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 7331 return false; 7332 } 7333 7334 return true; 7335 } 7336 7337 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 7338 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 7339 if (RD->isInvalidDecl()) return false; 7340 if (RD->isUnion()) { 7341 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 7342 // object's first non-static named data member is zero-initialized 7343 RecordDecl::field_iterator I = RD->field_begin(); 7344 if (I == RD->field_end()) { 7345 Result = APValue((const FieldDecl*)nullptr); 7346 return true; 7347 } 7348 7349 LValue Subobject = This; 7350 if (!HandleLValueMember(Info, E, Subobject, *I)) 7351 return false; 7352 Result = APValue(*I); 7353 ImplicitValueInitExpr VIE(I->getType()); 7354 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 7355 } 7356 7357 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 7358 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 7359 return false; 7360 } 7361 7362 return HandleClassZeroInitialization(Info, E, RD, This, Result); 7363 } 7364 7365 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 7366 switch (E->getCastKind()) { 7367 default: 7368 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7369 7370 case CK_ConstructorConversion: 7371 return Visit(E->getSubExpr()); 7372 7373 case CK_DerivedToBase: 7374 case CK_UncheckedDerivedToBase: { 7375 APValue DerivedObject; 7376 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 7377 return false; 7378 if (!DerivedObject.isStruct()) 7379 return Error(E->getSubExpr()); 7380 7381 // Derived-to-base rvalue conversion: just slice off the derived part. 7382 APValue *Value = &DerivedObject; 7383 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 7384 for (CastExpr::path_const_iterator PathI = E->path_begin(), 7385 PathE = E->path_end(); PathI != PathE; ++PathI) { 7386 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 7387 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 7388 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 7389 RD = Base; 7390 } 7391 Result = *Value; 7392 return true; 7393 } 7394 } 7395 } 7396 7397 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 7398 if (E->isTransparent()) 7399 return Visit(E->getInit(0)); 7400 7401 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 7402 if (RD->isInvalidDecl()) return false; 7403 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7404 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 7405 7406 EvalInfo::EvaluatingConstructorRAII EvalObj( 7407 Info, 7408 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 7409 CXXRD && CXXRD->getNumBases()); 7410 7411 if (RD->isUnion()) { 7412 const FieldDecl *Field = E->getInitializedFieldInUnion(); 7413 Result = APValue(Field); 7414 if (!Field) 7415 return true; 7416 7417 // If the initializer list for a union does not contain any elements, the 7418 // first element of the union is value-initialized. 7419 // FIXME: The element should be initialized from an initializer list. 7420 // Is this difference ever observable for initializer lists which 7421 // we don't build? 7422 ImplicitValueInitExpr VIE(Field->getType()); 7423 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 7424 7425 LValue Subobject = This; 7426 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 7427 return false; 7428 7429 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 7430 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 7431 isa<CXXDefaultInitExpr>(InitExpr)); 7432 7433 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 7434 } 7435 7436 if (!Result.hasValue()) 7437 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 7438 std::distance(RD->field_begin(), RD->field_end())); 7439 unsigned ElementNo = 0; 7440 bool Success = true; 7441 7442 // Initialize base classes. 7443 if (CXXRD && CXXRD->getNumBases()) { 7444 for (const auto &Base : CXXRD->bases()) { 7445 assert(ElementNo < E->getNumInits() && "missing init for base class"); 7446 const Expr *Init = E->getInit(ElementNo); 7447 7448 LValue Subobject = This; 7449 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 7450 return false; 7451 7452 APValue &FieldVal = Result.getStructBase(ElementNo); 7453 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 7454 if (!Info.noteFailure()) 7455 return false; 7456 Success = false; 7457 } 7458 ++ElementNo; 7459 } 7460 7461 EvalObj.finishedConstructingBases(); 7462 } 7463 7464 // Initialize members. 7465 for (const auto *Field : RD->fields()) { 7466 // Anonymous bit-fields are not considered members of the class for 7467 // purposes of aggregate initialization. 7468 if (Field->isUnnamedBitfield()) 7469 continue; 7470 7471 LValue Subobject = This; 7472 7473 bool HaveInit = ElementNo < E->getNumInits(); 7474 7475 // FIXME: Diagnostics here should point to the end of the initializer 7476 // list, not the start. 7477 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 7478 Subobject, Field, &Layout)) 7479 return false; 7480 7481 // Perform an implicit value-initialization for members beyond the end of 7482 // the initializer list. 7483 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 7484 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 7485 7486 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 7487 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 7488 isa<CXXDefaultInitExpr>(Init)); 7489 7490 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 7491 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 7492 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 7493 FieldVal, Field))) { 7494 if (!Info.noteFailure()) 7495 return false; 7496 Success = false; 7497 } 7498 } 7499 7500 return Success; 7501 } 7502 7503 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 7504 QualType T) { 7505 // Note that E's type is not necessarily the type of our class here; we might 7506 // be initializing an array element instead. 7507 const CXXConstructorDecl *FD = E->getConstructor(); 7508 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 7509 7510 bool ZeroInit = E->requiresZeroInitialization(); 7511 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 7512 // If we've already performed zero-initialization, we're already done. 7513 if (Result.hasValue()) 7514 return true; 7515 7516 // We can get here in two different ways: 7517 // 1) We're performing value-initialization, and should zero-initialize 7518 // the object, or 7519 // 2) We're performing default-initialization of an object with a trivial 7520 // constexpr default constructor, in which case we should start the 7521 // lifetimes of all the base subobjects (there can be no data member 7522 // subobjects in this case) per [basic.life]p1. 7523 // Either way, ZeroInitialization is appropriate. 7524 return ZeroInitialization(E, T); 7525 } 7526 7527 const FunctionDecl *Definition = nullptr; 7528 auto Body = FD->getBody(Definition); 7529 7530 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 7531 return false; 7532 7533 // Avoid materializing a temporary for an elidable copy/move constructor. 7534 if (E->isElidable() && !ZeroInit) 7535 if (const MaterializeTemporaryExpr *ME 7536 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 7537 return Visit(ME->GetTemporaryExpr()); 7538 7539 if (ZeroInit && !ZeroInitialization(E, T)) 7540 return false; 7541 7542 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7543 return HandleConstructorCall(E, This, Args, 7544 cast<CXXConstructorDecl>(Definition), Info, 7545 Result); 7546 } 7547 7548 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 7549 const CXXInheritedCtorInitExpr *E) { 7550 if (!Info.CurrentCall) { 7551 assert(Info.checkingPotentialConstantExpression()); 7552 return false; 7553 } 7554 7555 const CXXConstructorDecl *FD = E->getConstructor(); 7556 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 7557 return false; 7558 7559 const FunctionDecl *Definition = nullptr; 7560 auto Body = FD->getBody(Definition); 7561 7562 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 7563 return false; 7564 7565 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 7566 cast<CXXConstructorDecl>(Definition), Info, 7567 Result); 7568 } 7569 7570 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 7571 const CXXStdInitializerListExpr *E) { 7572 const ConstantArrayType *ArrayType = 7573 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 7574 7575 LValue Array; 7576 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 7577 return false; 7578 7579 // Get a pointer to the first element of the array. 7580 Array.addArray(Info, E, ArrayType); 7581 7582 // FIXME: Perform the checks on the field types in SemaInit. 7583 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 7584 RecordDecl::field_iterator Field = Record->field_begin(); 7585 if (Field == Record->field_end()) 7586 return Error(E); 7587 7588 // Start pointer. 7589 if (!Field->getType()->isPointerType() || 7590 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 7591 ArrayType->getElementType())) 7592 return Error(E); 7593 7594 // FIXME: What if the initializer_list type has base classes, etc? 7595 Result = APValue(APValue::UninitStruct(), 0, 2); 7596 Array.moveInto(Result.getStructField(0)); 7597 7598 if (++Field == Record->field_end()) 7599 return Error(E); 7600 7601 if (Field->getType()->isPointerType() && 7602 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 7603 ArrayType->getElementType())) { 7604 // End pointer. 7605 if (!HandleLValueArrayAdjustment(Info, E, Array, 7606 ArrayType->getElementType(), 7607 ArrayType->getSize().getZExtValue())) 7608 return false; 7609 Array.moveInto(Result.getStructField(1)); 7610 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 7611 // Length. 7612 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 7613 else 7614 return Error(E); 7615 7616 if (++Field != Record->field_end()) 7617 return Error(E); 7618 7619 return true; 7620 } 7621 7622 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 7623 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 7624 if (ClosureClass->isInvalidDecl()) return false; 7625 7626 if (Info.checkingPotentialConstantExpression()) return true; 7627 7628 const size_t NumFields = 7629 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 7630 7631 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 7632 E->capture_init_end()) && 7633 "The number of lambda capture initializers should equal the number of " 7634 "fields within the closure type"); 7635 7636 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 7637 // Iterate through all the lambda's closure object's fields and initialize 7638 // them. 7639 auto *CaptureInitIt = E->capture_init_begin(); 7640 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 7641 bool Success = true; 7642 for (const auto *Field : ClosureClass->fields()) { 7643 assert(CaptureInitIt != E->capture_init_end()); 7644 // Get the initializer for this field 7645 Expr *const CurFieldInit = *CaptureInitIt++; 7646 7647 // If there is no initializer, either this is a VLA or an error has 7648 // occurred. 7649 if (!CurFieldInit) 7650 return Error(E); 7651 7652 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 7653 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 7654 if (!Info.keepEvaluatingAfterFailure()) 7655 return false; 7656 Success = false; 7657 } 7658 ++CaptureIt; 7659 } 7660 return Success; 7661 } 7662 7663 static bool EvaluateRecord(const Expr *E, const LValue &This, 7664 APValue &Result, EvalInfo &Info) { 7665 assert(E->isRValue() && E->getType()->isRecordType() && 7666 "can't evaluate expression as a record rvalue"); 7667 return RecordExprEvaluator(Info, This, Result).Visit(E); 7668 } 7669 7670 //===----------------------------------------------------------------------===// 7671 // Temporary Evaluation 7672 // 7673 // Temporaries are represented in the AST as rvalues, but generally behave like 7674 // lvalues. The full-object of which the temporary is a subobject is implicitly 7675 // materialized so that a reference can bind to it. 7676 //===----------------------------------------------------------------------===// 7677 namespace { 7678 class TemporaryExprEvaluator 7679 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 7680 public: 7681 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 7682 LValueExprEvaluatorBaseTy(Info, Result, false) {} 7683 7684 /// Visit an expression which constructs the value of this temporary. 7685 bool VisitConstructExpr(const Expr *E) { 7686 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall); 7687 return EvaluateInPlace(Value, Info, Result, E); 7688 } 7689 7690 bool VisitCastExpr(const CastExpr *E) { 7691 switch (E->getCastKind()) { 7692 default: 7693 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 7694 7695 case CK_ConstructorConversion: 7696 return VisitConstructExpr(E->getSubExpr()); 7697 } 7698 } 7699 bool VisitInitListExpr(const InitListExpr *E) { 7700 return VisitConstructExpr(E); 7701 } 7702 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 7703 return VisitConstructExpr(E); 7704 } 7705 bool VisitCallExpr(const CallExpr *E) { 7706 return VisitConstructExpr(E); 7707 } 7708 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 7709 return VisitConstructExpr(E); 7710 } 7711 bool VisitLambdaExpr(const LambdaExpr *E) { 7712 return VisitConstructExpr(E); 7713 } 7714 }; 7715 } // end anonymous namespace 7716 7717 /// Evaluate an expression of record type as a temporary. 7718 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 7719 assert(E->isRValue() && E->getType()->isRecordType()); 7720 return TemporaryExprEvaluator(Info, Result).Visit(E); 7721 } 7722 7723 //===----------------------------------------------------------------------===// 7724 // Vector Evaluation 7725 //===----------------------------------------------------------------------===// 7726 7727 namespace { 7728 class VectorExprEvaluator 7729 : public ExprEvaluatorBase<VectorExprEvaluator> { 7730 APValue &Result; 7731 public: 7732 7733 VectorExprEvaluator(EvalInfo &info, APValue &Result) 7734 : ExprEvaluatorBaseTy(info), Result(Result) {} 7735 7736 bool Success(ArrayRef<APValue> V, const Expr *E) { 7737 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 7738 // FIXME: remove this APValue copy. 7739 Result = APValue(V.data(), V.size()); 7740 return true; 7741 } 7742 bool Success(const APValue &V, const Expr *E) { 7743 assert(V.isVector()); 7744 Result = V; 7745 return true; 7746 } 7747 bool ZeroInitialization(const Expr *E); 7748 7749 bool VisitUnaryReal(const UnaryOperator *E) 7750 { return Visit(E->getSubExpr()); } 7751 bool VisitCastExpr(const CastExpr* E); 7752 bool VisitInitListExpr(const InitListExpr *E); 7753 bool VisitUnaryImag(const UnaryOperator *E); 7754 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 7755 // binary comparisons, binary and/or/xor, 7756 // shufflevector, ExtVectorElementExpr 7757 }; 7758 } // end anonymous namespace 7759 7760 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 7761 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 7762 return VectorExprEvaluator(Info, Result).Visit(E); 7763 } 7764 7765 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 7766 const VectorType *VTy = E->getType()->castAs<VectorType>(); 7767 unsigned NElts = VTy->getNumElements(); 7768 7769 const Expr *SE = E->getSubExpr(); 7770 QualType SETy = SE->getType(); 7771 7772 switch (E->getCastKind()) { 7773 case CK_VectorSplat: { 7774 APValue Val = APValue(); 7775 if (SETy->isIntegerType()) { 7776 APSInt IntResult; 7777 if (!EvaluateInteger(SE, IntResult, Info)) 7778 return false; 7779 Val = APValue(std::move(IntResult)); 7780 } else if (SETy->isRealFloatingType()) { 7781 APFloat FloatResult(0.0); 7782 if (!EvaluateFloat(SE, FloatResult, Info)) 7783 return false; 7784 Val = APValue(std::move(FloatResult)); 7785 } else { 7786 return Error(E); 7787 } 7788 7789 // Splat and create vector APValue. 7790 SmallVector<APValue, 4> Elts(NElts, Val); 7791 return Success(Elts, E); 7792 } 7793 case CK_BitCast: { 7794 // Evaluate the operand into an APInt we can extract from. 7795 llvm::APInt SValInt; 7796 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 7797 return false; 7798 // Extract the elements 7799 QualType EltTy = VTy->getElementType(); 7800 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 7801 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 7802 SmallVector<APValue, 4> Elts; 7803 if (EltTy->isRealFloatingType()) { 7804 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 7805 unsigned FloatEltSize = EltSize; 7806 if (&Sem == &APFloat::x87DoubleExtended()) 7807 FloatEltSize = 80; 7808 for (unsigned i = 0; i < NElts; i++) { 7809 llvm::APInt Elt; 7810 if (BigEndian) 7811 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 7812 else 7813 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 7814 Elts.push_back(APValue(APFloat(Sem, Elt))); 7815 } 7816 } else if (EltTy->isIntegerType()) { 7817 for (unsigned i = 0; i < NElts; i++) { 7818 llvm::APInt Elt; 7819 if (BigEndian) 7820 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 7821 else 7822 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 7823 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 7824 } 7825 } else { 7826 return Error(E); 7827 } 7828 return Success(Elts, E); 7829 } 7830 default: 7831 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7832 } 7833 } 7834 7835 bool 7836 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 7837 const VectorType *VT = E->getType()->castAs<VectorType>(); 7838 unsigned NumInits = E->getNumInits(); 7839 unsigned NumElements = VT->getNumElements(); 7840 7841 QualType EltTy = VT->getElementType(); 7842 SmallVector<APValue, 4> Elements; 7843 7844 // The number of initializers can be less than the number of 7845 // vector elements. For OpenCL, this can be due to nested vector 7846 // initialization. For GCC compatibility, missing trailing elements 7847 // should be initialized with zeroes. 7848 unsigned CountInits = 0, CountElts = 0; 7849 while (CountElts < NumElements) { 7850 // Handle nested vector initialization. 7851 if (CountInits < NumInits 7852 && E->getInit(CountInits)->getType()->isVectorType()) { 7853 APValue v; 7854 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 7855 return Error(E); 7856 unsigned vlen = v.getVectorLength(); 7857 for (unsigned j = 0; j < vlen; j++) 7858 Elements.push_back(v.getVectorElt(j)); 7859 CountElts += vlen; 7860 } else if (EltTy->isIntegerType()) { 7861 llvm::APSInt sInt(32); 7862 if (CountInits < NumInits) { 7863 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 7864 return false; 7865 } else // trailing integer zero. 7866 sInt = Info.Ctx.MakeIntValue(0, EltTy); 7867 Elements.push_back(APValue(sInt)); 7868 CountElts++; 7869 } else { 7870 llvm::APFloat f(0.0); 7871 if (CountInits < NumInits) { 7872 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 7873 return false; 7874 } else // trailing float zero. 7875 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 7876 Elements.push_back(APValue(f)); 7877 CountElts++; 7878 } 7879 CountInits++; 7880 } 7881 return Success(Elements, E); 7882 } 7883 7884 bool 7885 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 7886 const VectorType *VT = E->getType()->getAs<VectorType>(); 7887 QualType EltTy = VT->getElementType(); 7888 APValue ZeroElement; 7889 if (EltTy->isIntegerType()) 7890 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 7891 else 7892 ZeroElement = 7893 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 7894 7895 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 7896 return Success(Elements, E); 7897 } 7898 7899 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 7900 VisitIgnoredValue(E->getSubExpr()); 7901 return ZeroInitialization(E); 7902 } 7903 7904 //===----------------------------------------------------------------------===// 7905 // Array Evaluation 7906 //===----------------------------------------------------------------------===// 7907 7908 namespace { 7909 class ArrayExprEvaluator 7910 : public ExprEvaluatorBase<ArrayExprEvaluator> { 7911 const LValue &This; 7912 APValue &Result; 7913 public: 7914 7915 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 7916 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 7917 7918 bool Success(const APValue &V, const Expr *E) { 7919 assert(V.isArray() && "expected array"); 7920 Result = V; 7921 return true; 7922 } 7923 7924 bool ZeroInitialization(const Expr *E) { 7925 const ConstantArrayType *CAT = 7926 Info.Ctx.getAsConstantArrayType(E->getType()); 7927 if (!CAT) 7928 return Error(E); 7929 7930 Result = APValue(APValue::UninitArray(), 0, 7931 CAT->getSize().getZExtValue()); 7932 if (!Result.hasArrayFiller()) return true; 7933 7934 // Zero-initialize all elements. 7935 LValue Subobject = This; 7936 Subobject.addArray(Info, E, CAT); 7937 ImplicitValueInitExpr VIE(CAT->getElementType()); 7938 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 7939 } 7940 7941 bool VisitCallExpr(const CallExpr *E) { 7942 return handleCallExpr(E, Result, &This); 7943 } 7944 bool VisitInitListExpr(const InitListExpr *E); 7945 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 7946 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 7947 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 7948 const LValue &Subobject, 7949 APValue *Value, QualType Type); 7950 bool VisitStringLiteral(const StringLiteral *E) { 7951 expandStringLiteral(Info, E, Result); 7952 return true; 7953 } 7954 }; 7955 } // end anonymous namespace 7956 7957 static bool EvaluateArray(const Expr *E, const LValue &This, 7958 APValue &Result, EvalInfo &Info) { 7959 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 7960 return ArrayExprEvaluator(Info, This, Result).Visit(E); 7961 } 7962 7963 // Return true iff the given array filler may depend on the element index. 7964 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 7965 // For now, just whitelist non-class value-initialization and initialization 7966 // lists comprised of them. 7967 if (isa<ImplicitValueInitExpr>(FillerExpr)) 7968 return false; 7969 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 7970 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 7971 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 7972 return true; 7973 } 7974 return false; 7975 } 7976 return true; 7977 } 7978 7979 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 7980 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 7981 if (!CAT) 7982 return Error(E); 7983 7984 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 7985 // an appropriately-typed string literal enclosed in braces. 7986 if (E->isStringLiteralInit()) 7987 return Visit(E->getInit(0)); 7988 7989 bool Success = true; 7990 7991 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 7992 "zero-initialized array shouldn't have any initialized elts"); 7993 APValue Filler; 7994 if (Result.isArray() && Result.hasArrayFiller()) 7995 Filler = Result.getArrayFiller(); 7996 7997 unsigned NumEltsToInit = E->getNumInits(); 7998 unsigned NumElts = CAT->getSize().getZExtValue(); 7999 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 8000 8001 // If the initializer might depend on the array index, run it for each 8002 // array element. 8003 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 8004 NumEltsToInit = NumElts; 8005 8006 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 8007 << NumEltsToInit << ".\n"); 8008 8009 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 8010 8011 // If the array was previously zero-initialized, preserve the 8012 // zero-initialized values. 8013 if (Filler.hasValue()) { 8014 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 8015 Result.getArrayInitializedElt(I) = Filler; 8016 if (Result.hasArrayFiller()) 8017 Result.getArrayFiller() = Filler; 8018 } 8019 8020 LValue Subobject = This; 8021 Subobject.addArray(Info, E, CAT); 8022 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 8023 const Expr *Init = 8024 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 8025 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 8026 Info, Subobject, Init) || 8027 !HandleLValueArrayAdjustment(Info, Init, Subobject, 8028 CAT->getElementType(), 1)) { 8029 if (!Info.noteFailure()) 8030 return false; 8031 Success = false; 8032 } 8033 } 8034 8035 if (!Result.hasArrayFiller()) 8036 return Success; 8037 8038 // If we get here, we have a trivial filler, which we can just evaluate 8039 // once and splat over the rest of the array elements. 8040 assert(FillerExpr && "no array filler for incomplete init list"); 8041 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 8042 FillerExpr) && Success; 8043 } 8044 8045 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 8046 if (E->getCommonExpr() && 8047 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false), 8048 Info, E->getCommonExpr()->getSourceExpr())) 8049 return false; 8050 8051 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 8052 8053 uint64_t Elements = CAT->getSize().getZExtValue(); 8054 Result = APValue(APValue::UninitArray(), Elements, Elements); 8055 8056 LValue Subobject = This; 8057 Subobject.addArray(Info, E, CAT); 8058 8059 bool Success = true; 8060 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 8061 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 8062 Info, Subobject, E->getSubExpr()) || 8063 !HandleLValueArrayAdjustment(Info, E, Subobject, 8064 CAT->getElementType(), 1)) { 8065 if (!Info.noteFailure()) 8066 return false; 8067 Success = false; 8068 } 8069 } 8070 8071 return Success; 8072 } 8073 8074 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 8075 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 8076 } 8077 8078 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 8079 const LValue &Subobject, 8080 APValue *Value, 8081 QualType Type) { 8082 bool HadZeroInit = Value->hasValue(); 8083 8084 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 8085 unsigned N = CAT->getSize().getZExtValue(); 8086 8087 // Preserve the array filler if we had prior zero-initialization. 8088 APValue Filler = 8089 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 8090 : APValue(); 8091 8092 *Value = APValue(APValue::UninitArray(), N, N); 8093 8094 if (HadZeroInit) 8095 for (unsigned I = 0; I != N; ++I) 8096 Value->getArrayInitializedElt(I) = Filler; 8097 8098 // Initialize the elements. 8099 LValue ArrayElt = Subobject; 8100 ArrayElt.addArray(Info, E, CAT); 8101 for (unsigned I = 0; I != N; ++I) 8102 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 8103 CAT->getElementType()) || 8104 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 8105 CAT->getElementType(), 1)) 8106 return false; 8107 8108 return true; 8109 } 8110 8111 if (!Type->isRecordType()) 8112 return Error(E); 8113 8114 return RecordExprEvaluator(Info, Subobject, *Value) 8115 .VisitCXXConstructExpr(E, Type); 8116 } 8117 8118 //===----------------------------------------------------------------------===// 8119 // Integer Evaluation 8120 // 8121 // As a GNU extension, we support casting pointers to sufficiently-wide integer 8122 // types and back in constant folding. Integer values are thus represented 8123 // either as an integer-valued APValue, or as an lvalue-valued APValue. 8124 //===----------------------------------------------------------------------===// 8125 8126 namespace { 8127 class IntExprEvaluator 8128 : public ExprEvaluatorBase<IntExprEvaluator> { 8129 APValue &Result; 8130 public: 8131 IntExprEvaluator(EvalInfo &info, APValue &result) 8132 : ExprEvaluatorBaseTy(info), Result(result) {} 8133 8134 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 8135 assert(E->getType()->isIntegralOrEnumerationType() && 8136 "Invalid evaluation result."); 8137 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 8138 "Invalid evaluation result."); 8139 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 8140 "Invalid evaluation result."); 8141 Result = APValue(SI); 8142 return true; 8143 } 8144 bool Success(const llvm::APSInt &SI, const Expr *E) { 8145 return Success(SI, E, Result); 8146 } 8147 8148 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 8149 assert(E->getType()->isIntegralOrEnumerationType() && 8150 "Invalid evaluation result."); 8151 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 8152 "Invalid evaluation result."); 8153 Result = APValue(APSInt(I)); 8154 Result.getInt().setIsUnsigned( 8155 E->getType()->isUnsignedIntegerOrEnumerationType()); 8156 return true; 8157 } 8158 bool Success(const llvm::APInt &I, const Expr *E) { 8159 return Success(I, E, Result); 8160 } 8161 8162 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 8163 assert(E->getType()->isIntegralOrEnumerationType() && 8164 "Invalid evaluation result."); 8165 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 8166 return true; 8167 } 8168 bool Success(uint64_t Value, const Expr *E) { 8169 return Success(Value, E, Result); 8170 } 8171 8172 bool Success(CharUnits Size, const Expr *E) { 8173 return Success(Size.getQuantity(), E); 8174 } 8175 8176 bool Success(const APValue &V, const Expr *E) { 8177 if (V.isLValue() || V.isAddrLabelDiff()) { 8178 Result = V; 8179 return true; 8180 } 8181 return Success(V.getInt(), E); 8182 } 8183 8184 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 8185 8186 //===--------------------------------------------------------------------===// 8187 // Visitor Methods 8188 //===--------------------------------------------------------------------===// 8189 8190 bool VisitConstantExpr(const ConstantExpr *E); 8191 8192 bool VisitIntegerLiteral(const IntegerLiteral *E) { 8193 return Success(E->getValue(), E); 8194 } 8195 bool VisitCharacterLiteral(const CharacterLiteral *E) { 8196 return Success(E->getValue(), E); 8197 } 8198 8199 bool CheckReferencedDecl(const Expr *E, const Decl *D); 8200 bool VisitDeclRefExpr(const DeclRefExpr *E) { 8201 if (CheckReferencedDecl(E, E->getDecl())) 8202 return true; 8203 8204 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 8205 } 8206 bool VisitMemberExpr(const MemberExpr *E) { 8207 if (CheckReferencedDecl(E, E->getMemberDecl())) { 8208 VisitIgnoredBaseExpression(E->getBase()); 8209 return true; 8210 } 8211 8212 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 8213 } 8214 8215 bool VisitCallExpr(const CallExpr *E); 8216 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8217 bool VisitBinaryOperator(const BinaryOperator *E); 8218 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 8219 bool VisitUnaryOperator(const UnaryOperator *E); 8220 8221 bool VisitCastExpr(const CastExpr* E); 8222 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 8223 8224 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 8225 return Success(E->getValue(), E); 8226 } 8227 8228 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 8229 return Success(E->getValue(), E); 8230 } 8231 8232 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 8233 if (Info.ArrayInitIndex == uint64_t(-1)) { 8234 // We were asked to evaluate this subexpression independent of the 8235 // enclosing ArrayInitLoopExpr. We can't do that. 8236 Info.FFDiag(E); 8237 return false; 8238 } 8239 return Success(Info.ArrayInitIndex, E); 8240 } 8241 8242 // Note, GNU defines __null as an integer, not a pointer. 8243 bool VisitGNUNullExpr(const GNUNullExpr *E) { 8244 return ZeroInitialization(E); 8245 } 8246 8247 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 8248 return Success(E->getValue(), E); 8249 } 8250 8251 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 8252 return Success(E->getValue(), E); 8253 } 8254 8255 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 8256 return Success(E->getValue(), E); 8257 } 8258 8259 bool VisitUnaryReal(const UnaryOperator *E); 8260 bool VisitUnaryImag(const UnaryOperator *E); 8261 8262 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 8263 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 8264 bool VisitSourceLocExpr(const SourceLocExpr *E); 8265 // FIXME: Missing: array subscript of vector, member of vector 8266 }; 8267 8268 class FixedPointExprEvaluator 8269 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 8270 APValue &Result; 8271 8272 public: 8273 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 8274 : ExprEvaluatorBaseTy(info), Result(result) {} 8275 8276 bool Success(const llvm::APInt &I, const Expr *E) { 8277 return Success( 8278 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 8279 } 8280 8281 bool Success(uint64_t Value, const Expr *E) { 8282 return Success( 8283 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 8284 } 8285 8286 bool Success(const APValue &V, const Expr *E) { 8287 return Success(V.getFixedPoint(), E); 8288 } 8289 8290 bool Success(const APFixedPoint &V, const Expr *E) { 8291 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 8292 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 8293 "Invalid evaluation result."); 8294 Result = APValue(V); 8295 return true; 8296 } 8297 8298 //===--------------------------------------------------------------------===// 8299 // Visitor Methods 8300 //===--------------------------------------------------------------------===// 8301 8302 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 8303 return Success(E->getValue(), E); 8304 } 8305 8306 bool VisitCastExpr(const CastExpr *E); 8307 bool VisitUnaryOperator(const UnaryOperator *E); 8308 bool VisitBinaryOperator(const BinaryOperator *E); 8309 }; 8310 } // end anonymous namespace 8311 8312 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 8313 /// produce either the integer value or a pointer. 8314 /// 8315 /// GCC has a heinous extension which folds casts between pointer types and 8316 /// pointer-sized integral types. We support this by allowing the evaluation of 8317 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 8318 /// Some simple arithmetic on such values is supported (they are treated much 8319 /// like char*). 8320 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 8321 EvalInfo &Info) { 8322 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 8323 return IntExprEvaluator(Info, Result).Visit(E); 8324 } 8325 8326 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 8327 APValue Val; 8328 if (!EvaluateIntegerOrLValue(E, Val, Info)) 8329 return false; 8330 if (!Val.isInt()) { 8331 // FIXME: It would be better to produce the diagnostic for casting 8332 // a pointer to an integer. 8333 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 8334 return false; 8335 } 8336 Result = Val.getInt(); 8337 return true; 8338 } 8339 8340 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 8341 APValue Evaluated = E->EvaluateInContext( 8342 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8343 return Success(Evaluated, E); 8344 } 8345 8346 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 8347 EvalInfo &Info) { 8348 if (E->getType()->isFixedPointType()) { 8349 APValue Val; 8350 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 8351 return false; 8352 if (!Val.isFixedPoint()) 8353 return false; 8354 8355 Result = Val.getFixedPoint(); 8356 return true; 8357 } 8358 return false; 8359 } 8360 8361 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 8362 EvalInfo &Info) { 8363 if (E->getType()->isIntegerType()) { 8364 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 8365 APSInt Val; 8366 if (!EvaluateInteger(E, Val, Info)) 8367 return false; 8368 Result = APFixedPoint(Val, FXSema); 8369 return true; 8370 } else if (E->getType()->isFixedPointType()) { 8371 return EvaluateFixedPoint(E, Result, Info); 8372 } 8373 return false; 8374 } 8375 8376 /// Check whether the given declaration can be directly converted to an integral 8377 /// rvalue. If not, no diagnostic is produced; there are other things we can 8378 /// try. 8379 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 8380 // Enums are integer constant exprs. 8381 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 8382 // Check for signedness/width mismatches between E type and ECD value. 8383 bool SameSign = (ECD->getInitVal().isSigned() 8384 == E->getType()->isSignedIntegerOrEnumerationType()); 8385 bool SameWidth = (ECD->getInitVal().getBitWidth() 8386 == Info.Ctx.getIntWidth(E->getType())); 8387 if (SameSign && SameWidth) 8388 return Success(ECD->getInitVal(), E); 8389 else { 8390 // Get rid of mismatch (otherwise Success assertions will fail) 8391 // by computing a new value matching the type of E. 8392 llvm::APSInt Val = ECD->getInitVal(); 8393 if (!SameSign) 8394 Val.setIsSigned(!ECD->getInitVal().isSigned()); 8395 if (!SameWidth) 8396 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 8397 return Success(Val, E); 8398 } 8399 } 8400 return false; 8401 } 8402 8403 /// Values returned by __builtin_classify_type, chosen to match the values 8404 /// produced by GCC's builtin. 8405 enum class GCCTypeClass { 8406 None = -1, 8407 Void = 0, 8408 Integer = 1, 8409 // GCC reserves 2 for character types, but instead classifies them as 8410 // integers. 8411 Enum = 3, 8412 Bool = 4, 8413 Pointer = 5, 8414 // GCC reserves 6 for references, but appears to never use it (because 8415 // expressions never have reference type, presumably). 8416 PointerToDataMember = 7, 8417 RealFloat = 8, 8418 Complex = 9, 8419 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 8420 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 8421 // GCC claims to reserve 11 for pointers to member functions, but *actually* 8422 // uses 12 for that purpose, same as for a class or struct. Maybe it 8423 // internally implements a pointer to member as a struct? Who knows. 8424 PointerToMemberFunction = 12, // Not a bug, see above. 8425 ClassOrStruct = 12, 8426 Union = 13, 8427 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 8428 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 8429 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 8430 // literals. 8431 }; 8432 8433 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 8434 /// as GCC. 8435 static GCCTypeClass 8436 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 8437 assert(!T->isDependentType() && "unexpected dependent type"); 8438 8439 QualType CanTy = T.getCanonicalType(); 8440 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 8441 8442 switch (CanTy->getTypeClass()) { 8443 #define TYPE(ID, BASE) 8444 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 8445 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 8446 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 8447 #include "clang/AST/TypeNodes.def" 8448 case Type::Auto: 8449 case Type::DeducedTemplateSpecialization: 8450 llvm_unreachable("unexpected non-canonical or dependent type"); 8451 8452 case Type::Builtin: 8453 switch (BT->getKind()) { 8454 #define BUILTIN_TYPE(ID, SINGLETON_ID) 8455 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 8456 case BuiltinType::ID: return GCCTypeClass::Integer; 8457 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 8458 case BuiltinType::ID: return GCCTypeClass::RealFloat; 8459 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 8460 case BuiltinType::ID: break; 8461 #include "clang/AST/BuiltinTypes.def" 8462 case BuiltinType::Void: 8463 return GCCTypeClass::Void; 8464 8465 case BuiltinType::Bool: 8466 return GCCTypeClass::Bool; 8467 8468 case BuiltinType::Char_U: 8469 case BuiltinType::UChar: 8470 case BuiltinType::WChar_U: 8471 case BuiltinType::Char8: 8472 case BuiltinType::Char16: 8473 case BuiltinType::Char32: 8474 case BuiltinType::UShort: 8475 case BuiltinType::UInt: 8476 case BuiltinType::ULong: 8477 case BuiltinType::ULongLong: 8478 case BuiltinType::UInt128: 8479 return GCCTypeClass::Integer; 8480 8481 case BuiltinType::UShortAccum: 8482 case BuiltinType::UAccum: 8483 case BuiltinType::ULongAccum: 8484 case BuiltinType::UShortFract: 8485 case BuiltinType::UFract: 8486 case BuiltinType::ULongFract: 8487 case BuiltinType::SatUShortAccum: 8488 case BuiltinType::SatUAccum: 8489 case BuiltinType::SatULongAccum: 8490 case BuiltinType::SatUShortFract: 8491 case BuiltinType::SatUFract: 8492 case BuiltinType::SatULongFract: 8493 return GCCTypeClass::None; 8494 8495 case BuiltinType::NullPtr: 8496 8497 case BuiltinType::ObjCId: 8498 case BuiltinType::ObjCClass: 8499 case BuiltinType::ObjCSel: 8500 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 8501 case BuiltinType::Id: 8502 #include "clang/Basic/OpenCLImageTypes.def" 8503 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 8504 case BuiltinType::Id: 8505 #include "clang/Basic/OpenCLExtensionTypes.def" 8506 case BuiltinType::OCLSampler: 8507 case BuiltinType::OCLEvent: 8508 case BuiltinType::OCLClkEvent: 8509 case BuiltinType::OCLQueue: 8510 case BuiltinType::OCLReserveID: 8511 return GCCTypeClass::None; 8512 8513 case BuiltinType::Dependent: 8514 llvm_unreachable("unexpected dependent type"); 8515 }; 8516 llvm_unreachable("unexpected placeholder type"); 8517 8518 case Type::Enum: 8519 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 8520 8521 case Type::Pointer: 8522 case Type::ConstantArray: 8523 case Type::VariableArray: 8524 case Type::IncompleteArray: 8525 case Type::FunctionNoProto: 8526 case Type::FunctionProto: 8527 return GCCTypeClass::Pointer; 8528 8529 case Type::MemberPointer: 8530 return CanTy->isMemberDataPointerType() 8531 ? GCCTypeClass::PointerToDataMember 8532 : GCCTypeClass::PointerToMemberFunction; 8533 8534 case Type::Complex: 8535 return GCCTypeClass::Complex; 8536 8537 case Type::Record: 8538 return CanTy->isUnionType() ? GCCTypeClass::Union 8539 : GCCTypeClass::ClassOrStruct; 8540 8541 case Type::Atomic: 8542 // GCC classifies _Atomic T the same as T. 8543 return EvaluateBuiltinClassifyType( 8544 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 8545 8546 case Type::BlockPointer: 8547 case Type::Vector: 8548 case Type::ExtVector: 8549 case Type::ObjCObject: 8550 case Type::ObjCInterface: 8551 case Type::ObjCObjectPointer: 8552 case Type::Pipe: 8553 // GCC classifies vectors as None. We follow its lead and classify all 8554 // other types that don't fit into the regular classification the same way. 8555 return GCCTypeClass::None; 8556 8557 case Type::LValueReference: 8558 case Type::RValueReference: 8559 llvm_unreachable("invalid type for expression"); 8560 } 8561 8562 llvm_unreachable("unexpected type class"); 8563 } 8564 8565 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 8566 /// as GCC. 8567 static GCCTypeClass 8568 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 8569 // If no argument was supplied, default to None. This isn't 8570 // ideal, however it is what gcc does. 8571 if (E->getNumArgs() == 0) 8572 return GCCTypeClass::None; 8573 8574 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 8575 // being an ICE, but still folds it to a constant using the type of the first 8576 // argument. 8577 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 8578 } 8579 8580 /// EvaluateBuiltinConstantPForLValue - Determine the result of 8581 /// __builtin_constant_p when applied to the given pointer. 8582 /// 8583 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 8584 /// or it points to the first character of a string literal. 8585 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 8586 APValue::LValueBase Base = LV.getLValueBase(); 8587 if (Base.isNull()) { 8588 // A null base is acceptable. 8589 return true; 8590 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 8591 if (!isa<StringLiteral>(E)) 8592 return false; 8593 return LV.getLValueOffset().isZero(); 8594 } else if (Base.is<TypeInfoLValue>()) { 8595 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 8596 // evaluate to true. 8597 return true; 8598 } else { 8599 // Any other base is not constant enough for GCC. 8600 return false; 8601 } 8602 } 8603 8604 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 8605 /// GCC as we can manage. 8606 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 8607 // This evaluation is not permitted to have side-effects, so evaluate it in 8608 // a speculative evaluation context. 8609 SpeculativeEvaluationRAII SpeculativeEval(Info); 8610 8611 // Constant-folding is always enabled for the operand of __builtin_constant_p 8612 // (even when the enclosing evaluation context otherwise requires a strict 8613 // language-specific constant expression). 8614 FoldConstant Fold(Info, true); 8615 8616 QualType ArgType = Arg->getType(); 8617 8618 // __builtin_constant_p always has one operand. The rules which gcc follows 8619 // are not precisely documented, but are as follows: 8620 // 8621 // - If the operand is of integral, floating, complex or enumeration type, 8622 // and can be folded to a known value of that type, it returns 1. 8623 // - If the operand can be folded to a pointer to the first character 8624 // of a string literal (or such a pointer cast to an integral type) 8625 // or to a null pointer or an integer cast to a pointer, it returns 1. 8626 // 8627 // Otherwise, it returns 0. 8628 // 8629 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 8630 // its support for this did not work prior to GCC 9 and is not yet well 8631 // understood. 8632 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 8633 ArgType->isAnyComplexType() || ArgType->isPointerType() || 8634 ArgType->isNullPtrType()) { 8635 APValue V; 8636 if (!::EvaluateAsRValue(Info, Arg, V)) { 8637 Fold.keepDiagnostics(); 8638 return false; 8639 } 8640 8641 // For a pointer (possibly cast to integer), there are special rules. 8642 if (V.getKind() == APValue::LValue) 8643 return EvaluateBuiltinConstantPForLValue(V); 8644 8645 // Otherwise, any constant value is good enough. 8646 return V.hasValue(); 8647 } 8648 8649 // Anything else isn't considered to be sufficiently constant. 8650 return false; 8651 } 8652 8653 /// Retrieves the "underlying object type" of the given expression, 8654 /// as used by __builtin_object_size. 8655 static QualType getObjectType(APValue::LValueBase B) { 8656 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 8657 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8658 return VD->getType(); 8659 } else if (const Expr *E = B.get<const Expr*>()) { 8660 if (isa<CompoundLiteralExpr>(E)) 8661 return E->getType(); 8662 } else if (B.is<TypeInfoLValue>()) { 8663 return B.getTypeInfoType(); 8664 } 8665 8666 return QualType(); 8667 } 8668 8669 /// A more selective version of E->IgnoreParenCasts for 8670 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 8671 /// to change the type of E. 8672 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 8673 /// 8674 /// Always returns an RValue with a pointer representation. 8675 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 8676 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8677 8678 auto *NoParens = E->IgnoreParens(); 8679 auto *Cast = dyn_cast<CastExpr>(NoParens); 8680 if (Cast == nullptr) 8681 return NoParens; 8682 8683 // We only conservatively allow a few kinds of casts, because this code is 8684 // inherently a simple solution that seeks to support the common case. 8685 auto CastKind = Cast->getCastKind(); 8686 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 8687 CastKind != CK_AddressSpaceConversion) 8688 return NoParens; 8689 8690 auto *SubExpr = Cast->getSubExpr(); 8691 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 8692 return NoParens; 8693 return ignorePointerCastsAndParens(SubExpr); 8694 } 8695 8696 /// Checks to see if the given LValue's Designator is at the end of the LValue's 8697 /// record layout. e.g. 8698 /// struct { struct { int a, b; } fst, snd; } obj; 8699 /// obj.fst // no 8700 /// obj.snd // yes 8701 /// obj.fst.a // no 8702 /// obj.fst.b // no 8703 /// obj.snd.a // no 8704 /// obj.snd.b // yes 8705 /// 8706 /// Please note: this function is specialized for how __builtin_object_size 8707 /// views "objects". 8708 /// 8709 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 8710 /// correct result, it will always return true. 8711 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 8712 assert(!LVal.Designator.Invalid); 8713 8714 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 8715 const RecordDecl *Parent = FD->getParent(); 8716 Invalid = Parent->isInvalidDecl(); 8717 if (Invalid || Parent->isUnion()) 8718 return true; 8719 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 8720 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 8721 }; 8722 8723 auto &Base = LVal.getLValueBase(); 8724 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 8725 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 8726 bool Invalid; 8727 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 8728 return Invalid; 8729 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 8730 for (auto *FD : IFD->chain()) { 8731 bool Invalid; 8732 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 8733 return Invalid; 8734 } 8735 } 8736 } 8737 8738 unsigned I = 0; 8739 QualType BaseType = getType(Base); 8740 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 8741 // If we don't know the array bound, conservatively assume we're looking at 8742 // the final array element. 8743 ++I; 8744 if (BaseType->isIncompleteArrayType()) 8745 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 8746 else 8747 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 8748 } 8749 8750 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 8751 const auto &Entry = LVal.Designator.Entries[I]; 8752 if (BaseType->isArrayType()) { 8753 // Because __builtin_object_size treats arrays as objects, we can ignore 8754 // the index iff this is the last array in the Designator. 8755 if (I + 1 == E) 8756 return true; 8757 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 8758 uint64_t Index = Entry.getAsArrayIndex(); 8759 if (Index + 1 != CAT->getSize()) 8760 return false; 8761 BaseType = CAT->getElementType(); 8762 } else if (BaseType->isAnyComplexType()) { 8763 const auto *CT = BaseType->castAs<ComplexType>(); 8764 uint64_t Index = Entry.getAsArrayIndex(); 8765 if (Index != 1) 8766 return false; 8767 BaseType = CT->getElementType(); 8768 } else if (auto *FD = getAsField(Entry)) { 8769 bool Invalid; 8770 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 8771 return Invalid; 8772 BaseType = FD->getType(); 8773 } else { 8774 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 8775 return false; 8776 } 8777 } 8778 return true; 8779 } 8780 8781 /// Tests to see if the LValue has a user-specified designator (that isn't 8782 /// necessarily valid). Note that this always returns 'true' if the LValue has 8783 /// an unsized array as its first designator entry, because there's currently no 8784 /// way to tell if the user typed *foo or foo[0]. 8785 static bool refersToCompleteObject(const LValue &LVal) { 8786 if (LVal.Designator.Invalid) 8787 return false; 8788 8789 if (!LVal.Designator.Entries.empty()) 8790 return LVal.Designator.isMostDerivedAnUnsizedArray(); 8791 8792 if (!LVal.InvalidBase) 8793 return true; 8794 8795 // If `E` is a MemberExpr, then the first part of the designator is hiding in 8796 // the LValueBase. 8797 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 8798 return !E || !isa<MemberExpr>(E); 8799 } 8800 8801 /// Attempts to detect a user writing into a piece of memory that's impossible 8802 /// to figure out the size of by just using types. 8803 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 8804 const SubobjectDesignator &Designator = LVal.Designator; 8805 // Notes: 8806 // - Users can only write off of the end when we have an invalid base. Invalid 8807 // bases imply we don't know where the memory came from. 8808 // - We used to be a bit more aggressive here; we'd only be conservative if 8809 // the array at the end was flexible, or if it had 0 or 1 elements. This 8810 // broke some common standard library extensions (PR30346), but was 8811 // otherwise seemingly fine. It may be useful to reintroduce this behavior 8812 // with some sort of whitelist. OTOH, it seems that GCC is always 8813 // conservative with the last element in structs (if it's an array), so our 8814 // current behavior is more compatible than a whitelisting approach would 8815 // be. 8816 return LVal.InvalidBase && 8817 Designator.Entries.size() == Designator.MostDerivedPathLength && 8818 Designator.MostDerivedIsArrayElement && 8819 isDesignatorAtObjectEnd(Ctx, LVal); 8820 } 8821 8822 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 8823 /// Fails if the conversion would cause loss of precision. 8824 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 8825 CharUnits &Result) { 8826 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 8827 if (Int.ugt(CharUnitsMax)) 8828 return false; 8829 Result = CharUnits::fromQuantity(Int.getZExtValue()); 8830 return true; 8831 } 8832 8833 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 8834 /// determine how many bytes exist from the beginning of the object to either 8835 /// the end of the current subobject, or the end of the object itself, depending 8836 /// on what the LValue looks like + the value of Type. 8837 /// 8838 /// If this returns false, the value of Result is undefined. 8839 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 8840 unsigned Type, const LValue &LVal, 8841 CharUnits &EndOffset) { 8842 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 8843 8844 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 8845 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 8846 return false; 8847 return HandleSizeof(Info, ExprLoc, Ty, Result); 8848 }; 8849 8850 // We want to evaluate the size of the entire object. This is a valid fallback 8851 // for when Type=1 and the designator is invalid, because we're asked for an 8852 // upper-bound. 8853 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 8854 // Type=3 wants a lower bound, so we can't fall back to this. 8855 if (Type == 3 && !DetermineForCompleteObject) 8856 return false; 8857 8858 llvm::APInt APEndOffset; 8859 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8860 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 8861 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 8862 8863 if (LVal.InvalidBase) 8864 return false; 8865 8866 QualType BaseTy = getObjectType(LVal.getLValueBase()); 8867 return CheckedHandleSizeof(BaseTy, EndOffset); 8868 } 8869 8870 // We want to evaluate the size of a subobject. 8871 const SubobjectDesignator &Designator = LVal.Designator; 8872 8873 // The following is a moderately common idiom in C: 8874 // 8875 // struct Foo { int a; char c[1]; }; 8876 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 8877 // strcpy(&F->c[0], Bar); 8878 // 8879 // In order to not break too much legacy code, we need to support it. 8880 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 8881 // If we can resolve this to an alloc_size call, we can hand that back, 8882 // because we know for certain how many bytes there are to write to. 8883 llvm::APInt APEndOffset; 8884 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8885 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 8886 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 8887 8888 // If we cannot determine the size of the initial allocation, then we can't 8889 // given an accurate upper-bound. However, we are still able to give 8890 // conservative lower-bounds for Type=3. 8891 if (Type == 1) 8892 return false; 8893 } 8894 8895 CharUnits BytesPerElem; 8896 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 8897 return false; 8898 8899 // According to the GCC documentation, we want the size of the subobject 8900 // denoted by the pointer. But that's not quite right -- what we actually 8901 // want is the size of the immediately-enclosing array, if there is one. 8902 int64_t ElemsRemaining; 8903 if (Designator.MostDerivedIsArrayElement && 8904 Designator.Entries.size() == Designator.MostDerivedPathLength) { 8905 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 8906 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 8907 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 8908 } else { 8909 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 8910 } 8911 8912 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 8913 return true; 8914 } 8915 8916 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 8917 /// returns true and stores the result in @p Size. 8918 /// 8919 /// If @p WasError is non-null, this will report whether the failure to evaluate 8920 /// is to be treated as an Error in IntExprEvaluator. 8921 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 8922 EvalInfo &Info, uint64_t &Size) { 8923 // Determine the denoted object. 8924 LValue LVal; 8925 { 8926 // The operand of __builtin_object_size is never evaluated for side-effects. 8927 // If there are any, but we can determine the pointed-to object anyway, then 8928 // ignore the side-effects. 8929 SpeculativeEvaluationRAII SpeculativeEval(Info); 8930 IgnoreSideEffectsRAII Fold(Info); 8931 8932 if (E->isGLValue()) { 8933 // It's possible for us to be given GLValues if we're called via 8934 // Expr::tryEvaluateObjectSize. 8935 APValue RVal; 8936 if (!EvaluateAsRValue(Info, E, RVal)) 8937 return false; 8938 LVal.setFrom(Info.Ctx, RVal); 8939 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 8940 /*InvalidBaseOK=*/true)) 8941 return false; 8942 } 8943 8944 // If we point to before the start of the object, there are no accessible 8945 // bytes. 8946 if (LVal.getLValueOffset().isNegative()) { 8947 Size = 0; 8948 return true; 8949 } 8950 8951 CharUnits EndOffset; 8952 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 8953 return false; 8954 8955 // If we've fallen outside of the end offset, just pretend there's nothing to 8956 // write to/read from. 8957 if (EndOffset <= LVal.getLValueOffset()) 8958 Size = 0; 8959 else 8960 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 8961 return true; 8962 } 8963 8964 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) { 8965 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true); 8966 if (E->getResultAPValueKind() != APValue::None) 8967 return Success(E->getAPValueResult(), E); 8968 return ExprEvaluatorBaseTy::VisitConstantExpr(E); 8969 } 8970 8971 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 8972 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8973 return VisitBuiltinCallExpr(E, BuiltinOp); 8974 8975 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8976 } 8977 8978 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8979 unsigned BuiltinOp) { 8980 switch (unsigned BuiltinOp = E->getBuiltinCallee()) { 8981 default: 8982 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8983 8984 case Builtin::BI__builtin_dynamic_object_size: 8985 case Builtin::BI__builtin_object_size: { 8986 // The type was checked when we built the expression. 8987 unsigned Type = 8988 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 8989 assert(Type <= 3 && "unexpected type"); 8990 8991 uint64_t Size; 8992 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 8993 return Success(Size, E); 8994 8995 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 8996 return Success((Type & 2) ? 0 : -1, E); 8997 8998 // Expression had no side effects, but we couldn't statically determine the 8999 // size of the referenced object. 9000 switch (Info.EvalMode) { 9001 case EvalInfo::EM_ConstantExpression: 9002 case EvalInfo::EM_PotentialConstantExpression: 9003 case EvalInfo::EM_ConstantFold: 9004 case EvalInfo::EM_EvaluateForOverflow: 9005 case EvalInfo::EM_IgnoreSideEffects: 9006 // Leave it to IR generation. 9007 return Error(E); 9008 case EvalInfo::EM_ConstantExpressionUnevaluated: 9009 case EvalInfo::EM_PotentialConstantExpressionUnevaluated: 9010 // Reduce it to a constant now. 9011 return Success((Type & 2) ? 0 : -1, E); 9012 } 9013 9014 llvm_unreachable("unexpected EvalMode"); 9015 } 9016 9017 case Builtin::BI__builtin_os_log_format_buffer_size: { 9018 analyze_os_log::OSLogBufferLayout Layout; 9019 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 9020 return Success(Layout.size().getQuantity(), E); 9021 } 9022 9023 case Builtin::BI__builtin_bswap16: 9024 case Builtin::BI__builtin_bswap32: 9025 case Builtin::BI__builtin_bswap64: { 9026 APSInt Val; 9027 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9028 return false; 9029 9030 return Success(Val.byteSwap(), E); 9031 } 9032 9033 case Builtin::BI__builtin_classify_type: 9034 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 9035 9036 case Builtin::BI__builtin_clrsb: 9037 case Builtin::BI__builtin_clrsbl: 9038 case Builtin::BI__builtin_clrsbll: { 9039 APSInt Val; 9040 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9041 return false; 9042 9043 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 9044 } 9045 9046 case Builtin::BI__builtin_clz: 9047 case Builtin::BI__builtin_clzl: 9048 case Builtin::BI__builtin_clzll: 9049 case Builtin::BI__builtin_clzs: { 9050 APSInt Val; 9051 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9052 return false; 9053 if (!Val) 9054 return Error(E); 9055 9056 return Success(Val.countLeadingZeros(), E); 9057 } 9058 9059 case Builtin::BI__builtin_constant_p: { 9060 const Expr *Arg = E->getArg(0); 9061 if (EvaluateBuiltinConstantP(Info, Arg)) 9062 return Success(true, E); 9063 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 9064 // Outside a constant context, eagerly evaluate to false in the presence 9065 // of side-effects in order to avoid -Wunsequenced false-positives in 9066 // a branch on __builtin_constant_p(expr). 9067 return Success(false, E); 9068 } 9069 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 9070 return false; 9071 } 9072 9073 case Builtin::BI__builtin_is_constant_evaluated: 9074 return Success(Info.InConstantContext, E); 9075 9076 case Builtin::BI__builtin_ctz: 9077 case Builtin::BI__builtin_ctzl: 9078 case Builtin::BI__builtin_ctzll: 9079 case Builtin::BI__builtin_ctzs: { 9080 APSInt Val; 9081 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9082 return false; 9083 if (!Val) 9084 return Error(E); 9085 9086 return Success(Val.countTrailingZeros(), E); 9087 } 9088 9089 case Builtin::BI__builtin_eh_return_data_regno: { 9090 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 9091 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 9092 return Success(Operand, E); 9093 } 9094 9095 case Builtin::BI__builtin_expect: 9096 return Visit(E->getArg(0)); 9097 9098 case Builtin::BI__builtin_ffs: 9099 case Builtin::BI__builtin_ffsl: 9100 case Builtin::BI__builtin_ffsll: { 9101 APSInt Val; 9102 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9103 return false; 9104 9105 unsigned N = Val.countTrailingZeros(); 9106 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 9107 } 9108 9109 case Builtin::BI__builtin_fpclassify: { 9110 APFloat Val(0.0); 9111 if (!EvaluateFloat(E->getArg(5), Val, Info)) 9112 return false; 9113 unsigned Arg; 9114 switch (Val.getCategory()) { 9115 case APFloat::fcNaN: Arg = 0; break; 9116 case APFloat::fcInfinity: Arg = 1; break; 9117 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 9118 case APFloat::fcZero: Arg = 4; break; 9119 } 9120 return Visit(E->getArg(Arg)); 9121 } 9122 9123 case Builtin::BI__builtin_isinf_sign: { 9124 APFloat Val(0.0); 9125 return EvaluateFloat(E->getArg(0), Val, Info) && 9126 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 9127 } 9128 9129 case Builtin::BI__builtin_isinf: { 9130 APFloat Val(0.0); 9131 return EvaluateFloat(E->getArg(0), Val, Info) && 9132 Success(Val.isInfinity() ? 1 : 0, E); 9133 } 9134 9135 case Builtin::BI__builtin_isfinite: { 9136 APFloat Val(0.0); 9137 return EvaluateFloat(E->getArg(0), Val, Info) && 9138 Success(Val.isFinite() ? 1 : 0, E); 9139 } 9140 9141 case Builtin::BI__builtin_isnan: { 9142 APFloat Val(0.0); 9143 return EvaluateFloat(E->getArg(0), Val, Info) && 9144 Success(Val.isNaN() ? 1 : 0, E); 9145 } 9146 9147 case Builtin::BI__builtin_isnormal: { 9148 APFloat Val(0.0); 9149 return EvaluateFloat(E->getArg(0), Val, Info) && 9150 Success(Val.isNormal() ? 1 : 0, E); 9151 } 9152 9153 case Builtin::BI__builtin_parity: 9154 case Builtin::BI__builtin_parityl: 9155 case Builtin::BI__builtin_parityll: { 9156 APSInt Val; 9157 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9158 return false; 9159 9160 return Success(Val.countPopulation() % 2, E); 9161 } 9162 9163 case Builtin::BI__builtin_popcount: 9164 case Builtin::BI__builtin_popcountl: 9165 case Builtin::BI__builtin_popcountll: { 9166 APSInt Val; 9167 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9168 return false; 9169 9170 return Success(Val.countPopulation(), E); 9171 } 9172 9173 case Builtin::BIstrlen: 9174 case Builtin::BIwcslen: 9175 // A call to strlen is not a constant expression. 9176 if (Info.getLangOpts().CPlusPlus11) 9177 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9178 << /*isConstexpr*/0 << /*isConstructor*/0 9179 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9180 else 9181 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9182 LLVM_FALLTHROUGH; 9183 case Builtin::BI__builtin_strlen: 9184 case Builtin::BI__builtin_wcslen: { 9185 // As an extension, we support __builtin_strlen() as a constant expression, 9186 // and support folding strlen() to a constant. 9187 LValue String; 9188 if (!EvaluatePointer(E->getArg(0), String, Info)) 9189 return false; 9190 9191 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 9192 9193 // Fast path: if it's a string literal, search the string value. 9194 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 9195 String.getLValueBase().dyn_cast<const Expr *>())) { 9196 // The string literal may have embedded null characters. Find the first 9197 // one and truncate there. 9198 StringRef Str = S->getBytes(); 9199 int64_t Off = String.Offset.getQuantity(); 9200 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 9201 S->getCharByteWidth() == 1 && 9202 // FIXME: Add fast-path for wchar_t too. 9203 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 9204 Str = Str.substr(Off); 9205 9206 StringRef::size_type Pos = Str.find(0); 9207 if (Pos != StringRef::npos) 9208 Str = Str.substr(0, Pos); 9209 9210 return Success(Str.size(), E); 9211 } 9212 9213 // Fall through to slow path to issue appropriate diagnostic. 9214 } 9215 9216 // Slow path: scan the bytes of the string looking for the terminating 0. 9217 for (uint64_t Strlen = 0; /**/; ++Strlen) { 9218 APValue Char; 9219 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 9220 !Char.isInt()) 9221 return false; 9222 if (!Char.getInt()) 9223 return Success(Strlen, E); 9224 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 9225 return false; 9226 } 9227 } 9228 9229 case Builtin::BIstrcmp: 9230 case Builtin::BIwcscmp: 9231 case Builtin::BIstrncmp: 9232 case Builtin::BIwcsncmp: 9233 case Builtin::BImemcmp: 9234 case Builtin::BIbcmp: 9235 case Builtin::BIwmemcmp: 9236 // A call to strlen is not a constant expression. 9237 if (Info.getLangOpts().CPlusPlus11) 9238 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9239 << /*isConstexpr*/0 << /*isConstructor*/0 9240 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9241 else 9242 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9243 LLVM_FALLTHROUGH; 9244 case Builtin::BI__builtin_strcmp: 9245 case Builtin::BI__builtin_wcscmp: 9246 case Builtin::BI__builtin_strncmp: 9247 case Builtin::BI__builtin_wcsncmp: 9248 case Builtin::BI__builtin_memcmp: 9249 case Builtin::BI__builtin_bcmp: 9250 case Builtin::BI__builtin_wmemcmp: { 9251 LValue String1, String2; 9252 if (!EvaluatePointer(E->getArg(0), String1, Info) || 9253 !EvaluatePointer(E->getArg(1), String2, Info)) 9254 return false; 9255 9256 uint64_t MaxLength = uint64_t(-1); 9257 if (BuiltinOp != Builtin::BIstrcmp && 9258 BuiltinOp != Builtin::BIwcscmp && 9259 BuiltinOp != Builtin::BI__builtin_strcmp && 9260 BuiltinOp != Builtin::BI__builtin_wcscmp) { 9261 APSInt N; 9262 if (!EvaluateInteger(E->getArg(2), N, Info)) 9263 return false; 9264 MaxLength = N.getExtValue(); 9265 } 9266 9267 // Empty substrings compare equal by definition. 9268 if (MaxLength == 0u) 9269 return Success(0, E); 9270 9271 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9272 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9273 String1.Designator.Invalid || String2.Designator.Invalid) 9274 return false; 9275 9276 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 9277 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 9278 9279 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 9280 BuiltinOp == Builtin::BIbcmp || 9281 BuiltinOp == Builtin::BI__builtin_memcmp || 9282 BuiltinOp == Builtin::BI__builtin_bcmp; 9283 9284 assert(IsRawByte || 9285 (Info.Ctx.hasSameUnqualifiedType( 9286 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 9287 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 9288 9289 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 9290 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 9291 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 9292 Char1.isInt() && Char2.isInt(); 9293 }; 9294 const auto &AdvanceElems = [&] { 9295 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 9296 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 9297 }; 9298 9299 if (IsRawByte) { 9300 uint64_t BytesRemaining = MaxLength; 9301 // Pointers to const void may point to objects of incomplete type. 9302 if (CharTy1->isIncompleteType()) { 9303 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1; 9304 return false; 9305 } 9306 if (CharTy2->isIncompleteType()) { 9307 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2; 9308 return false; 9309 } 9310 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)}; 9311 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width); 9312 // Give up on comparing between elements with disparate widths. 9313 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2)) 9314 return false; 9315 uint64_t BytesPerElement = CharTy1Size.getQuantity(); 9316 assert(BytesRemaining && "BytesRemaining should not be zero: the " 9317 "following loop considers at least one element"); 9318 while (true) { 9319 APValue Char1, Char2; 9320 if (!ReadCurElems(Char1, Char2)) 9321 return false; 9322 // We have compatible in-memory widths, but a possible type and 9323 // (for `bool`) internal representation mismatch. 9324 // Assuming two's complement representation, including 0 for `false` and 9325 // 1 for `true`, we can check an appropriate number of elements for 9326 // equality even if they are not byte-sized. 9327 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width); 9328 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width); 9329 if (Char1InMem.ne(Char2InMem)) { 9330 // If the elements are byte-sized, then we can produce a three-way 9331 // comparison result in a straightforward manner. 9332 if (BytesPerElement == 1u) { 9333 // memcmp always compares unsigned chars. 9334 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E); 9335 } 9336 // The result is byte-order sensitive, and we have multibyte elements. 9337 // FIXME: We can compare the remaining bytes in the correct order. 9338 return false; 9339 } 9340 if (!AdvanceElems()) 9341 return false; 9342 if (BytesRemaining <= BytesPerElement) 9343 break; 9344 BytesRemaining -= BytesPerElement; 9345 } 9346 // Enough elements are equal to account for the memcmp limit. 9347 return Success(0, E); 9348 } 9349 9350 bool StopAtNull = 9351 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 9352 BuiltinOp != Builtin::BIwmemcmp && 9353 BuiltinOp != Builtin::BI__builtin_memcmp && 9354 BuiltinOp != Builtin::BI__builtin_bcmp && 9355 BuiltinOp != Builtin::BI__builtin_wmemcmp); 9356 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 9357 BuiltinOp == Builtin::BIwcsncmp || 9358 BuiltinOp == Builtin::BIwmemcmp || 9359 BuiltinOp == Builtin::BI__builtin_wcscmp || 9360 BuiltinOp == Builtin::BI__builtin_wcsncmp || 9361 BuiltinOp == Builtin::BI__builtin_wmemcmp; 9362 9363 for (; MaxLength; --MaxLength) { 9364 APValue Char1, Char2; 9365 if (!ReadCurElems(Char1, Char2)) 9366 return false; 9367 if (Char1.getInt() != Char2.getInt()) { 9368 if (IsWide) // wmemcmp compares with wchar_t signedness. 9369 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 9370 // memcmp always compares unsigned chars. 9371 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 9372 } 9373 if (StopAtNull && !Char1.getInt()) 9374 return Success(0, E); 9375 assert(!(StopAtNull && !Char2.getInt())); 9376 if (!AdvanceElems()) 9377 return false; 9378 } 9379 // We hit the strncmp / memcmp limit. 9380 return Success(0, E); 9381 } 9382 9383 case Builtin::BI__atomic_always_lock_free: 9384 case Builtin::BI__atomic_is_lock_free: 9385 case Builtin::BI__c11_atomic_is_lock_free: { 9386 APSInt SizeVal; 9387 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 9388 return false; 9389 9390 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 9391 // of two less than the maximum inline atomic width, we know it is 9392 // lock-free. If the size isn't a power of two, or greater than the 9393 // maximum alignment where we promote atomics, we know it is not lock-free 9394 // (at least not in the sense of atomic_is_lock_free). Otherwise, 9395 // the answer can only be determined at runtime; for example, 16-byte 9396 // atomics have lock-free implementations on some, but not all, 9397 // x86-64 processors. 9398 9399 // Check power-of-two. 9400 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 9401 if (Size.isPowerOfTwo()) { 9402 // Check against inlining width. 9403 unsigned InlineWidthBits = 9404 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 9405 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 9406 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 9407 Size == CharUnits::One() || 9408 E->getArg(1)->isNullPointerConstant(Info.Ctx, 9409 Expr::NPC_NeverValueDependent)) 9410 // OK, we will inline appropriately-aligned operations of this size, 9411 // and _Atomic(T) is appropriately-aligned. 9412 return Success(1, E); 9413 9414 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 9415 castAs<PointerType>()->getPointeeType(); 9416 if (!PointeeType->isIncompleteType() && 9417 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 9418 // OK, we will inline operations on this object. 9419 return Success(1, E); 9420 } 9421 } 9422 } 9423 9424 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 9425 Success(0, E) : Error(E); 9426 } 9427 case Builtin::BIomp_is_initial_device: 9428 // We can decide statically which value the runtime would return if called. 9429 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 9430 case Builtin::BI__builtin_add_overflow: 9431 case Builtin::BI__builtin_sub_overflow: 9432 case Builtin::BI__builtin_mul_overflow: 9433 case Builtin::BI__builtin_sadd_overflow: 9434 case Builtin::BI__builtin_uadd_overflow: 9435 case Builtin::BI__builtin_uaddl_overflow: 9436 case Builtin::BI__builtin_uaddll_overflow: 9437 case Builtin::BI__builtin_usub_overflow: 9438 case Builtin::BI__builtin_usubl_overflow: 9439 case Builtin::BI__builtin_usubll_overflow: 9440 case Builtin::BI__builtin_umul_overflow: 9441 case Builtin::BI__builtin_umull_overflow: 9442 case Builtin::BI__builtin_umulll_overflow: 9443 case Builtin::BI__builtin_saddl_overflow: 9444 case Builtin::BI__builtin_saddll_overflow: 9445 case Builtin::BI__builtin_ssub_overflow: 9446 case Builtin::BI__builtin_ssubl_overflow: 9447 case Builtin::BI__builtin_ssubll_overflow: 9448 case Builtin::BI__builtin_smul_overflow: 9449 case Builtin::BI__builtin_smull_overflow: 9450 case Builtin::BI__builtin_smulll_overflow: { 9451 LValue ResultLValue; 9452 APSInt LHS, RHS; 9453 9454 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 9455 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 9456 !EvaluateInteger(E->getArg(1), RHS, Info) || 9457 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 9458 return false; 9459 9460 APSInt Result; 9461 bool DidOverflow = false; 9462 9463 // If the types don't have to match, enlarge all 3 to the largest of them. 9464 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 9465 BuiltinOp == Builtin::BI__builtin_sub_overflow || 9466 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 9467 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 9468 ResultType->isSignedIntegerOrEnumerationType(); 9469 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 9470 ResultType->isSignedIntegerOrEnumerationType(); 9471 uint64_t LHSSize = LHS.getBitWidth(); 9472 uint64_t RHSSize = RHS.getBitWidth(); 9473 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 9474 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 9475 9476 // Add an additional bit if the signedness isn't uniformly agreed to. We 9477 // could do this ONLY if there is a signed and an unsigned that both have 9478 // MaxBits, but the code to check that is pretty nasty. The issue will be 9479 // caught in the shrink-to-result later anyway. 9480 if (IsSigned && !AllSigned) 9481 ++MaxBits; 9482 9483 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 9484 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 9485 Result = APSInt(MaxBits, !IsSigned); 9486 } 9487 9488 // Find largest int. 9489 switch (BuiltinOp) { 9490 default: 9491 llvm_unreachable("Invalid value for BuiltinOp"); 9492 case Builtin::BI__builtin_add_overflow: 9493 case Builtin::BI__builtin_sadd_overflow: 9494 case Builtin::BI__builtin_saddl_overflow: 9495 case Builtin::BI__builtin_saddll_overflow: 9496 case Builtin::BI__builtin_uadd_overflow: 9497 case Builtin::BI__builtin_uaddl_overflow: 9498 case Builtin::BI__builtin_uaddll_overflow: 9499 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 9500 : LHS.uadd_ov(RHS, DidOverflow); 9501 break; 9502 case Builtin::BI__builtin_sub_overflow: 9503 case Builtin::BI__builtin_ssub_overflow: 9504 case Builtin::BI__builtin_ssubl_overflow: 9505 case Builtin::BI__builtin_ssubll_overflow: 9506 case Builtin::BI__builtin_usub_overflow: 9507 case Builtin::BI__builtin_usubl_overflow: 9508 case Builtin::BI__builtin_usubll_overflow: 9509 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 9510 : LHS.usub_ov(RHS, DidOverflow); 9511 break; 9512 case Builtin::BI__builtin_mul_overflow: 9513 case Builtin::BI__builtin_smul_overflow: 9514 case Builtin::BI__builtin_smull_overflow: 9515 case Builtin::BI__builtin_smulll_overflow: 9516 case Builtin::BI__builtin_umul_overflow: 9517 case Builtin::BI__builtin_umull_overflow: 9518 case Builtin::BI__builtin_umulll_overflow: 9519 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 9520 : LHS.umul_ov(RHS, DidOverflow); 9521 break; 9522 } 9523 9524 // In the case where multiple sizes are allowed, truncate and see if 9525 // the values are the same. 9526 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 9527 BuiltinOp == Builtin::BI__builtin_sub_overflow || 9528 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 9529 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 9530 // since it will give us the behavior of a TruncOrSelf in the case where 9531 // its parameter <= its size. We previously set Result to be at least the 9532 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 9533 // will work exactly like TruncOrSelf. 9534 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 9535 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 9536 9537 if (!APSInt::isSameValue(Temp, Result)) 9538 DidOverflow = true; 9539 Result = Temp; 9540 } 9541 9542 APValue APV{Result}; 9543 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 9544 return false; 9545 return Success(DidOverflow, E); 9546 } 9547 } 9548 } 9549 9550 /// Determine whether this is a pointer past the end of the complete 9551 /// object referred to by the lvalue. 9552 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 9553 const LValue &LV) { 9554 // A null pointer can be viewed as being "past the end" but we don't 9555 // choose to look at it that way here. 9556 if (!LV.getLValueBase()) 9557 return false; 9558 9559 // If the designator is valid and refers to a subobject, we're not pointing 9560 // past the end. 9561 if (!LV.getLValueDesignator().Invalid && 9562 !LV.getLValueDesignator().isOnePastTheEnd()) 9563 return false; 9564 9565 // A pointer to an incomplete type might be past-the-end if the type's size is 9566 // zero. We cannot tell because the type is incomplete. 9567 QualType Ty = getType(LV.getLValueBase()); 9568 if (Ty->isIncompleteType()) 9569 return true; 9570 9571 // We're a past-the-end pointer if we point to the byte after the object, 9572 // no matter what our type or path is. 9573 auto Size = Ctx.getTypeSizeInChars(Ty); 9574 return LV.getLValueOffset() == Size; 9575 } 9576 9577 namespace { 9578 9579 /// Data recursive integer evaluator of certain binary operators. 9580 /// 9581 /// We use a data recursive algorithm for binary operators so that we are able 9582 /// to handle extreme cases of chained binary operators without causing stack 9583 /// overflow. 9584 class DataRecursiveIntBinOpEvaluator { 9585 struct EvalResult { 9586 APValue Val; 9587 bool Failed; 9588 9589 EvalResult() : Failed(false) { } 9590 9591 void swap(EvalResult &RHS) { 9592 Val.swap(RHS.Val); 9593 Failed = RHS.Failed; 9594 RHS.Failed = false; 9595 } 9596 }; 9597 9598 struct Job { 9599 const Expr *E; 9600 EvalResult LHSResult; // meaningful only for binary operator expression. 9601 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 9602 9603 Job() = default; 9604 Job(Job &&) = default; 9605 9606 void startSpeculativeEval(EvalInfo &Info) { 9607 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 9608 } 9609 9610 private: 9611 SpeculativeEvaluationRAII SpecEvalRAII; 9612 }; 9613 9614 SmallVector<Job, 16> Queue; 9615 9616 IntExprEvaluator &IntEval; 9617 EvalInfo &Info; 9618 APValue &FinalResult; 9619 9620 public: 9621 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 9622 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 9623 9624 /// True if \param E is a binary operator that we are going to handle 9625 /// data recursively. 9626 /// We handle binary operators that are comma, logical, or that have operands 9627 /// with integral or enumeration type. 9628 static bool shouldEnqueue(const BinaryOperator *E) { 9629 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 9630 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 9631 E->getLHS()->getType()->isIntegralOrEnumerationType() && 9632 E->getRHS()->getType()->isIntegralOrEnumerationType()); 9633 } 9634 9635 bool Traverse(const BinaryOperator *E) { 9636 enqueue(E); 9637 EvalResult PrevResult; 9638 while (!Queue.empty()) 9639 process(PrevResult); 9640 9641 if (PrevResult.Failed) return false; 9642 9643 FinalResult.swap(PrevResult.Val); 9644 return true; 9645 } 9646 9647 private: 9648 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 9649 return IntEval.Success(Value, E, Result); 9650 } 9651 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 9652 return IntEval.Success(Value, E, Result); 9653 } 9654 bool Error(const Expr *E) { 9655 return IntEval.Error(E); 9656 } 9657 bool Error(const Expr *E, diag::kind D) { 9658 return IntEval.Error(E, D); 9659 } 9660 9661 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 9662 return Info.CCEDiag(E, D); 9663 } 9664 9665 // Returns true if visiting the RHS is necessary, false otherwise. 9666 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 9667 bool &SuppressRHSDiags); 9668 9669 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 9670 const BinaryOperator *E, APValue &Result); 9671 9672 void EvaluateExpr(const Expr *E, EvalResult &Result) { 9673 Result.Failed = !Evaluate(Result.Val, Info, E); 9674 if (Result.Failed) 9675 Result.Val = APValue(); 9676 } 9677 9678 void process(EvalResult &Result); 9679 9680 void enqueue(const Expr *E) { 9681 E = E->IgnoreParens(); 9682 Queue.resize(Queue.size()+1); 9683 Queue.back().E = E; 9684 Queue.back().Kind = Job::AnyExprKind; 9685 } 9686 }; 9687 9688 } 9689 9690 bool DataRecursiveIntBinOpEvaluator:: 9691 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 9692 bool &SuppressRHSDiags) { 9693 if (E->getOpcode() == BO_Comma) { 9694 // Ignore LHS but note if we could not evaluate it. 9695 if (LHSResult.Failed) 9696 return Info.noteSideEffect(); 9697 return true; 9698 } 9699 9700 if (E->isLogicalOp()) { 9701 bool LHSAsBool; 9702 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 9703 // We were able to evaluate the LHS, see if we can get away with not 9704 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 9705 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 9706 Success(LHSAsBool, E, LHSResult.Val); 9707 return false; // Ignore RHS 9708 } 9709 } else { 9710 LHSResult.Failed = true; 9711 9712 // Since we weren't able to evaluate the left hand side, it 9713 // might have had side effects. 9714 if (!Info.noteSideEffect()) 9715 return false; 9716 9717 // We can't evaluate the LHS; however, sometimes the result 9718 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 9719 // Don't ignore RHS and suppress diagnostics from this arm. 9720 SuppressRHSDiags = true; 9721 } 9722 9723 return true; 9724 } 9725 9726 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 9727 E->getRHS()->getType()->isIntegralOrEnumerationType()); 9728 9729 if (LHSResult.Failed && !Info.noteFailure()) 9730 return false; // Ignore RHS; 9731 9732 return true; 9733 } 9734 9735 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 9736 bool IsSub) { 9737 // Compute the new offset in the appropriate width, wrapping at 64 bits. 9738 // FIXME: When compiling for a 32-bit target, we should use 32-bit 9739 // offsets. 9740 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 9741 CharUnits &Offset = LVal.getLValueOffset(); 9742 uint64_t Offset64 = Offset.getQuantity(); 9743 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 9744 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 9745 : Offset64 + Index64); 9746 } 9747 9748 bool DataRecursiveIntBinOpEvaluator:: 9749 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 9750 const BinaryOperator *E, APValue &Result) { 9751 if (E->getOpcode() == BO_Comma) { 9752 if (RHSResult.Failed) 9753 return false; 9754 Result = RHSResult.Val; 9755 return true; 9756 } 9757 9758 if (E->isLogicalOp()) { 9759 bool lhsResult, rhsResult; 9760 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 9761 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 9762 9763 if (LHSIsOK) { 9764 if (RHSIsOK) { 9765 if (E->getOpcode() == BO_LOr) 9766 return Success(lhsResult || rhsResult, E, Result); 9767 else 9768 return Success(lhsResult && rhsResult, E, Result); 9769 } 9770 } else { 9771 if (RHSIsOK) { 9772 // We can't evaluate the LHS; however, sometimes the result 9773 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 9774 if (rhsResult == (E->getOpcode() == BO_LOr)) 9775 return Success(rhsResult, E, Result); 9776 } 9777 } 9778 9779 return false; 9780 } 9781 9782 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 9783 E->getRHS()->getType()->isIntegralOrEnumerationType()); 9784 9785 if (LHSResult.Failed || RHSResult.Failed) 9786 return false; 9787 9788 const APValue &LHSVal = LHSResult.Val; 9789 const APValue &RHSVal = RHSResult.Val; 9790 9791 // Handle cases like (unsigned long)&a + 4. 9792 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 9793 Result = LHSVal; 9794 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 9795 return true; 9796 } 9797 9798 // Handle cases like 4 + (unsigned long)&a 9799 if (E->getOpcode() == BO_Add && 9800 RHSVal.isLValue() && LHSVal.isInt()) { 9801 Result = RHSVal; 9802 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 9803 return true; 9804 } 9805 9806 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 9807 // Handle (intptr_t)&&A - (intptr_t)&&B. 9808 if (!LHSVal.getLValueOffset().isZero() || 9809 !RHSVal.getLValueOffset().isZero()) 9810 return false; 9811 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 9812 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 9813 if (!LHSExpr || !RHSExpr) 9814 return false; 9815 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 9816 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 9817 if (!LHSAddrExpr || !RHSAddrExpr) 9818 return false; 9819 // Make sure both labels come from the same function. 9820 if (LHSAddrExpr->getLabel()->getDeclContext() != 9821 RHSAddrExpr->getLabel()->getDeclContext()) 9822 return false; 9823 Result = APValue(LHSAddrExpr, RHSAddrExpr); 9824 return true; 9825 } 9826 9827 // All the remaining cases expect both operands to be an integer 9828 if (!LHSVal.isInt() || !RHSVal.isInt()) 9829 return Error(E); 9830 9831 // Set up the width and signedness manually, in case it can't be deduced 9832 // from the operation we're performing. 9833 // FIXME: Don't do this in the cases where we can deduce it. 9834 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 9835 E->getType()->isUnsignedIntegerOrEnumerationType()); 9836 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 9837 RHSVal.getInt(), Value)) 9838 return false; 9839 return Success(Value, E, Result); 9840 } 9841 9842 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 9843 Job &job = Queue.back(); 9844 9845 switch (job.Kind) { 9846 case Job::AnyExprKind: { 9847 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 9848 if (shouldEnqueue(Bop)) { 9849 job.Kind = Job::BinOpKind; 9850 enqueue(Bop->getLHS()); 9851 return; 9852 } 9853 } 9854 9855 EvaluateExpr(job.E, Result); 9856 Queue.pop_back(); 9857 return; 9858 } 9859 9860 case Job::BinOpKind: { 9861 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 9862 bool SuppressRHSDiags = false; 9863 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 9864 Queue.pop_back(); 9865 return; 9866 } 9867 if (SuppressRHSDiags) 9868 job.startSpeculativeEval(Info); 9869 job.LHSResult.swap(Result); 9870 job.Kind = Job::BinOpVisitedLHSKind; 9871 enqueue(Bop->getRHS()); 9872 return; 9873 } 9874 9875 case Job::BinOpVisitedLHSKind: { 9876 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 9877 EvalResult RHS; 9878 RHS.swap(Result); 9879 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 9880 Queue.pop_back(); 9881 return; 9882 } 9883 } 9884 9885 llvm_unreachable("Invalid Job::Kind!"); 9886 } 9887 9888 namespace { 9889 /// Used when we determine that we should fail, but can keep evaluating prior to 9890 /// noting that we had a failure. 9891 class DelayedNoteFailureRAII { 9892 EvalInfo &Info; 9893 bool NoteFailure; 9894 9895 public: 9896 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 9897 : Info(Info), NoteFailure(NoteFailure) {} 9898 ~DelayedNoteFailureRAII() { 9899 if (NoteFailure) { 9900 bool ContinueAfterFailure = Info.noteFailure(); 9901 (void)ContinueAfterFailure; 9902 assert(ContinueAfterFailure && 9903 "Shouldn't have kept evaluating on failure."); 9904 } 9905 } 9906 }; 9907 } 9908 9909 template <class SuccessCB, class AfterCB> 9910 static bool 9911 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 9912 SuccessCB &&Success, AfterCB &&DoAfter) { 9913 assert(E->isComparisonOp() && "expected comparison operator"); 9914 assert((E->getOpcode() == BO_Cmp || 9915 E->getType()->isIntegralOrEnumerationType()) && 9916 "unsupported binary expression evaluation"); 9917 auto Error = [&](const Expr *E) { 9918 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 9919 return false; 9920 }; 9921 9922 using CCR = ComparisonCategoryResult; 9923 bool IsRelational = E->isRelationalOp(); 9924 bool IsEquality = E->isEqualityOp(); 9925 if (E->getOpcode() == BO_Cmp) { 9926 const ComparisonCategoryInfo &CmpInfo = 9927 Info.Ctx.CompCategories.getInfoForType(E->getType()); 9928 IsRelational = CmpInfo.isOrdered(); 9929 IsEquality = CmpInfo.isEquality(); 9930 } 9931 9932 QualType LHSTy = E->getLHS()->getType(); 9933 QualType RHSTy = E->getRHS()->getType(); 9934 9935 if (LHSTy->isIntegralOrEnumerationType() && 9936 RHSTy->isIntegralOrEnumerationType()) { 9937 APSInt LHS, RHS; 9938 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 9939 if (!LHSOK && !Info.noteFailure()) 9940 return false; 9941 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 9942 return false; 9943 if (LHS < RHS) 9944 return Success(CCR::Less, E); 9945 if (LHS > RHS) 9946 return Success(CCR::Greater, E); 9947 return Success(CCR::Equal, E); 9948 } 9949 9950 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 9951 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 9952 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 9953 9954 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 9955 if (!LHSOK && !Info.noteFailure()) 9956 return false; 9957 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 9958 return false; 9959 if (LHSFX < RHSFX) 9960 return Success(CCR::Less, E); 9961 if (LHSFX > RHSFX) 9962 return Success(CCR::Greater, E); 9963 return Success(CCR::Equal, E); 9964 } 9965 9966 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 9967 ComplexValue LHS, RHS; 9968 bool LHSOK; 9969 if (E->isAssignmentOp()) { 9970 LValue LV; 9971 EvaluateLValue(E->getLHS(), LV, Info); 9972 LHSOK = false; 9973 } else if (LHSTy->isRealFloatingType()) { 9974 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 9975 if (LHSOK) { 9976 LHS.makeComplexFloat(); 9977 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 9978 } 9979 } else { 9980 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 9981 } 9982 if (!LHSOK && !Info.noteFailure()) 9983 return false; 9984 9985 if (E->getRHS()->getType()->isRealFloatingType()) { 9986 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 9987 return false; 9988 RHS.makeComplexFloat(); 9989 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 9990 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 9991 return false; 9992 9993 if (LHS.isComplexFloat()) { 9994 APFloat::cmpResult CR_r = 9995 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 9996 APFloat::cmpResult CR_i = 9997 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 9998 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 9999 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 10000 } else { 10001 assert(IsEquality && "invalid complex comparison"); 10002 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 10003 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 10004 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 10005 } 10006 } 10007 10008 if (LHSTy->isRealFloatingType() && 10009 RHSTy->isRealFloatingType()) { 10010 APFloat RHS(0.0), LHS(0.0); 10011 10012 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 10013 if (!LHSOK && !Info.noteFailure()) 10014 return false; 10015 10016 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 10017 return false; 10018 10019 assert(E->isComparisonOp() && "Invalid binary operator!"); 10020 auto GetCmpRes = [&]() { 10021 switch (LHS.compare(RHS)) { 10022 case APFloat::cmpEqual: 10023 return CCR::Equal; 10024 case APFloat::cmpLessThan: 10025 return CCR::Less; 10026 case APFloat::cmpGreaterThan: 10027 return CCR::Greater; 10028 case APFloat::cmpUnordered: 10029 return CCR::Unordered; 10030 } 10031 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 10032 }; 10033 return Success(GetCmpRes(), E); 10034 } 10035 10036 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 10037 LValue LHSValue, RHSValue; 10038 10039 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 10040 if (!LHSOK && !Info.noteFailure()) 10041 return false; 10042 10043 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 10044 return false; 10045 10046 // Reject differing bases from the normal codepath; we special-case 10047 // comparisons to null. 10048 if (!HasSameBase(LHSValue, RHSValue)) { 10049 // Inequalities and subtractions between unrelated pointers have 10050 // unspecified or undefined behavior. 10051 if (!IsEquality) 10052 return Error(E); 10053 // A constant address may compare equal to the address of a symbol. 10054 // The one exception is that address of an object cannot compare equal 10055 // to a null pointer constant. 10056 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 10057 (!RHSValue.Base && !RHSValue.Offset.isZero())) 10058 return Error(E); 10059 // It's implementation-defined whether distinct literals will have 10060 // distinct addresses. In clang, the result of such a comparison is 10061 // unspecified, so it is not a constant expression. However, we do know 10062 // that the address of a literal will be non-null. 10063 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 10064 LHSValue.Base && RHSValue.Base) 10065 return Error(E); 10066 // We can't tell whether weak symbols will end up pointing to the same 10067 // object. 10068 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 10069 return Error(E); 10070 // We can't compare the address of the start of one object with the 10071 // past-the-end address of another object, per C++ DR1652. 10072 if ((LHSValue.Base && LHSValue.Offset.isZero() && 10073 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 10074 (RHSValue.Base && RHSValue.Offset.isZero() && 10075 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 10076 return Error(E); 10077 // We can't tell whether an object is at the same address as another 10078 // zero sized object. 10079 if ((RHSValue.Base && isZeroSized(LHSValue)) || 10080 (LHSValue.Base && isZeroSized(RHSValue))) 10081 return Error(E); 10082 return Success(CCR::Nonequal, E); 10083 } 10084 10085 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 10086 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 10087 10088 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 10089 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 10090 10091 // C++11 [expr.rel]p3: 10092 // Pointers to void (after pointer conversions) can be compared, with a 10093 // result defined as follows: If both pointers represent the same 10094 // address or are both the null pointer value, the result is true if the 10095 // operator is <= or >= and false otherwise; otherwise the result is 10096 // unspecified. 10097 // We interpret this as applying to pointers to *cv* void. 10098 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 10099 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 10100 10101 // C++11 [expr.rel]p2: 10102 // - If two pointers point to non-static data members of the same object, 10103 // or to subobjects or array elements fo such members, recursively, the 10104 // pointer to the later declared member compares greater provided the 10105 // two members have the same access control and provided their class is 10106 // not a union. 10107 // [...] 10108 // - Otherwise pointer comparisons are unspecified. 10109 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 10110 bool WasArrayIndex; 10111 unsigned Mismatch = FindDesignatorMismatch( 10112 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 10113 // At the point where the designators diverge, the comparison has a 10114 // specified value if: 10115 // - we are comparing array indices 10116 // - we are comparing fields of a union, or fields with the same access 10117 // Otherwise, the result is unspecified and thus the comparison is not a 10118 // constant expression. 10119 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 10120 Mismatch < RHSDesignator.Entries.size()) { 10121 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 10122 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 10123 if (!LF && !RF) 10124 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 10125 else if (!LF) 10126 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 10127 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 10128 << RF->getParent() << RF; 10129 else if (!RF) 10130 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 10131 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 10132 << LF->getParent() << LF; 10133 else if (!LF->getParent()->isUnion() && 10134 LF->getAccess() != RF->getAccess()) 10135 Info.CCEDiag(E, 10136 diag::note_constexpr_pointer_comparison_differing_access) 10137 << LF << LF->getAccess() << RF << RF->getAccess() 10138 << LF->getParent(); 10139 } 10140 } 10141 10142 // The comparison here must be unsigned, and performed with the same 10143 // width as the pointer. 10144 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 10145 uint64_t CompareLHS = LHSOffset.getQuantity(); 10146 uint64_t CompareRHS = RHSOffset.getQuantity(); 10147 assert(PtrSize <= 64 && "Unexpected pointer width"); 10148 uint64_t Mask = ~0ULL >> (64 - PtrSize); 10149 CompareLHS &= Mask; 10150 CompareRHS &= Mask; 10151 10152 // If there is a base and this is a relational operator, we can only 10153 // compare pointers within the object in question; otherwise, the result 10154 // depends on where the object is located in memory. 10155 if (!LHSValue.Base.isNull() && IsRelational) { 10156 QualType BaseTy = getType(LHSValue.Base); 10157 if (BaseTy->isIncompleteType()) 10158 return Error(E); 10159 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 10160 uint64_t OffsetLimit = Size.getQuantity(); 10161 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 10162 return Error(E); 10163 } 10164 10165 if (CompareLHS < CompareRHS) 10166 return Success(CCR::Less, E); 10167 if (CompareLHS > CompareRHS) 10168 return Success(CCR::Greater, E); 10169 return Success(CCR::Equal, E); 10170 } 10171 10172 if (LHSTy->isMemberPointerType()) { 10173 assert(IsEquality && "unexpected member pointer operation"); 10174 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 10175 10176 MemberPtr LHSValue, RHSValue; 10177 10178 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 10179 if (!LHSOK && !Info.noteFailure()) 10180 return false; 10181 10182 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 10183 return false; 10184 10185 // C++11 [expr.eq]p2: 10186 // If both operands are null, they compare equal. Otherwise if only one is 10187 // null, they compare unequal. 10188 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 10189 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 10190 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 10191 } 10192 10193 // Otherwise if either is a pointer to a virtual member function, the 10194 // result is unspecified. 10195 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 10196 if (MD->isVirtual()) 10197 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 10198 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 10199 if (MD->isVirtual()) 10200 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 10201 10202 // Otherwise they compare equal if and only if they would refer to the 10203 // same member of the same most derived object or the same subobject if 10204 // they were dereferenced with a hypothetical object of the associated 10205 // class type. 10206 bool Equal = LHSValue == RHSValue; 10207 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 10208 } 10209 10210 if (LHSTy->isNullPtrType()) { 10211 assert(E->isComparisonOp() && "unexpected nullptr operation"); 10212 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 10213 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 10214 // are compared, the result is true of the operator is <=, >= or ==, and 10215 // false otherwise. 10216 return Success(CCR::Equal, E); 10217 } 10218 10219 return DoAfter(); 10220 } 10221 10222 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 10223 if (!CheckLiteralType(Info, E)) 10224 return false; 10225 10226 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 10227 const BinaryOperator *E) { 10228 // Evaluation succeeded. Lookup the information for the comparison category 10229 // type and fetch the VarDecl for the result. 10230 const ComparisonCategoryInfo &CmpInfo = 10231 Info.Ctx.CompCategories.getInfoForType(E->getType()); 10232 const VarDecl *VD = 10233 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD; 10234 // Check and evaluate the result as a constant expression. 10235 LValue LV; 10236 LV.set(VD); 10237 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 10238 return false; 10239 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 10240 }; 10241 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 10242 return ExprEvaluatorBaseTy::VisitBinCmp(E); 10243 }); 10244 } 10245 10246 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10247 // We don't call noteFailure immediately because the assignment happens after 10248 // we evaluate LHS and RHS. 10249 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 10250 return Error(E); 10251 10252 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 10253 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 10254 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 10255 10256 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 10257 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 10258 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 10259 10260 if (E->isComparisonOp()) { 10261 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way 10262 // comparisons and then translating the result. 10263 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 10264 const BinaryOperator *E) { 10265 using CCR = ComparisonCategoryResult; 10266 bool IsEqual = ResKind == CCR::Equal, 10267 IsLess = ResKind == CCR::Less, 10268 IsGreater = ResKind == CCR::Greater; 10269 auto Op = E->getOpcode(); 10270 switch (Op) { 10271 default: 10272 llvm_unreachable("unsupported binary operator"); 10273 case BO_EQ: 10274 case BO_NE: 10275 return Success(IsEqual == (Op == BO_EQ), E); 10276 case BO_LT: return Success(IsLess, E); 10277 case BO_GT: return Success(IsGreater, E); 10278 case BO_LE: return Success(IsEqual || IsLess, E); 10279 case BO_GE: return Success(IsEqual || IsGreater, E); 10280 } 10281 }; 10282 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 10283 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10284 }); 10285 } 10286 10287 QualType LHSTy = E->getLHS()->getType(); 10288 QualType RHSTy = E->getRHS()->getType(); 10289 10290 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 10291 E->getOpcode() == BO_Sub) { 10292 LValue LHSValue, RHSValue; 10293 10294 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 10295 if (!LHSOK && !Info.noteFailure()) 10296 return false; 10297 10298 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 10299 return false; 10300 10301 // Reject differing bases from the normal codepath; we special-case 10302 // comparisons to null. 10303 if (!HasSameBase(LHSValue, RHSValue)) { 10304 // Handle &&A - &&B. 10305 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 10306 return Error(E); 10307 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 10308 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 10309 if (!LHSExpr || !RHSExpr) 10310 return Error(E); 10311 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 10312 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 10313 if (!LHSAddrExpr || !RHSAddrExpr) 10314 return Error(E); 10315 // Make sure both labels come from the same function. 10316 if (LHSAddrExpr->getLabel()->getDeclContext() != 10317 RHSAddrExpr->getLabel()->getDeclContext()) 10318 return Error(E); 10319 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 10320 } 10321 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 10322 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 10323 10324 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 10325 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 10326 10327 // C++11 [expr.add]p6: 10328 // Unless both pointers point to elements of the same array object, or 10329 // one past the last element of the array object, the behavior is 10330 // undefined. 10331 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 10332 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 10333 RHSDesignator)) 10334 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 10335 10336 QualType Type = E->getLHS()->getType(); 10337 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 10338 10339 CharUnits ElementSize; 10340 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 10341 return false; 10342 10343 // As an extension, a type may have zero size (empty struct or union in 10344 // C, array of zero length). Pointer subtraction in such cases has 10345 // undefined behavior, so is not constant. 10346 if (ElementSize.isZero()) { 10347 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 10348 << ElementType; 10349 return false; 10350 } 10351 10352 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 10353 // and produce incorrect results when it overflows. Such behavior 10354 // appears to be non-conforming, but is common, so perhaps we should 10355 // assume the standard intended for such cases to be undefined behavior 10356 // and check for them. 10357 10358 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 10359 // overflow in the final conversion to ptrdiff_t. 10360 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 10361 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 10362 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 10363 false); 10364 APSInt TrueResult = (LHS - RHS) / ElemSize; 10365 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 10366 10367 if (Result.extend(65) != TrueResult && 10368 !HandleOverflow(Info, E, TrueResult, E->getType())) 10369 return false; 10370 return Success(Result, E); 10371 } 10372 10373 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10374 } 10375 10376 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 10377 /// a result as the expression's type. 10378 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 10379 const UnaryExprOrTypeTraitExpr *E) { 10380 switch(E->getKind()) { 10381 case UETT_PreferredAlignOf: 10382 case UETT_AlignOf: { 10383 if (E->isArgumentType()) 10384 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 10385 E); 10386 else 10387 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 10388 E); 10389 } 10390 10391 case UETT_VecStep: { 10392 QualType Ty = E->getTypeOfArgument(); 10393 10394 if (Ty->isVectorType()) { 10395 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 10396 10397 // The vec_step built-in functions that take a 3-component 10398 // vector return 4. (OpenCL 1.1 spec 6.11.12) 10399 if (n == 3) 10400 n = 4; 10401 10402 return Success(n, E); 10403 } else 10404 return Success(1, E); 10405 } 10406 10407 case UETT_SizeOf: { 10408 QualType SrcTy = E->getTypeOfArgument(); 10409 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 10410 // the result is the size of the referenced type." 10411 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 10412 SrcTy = Ref->getPointeeType(); 10413 10414 CharUnits Sizeof; 10415 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 10416 return false; 10417 return Success(Sizeof, E); 10418 } 10419 case UETT_OpenMPRequiredSimdAlign: 10420 assert(E->isArgumentType()); 10421 return Success( 10422 Info.Ctx.toCharUnitsFromBits( 10423 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 10424 .getQuantity(), 10425 E); 10426 } 10427 10428 llvm_unreachable("unknown expr/type trait"); 10429 } 10430 10431 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 10432 CharUnits Result; 10433 unsigned n = OOE->getNumComponents(); 10434 if (n == 0) 10435 return Error(OOE); 10436 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 10437 for (unsigned i = 0; i != n; ++i) { 10438 OffsetOfNode ON = OOE->getComponent(i); 10439 switch (ON.getKind()) { 10440 case OffsetOfNode::Array: { 10441 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 10442 APSInt IdxResult; 10443 if (!EvaluateInteger(Idx, IdxResult, Info)) 10444 return false; 10445 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 10446 if (!AT) 10447 return Error(OOE); 10448 CurrentType = AT->getElementType(); 10449 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 10450 Result += IdxResult.getSExtValue() * ElementSize; 10451 break; 10452 } 10453 10454 case OffsetOfNode::Field: { 10455 FieldDecl *MemberDecl = ON.getField(); 10456 const RecordType *RT = CurrentType->getAs<RecordType>(); 10457 if (!RT) 10458 return Error(OOE); 10459 RecordDecl *RD = RT->getDecl(); 10460 if (RD->isInvalidDecl()) return false; 10461 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 10462 unsigned i = MemberDecl->getFieldIndex(); 10463 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 10464 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 10465 CurrentType = MemberDecl->getType().getNonReferenceType(); 10466 break; 10467 } 10468 10469 case OffsetOfNode::Identifier: 10470 llvm_unreachable("dependent __builtin_offsetof"); 10471 10472 case OffsetOfNode::Base: { 10473 CXXBaseSpecifier *BaseSpec = ON.getBase(); 10474 if (BaseSpec->isVirtual()) 10475 return Error(OOE); 10476 10477 // Find the layout of the class whose base we are looking into. 10478 const RecordType *RT = CurrentType->getAs<RecordType>(); 10479 if (!RT) 10480 return Error(OOE); 10481 RecordDecl *RD = RT->getDecl(); 10482 if (RD->isInvalidDecl()) return false; 10483 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 10484 10485 // Find the base class itself. 10486 CurrentType = BaseSpec->getType(); 10487 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 10488 if (!BaseRT) 10489 return Error(OOE); 10490 10491 // Add the offset to the base. 10492 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 10493 break; 10494 } 10495 } 10496 } 10497 return Success(Result, OOE); 10498 } 10499 10500 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10501 switch (E->getOpcode()) { 10502 default: 10503 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 10504 // See C99 6.6p3. 10505 return Error(E); 10506 case UO_Extension: 10507 // FIXME: Should extension allow i-c-e extension expressions in its scope? 10508 // If so, we could clear the diagnostic ID. 10509 return Visit(E->getSubExpr()); 10510 case UO_Plus: 10511 // The result is just the value. 10512 return Visit(E->getSubExpr()); 10513 case UO_Minus: { 10514 if (!Visit(E->getSubExpr())) 10515 return false; 10516 if (!Result.isInt()) return Error(E); 10517 const APSInt &Value = Result.getInt(); 10518 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 10519 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 10520 E->getType())) 10521 return false; 10522 return Success(-Value, E); 10523 } 10524 case UO_Not: { 10525 if (!Visit(E->getSubExpr())) 10526 return false; 10527 if (!Result.isInt()) return Error(E); 10528 return Success(~Result.getInt(), E); 10529 } 10530 case UO_LNot: { 10531 bool bres; 10532 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 10533 return false; 10534 return Success(!bres, E); 10535 } 10536 } 10537 } 10538 10539 /// HandleCast - This is used to evaluate implicit or explicit casts where the 10540 /// result type is integer. 10541 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 10542 const Expr *SubExpr = E->getSubExpr(); 10543 QualType DestType = E->getType(); 10544 QualType SrcType = SubExpr->getType(); 10545 10546 switch (E->getCastKind()) { 10547 case CK_BaseToDerived: 10548 case CK_DerivedToBase: 10549 case CK_UncheckedDerivedToBase: 10550 case CK_Dynamic: 10551 case CK_ToUnion: 10552 case CK_ArrayToPointerDecay: 10553 case CK_FunctionToPointerDecay: 10554 case CK_NullToPointer: 10555 case CK_NullToMemberPointer: 10556 case CK_BaseToDerivedMemberPointer: 10557 case CK_DerivedToBaseMemberPointer: 10558 case CK_ReinterpretMemberPointer: 10559 case CK_ConstructorConversion: 10560 case CK_IntegralToPointer: 10561 case CK_ToVoid: 10562 case CK_VectorSplat: 10563 case CK_IntegralToFloating: 10564 case CK_FloatingCast: 10565 case CK_CPointerToObjCPointerCast: 10566 case CK_BlockPointerToObjCPointerCast: 10567 case CK_AnyPointerToBlockPointerCast: 10568 case CK_ObjCObjectLValueCast: 10569 case CK_FloatingRealToComplex: 10570 case CK_FloatingComplexToReal: 10571 case CK_FloatingComplexCast: 10572 case CK_FloatingComplexToIntegralComplex: 10573 case CK_IntegralRealToComplex: 10574 case CK_IntegralComplexCast: 10575 case CK_IntegralComplexToFloatingComplex: 10576 case CK_BuiltinFnToFnPtr: 10577 case CK_ZeroToOCLOpaqueType: 10578 case CK_NonAtomicToAtomic: 10579 case CK_AddressSpaceConversion: 10580 case CK_IntToOCLSampler: 10581 case CK_FixedPointCast: 10582 case CK_IntegralToFixedPoint: 10583 llvm_unreachable("invalid cast kind for integral value"); 10584 10585 case CK_BitCast: 10586 case CK_Dependent: 10587 case CK_LValueBitCast: 10588 case CK_ARCProduceObject: 10589 case CK_ARCConsumeObject: 10590 case CK_ARCReclaimReturnedObject: 10591 case CK_ARCExtendBlockObject: 10592 case CK_CopyAndAutoreleaseBlockObject: 10593 return Error(E); 10594 10595 case CK_UserDefinedConversion: 10596 case CK_LValueToRValue: 10597 case CK_AtomicToNonAtomic: 10598 case CK_NoOp: 10599 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10600 10601 case CK_MemberPointerToBoolean: 10602 case CK_PointerToBoolean: 10603 case CK_IntegralToBoolean: 10604 case CK_FloatingToBoolean: 10605 case CK_BooleanToSignedIntegral: 10606 case CK_FloatingComplexToBoolean: 10607 case CK_IntegralComplexToBoolean: { 10608 bool BoolResult; 10609 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 10610 return false; 10611 uint64_t IntResult = BoolResult; 10612 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 10613 IntResult = (uint64_t)-1; 10614 return Success(IntResult, E); 10615 } 10616 10617 case CK_FixedPointToIntegral: { 10618 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 10619 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 10620 return false; 10621 bool Overflowed; 10622 llvm::APSInt Result = Src.convertToInt( 10623 Info.Ctx.getIntWidth(DestType), 10624 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 10625 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 10626 return false; 10627 return Success(Result, E); 10628 } 10629 10630 case CK_FixedPointToBoolean: { 10631 // Unsigned padding does not affect this. 10632 APValue Val; 10633 if (!Evaluate(Val, Info, SubExpr)) 10634 return false; 10635 return Success(Val.getFixedPoint().getBoolValue(), E); 10636 } 10637 10638 case CK_IntegralCast: { 10639 if (!Visit(SubExpr)) 10640 return false; 10641 10642 if (!Result.isInt()) { 10643 // Allow casts of address-of-label differences if they are no-ops 10644 // or narrowing. (The narrowing case isn't actually guaranteed to 10645 // be constant-evaluatable except in some narrow cases which are hard 10646 // to detect here. We let it through on the assumption the user knows 10647 // what they are doing.) 10648 if (Result.isAddrLabelDiff()) 10649 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 10650 // Only allow casts of lvalues if they are lossless. 10651 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 10652 } 10653 10654 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 10655 Result.getInt()), E); 10656 } 10657 10658 case CK_PointerToIntegral: { 10659 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 10660 10661 LValue LV; 10662 if (!EvaluatePointer(SubExpr, LV, Info)) 10663 return false; 10664 10665 if (LV.getLValueBase()) { 10666 // Only allow based lvalue casts if they are lossless. 10667 // FIXME: Allow a larger integer size than the pointer size, and allow 10668 // narrowing back down to pointer width in subsequent integral casts. 10669 // FIXME: Check integer type's active bits, not its type size. 10670 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 10671 return Error(E); 10672 10673 LV.Designator.setInvalid(); 10674 LV.moveInto(Result); 10675 return true; 10676 } 10677 10678 APSInt AsInt; 10679 APValue V; 10680 LV.moveInto(V); 10681 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 10682 llvm_unreachable("Can't cast this!"); 10683 10684 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 10685 } 10686 10687 case CK_IntegralComplexToReal: { 10688 ComplexValue C; 10689 if (!EvaluateComplex(SubExpr, C, Info)) 10690 return false; 10691 return Success(C.getComplexIntReal(), E); 10692 } 10693 10694 case CK_FloatingToIntegral: { 10695 APFloat F(0.0); 10696 if (!EvaluateFloat(SubExpr, F, Info)) 10697 return false; 10698 10699 APSInt Value; 10700 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 10701 return false; 10702 return Success(Value, E); 10703 } 10704 } 10705 10706 llvm_unreachable("unknown cast resulting in integral value"); 10707 } 10708 10709 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 10710 if (E->getSubExpr()->getType()->isAnyComplexType()) { 10711 ComplexValue LV; 10712 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 10713 return false; 10714 if (!LV.isComplexInt()) 10715 return Error(E); 10716 return Success(LV.getComplexIntReal(), E); 10717 } 10718 10719 return Visit(E->getSubExpr()); 10720 } 10721 10722 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10723 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 10724 ComplexValue LV; 10725 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 10726 return false; 10727 if (!LV.isComplexInt()) 10728 return Error(E); 10729 return Success(LV.getComplexIntImag(), E); 10730 } 10731 10732 VisitIgnoredValue(E->getSubExpr()); 10733 return Success(0, E); 10734 } 10735 10736 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 10737 return Success(E->getPackLength(), E); 10738 } 10739 10740 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 10741 return Success(E->getValue(), E); 10742 } 10743 10744 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10745 switch (E->getOpcode()) { 10746 default: 10747 // Invalid unary operators 10748 return Error(E); 10749 case UO_Plus: 10750 // The result is just the value. 10751 return Visit(E->getSubExpr()); 10752 case UO_Minus: { 10753 if (!Visit(E->getSubExpr())) return false; 10754 if (!Result.isFixedPoint()) 10755 return Error(E); 10756 bool Overflowed; 10757 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 10758 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 10759 return false; 10760 return Success(Negated, E); 10761 } 10762 case UO_LNot: { 10763 bool bres; 10764 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 10765 return false; 10766 return Success(!bres, E); 10767 } 10768 } 10769 } 10770 10771 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 10772 const Expr *SubExpr = E->getSubExpr(); 10773 QualType DestType = E->getType(); 10774 assert(DestType->isFixedPointType() && 10775 "Expected destination type to be a fixed point type"); 10776 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 10777 10778 switch (E->getCastKind()) { 10779 case CK_FixedPointCast: { 10780 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 10781 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 10782 return false; 10783 bool Overflowed; 10784 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 10785 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 10786 return false; 10787 return Success(Result, E); 10788 } 10789 case CK_IntegralToFixedPoint: { 10790 APSInt Src; 10791 if (!EvaluateInteger(SubExpr, Src, Info)) 10792 return false; 10793 10794 bool Overflowed; 10795 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 10796 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 10797 10798 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType)) 10799 return false; 10800 10801 return Success(IntResult, E); 10802 } 10803 case CK_NoOp: 10804 case CK_LValueToRValue: 10805 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10806 default: 10807 return Error(E); 10808 } 10809 } 10810 10811 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10812 const Expr *LHS = E->getLHS(); 10813 const Expr *RHS = E->getRHS(); 10814 FixedPointSemantics ResultFXSema = 10815 Info.Ctx.getFixedPointSemantics(E->getType()); 10816 10817 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 10818 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 10819 return false; 10820 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 10821 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 10822 return false; 10823 10824 switch (E->getOpcode()) { 10825 case BO_Add: { 10826 bool AddOverflow, ConversionOverflow; 10827 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow) 10828 .convert(ResultFXSema, &ConversionOverflow); 10829 if ((AddOverflow || ConversionOverflow) && 10830 !HandleOverflow(Info, E, Result, E->getType())) 10831 return false; 10832 return Success(Result, E); 10833 } 10834 default: 10835 return false; 10836 } 10837 llvm_unreachable("Should've exited before this"); 10838 } 10839 10840 //===----------------------------------------------------------------------===// 10841 // Float Evaluation 10842 //===----------------------------------------------------------------------===// 10843 10844 namespace { 10845 class FloatExprEvaluator 10846 : public ExprEvaluatorBase<FloatExprEvaluator> { 10847 APFloat &Result; 10848 public: 10849 FloatExprEvaluator(EvalInfo &info, APFloat &result) 10850 : ExprEvaluatorBaseTy(info), Result(result) {} 10851 10852 bool Success(const APValue &V, const Expr *e) { 10853 Result = V.getFloat(); 10854 return true; 10855 } 10856 10857 bool ZeroInitialization(const Expr *E) { 10858 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 10859 return true; 10860 } 10861 10862 bool VisitCallExpr(const CallExpr *E); 10863 10864 bool VisitUnaryOperator(const UnaryOperator *E); 10865 bool VisitBinaryOperator(const BinaryOperator *E); 10866 bool VisitFloatingLiteral(const FloatingLiteral *E); 10867 bool VisitCastExpr(const CastExpr *E); 10868 10869 bool VisitUnaryReal(const UnaryOperator *E); 10870 bool VisitUnaryImag(const UnaryOperator *E); 10871 10872 // FIXME: Missing: array subscript of vector, member of vector 10873 }; 10874 } // end anonymous namespace 10875 10876 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 10877 assert(E->isRValue() && E->getType()->isRealFloatingType()); 10878 return FloatExprEvaluator(Info, Result).Visit(E); 10879 } 10880 10881 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 10882 QualType ResultTy, 10883 const Expr *Arg, 10884 bool SNaN, 10885 llvm::APFloat &Result) { 10886 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 10887 if (!S) return false; 10888 10889 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 10890 10891 llvm::APInt fill; 10892 10893 // Treat empty strings as if they were zero. 10894 if (S->getString().empty()) 10895 fill = llvm::APInt(32, 0); 10896 else if (S->getString().getAsInteger(0, fill)) 10897 return false; 10898 10899 if (Context.getTargetInfo().isNan2008()) { 10900 if (SNaN) 10901 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 10902 else 10903 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 10904 } else { 10905 // Prior to IEEE 754-2008, architectures were allowed to choose whether 10906 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 10907 // a different encoding to what became a standard in 2008, and for pre- 10908 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 10909 // sNaN. This is now known as "legacy NaN" encoding. 10910 if (SNaN) 10911 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 10912 else 10913 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 10914 } 10915 10916 return true; 10917 } 10918 10919 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 10920 switch (E->getBuiltinCallee()) { 10921 default: 10922 return ExprEvaluatorBaseTy::VisitCallExpr(E); 10923 10924 case Builtin::BI__builtin_huge_val: 10925 case Builtin::BI__builtin_huge_valf: 10926 case Builtin::BI__builtin_huge_vall: 10927 case Builtin::BI__builtin_huge_valf128: 10928 case Builtin::BI__builtin_inf: 10929 case Builtin::BI__builtin_inff: 10930 case Builtin::BI__builtin_infl: 10931 case Builtin::BI__builtin_inff128: { 10932 const llvm::fltSemantics &Sem = 10933 Info.Ctx.getFloatTypeSemantics(E->getType()); 10934 Result = llvm::APFloat::getInf(Sem); 10935 return true; 10936 } 10937 10938 case Builtin::BI__builtin_nans: 10939 case Builtin::BI__builtin_nansf: 10940 case Builtin::BI__builtin_nansl: 10941 case Builtin::BI__builtin_nansf128: 10942 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 10943 true, Result)) 10944 return Error(E); 10945 return true; 10946 10947 case Builtin::BI__builtin_nan: 10948 case Builtin::BI__builtin_nanf: 10949 case Builtin::BI__builtin_nanl: 10950 case Builtin::BI__builtin_nanf128: 10951 // If this is __builtin_nan() turn this into a nan, otherwise we 10952 // can't constant fold it. 10953 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 10954 false, Result)) 10955 return Error(E); 10956 return true; 10957 10958 case Builtin::BI__builtin_fabs: 10959 case Builtin::BI__builtin_fabsf: 10960 case Builtin::BI__builtin_fabsl: 10961 case Builtin::BI__builtin_fabsf128: 10962 if (!EvaluateFloat(E->getArg(0), Result, Info)) 10963 return false; 10964 10965 if (Result.isNegative()) 10966 Result.changeSign(); 10967 return true; 10968 10969 // FIXME: Builtin::BI__builtin_powi 10970 // FIXME: Builtin::BI__builtin_powif 10971 // FIXME: Builtin::BI__builtin_powil 10972 10973 case Builtin::BI__builtin_copysign: 10974 case Builtin::BI__builtin_copysignf: 10975 case Builtin::BI__builtin_copysignl: 10976 case Builtin::BI__builtin_copysignf128: { 10977 APFloat RHS(0.); 10978 if (!EvaluateFloat(E->getArg(0), Result, Info) || 10979 !EvaluateFloat(E->getArg(1), RHS, Info)) 10980 return false; 10981 Result.copySign(RHS); 10982 return true; 10983 } 10984 } 10985 } 10986 10987 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 10988 if (E->getSubExpr()->getType()->isAnyComplexType()) { 10989 ComplexValue CV; 10990 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 10991 return false; 10992 Result = CV.FloatReal; 10993 return true; 10994 } 10995 10996 return Visit(E->getSubExpr()); 10997 } 10998 10999 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 11000 if (E->getSubExpr()->getType()->isAnyComplexType()) { 11001 ComplexValue CV; 11002 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 11003 return false; 11004 Result = CV.FloatImag; 11005 return true; 11006 } 11007 11008 VisitIgnoredValue(E->getSubExpr()); 11009 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 11010 Result = llvm::APFloat::getZero(Sem); 11011 return true; 11012 } 11013 11014 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 11015 switch (E->getOpcode()) { 11016 default: return Error(E); 11017 case UO_Plus: 11018 return EvaluateFloat(E->getSubExpr(), Result, Info); 11019 case UO_Minus: 11020 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 11021 return false; 11022 Result.changeSign(); 11023 return true; 11024 } 11025 } 11026 11027 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 11028 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 11029 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 11030 11031 APFloat RHS(0.0); 11032 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 11033 if (!LHSOK && !Info.noteFailure()) 11034 return false; 11035 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 11036 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 11037 } 11038 11039 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 11040 Result = E->getValue(); 11041 return true; 11042 } 11043 11044 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 11045 const Expr* SubExpr = E->getSubExpr(); 11046 11047 switch (E->getCastKind()) { 11048 default: 11049 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11050 11051 case CK_IntegralToFloating: { 11052 APSInt IntResult; 11053 return EvaluateInteger(SubExpr, IntResult, Info) && 11054 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 11055 E->getType(), Result); 11056 } 11057 11058 case CK_FloatingCast: { 11059 if (!Visit(SubExpr)) 11060 return false; 11061 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 11062 Result); 11063 } 11064 11065 case CK_FloatingComplexToReal: { 11066 ComplexValue V; 11067 if (!EvaluateComplex(SubExpr, V, Info)) 11068 return false; 11069 Result = V.getComplexFloatReal(); 11070 return true; 11071 } 11072 } 11073 } 11074 11075 //===----------------------------------------------------------------------===// 11076 // Complex Evaluation (for float and integer) 11077 //===----------------------------------------------------------------------===// 11078 11079 namespace { 11080 class ComplexExprEvaluator 11081 : public ExprEvaluatorBase<ComplexExprEvaluator> { 11082 ComplexValue &Result; 11083 11084 public: 11085 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 11086 : ExprEvaluatorBaseTy(info), Result(Result) {} 11087 11088 bool Success(const APValue &V, const Expr *e) { 11089 Result.setFrom(V); 11090 return true; 11091 } 11092 11093 bool ZeroInitialization(const Expr *E); 11094 11095 //===--------------------------------------------------------------------===// 11096 // Visitor Methods 11097 //===--------------------------------------------------------------------===// 11098 11099 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 11100 bool VisitCastExpr(const CastExpr *E); 11101 bool VisitBinaryOperator(const BinaryOperator *E); 11102 bool VisitUnaryOperator(const UnaryOperator *E); 11103 bool VisitInitListExpr(const InitListExpr *E); 11104 }; 11105 } // end anonymous namespace 11106 11107 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 11108 EvalInfo &Info) { 11109 assert(E->isRValue() && E->getType()->isAnyComplexType()); 11110 return ComplexExprEvaluator(Info, Result).Visit(E); 11111 } 11112 11113 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 11114 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 11115 if (ElemTy->isRealFloatingType()) { 11116 Result.makeComplexFloat(); 11117 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 11118 Result.FloatReal = Zero; 11119 Result.FloatImag = Zero; 11120 } else { 11121 Result.makeComplexInt(); 11122 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 11123 Result.IntReal = Zero; 11124 Result.IntImag = Zero; 11125 } 11126 return true; 11127 } 11128 11129 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 11130 const Expr* SubExpr = E->getSubExpr(); 11131 11132 if (SubExpr->getType()->isRealFloatingType()) { 11133 Result.makeComplexFloat(); 11134 APFloat &Imag = Result.FloatImag; 11135 if (!EvaluateFloat(SubExpr, Imag, Info)) 11136 return false; 11137 11138 Result.FloatReal = APFloat(Imag.getSemantics()); 11139 return true; 11140 } else { 11141 assert(SubExpr->getType()->isIntegerType() && 11142 "Unexpected imaginary literal."); 11143 11144 Result.makeComplexInt(); 11145 APSInt &Imag = Result.IntImag; 11146 if (!EvaluateInteger(SubExpr, Imag, Info)) 11147 return false; 11148 11149 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 11150 return true; 11151 } 11152 } 11153 11154 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 11155 11156 switch (E->getCastKind()) { 11157 case CK_BitCast: 11158 case CK_BaseToDerived: 11159 case CK_DerivedToBase: 11160 case CK_UncheckedDerivedToBase: 11161 case CK_Dynamic: 11162 case CK_ToUnion: 11163 case CK_ArrayToPointerDecay: 11164 case CK_FunctionToPointerDecay: 11165 case CK_NullToPointer: 11166 case CK_NullToMemberPointer: 11167 case CK_BaseToDerivedMemberPointer: 11168 case CK_DerivedToBaseMemberPointer: 11169 case CK_MemberPointerToBoolean: 11170 case CK_ReinterpretMemberPointer: 11171 case CK_ConstructorConversion: 11172 case CK_IntegralToPointer: 11173 case CK_PointerToIntegral: 11174 case CK_PointerToBoolean: 11175 case CK_ToVoid: 11176 case CK_VectorSplat: 11177 case CK_IntegralCast: 11178 case CK_BooleanToSignedIntegral: 11179 case CK_IntegralToBoolean: 11180 case CK_IntegralToFloating: 11181 case CK_FloatingToIntegral: 11182 case CK_FloatingToBoolean: 11183 case CK_FloatingCast: 11184 case CK_CPointerToObjCPointerCast: 11185 case CK_BlockPointerToObjCPointerCast: 11186 case CK_AnyPointerToBlockPointerCast: 11187 case CK_ObjCObjectLValueCast: 11188 case CK_FloatingComplexToReal: 11189 case CK_FloatingComplexToBoolean: 11190 case CK_IntegralComplexToReal: 11191 case CK_IntegralComplexToBoolean: 11192 case CK_ARCProduceObject: 11193 case CK_ARCConsumeObject: 11194 case CK_ARCReclaimReturnedObject: 11195 case CK_ARCExtendBlockObject: 11196 case CK_CopyAndAutoreleaseBlockObject: 11197 case CK_BuiltinFnToFnPtr: 11198 case CK_ZeroToOCLOpaqueType: 11199 case CK_NonAtomicToAtomic: 11200 case CK_AddressSpaceConversion: 11201 case CK_IntToOCLSampler: 11202 case CK_FixedPointCast: 11203 case CK_FixedPointToBoolean: 11204 case CK_FixedPointToIntegral: 11205 case CK_IntegralToFixedPoint: 11206 llvm_unreachable("invalid cast kind for complex value"); 11207 11208 case CK_LValueToRValue: 11209 case CK_AtomicToNonAtomic: 11210 case CK_NoOp: 11211 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11212 11213 case CK_Dependent: 11214 case CK_LValueBitCast: 11215 case CK_UserDefinedConversion: 11216 return Error(E); 11217 11218 case CK_FloatingRealToComplex: { 11219 APFloat &Real = Result.FloatReal; 11220 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 11221 return false; 11222 11223 Result.makeComplexFloat(); 11224 Result.FloatImag = APFloat(Real.getSemantics()); 11225 return true; 11226 } 11227 11228 case CK_FloatingComplexCast: { 11229 if (!Visit(E->getSubExpr())) 11230 return false; 11231 11232 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 11233 QualType From 11234 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 11235 11236 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 11237 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 11238 } 11239 11240 case CK_FloatingComplexToIntegralComplex: { 11241 if (!Visit(E->getSubExpr())) 11242 return false; 11243 11244 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 11245 QualType From 11246 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 11247 Result.makeComplexInt(); 11248 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 11249 To, Result.IntReal) && 11250 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 11251 To, Result.IntImag); 11252 } 11253 11254 case CK_IntegralRealToComplex: { 11255 APSInt &Real = Result.IntReal; 11256 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 11257 return false; 11258 11259 Result.makeComplexInt(); 11260 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 11261 return true; 11262 } 11263 11264 case CK_IntegralComplexCast: { 11265 if (!Visit(E->getSubExpr())) 11266 return false; 11267 11268 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 11269 QualType From 11270 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 11271 11272 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 11273 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 11274 return true; 11275 } 11276 11277 case CK_IntegralComplexToFloatingComplex: { 11278 if (!Visit(E->getSubExpr())) 11279 return false; 11280 11281 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 11282 QualType From 11283 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 11284 Result.makeComplexFloat(); 11285 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 11286 To, Result.FloatReal) && 11287 HandleIntToFloatCast(Info, E, From, Result.IntImag, 11288 To, Result.FloatImag); 11289 } 11290 } 11291 11292 llvm_unreachable("unknown cast resulting in complex value"); 11293 } 11294 11295 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 11296 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 11297 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 11298 11299 // Track whether the LHS or RHS is real at the type system level. When this is 11300 // the case we can simplify our evaluation strategy. 11301 bool LHSReal = false, RHSReal = false; 11302 11303 bool LHSOK; 11304 if (E->getLHS()->getType()->isRealFloatingType()) { 11305 LHSReal = true; 11306 APFloat &Real = Result.FloatReal; 11307 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 11308 if (LHSOK) { 11309 Result.makeComplexFloat(); 11310 Result.FloatImag = APFloat(Real.getSemantics()); 11311 } 11312 } else { 11313 LHSOK = Visit(E->getLHS()); 11314 } 11315 if (!LHSOK && !Info.noteFailure()) 11316 return false; 11317 11318 ComplexValue RHS; 11319 if (E->getRHS()->getType()->isRealFloatingType()) { 11320 RHSReal = true; 11321 APFloat &Real = RHS.FloatReal; 11322 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 11323 return false; 11324 RHS.makeComplexFloat(); 11325 RHS.FloatImag = APFloat(Real.getSemantics()); 11326 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 11327 return false; 11328 11329 assert(!(LHSReal && RHSReal) && 11330 "Cannot have both operands of a complex operation be real."); 11331 switch (E->getOpcode()) { 11332 default: return Error(E); 11333 case BO_Add: 11334 if (Result.isComplexFloat()) { 11335 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 11336 APFloat::rmNearestTiesToEven); 11337 if (LHSReal) 11338 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 11339 else if (!RHSReal) 11340 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 11341 APFloat::rmNearestTiesToEven); 11342 } else { 11343 Result.getComplexIntReal() += RHS.getComplexIntReal(); 11344 Result.getComplexIntImag() += RHS.getComplexIntImag(); 11345 } 11346 break; 11347 case BO_Sub: 11348 if (Result.isComplexFloat()) { 11349 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 11350 APFloat::rmNearestTiesToEven); 11351 if (LHSReal) { 11352 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 11353 Result.getComplexFloatImag().changeSign(); 11354 } else if (!RHSReal) { 11355 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 11356 APFloat::rmNearestTiesToEven); 11357 } 11358 } else { 11359 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 11360 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 11361 } 11362 break; 11363 case BO_Mul: 11364 if (Result.isComplexFloat()) { 11365 // This is an implementation of complex multiplication according to the 11366 // constraints laid out in C11 Annex G. The implementation uses the 11367 // following naming scheme: 11368 // (a + ib) * (c + id) 11369 ComplexValue LHS = Result; 11370 APFloat &A = LHS.getComplexFloatReal(); 11371 APFloat &B = LHS.getComplexFloatImag(); 11372 APFloat &C = RHS.getComplexFloatReal(); 11373 APFloat &D = RHS.getComplexFloatImag(); 11374 APFloat &ResR = Result.getComplexFloatReal(); 11375 APFloat &ResI = Result.getComplexFloatImag(); 11376 if (LHSReal) { 11377 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 11378 ResR = A * C; 11379 ResI = A * D; 11380 } else if (RHSReal) { 11381 ResR = C * A; 11382 ResI = C * B; 11383 } else { 11384 // In the fully general case, we need to handle NaNs and infinities 11385 // robustly. 11386 APFloat AC = A * C; 11387 APFloat BD = B * D; 11388 APFloat AD = A * D; 11389 APFloat BC = B * C; 11390 ResR = AC - BD; 11391 ResI = AD + BC; 11392 if (ResR.isNaN() && ResI.isNaN()) { 11393 bool Recalc = false; 11394 if (A.isInfinity() || B.isInfinity()) { 11395 A = APFloat::copySign( 11396 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 11397 B = APFloat::copySign( 11398 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 11399 if (C.isNaN()) 11400 C = APFloat::copySign(APFloat(C.getSemantics()), C); 11401 if (D.isNaN()) 11402 D = APFloat::copySign(APFloat(D.getSemantics()), D); 11403 Recalc = true; 11404 } 11405 if (C.isInfinity() || D.isInfinity()) { 11406 C = APFloat::copySign( 11407 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 11408 D = APFloat::copySign( 11409 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 11410 if (A.isNaN()) 11411 A = APFloat::copySign(APFloat(A.getSemantics()), A); 11412 if (B.isNaN()) 11413 B = APFloat::copySign(APFloat(B.getSemantics()), B); 11414 Recalc = true; 11415 } 11416 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 11417 AD.isInfinity() || BC.isInfinity())) { 11418 if (A.isNaN()) 11419 A = APFloat::copySign(APFloat(A.getSemantics()), A); 11420 if (B.isNaN()) 11421 B = APFloat::copySign(APFloat(B.getSemantics()), B); 11422 if (C.isNaN()) 11423 C = APFloat::copySign(APFloat(C.getSemantics()), C); 11424 if (D.isNaN()) 11425 D = APFloat::copySign(APFloat(D.getSemantics()), D); 11426 Recalc = true; 11427 } 11428 if (Recalc) { 11429 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 11430 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 11431 } 11432 } 11433 } 11434 } else { 11435 ComplexValue LHS = Result; 11436 Result.getComplexIntReal() = 11437 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 11438 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 11439 Result.getComplexIntImag() = 11440 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 11441 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 11442 } 11443 break; 11444 case BO_Div: 11445 if (Result.isComplexFloat()) { 11446 // This is an implementation of complex division according to the 11447 // constraints laid out in C11 Annex G. The implementation uses the 11448 // following naming scheme: 11449 // (a + ib) / (c + id) 11450 ComplexValue LHS = Result; 11451 APFloat &A = LHS.getComplexFloatReal(); 11452 APFloat &B = LHS.getComplexFloatImag(); 11453 APFloat &C = RHS.getComplexFloatReal(); 11454 APFloat &D = RHS.getComplexFloatImag(); 11455 APFloat &ResR = Result.getComplexFloatReal(); 11456 APFloat &ResI = Result.getComplexFloatImag(); 11457 if (RHSReal) { 11458 ResR = A / C; 11459 ResI = B / C; 11460 } else { 11461 if (LHSReal) { 11462 // No real optimizations we can do here, stub out with zero. 11463 B = APFloat::getZero(A.getSemantics()); 11464 } 11465 int DenomLogB = 0; 11466 APFloat MaxCD = maxnum(abs(C), abs(D)); 11467 if (MaxCD.isFinite()) { 11468 DenomLogB = ilogb(MaxCD); 11469 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 11470 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 11471 } 11472 APFloat Denom = C * C + D * D; 11473 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 11474 APFloat::rmNearestTiesToEven); 11475 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 11476 APFloat::rmNearestTiesToEven); 11477 if (ResR.isNaN() && ResI.isNaN()) { 11478 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 11479 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 11480 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 11481 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 11482 D.isFinite()) { 11483 A = APFloat::copySign( 11484 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 11485 B = APFloat::copySign( 11486 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 11487 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 11488 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 11489 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 11490 C = APFloat::copySign( 11491 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 11492 D = APFloat::copySign( 11493 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 11494 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 11495 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 11496 } 11497 } 11498 } 11499 } else { 11500 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 11501 return Error(E, diag::note_expr_divide_by_zero); 11502 11503 ComplexValue LHS = Result; 11504 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 11505 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 11506 Result.getComplexIntReal() = 11507 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 11508 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 11509 Result.getComplexIntImag() = 11510 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 11511 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 11512 } 11513 break; 11514 } 11515 11516 return true; 11517 } 11518 11519 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 11520 // Get the operand value into 'Result'. 11521 if (!Visit(E->getSubExpr())) 11522 return false; 11523 11524 switch (E->getOpcode()) { 11525 default: 11526 return Error(E); 11527 case UO_Extension: 11528 return true; 11529 case UO_Plus: 11530 // The result is always just the subexpr. 11531 return true; 11532 case UO_Minus: 11533 if (Result.isComplexFloat()) { 11534 Result.getComplexFloatReal().changeSign(); 11535 Result.getComplexFloatImag().changeSign(); 11536 } 11537 else { 11538 Result.getComplexIntReal() = -Result.getComplexIntReal(); 11539 Result.getComplexIntImag() = -Result.getComplexIntImag(); 11540 } 11541 return true; 11542 case UO_Not: 11543 if (Result.isComplexFloat()) 11544 Result.getComplexFloatImag().changeSign(); 11545 else 11546 Result.getComplexIntImag() = -Result.getComplexIntImag(); 11547 return true; 11548 } 11549 } 11550 11551 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 11552 if (E->getNumInits() == 2) { 11553 if (E->getType()->isComplexType()) { 11554 Result.makeComplexFloat(); 11555 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 11556 return false; 11557 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 11558 return false; 11559 } else { 11560 Result.makeComplexInt(); 11561 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 11562 return false; 11563 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 11564 return false; 11565 } 11566 return true; 11567 } 11568 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 11569 } 11570 11571 //===----------------------------------------------------------------------===// 11572 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 11573 // implicit conversion. 11574 //===----------------------------------------------------------------------===// 11575 11576 namespace { 11577 class AtomicExprEvaluator : 11578 public ExprEvaluatorBase<AtomicExprEvaluator> { 11579 const LValue *This; 11580 APValue &Result; 11581 public: 11582 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 11583 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 11584 11585 bool Success(const APValue &V, const Expr *E) { 11586 Result = V; 11587 return true; 11588 } 11589 11590 bool ZeroInitialization(const Expr *E) { 11591 ImplicitValueInitExpr VIE( 11592 E->getType()->castAs<AtomicType>()->getValueType()); 11593 // For atomic-qualified class (and array) types in C++, initialize the 11594 // _Atomic-wrapped subobject directly, in-place. 11595 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 11596 : Evaluate(Result, Info, &VIE); 11597 } 11598 11599 bool VisitCastExpr(const CastExpr *E) { 11600 switch (E->getCastKind()) { 11601 default: 11602 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11603 case CK_NonAtomicToAtomic: 11604 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 11605 : Evaluate(Result, Info, E->getSubExpr()); 11606 } 11607 } 11608 }; 11609 } // end anonymous namespace 11610 11611 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 11612 EvalInfo &Info) { 11613 assert(E->isRValue() && E->getType()->isAtomicType()); 11614 return AtomicExprEvaluator(Info, This, Result).Visit(E); 11615 } 11616 11617 //===----------------------------------------------------------------------===// 11618 // Void expression evaluation, primarily for a cast to void on the LHS of a 11619 // comma operator 11620 //===----------------------------------------------------------------------===// 11621 11622 namespace { 11623 class VoidExprEvaluator 11624 : public ExprEvaluatorBase<VoidExprEvaluator> { 11625 public: 11626 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 11627 11628 bool Success(const APValue &V, const Expr *e) { return true; } 11629 11630 bool ZeroInitialization(const Expr *E) { return true; } 11631 11632 bool VisitCastExpr(const CastExpr *E) { 11633 switch (E->getCastKind()) { 11634 default: 11635 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11636 case CK_ToVoid: 11637 VisitIgnoredValue(E->getSubExpr()); 11638 return true; 11639 } 11640 } 11641 11642 bool VisitCallExpr(const CallExpr *E) { 11643 switch (E->getBuiltinCallee()) { 11644 default: 11645 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11646 case Builtin::BI__assume: 11647 case Builtin::BI__builtin_assume: 11648 // The argument is not evaluated! 11649 return true; 11650 } 11651 } 11652 }; 11653 } // end anonymous namespace 11654 11655 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 11656 assert(E->isRValue() && E->getType()->isVoidType()); 11657 return VoidExprEvaluator(Info).Visit(E); 11658 } 11659 11660 //===----------------------------------------------------------------------===// 11661 // Top level Expr::EvaluateAsRValue method. 11662 //===----------------------------------------------------------------------===// 11663 11664 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 11665 // In C, function designators are not lvalues, but we evaluate them as if they 11666 // are. 11667 QualType T = E->getType(); 11668 if (E->isGLValue() || T->isFunctionType()) { 11669 LValue LV; 11670 if (!EvaluateLValue(E, LV, Info)) 11671 return false; 11672 LV.moveInto(Result); 11673 } else if (T->isVectorType()) { 11674 if (!EvaluateVector(E, Result, Info)) 11675 return false; 11676 } else if (T->isIntegralOrEnumerationType()) { 11677 if (!IntExprEvaluator(Info, Result).Visit(E)) 11678 return false; 11679 } else if (T->hasPointerRepresentation()) { 11680 LValue LV; 11681 if (!EvaluatePointer(E, LV, Info)) 11682 return false; 11683 LV.moveInto(Result); 11684 } else if (T->isRealFloatingType()) { 11685 llvm::APFloat F(0.0); 11686 if (!EvaluateFloat(E, F, Info)) 11687 return false; 11688 Result = APValue(F); 11689 } else if (T->isAnyComplexType()) { 11690 ComplexValue C; 11691 if (!EvaluateComplex(E, C, Info)) 11692 return false; 11693 C.moveInto(Result); 11694 } else if (T->isFixedPointType()) { 11695 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 11696 } else if (T->isMemberPointerType()) { 11697 MemberPtr P; 11698 if (!EvaluateMemberPointer(E, P, Info)) 11699 return false; 11700 P.moveInto(Result); 11701 return true; 11702 } else if (T->isArrayType()) { 11703 LValue LV; 11704 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 11705 if (!EvaluateArray(E, LV, Value, Info)) 11706 return false; 11707 Result = Value; 11708 } else if (T->isRecordType()) { 11709 LValue LV; 11710 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 11711 if (!EvaluateRecord(E, LV, Value, Info)) 11712 return false; 11713 Result = Value; 11714 } else if (T->isVoidType()) { 11715 if (!Info.getLangOpts().CPlusPlus11) 11716 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 11717 << E->getType(); 11718 if (!EvaluateVoid(E, Info)) 11719 return false; 11720 } else if (T->isAtomicType()) { 11721 QualType Unqual = T.getAtomicUnqualifiedType(); 11722 if (Unqual->isArrayType() || Unqual->isRecordType()) { 11723 LValue LV; 11724 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 11725 if (!EvaluateAtomic(E, &LV, Value, Info)) 11726 return false; 11727 } else { 11728 if (!EvaluateAtomic(E, nullptr, Result, Info)) 11729 return false; 11730 } 11731 } else if (Info.getLangOpts().CPlusPlus11) { 11732 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 11733 return false; 11734 } else { 11735 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11736 return false; 11737 } 11738 11739 return true; 11740 } 11741 11742 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 11743 /// cases, the in-place evaluation is essential, since later initializers for 11744 /// an object can indirectly refer to subobjects which were initialized earlier. 11745 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 11746 const Expr *E, bool AllowNonLiteralTypes) { 11747 assert(!E->isValueDependent()); 11748 11749 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 11750 return false; 11751 11752 if (E->isRValue()) { 11753 // Evaluate arrays and record types in-place, so that later initializers can 11754 // refer to earlier-initialized members of the object. 11755 QualType T = E->getType(); 11756 if (T->isArrayType()) 11757 return EvaluateArray(E, This, Result, Info); 11758 else if (T->isRecordType()) 11759 return EvaluateRecord(E, This, Result, Info); 11760 else if (T->isAtomicType()) { 11761 QualType Unqual = T.getAtomicUnqualifiedType(); 11762 if (Unqual->isArrayType() || Unqual->isRecordType()) 11763 return EvaluateAtomic(E, &This, Result, Info); 11764 } 11765 } 11766 11767 // For any other type, in-place evaluation is unimportant. 11768 return Evaluate(Result, Info, E); 11769 } 11770 11771 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 11772 /// lvalue-to-rvalue cast if it is an lvalue. 11773 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 11774 if (E->getType().isNull()) 11775 return false; 11776 11777 if (!CheckLiteralType(Info, E)) 11778 return false; 11779 11780 if (!::Evaluate(Result, Info, E)) 11781 return false; 11782 11783 if (E->isGLValue()) { 11784 LValue LV; 11785 LV.setFrom(Info.Ctx, Result); 11786 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 11787 return false; 11788 } 11789 11790 // Check this core constant expression is a constant expression. 11791 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 11792 } 11793 11794 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 11795 const ASTContext &Ctx, bool &IsConst) { 11796 // Fast-path evaluations of integer literals, since we sometimes see files 11797 // containing vast quantities of these. 11798 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 11799 Result.Val = APValue(APSInt(L->getValue(), 11800 L->getType()->isUnsignedIntegerType())); 11801 IsConst = true; 11802 return true; 11803 } 11804 11805 // This case should be rare, but we need to check it before we check on 11806 // the type below. 11807 if (Exp->getType().isNull()) { 11808 IsConst = false; 11809 return true; 11810 } 11811 11812 // FIXME: Evaluating values of large array and record types can cause 11813 // performance problems. Only do so in C++11 for now. 11814 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 11815 Exp->getType()->isRecordType()) && 11816 !Ctx.getLangOpts().CPlusPlus11) { 11817 IsConst = false; 11818 return true; 11819 } 11820 return false; 11821 } 11822 11823 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 11824 Expr::SideEffectsKind SEK) { 11825 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 11826 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 11827 } 11828 11829 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 11830 const ASTContext &Ctx, EvalInfo &Info) { 11831 bool IsConst; 11832 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 11833 return IsConst; 11834 11835 return EvaluateAsRValue(Info, E, Result.Val); 11836 } 11837 11838 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 11839 const ASTContext &Ctx, 11840 Expr::SideEffectsKind AllowSideEffects, 11841 EvalInfo &Info) { 11842 if (!E->getType()->isIntegralOrEnumerationType()) 11843 return false; 11844 11845 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 11846 !ExprResult.Val.isInt() || 11847 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 11848 return false; 11849 11850 return true; 11851 } 11852 11853 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 11854 const ASTContext &Ctx, 11855 Expr::SideEffectsKind AllowSideEffects, 11856 EvalInfo &Info) { 11857 if (!E->getType()->isFixedPointType()) 11858 return false; 11859 11860 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 11861 return false; 11862 11863 if (!ExprResult.Val.isFixedPoint() || 11864 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 11865 return false; 11866 11867 return true; 11868 } 11869 11870 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 11871 /// any crazy technique (that has nothing to do with language standards) that 11872 /// we want to. If this function returns true, it returns the folded constant 11873 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 11874 /// will be applied to the result. 11875 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 11876 bool InConstantContext) const { 11877 assert(!isValueDependent() && 11878 "Expression evaluator can't be called on a dependent expression."); 11879 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 11880 Info.InConstantContext = InConstantContext; 11881 return ::EvaluateAsRValue(this, Result, Ctx, Info); 11882 } 11883 11884 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 11885 bool InConstantContext) const { 11886 assert(!isValueDependent() && 11887 "Expression evaluator can't be called on a dependent expression."); 11888 EvalResult Scratch; 11889 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 11890 HandleConversionToBool(Scratch.Val, Result); 11891 } 11892 11893 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 11894 SideEffectsKind AllowSideEffects, 11895 bool InConstantContext) const { 11896 assert(!isValueDependent() && 11897 "Expression evaluator can't be called on a dependent expression."); 11898 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 11899 Info.InConstantContext = InConstantContext; 11900 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 11901 } 11902 11903 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 11904 SideEffectsKind AllowSideEffects, 11905 bool InConstantContext) const { 11906 assert(!isValueDependent() && 11907 "Expression evaluator can't be called on a dependent expression."); 11908 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 11909 Info.InConstantContext = InConstantContext; 11910 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 11911 } 11912 11913 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 11914 SideEffectsKind AllowSideEffects, 11915 bool InConstantContext) const { 11916 assert(!isValueDependent() && 11917 "Expression evaluator can't be called on a dependent expression."); 11918 11919 if (!getType()->isRealFloatingType()) 11920 return false; 11921 11922 EvalResult ExprResult; 11923 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 11924 !ExprResult.Val.isFloat() || 11925 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 11926 return false; 11927 11928 Result = ExprResult.Val.getFloat(); 11929 return true; 11930 } 11931 11932 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 11933 bool InConstantContext) const { 11934 assert(!isValueDependent() && 11935 "Expression evaluator can't be called on a dependent expression."); 11936 11937 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 11938 Info.InConstantContext = InConstantContext; 11939 LValue LV; 11940 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects || 11941 !CheckLValueConstantExpression(Info, getExprLoc(), 11942 Ctx.getLValueReferenceType(getType()), LV, 11943 Expr::EvaluateForCodeGen)) 11944 return false; 11945 11946 LV.moveInto(Result.Val); 11947 return true; 11948 } 11949 11950 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 11951 const ASTContext &Ctx) const { 11952 assert(!isValueDependent() && 11953 "Expression evaluator can't be called on a dependent expression."); 11954 11955 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 11956 EvalInfo Info(Ctx, Result, EM); 11957 Info.InConstantContext = true; 11958 11959 if (!::Evaluate(Result.Val, Info, this)) 11960 return false; 11961 11962 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val, 11963 Usage); 11964 } 11965 11966 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 11967 const VarDecl *VD, 11968 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 11969 assert(!isValueDependent() && 11970 "Expression evaluator can't be called on a dependent expression."); 11971 11972 // FIXME: Evaluating initializers for large array and record types can cause 11973 // performance problems. Only do so in C++11 for now. 11974 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 11975 !Ctx.getLangOpts().CPlusPlus11) 11976 return false; 11977 11978 Expr::EvalStatus EStatus; 11979 EStatus.Diag = &Notes; 11980 11981 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr() 11982 ? EvalInfo::EM_ConstantExpression 11983 : EvalInfo::EM_ConstantFold); 11984 InitInfo.setEvaluatingDecl(VD, Value); 11985 InitInfo.InConstantContext = true; 11986 11987 LValue LVal; 11988 LVal.set(VD); 11989 11990 // C++11 [basic.start.init]p2: 11991 // Variables with static storage duration or thread storage duration shall be 11992 // zero-initialized before any other initialization takes place. 11993 // This behavior is not present in C. 11994 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && 11995 !VD->getType()->isReferenceType()) { 11996 ImplicitValueInitExpr VIE(VD->getType()); 11997 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, 11998 /*AllowNonLiteralTypes=*/true)) 11999 return false; 12000 } 12001 12002 if (!EvaluateInPlace(Value, InitInfo, LVal, this, 12003 /*AllowNonLiteralTypes=*/true) || 12004 EStatus.HasSideEffects) 12005 return false; 12006 12007 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(), 12008 Value); 12009 } 12010 12011 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 12012 /// constant folded, but discard the result. 12013 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 12014 assert(!isValueDependent() && 12015 "Expression evaluator can't be called on a dependent expression."); 12016 12017 EvalResult Result; 12018 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 12019 !hasUnacceptableSideEffect(Result, SEK); 12020 } 12021 12022 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 12023 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 12024 assert(!isValueDependent() && 12025 "Expression evaluator can't be called on a dependent expression."); 12026 12027 EvalResult EVResult; 12028 EVResult.Diag = Diag; 12029 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 12030 Info.InConstantContext = true; 12031 12032 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 12033 (void)Result; 12034 assert(Result && "Could not evaluate expression"); 12035 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 12036 12037 return EVResult.Val.getInt(); 12038 } 12039 12040 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 12041 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 12042 assert(!isValueDependent() && 12043 "Expression evaluator can't be called on a dependent expression."); 12044 12045 EvalResult EVResult; 12046 EVResult.Diag = Diag; 12047 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow); 12048 Info.InConstantContext = true; 12049 12050 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 12051 (void)Result; 12052 assert(Result && "Could not evaluate expression"); 12053 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 12054 12055 return EVResult.Val.getInt(); 12056 } 12057 12058 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 12059 assert(!isValueDependent() && 12060 "Expression evaluator can't be called on a dependent expression."); 12061 12062 bool IsConst; 12063 EvalResult EVResult; 12064 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 12065 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow); 12066 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 12067 } 12068 } 12069 12070 bool Expr::EvalResult::isGlobalLValue() const { 12071 assert(Val.isLValue()); 12072 return IsGlobalLValue(Val.getLValueBase()); 12073 } 12074 12075 12076 /// isIntegerConstantExpr - this recursive routine will test if an expression is 12077 /// an integer constant expression. 12078 12079 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 12080 /// comma, etc 12081 12082 // CheckICE - This function does the fundamental ICE checking: the returned 12083 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 12084 // and a (possibly null) SourceLocation indicating the location of the problem. 12085 // 12086 // Note that to reduce code duplication, this helper does no evaluation 12087 // itself; the caller checks whether the expression is evaluatable, and 12088 // in the rare cases where CheckICE actually cares about the evaluated 12089 // value, it calls into Evaluate. 12090 12091 namespace { 12092 12093 enum ICEKind { 12094 /// This expression is an ICE. 12095 IK_ICE, 12096 /// This expression is not an ICE, but if it isn't evaluated, it's 12097 /// a legal subexpression for an ICE. This return value is used to handle 12098 /// the comma operator in C99 mode, and non-constant subexpressions. 12099 IK_ICEIfUnevaluated, 12100 /// This expression is not an ICE, and is not a legal subexpression for one. 12101 IK_NotICE 12102 }; 12103 12104 struct ICEDiag { 12105 ICEKind Kind; 12106 SourceLocation Loc; 12107 12108 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 12109 }; 12110 12111 } 12112 12113 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 12114 12115 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 12116 12117 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 12118 Expr::EvalResult EVResult; 12119 Expr::EvalStatus Status; 12120 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 12121 12122 Info.InConstantContext = true; 12123 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 12124 !EVResult.Val.isInt()) 12125 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12126 12127 return NoDiag(); 12128 } 12129 12130 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 12131 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 12132 if (!E->getType()->isIntegralOrEnumerationType()) 12133 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12134 12135 switch (E->getStmtClass()) { 12136 #define ABSTRACT_STMT(Node) 12137 #define STMT(Node, Base) case Expr::Node##Class: 12138 #define EXPR(Node, Base) 12139 #include "clang/AST/StmtNodes.inc" 12140 case Expr::PredefinedExprClass: 12141 case Expr::FloatingLiteralClass: 12142 case Expr::ImaginaryLiteralClass: 12143 case Expr::StringLiteralClass: 12144 case Expr::ArraySubscriptExprClass: 12145 case Expr::OMPArraySectionExprClass: 12146 case Expr::MemberExprClass: 12147 case Expr::CompoundAssignOperatorClass: 12148 case Expr::CompoundLiteralExprClass: 12149 case Expr::ExtVectorElementExprClass: 12150 case Expr::DesignatedInitExprClass: 12151 case Expr::ArrayInitLoopExprClass: 12152 case Expr::ArrayInitIndexExprClass: 12153 case Expr::NoInitExprClass: 12154 case Expr::DesignatedInitUpdateExprClass: 12155 case Expr::ImplicitValueInitExprClass: 12156 case Expr::ParenListExprClass: 12157 case Expr::VAArgExprClass: 12158 case Expr::AddrLabelExprClass: 12159 case Expr::StmtExprClass: 12160 case Expr::CXXMemberCallExprClass: 12161 case Expr::CUDAKernelCallExprClass: 12162 case Expr::CXXDynamicCastExprClass: 12163 case Expr::CXXTypeidExprClass: 12164 case Expr::CXXUuidofExprClass: 12165 case Expr::MSPropertyRefExprClass: 12166 case Expr::MSPropertySubscriptExprClass: 12167 case Expr::CXXNullPtrLiteralExprClass: 12168 case Expr::UserDefinedLiteralClass: 12169 case Expr::CXXThisExprClass: 12170 case Expr::CXXThrowExprClass: 12171 case Expr::CXXNewExprClass: 12172 case Expr::CXXDeleteExprClass: 12173 case Expr::CXXPseudoDestructorExprClass: 12174 case Expr::UnresolvedLookupExprClass: 12175 case Expr::TypoExprClass: 12176 case Expr::DependentScopeDeclRefExprClass: 12177 case Expr::CXXConstructExprClass: 12178 case Expr::CXXInheritedCtorInitExprClass: 12179 case Expr::CXXStdInitializerListExprClass: 12180 case Expr::CXXBindTemporaryExprClass: 12181 case Expr::ExprWithCleanupsClass: 12182 case Expr::CXXTemporaryObjectExprClass: 12183 case Expr::CXXUnresolvedConstructExprClass: 12184 case Expr::CXXDependentScopeMemberExprClass: 12185 case Expr::UnresolvedMemberExprClass: 12186 case Expr::ObjCStringLiteralClass: 12187 case Expr::ObjCBoxedExprClass: 12188 case Expr::ObjCArrayLiteralClass: 12189 case Expr::ObjCDictionaryLiteralClass: 12190 case Expr::ObjCEncodeExprClass: 12191 case Expr::ObjCMessageExprClass: 12192 case Expr::ObjCSelectorExprClass: 12193 case Expr::ObjCProtocolExprClass: 12194 case Expr::ObjCIvarRefExprClass: 12195 case Expr::ObjCPropertyRefExprClass: 12196 case Expr::ObjCSubscriptRefExprClass: 12197 case Expr::ObjCIsaExprClass: 12198 case Expr::ObjCAvailabilityCheckExprClass: 12199 case Expr::ShuffleVectorExprClass: 12200 case Expr::ConvertVectorExprClass: 12201 case Expr::BlockExprClass: 12202 case Expr::NoStmtClass: 12203 case Expr::OpaqueValueExprClass: 12204 case Expr::PackExpansionExprClass: 12205 case Expr::SubstNonTypeTemplateParmPackExprClass: 12206 case Expr::FunctionParmPackExprClass: 12207 case Expr::AsTypeExprClass: 12208 case Expr::ObjCIndirectCopyRestoreExprClass: 12209 case Expr::MaterializeTemporaryExprClass: 12210 case Expr::PseudoObjectExprClass: 12211 case Expr::AtomicExprClass: 12212 case Expr::LambdaExprClass: 12213 case Expr::CXXFoldExprClass: 12214 case Expr::CoawaitExprClass: 12215 case Expr::DependentCoawaitExprClass: 12216 case Expr::CoyieldExprClass: 12217 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12218 12219 case Expr::InitListExprClass: { 12220 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 12221 // form "T x = { a };" is equivalent to "T x = a;". 12222 // Unless we're initializing a reference, T is a scalar as it is known to be 12223 // of integral or enumeration type. 12224 if (E->isRValue()) 12225 if (cast<InitListExpr>(E)->getNumInits() == 1) 12226 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 12227 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12228 } 12229 12230 case Expr::SizeOfPackExprClass: 12231 case Expr::GNUNullExprClass: 12232 case Expr::SourceLocExprClass: 12233 return NoDiag(); 12234 12235 case Expr::SubstNonTypeTemplateParmExprClass: 12236 return 12237 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 12238 12239 case Expr::ConstantExprClass: 12240 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 12241 12242 case Expr::ParenExprClass: 12243 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 12244 case Expr::GenericSelectionExprClass: 12245 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 12246 case Expr::IntegerLiteralClass: 12247 case Expr::FixedPointLiteralClass: 12248 case Expr::CharacterLiteralClass: 12249 case Expr::ObjCBoolLiteralExprClass: 12250 case Expr::CXXBoolLiteralExprClass: 12251 case Expr::CXXScalarValueInitExprClass: 12252 case Expr::TypeTraitExprClass: 12253 case Expr::ArrayTypeTraitExprClass: 12254 case Expr::ExpressionTraitExprClass: 12255 case Expr::CXXNoexceptExprClass: 12256 return NoDiag(); 12257 case Expr::CallExprClass: 12258 case Expr::CXXOperatorCallExprClass: { 12259 // C99 6.6/3 allows function calls within unevaluated subexpressions of 12260 // constant expressions, but they can never be ICEs because an ICE cannot 12261 // contain an operand of (pointer to) function type. 12262 const CallExpr *CE = cast<CallExpr>(E); 12263 if (CE->getBuiltinCallee()) 12264 return CheckEvalInICE(E, Ctx); 12265 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12266 } 12267 case Expr::DeclRefExprClass: { 12268 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 12269 return NoDiag(); 12270 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 12271 if (Ctx.getLangOpts().CPlusPlus && 12272 D && IsConstNonVolatile(D->getType())) { 12273 // Parameter variables are never constants. Without this check, 12274 // getAnyInitializer() can find a default argument, which leads 12275 // to chaos. 12276 if (isa<ParmVarDecl>(D)) 12277 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 12278 12279 // C++ 7.1.5.1p2 12280 // A variable of non-volatile const-qualified integral or enumeration 12281 // type initialized by an ICE can be used in ICEs. 12282 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 12283 if (!Dcl->getType()->isIntegralOrEnumerationType()) 12284 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 12285 12286 const VarDecl *VD; 12287 // Look for a declaration of this variable that has an initializer, and 12288 // check whether it is an ICE. 12289 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 12290 return NoDiag(); 12291 else 12292 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 12293 } 12294 } 12295 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12296 } 12297 case Expr::UnaryOperatorClass: { 12298 const UnaryOperator *Exp = cast<UnaryOperator>(E); 12299 switch (Exp->getOpcode()) { 12300 case UO_PostInc: 12301 case UO_PostDec: 12302 case UO_PreInc: 12303 case UO_PreDec: 12304 case UO_AddrOf: 12305 case UO_Deref: 12306 case UO_Coawait: 12307 // C99 6.6/3 allows increment and decrement within unevaluated 12308 // subexpressions of constant expressions, but they can never be ICEs 12309 // because an ICE cannot contain an lvalue operand. 12310 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12311 case UO_Extension: 12312 case UO_LNot: 12313 case UO_Plus: 12314 case UO_Minus: 12315 case UO_Not: 12316 case UO_Real: 12317 case UO_Imag: 12318 return CheckICE(Exp->getSubExpr(), Ctx); 12319 } 12320 llvm_unreachable("invalid unary operator class"); 12321 } 12322 case Expr::OffsetOfExprClass: { 12323 // Note that per C99, offsetof must be an ICE. And AFAIK, using 12324 // EvaluateAsRValue matches the proposed gcc behavior for cases like 12325 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 12326 // compliance: we should warn earlier for offsetof expressions with 12327 // array subscripts that aren't ICEs, and if the array subscripts 12328 // are ICEs, the value of the offsetof must be an integer constant. 12329 return CheckEvalInICE(E, Ctx); 12330 } 12331 case Expr::UnaryExprOrTypeTraitExprClass: { 12332 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 12333 if ((Exp->getKind() == UETT_SizeOf) && 12334 Exp->getTypeOfArgument()->isVariableArrayType()) 12335 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12336 return NoDiag(); 12337 } 12338 case Expr::BinaryOperatorClass: { 12339 const BinaryOperator *Exp = cast<BinaryOperator>(E); 12340 switch (Exp->getOpcode()) { 12341 case BO_PtrMemD: 12342 case BO_PtrMemI: 12343 case BO_Assign: 12344 case BO_MulAssign: 12345 case BO_DivAssign: 12346 case BO_RemAssign: 12347 case BO_AddAssign: 12348 case BO_SubAssign: 12349 case BO_ShlAssign: 12350 case BO_ShrAssign: 12351 case BO_AndAssign: 12352 case BO_XorAssign: 12353 case BO_OrAssign: 12354 // C99 6.6/3 allows assignments within unevaluated subexpressions of 12355 // constant expressions, but they can never be ICEs because an ICE cannot 12356 // contain an lvalue operand. 12357 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12358 12359 case BO_Mul: 12360 case BO_Div: 12361 case BO_Rem: 12362 case BO_Add: 12363 case BO_Sub: 12364 case BO_Shl: 12365 case BO_Shr: 12366 case BO_LT: 12367 case BO_GT: 12368 case BO_LE: 12369 case BO_GE: 12370 case BO_EQ: 12371 case BO_NE: 12372 case BO_And: 12373 case BO_Xor: 12374 case BO_Or: 12375 case BO_Comma: 12376 case BO_Cmp: { 12377 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 12378 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 12379 if (Exp->getOpcode() == BO_Div || 12380 Exp->getOpcode() == BO_Rem) { 12381 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 12382 // we don't evaluate one. 12383 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 12384 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 12385 if (REval == 0) 12386 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 12387 if (REval.isSigned() && REval.isAllOnesValue()) { 12388 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 12389 if (LEval.isMinSignedValue()) 12390 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 12391 } 12392 } 12393 } 12394 if (Exp->getOpcode() == BO_Comma) { 12395 if (Ctx.getLangOpts().C99) { 12396 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 12397 // if it isn't evaluated. 12398 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 12399 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 12400 } else { 12401 // In both C89 and C++, commas in ICEs are illegal. 12402 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12403 } 12404 } 12405 return Worst(LHSResult, RHSResult); 12406 } 12407 case BO_LAnd: 12408 case BO_LOr: { 12409 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 12410 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 12411 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 12412 // Rare case where the RHS has a comma "side-effect"; we need 12413 // to actually check the condition to see whether the side 12414 // with the comma is evaluated. 12415 if ((Exp->getOpcode() == BO_LAnd) != 12416 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 12417 return RHSResult; 12418 return NoDiag(); 12419 } 12420 12421 return Worst(LHSResult, RHSResult); 12422 } 12423 } 12424 llvm_unreachable("invalid binary operator kind"); 12425 } 12426 case Expr::ImplicitCastExprClass: 12427 case Expr::CStyleCastExprClass: 12428 case Expr::CXXFunctionalCastExprClass: 12429 case Expr::CXXStaticCastExprClass: 12430 case Expr::CXXReinterpretCastExprClass: 12431 case Expr::CXXConstCastExprClass: 12432 case Expr::ObjCBridgedCastExprClass: { 12433 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 12434 if (isa<ExplicitCastExpr>(E)) { 12435 if (const FloatingLiteral *FL 12436 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 12437 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 12438 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 12439 APSInt IgnoredVal(DestWidth, !DestSigned); 12440 bool Ignored; 12441 // If the value does not fit in the destination type, the behavior is 12442 // undefined, so we are not required to treat it as a constant 12443 // expression. 12444 if (FL->getValue().convertToInteger(IgnoredVal, 12445 llvm::APFloat::rmTowardZero, 12446 &Ignored) & APFloat::opInvalidOp) 12447 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12448 return NoDiag(); 12449 } 12450 } 12451 switch (cast<CastExpr>(E)->getCastKind()) { 12452 case CK_LValueToRValue: 12453 case CK_AtomicToNonAtomic: 12454 case CK_NonAtomicToAtomic: 12455 case CK_NoOp: 12456 case CK_IntegralToBoolean: 12457 case CK_IntegralCast: 12458 return CheckICE(SubExpr, Ctx); 12459 default: 12460 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12461 } 12462 } 12463 case Expr::BinaryConditionalOperatorClass: { 12464 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 12465 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 12466 if (CommonResult.Kind == IK_NotICE) return CommonResult; 12467 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 12468 if (FalseResult.Kind == IK_NotICE) return FalseResult; 12469 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 12470 if (FalseResult.Kind == IK_ICEIfUnevaluated && 12471 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 12472 return FalseResult; 12473 } 12474 case Expr::ConditionalOperatorClass: { 12475 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 12476 // If the condition (ignoring parens) is a __builtin_constant_p call, 12477 // then only the true side is actually considered in an integer constant 12478 // expression, and it is fully evaluated. This is an important GNU 12479 // extension. See GCC PR38377 for discussion. 12480 if (const CallExpr *CallCE 12481 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 12482 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 12483 return CheckEvalInICE(E, Ctx); 12484 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 12485 if (CondResult.Kind == IK_NotICE) 12486 return CondResult; 12487 12488 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 12489 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 12490 12491 if (TrueResult.Kind == IK_NotICE) 12492 return TrueResult; 12493 if (FalseResult.Kind == IK_NotICE) 12494 return FalseResult; 12495 if (CondResult.Kind == IK_ICEIfUnevaluated) 12496 return CondResult; 12497 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 12498 return NoDiag(); 12499 // Rare case where the diagnostics depend on which side is evaluated 12500 // Note that if we get here, CondResult is 0, and at least one of 12501 // TrueResult and FalseResult is non-zero. 12502 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 12503 return FalseResult; 12504 return TrueResult; 12505 } 12506 case Expr::CXXDefaultArgExprClass: 12507 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 12508 case Expr::CXXDefaultInitExprClass: 12509 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 12510 case Expr::ChooseExprClass: { 12511 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 12512 } 12513 } 12514 12515 llvm_unreachable("Invalid StmtClass!"); 12516 } 12517 12518 /// Evaluate an expression as a C++11 integral constant expression. 12519 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 12520 const Expr *E, 12521 llvm::APSInt *Value, 12522 SourceLocation *Loc) { 12523 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12524 if (Loc) *Loc = E->getExprLoc(); 12525 return false; 12526 } 12527 12528 APValue Result; 12529 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 12530 return false; 12531 12532 if (!Result.isInt()) { 12533 if (Loc) *Loc = E->getExprLoc(); 12534 return false; 12535 } 12536 12537 if (Value) *Value = Result.getInt(); 12538 return true; 12539 } 12540 12541 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 12542 SourceLocation *Loc) const { 12543 assert(!isValueDependent() && 12544 "Expression evaluator can't be called on a dependent expression."); 12545 12546 if (Ctx.getLangOpts().CPlusPlus11) 12547 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 12548 12549 ICEDiag D = CheckICE(this, Ctx); 12550 if (D.Kind != IK_ICE) { 12551 if (Loc) *Loc = D.Loc; 12552 return false; 12553 } 12554 return true; 12555 } 12556 12557 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, 12558 SourceLocation *Loc, bool isEvaluated) const { 12559 assert(!isValueDependent() && 12560 "Expression evaluator can't be called on a dependent expression."); 12561 12562 if (Ctx.getLangOpts().CPlusPlus11) 12563 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 12564 12565 if (!isIntegerConstantExpr(Ctx, Loc)) 12566 return false; 12567 12568 // The only possible side-effects here are due to UB discovered in the 12569 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 12570 // required to treat the expression as an ICE, so we produce the folded 12571 // value. 12572 EvalResult ExprResult; 12573 Expr::EvalStatus Status; 12574 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 12575 Info.InConstantContext = true; 12576 12577 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 12578 llvm_unreachable("ICE cannot be evaluated!"); 12579 12580 Value = ExprResult.Val.getInt(); 12581 return true; 12582 } 12583 12584 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 12585 assert(!isValueDependent() && 12586 "Expression evaluator can't be called on a dependent expression."); 12587 12588 return CheckICE(this, Ctx).Kind == IK_ICE; 12589 } 12590 12591 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 12592 SourceLocation *Loc) const { 12593 assert(!isValueDependent() && 12594 "Expression evaluator can't be called on a dependent expression."); 12595 12596 // We support this checking in C++98 mode in order to diagnose compatibility 12597 // issues. 12598 assert(Ctx.getLangOpts().CPlusPlus); 12599 12600 // Build evaluation settings. 12601 Expr::EvalStatus Status; 12602 SmallVector<PartialDiagnosticAt, 8> Diags; 12603 Status.Diag = &Diags; 12604 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 12605 12606 APValue Scratch; 12607 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch); 12608 12609 if (!Diags.empty()) { 12610 IsConstExpr = false; 12611 if (Loc) *Loc = Diags[0].first; 12612 } else if (!IsConstExpr) { 12613 // FIXME: This shouldn't happen. 12614 if (Loc) *Loc = getExprLoc(); 12615 } 12616 12617 return IsConstExpr; 12618 } 12619 12620 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 12621 const FunctionDecl *Callee, 12622 ArrayRef<const Expr*> Args, 12623 const Expr *This) const { 12624 assert(!isValueDependent() && 12625 "Expression evaluator can't be called on a dependent expression."); 12626 12627 Expr::EvalStatus Status; 12628 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 12629 Info.InConstantContext = true; 12630 12631 LValue ThisVal; 12632 const LValue *ThisPtr = nullptr; 12633 if (This) { 12634 #ifndef NDEBUG 12635 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 12636 assert(MD && "Don't provide `this` for non-methods."); 12637 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 12638 #endif 12639 if (EvaluateObjectArgument(Info, This, ThisVal)) 12640 ThisPtr = &ThisVal; 12641 if (Info.EvalStatus.HasSideEffects) 12642 return false; 12643 } 12644 12645 ArgVector ArgValues(Args.size()); 12646 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 12647 I != E; ++I) { 12648 if ((*I)->isValueDependent() || 12649 !Evaluate(ArgValues[I - Args.begin()], Info, *I)) 12650 // If evaluation fails, throw away the argument entirely. 12651 ArgValues[I - Args.begin()] = APValue(); 12652 if (Info.EvalStatus.HasSideEffects) 12653 return false; 12654 } 12655 12656 // Build fake call to Callee. 12657 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 12658 ArgValues.data()); 12659 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects; 12660 } 12661 12662 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 12663 SmallVectorImpl< 12664 PartialDiagnosticAt> &Diags) { 12665 // FIXME: It would be useful to check constexpr function templates, but at the 12666 // moment the constant expression evaluator cannot cope with the non-rigorous 12667 // ASTs which we build for dependent expressions. 12668 if (FD->isDependentContext()) 12669 return true; 12670 12671 Expr::EvalStatus Status; 12672 Status.Diag = &Diags; 12673 12674 EvalInfo Info(FD->getASTContext(), Status, 12675 EvalInfo::EM_PotentialConstantExpression); 12676 Info.InConstantContext = true; 12677 12678 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 12679 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 12680 12681 // Fabricate an arbitrary expression on the stack and pretend that it 12682 // is a temporary being used as the 'this' pointer. 12683 LValue This; 12684 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 12685 This.set({&VIE, Info.CurrentCall->Index}); 12686 12687 ArrayRef<const Expr*> Args; 12688 12689 APValue Scratch; 12690 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 12691 // Evaluate the call as a constant initializer, to allow the construction 12692 // of objects of non-literal types. 12693 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 12694 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 12695 } else { 12696 SourceLocation Loc = FD->getLocation(); 12697 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 12698 Args, FD->getBody(), Info, Scratch, nullptr); 12699 } 12700 12701 return Diags.empty(); 12702 } 12703 12704 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 12705 const FunctionDecl *FD, 12706 SmallVectorImpl< 12707 PartialDiagnosticAt> &Diags) { 12708 assert(!E->isValueDependent() && 12709 "Expression evaluator can't be called on a dependent expression."); 12710 12711 Expr::EvalStatus Status; 12712 Status.Diag = &Diags; 12713 12714 EvalInfo Info(FD->getASTContext(), Status, 12715 EvalInfo::EM_PotentialConstantExpressionUnevaluated); 12716 Info.InConstantContext = true; 12717 12718 // Fabricate a call stack frame to give the arguments a plausible cover story. 12719 ArrayRef<const Expr*> Args; 12720 ArgVector ArgValues(0); 12721 bool Success = EvaluateArgs(Args, ArgValues, Info, FD); 12722 (void)Success; 12723 assert(Success && 12724 "Failed to set up arguments for potential constant evaluation"); 12725 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 12726 12727 APValue ResultScratch; 12728 Evaluate(ResultScratch, Info, E); 12729 return Diags.empty(); 12730 } 12731 12732 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 12733 unsigned Type) const { 12734 if (!getType()->isPointerType()) 12735 return false; 12736 12737 Expr::EvalStatus Status; 12738 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 12739 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 12740 } 12741