1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Expr constant evaluator. 11 // 12 // Constant expression evaluation produces four main results: 13 // 14 // * A success/failure flag indicating whether constant folding was successful. 15 // This is the 'bool' return value used by most of the code in this file. A 16 // 'false' return value indicates that constant folding has failed, and any 17 // appropriate diagnostic has already been produced. 18 // 19 // * An evaluated result, valid only if constant folding has not failed. 20 // 21 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 22 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 23 // where it is possible to determine the evaluated result regardless. 24 // 25 // * A set of notes indicating why the evaluation was not a constant expression 26 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 27 // too, why the expression could not be folded. 28 // 29 // If we are checking for a potential constant expression, failure to constant 30 // fold a potential constant sub-expression will be indicated by a 'false' 31 // return value (the expression could not be folded) and no diagnostic (the 32 // expression is not necessarily non-constant). 33 // 34 //===----------------------------------------------------------------------===// 35 36 #include "clang/AST/APValue.h" 37 #include "clang/AST/ASTContext.h" 38 #include "clang/AST/ASTDiagnostic.h" 39 #include "clang/AST/ASTLambda.h" 40 #include "clang/AST/CharUnits.h" 41 #include "clang/AST/Expr.h" 42 #include "clang/AST/OSLog.h" 43 #include "clang/AST/RecordLayout.h" 44 #include "clang/AST/StmtVisitor.h" 45 #include "clang/AST/TypeLoc.h" 46 #include "clang/Basic/Builtins.h" 47 #include "clang/Basic/TargetInfo.h" 48 #include "llvm/Support/raw_ostream.h" 49 #include <cstring> 50 #include <functional> 51 52 #define DEBUG_TYPE "exprconstant" 53 54 using namespace clang; 55 using llvm::APSInt; 56 using llvm::APFloat; 57 58 static bool IsGlobalLValue(APValue::LValueBase B); 59 60 namespace { 61 struct LValue; 62 struct CallStackFrame; 63 struct EvalInfo; 64 65 static QualType getType(APValue::LValueBase B) { 66 if (!B) return QualType(); 67 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 68 // FIXME: It's unclear where we're supposed to take the type from, and 69 // this actually matters for arrays of unknown bound. Eg: 70 // 71 // extern int arr[]; void f() { extern int arr[3]; }; 72 // constexpr int *p = &arr[1]; // valid? 73 // 74 // For now, we take the array bound from the most recent declaration. 75 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 76 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 77 QualType T = Redecl->getType(); 78 if (!T->isIncompleteArrayType()) 79 return T; 80 } 81 return D->getType(); 82 } 83 84 const Expr *Base = B.get<const Expr*>(); 85 86 // For a materialized temporary, the type of the temporary we materialized 87 // may not be the type of the expression. 88 if (const MaterializeTemporaryExpr *MTE = 89 dyn_cast<MaterializeTemporaryExpr>(Base)) { 90 SmallVector<const Expr *, 2> CommaLHSs; 91 SmallVector<SubobjectAdjustment, 2> Adjustments; 92 const Expr *Temp = MTE->GetTemporaryExpr(); 93 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 94 Adjustments); 95 // Keep any cv-qualifiers from the reference if we generated a temporary 96 // for it directly. Otherwise use the type after adjustment. 97 if (!Adjustments.empty()) 98 return Inner->getType(); 99 } 100 101 return Base->getType(); 102 } 103 104 /// Get an LValue path entry, which is known to not be an array index, as a 105 /// field or base class. 106 static 107 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) { 108 APValue::BaseOrMemberType Value; 109 Value.setFromOpaqueValue(E.BaseOrMember); 110 return Value; 111 } 112 113 /// Get an LValue path entry, which is known to not be an array index, as a 114 /// field declaration. 115 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 116 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer()); 117 } 118 /// Get an LValue path entry, which is known to not be an array index, as a 119 /// base class declaration. 120 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 121 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer()); 122 } 123 /// Determine whether this LValue path entry for a base class names a virtual 124 /// base class. 125 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 126 return getAsBaseOrMember(E).getInt(); 127 } 128 129 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 130 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 131 const FunctionDecl *Callee = CE->getDirectCallee(); 132 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 133 } 134 135 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 136 /// This will look through a single cast. 137 /// 138 /// Returns null if we couldn't unwrap a function with alloc_size. 139 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 140 if (!E->getType()->isPointerType()) 141 return nullptr; 142 143 E = E->IgnoreParens(); 144 // If we're doing a variable assignment from e.g. malloc(N), there will 145 // probably be a cast of some kind. In exotic cases, we might also see a 146 // top-level ExprWithCleanups. Ignore them either way. 147 if (const auto *FE = dyn_cast<FullExpr>(E)) 148 E = FE->getSubExpr()->IgnoreParens(); 149 150 if (const auto *Cast = dyn_cast<CastExpr>(E)) 151 E = Cast->getSubExpr()->IgnoreParens(); 152 153 if (const auto *CE = dyn_cast<CallExpr>(E)) 154 return getAllocSizeAttr(CE) ? CE : nullptr; 155 return nullptr; 156 } 157 158 /// Determines whether or not the given Base contains a call to a function 159 /// with the alloc_size attribute. 160 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 161 const auto *E = Base.dyn_cast<const Expr *>(); 162 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 163 } 164 165 /// The bound to claim that an array of unknown bound has. 166 /// The value in MostDerivedArraySize is undefined in this case. So, set it 167 /// to an arbitrary value that's likely to loudly break things if it's used. 168 static const uint64_t AssumedSizeForUnsizedArray = 169 std::numeric_limits<uint64_t>::max() / 2; 170 171 /// Determines if an LValue with the given LValueBase will have an unsized 172 /// array in its designator. 173 /// Find the path length and type of the most-derived subobject in the given 174 /// path, and find the size of the containing array, if any. 175 static unsigned 176 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 177 ArrayRef<APValue::LValuePathEntry> Path, 178 uint64_t &ArraySize, QualType &Type, bool &IsArray, 179 bool &FirstEntryIsUnsizedArray) { 180 // This only accepts LValueBases from APValues, and APValues don't support 181 // arrays that lack size info. 182 assert(!isBaseAnAllocSizeCall(Base) && 183 "Unsized arrays shouldn't appear here"); 184 unsigned MostDerivedLength = 0; 185 Type = getType(Base); 186 187 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 188 if (Type->isArrayType()) { 189 const ArrayType *AT = Ctx.getAsArrayType(Type); 190 Type = AT->getElementType(); 191 MostDerivedLength = I + 1; 192 IsArray = true; 193 194 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 195 ArraySize = CAT->getSize().getZExtValue(); 196 } else { 197 assert(I == 0 && "unexpected unsized array designator"); 198 FirstEntryIsUnsizedArray = true; 199 ArraySize = AssumedSizeForUnsizedArray; 200 } 201 } else if (Type->isAnyComplexType()) { 202 const ComplexType *CT = Type->castAs<ComplexType>(); 203 Type = CT->getElementType(); 204 ArraySize = 2; 205 MostDerivedLength = I + 1; 206 IsArray = true; 207 } else if (const FieldDecl *FD = getAsField(Path[I])) { 208 Type = FD->getType(); 209 ArraySize = 0; 210 MostDerivedLength = I + 1; 211 IsArray = false; 212 } else { 213 // Path[I] describes a base class. 214 ArraySize = 0; 215 IsArray = false; 216 } 217 } 218 return MostDerivedLength; 219 } 220 221 // The order of this enum is important for diagnostics. 222 enum CheckSubobjectKind { 223 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex, 224 CSK_This, CSK_Real, CSK_Imag 225 }; 226 227 /// A path from a glvalue to a subobject of that glvalue. 228 struct SubobjectDesignator { 229 /// True if the subobject was named in a manner not supported by C++11. Such 230 /// lvalues can still be folded, but they are not core constant expressions 231 /// and we cannot perform lvalue-to-rvalue conversions on them. 232 unsigned Invalid : 1; 233 234 /// Is this a pointer one past the end of an object? 235 unsigned IsOnePastTheEnd : 1; 236 237 /// Indicator of whether the first entry is an unsized array. 238 unsigned FirstEntryIsAnUnsizedArray : 1; 239 240 /// Indicator of whether the most-derived object is an array element. 241 unsigned MostDerivedIsArrayElement : 1; 242 243 /// The length of the path to the most-derived object of which this is a 244 /// subobject. 245 unsigned MostDerivedPathLength : 28; 246 247 /// The size of the array of which the most-derived object is an element. 248 /// This will always be 0 if the most-derived object is not an array 249 /// element. 0 is not an indicator of whether or not the most-derived object 250 /// is an array, however, because 0-length arrays are allowed. 251 /// 252 /// If the current array is an unsized array, the value of this is 253 /// undefined. 254 uint64_t MostDerivedArraySize; 255 256 /// The type of the most derived object referred to by this address. 257 QualType MostDerivedType; 258 259 typedef APValue::LValuePathEntry PathEntry; 260 261 /// The entries on the path from the glvalue to the designated subobject. 262 SmallVector<PathEntry, 8> Entries; 263 264 SubobjectDesignator() : Invalid(true) {} 265 266 explicit SubobjectDesignator(QualType T) 267 : Invalid(false), IsOnePastTheEnd(false), 268 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 269 MostDerivedPathLength(0), MostDerivedArraySize(0), 270 MostDerivedType(T) {} 271 272 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 273 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 274 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 275 MostDerivedPathLength(0), MostDerivedArraySize(0) { 276 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 277 if (!Invalid) { 278 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 279 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 280 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 281 if (V.getLValueBase()) { 282 bool IsArray = false; 283 bool FirstIsUnsizedArray = false; 284 MostDerivedPathLength = findMostDerivedSubobject( 285 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 286 MostDerivedType, IsArray, FirstIsUnsizedArray); 287 MostDerivedIsArrayElement = IsArray; 288 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 289 } 290 } 291 } 292 293 void setInvalid() { 294 Invalid = true; 295 Entries.clear(); 296 } 297 298 /// Determine whether the most derived subobject is an array without a 299 /// known bound. 300 bool isMostDerivedAnUnsizedArray() const { 301 assert(!Invalid && "Calling this makes no sense on invalid designators"); 302 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 303 } 304 305 /// Determine what the most derived array's size is. Results in an assertion 306 /// failure if the most derived array lacks a size. 307 uint64_t getMostDerivedArraySize() const { 308 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 309 return MostDerivedArraySize; 310 } 311 312 /// Determine whether this is a one-past-the-end pointer. 313 bool isOnePastTheEnd() const { 314 assert(!Invalid); 315 if (IsOnePastTheEnd) 316 return true; 317 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 318 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize) 319 return true; 320 return false; 321 } 322 323 /// Get the range of valid index adjustments in the form 324 /// {maximum value that can be subtracted from this pointer, 325 /// maximum value that can be added to this pointer} 326 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 327 if (Invalid || isMostDerivedAnUnsizedArray()) 328 return {0, 0}; 329 330 // [expr.add]p4: For the purposes of these operators, a pointer to a 331 // nonarray object behaves the same as a pointer to the first element of 332 // an array of length one with the type of the object as its element type. 333 bool IsArray = MostDerivedPathLength == Entries.size() && 334 MostDerivedIsArrayElement; 335 uint64_t ArrayIndex = 336 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd; 337 uint64_t ArraySize = 338 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 339 return {ArrayIndex, ArraySize - ArrayIndex}; 340 } 341 342 /// Check that this refers to a valid subobject. 343 bool isValidSubobject() const { 344 if (Invalid) 345 return false; 346 return !isOnePastTheEnd(); 347 } 348 /// Check that this refers to a valid subobject, and if not, produce a 349 /// relevant diagnostic and set the designator as invalid. 350 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 351 352 /// Get the type of the designated object. 353 QualType getType(ASTContext &Ctx) const { 354 assert(!Invalid && "invalid designator has no subobject type"); 355 return MostDerivedPathLength == Entries.size() 356 ? MostDerivedType 357 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 358 } 359 360 /// Update this designator to refer to the first element within this array. 361 void addArrayUnchecked(const ConstantArrayType *CAT) { 362 PathEntry Entry; 363 Entry.ArrayIndex = 0; 364 Entries.push_back(Entry); 365 366 // This is a most-derived object. 367 MostDerivedType = CAT->getElementType(); 368 MostDerivedIsArrayElement = true; 369 MostDerivedArraySize = CAT->getSize().getZExtValue(); 370 MostDerivedPathLength = Entries.size(); 371 } 372 /// Update this designator to refer to the first element within the array of 373 /// elements of type T. This is an array of unknown size. 374 void addUnsizedArrayUnchecked(QualType ElemTy) { 375 PathEntry Entry; 376 Entry.ArrayIndex = 0; 377 Entries.push_back(Entry); 378 379 MostDerivedType = ElemTy; 380 MostDerivedIsArrayElement = true; 381 // The value in MostDerivedArraySize is undefined in this case. So, set it 382 // to an arbitrary value that's likely to loudly break things if it's 383 // used. 384 MostDerivedArraySize = AssumedSizeForUnsizedArray; 385 MostDerivedPathLength = Entries.size(); 386 } 387 /// Update this designator to refer to the given base or member of this 388 /// object. 389 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 390 PathEntry Entry; 391 APValue::BaseOrMemberType Value(D, Virtual); 392 Entry.BaseOrMember = Value.getOpaqueValue(); 393 Entries.push_back(Entry); 394 395 // If this isn't a base class, it's a new most-derived object. 396 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 397 MostDerivedType = FD->getType(); 398 MostDerivedIsArrayElement = false; 399 MostDerivedArraySize = 0; 400 MostDerivedPathLength = Entries.size(); 401 } 402 } 403 /// Update this designator to refer to the given complex component. 404 void addComplexUnchecked(QualType EltTy, bool Imag) { 405 PathEntry Entry; 406 Entry.ArrayIndex = Imag; 407 Entries.push_back(Entry); 408 409 // This is technically a most-derived object, though in practice this 410 // is unlikely to matter. 411 MostDerivedType = EltTy; 412 MostDerivedIsArrayElement = true; 413 MostDerivedArraySize = 2; 414 MostDerivedPathLength = Entries.size(); 415 } 416 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 417 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 418 const APSInt &N); 419 /// Add N to the address of this subobject. 420 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 421 if (Invalid || !N) return; 422 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 423 if (isMostDerivedAnUnsizedArray()) { 424 diagnoseUnsizedArrayPointerArithmetic(Info, E); 425 // Can't verify -- trust that the user is doing the right thing (or if 426 // not, trust that the caller will catch the bad behavior). 427 // FIXME: Should we reject if this overflows, at least? 428 Entries.back().ArrayIndex += TruncatedN; 429 return; 430 } 431 432 // [expr.add]p4: For the purposes of these operators, a pointer to a 433 // nonarray object behaves the same as a pointer to the first element of 434 // an array of length one with the type of the object as its element type. 435 bool IsArray = MostDerivedPathLength == Entries.size() && 436 MostDerivedIsArrayElement; 437 uint64_t ArrayIndex = 438 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd; 439 uint64_t ArraySize = 440 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 441 442 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 443 // Calculate the actual index in a wide enough type, so we can include 444 // it in the note. 445 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 446 (llvm::APInt&)N += ArrayIndex; 447 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 448 diagnosePointerArithmetic(Info, E, N); 449 setInvalid(); 450 return; 451 } 452 453 ArrayIndex += TruncatedN; 454 assert(ArrayIndex <= ArraySize && 455 "bounds check succeeded for out-of-bounds index"); 456 457 if (IsArray) 458 Entries.back().ArrayIndex = ArrayIndex; 459 else 460 IsOnePastTheEnd = (ArrayIndex != 0); 461 } 462 }; 463 464 /// A stack frame in the constexpr call stack. 465 struct CallStackFrame { 466 EvalInfo &Info; 467 468 /// Parent - The caller of this stack frame. 469 CallStackFrame *Caller; 470 471 /// Callee - The function which was called. 472 const FunctionDecl *Callee; 473 474 /// This - The binding for the this pointer in this call, if any. 475 const LValue *This; 476 477 /// Arguments - Parameter bindings for this function call, indexed by 478 /// parameters' function scope indices. 479 APValue *Arguments; 480 481 // Note that we intentionally use std::map here so that references to 482 // values are stable. 483 typedef std::pair<const void *, unsigned> MapKeyTy; 484 typedef std::map<MapKeyTy, APValue> MapTy; 485 /// Temporaries - Temporary lvalues materialized within this stack frame. 486 MapTy Temporaries; 487 488 /// CallLoc - The location of the call expression for this call. 489 SourceLocation CallLoc; 490 491 /// Index - The call index of this call. 492 unsigned Index; 493 494 /// The stack of integers for tracking version numbers for temporaries. 495 SmallVector<unsigned, 2> TempVersionStack = {1}; 496 unsigned CurTempVersion = TempVersionStack.back(); 497 498 unsigned getTempVersion() const { return TempVersionStack.back(); } 499 500 void pushTempVersion() { 501 TempVersionStack.push_back(++CurTempVersion); 502 } 503 504 void popTempVersion() { 505 TempVersionStack.pop_back(); 506 } 507 508 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 509 // on the overall stack usage of deeply-recursing constexpr evaluataions. 510 // (We should cache this map rather than recomputing it repeatedly.) 511 // But let's try this and see how it goes; we can look into caching the map 512 // as a later change. 513 514 /// LambdaCaptureFields - Mapping from captured variables/this to 515 /// corresponding data members in the closure class. 516 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 517 FieldDecl *LambdaThisCaptureField; 518 519 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 520 const FunctionDecl *Callee, const LValue *This, 521 APValue *Arguments); 522 ~CallStackFrame(); 523 524 // Return the temporary for Key whose version number is Version. 525 APValue *getTemporary(const void *Key, unsigned Version) { 526 MapKeyTy KV(Key, Version); 527 auto LB = Temporaries.lower_bound(KV); 528 if (LB != Temporaries.end() && LB->first == KV) 529 return &LB->second; 530 // Pair (Key,Version) wasn't found in the map. Check that no elements 531 // in the map have 'Key' as their key. 532 assert((LB == Temporaries.end() || LB->first.first != Key) && 533 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 534 "Element with key 'Key' found in map"); 535 return nullptr; 536 } 537 538 // Return the current temporary for Key in the map. 539 APValue *getCurrentTemporary(const void *Key) { 540 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 541 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 542 return &std::prev(UB)->second; 543 return nullptr; 544 } 545 546 // Return the version number of the current temporary for Key. 547 unsigned getCurrentTemporaryVersion(const void *Key) const { 548 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 549 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 550 return std::prev(UB)->first.second; 551 return 0; 552 } 553 554 APValue &createTemporary(const void *Key, bool IsLifetimeExtended); 555 }; 556 557 /// Temporarily override 'this'. 558 class ThisOverrideRAII { 559 public: 560 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 561 : Frame(Frame), OldThis(Frame.This) { 562 if (Enable) 563 Frame.This = NewThis; 564 } 565 ~ThisOverrideRAII() { 566 Frame.This = OldThis; 567 } 568 private: 569 CallStackFrame &Frame; 570 const LValue *OldThis; 571 }; 572 573 /// A partial diagnostic which we might know in advance that we are not going 574 /// to emit. 575 class OptionalDiagnostic { 576 PartialDiagnostic *Diag; 577 578 public: 579 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr) 580 : Diag(Diag) {} 581 582 template<typename T> 583 OptionalDiagnostic &operator<<(const T &v) { 584 if (Diag) 585 *Diag << v; 586 return *this; 587 } 588 589 OptionalDiagnostic &operator<<(const APSInt &I) { 590 if (Diag) { 591 SmallVector<char, 32> Buffer; 592 I.toString(Buffer); 593 *Diag << StringRef(Buffer.data(), Buffer.size()); 594 } 595 return *this; 596 } 597 598 OptionalDiagnostic &operator<<(const APFloat &F) { 599 if (Diag) { 600 // FIXME: Force the precision of the source value down so we don't 601 // print digits which are usually useless (we don't really care here if 602 // we truncate a digit by accident in edge cases). Ideally, 603 // APFloat::toString would automatically print the shortest 604 // representation which rounds to the correct value, but it's a bit 605 // tricky to implement. 606 unsigned precision = 607 llvm::APFloat::semanticsPrecision(F.getSemantics()); 608 precision = (precision * 59 + 195) / 196; 609 SmallVector<char, 32> Buffer; 610 F.toString(Buffer, precision); 611 *Diag << StringRef(Buffer.data(), Buffer.size()); 612 } 613 return *this; 614 } 615 }; 616 617 /// A cleanup, and a flag indicating whether it is lifetime-extended. 618 class Cleanup { 619 llvm::PointerIntPair<APValue*, 1, bool> Value; 620 621 public: 622 Cleanup(APValue *Val, bool IsLifetimeExtended) 623 : Value(Val, IsLifetimeExtended) {} 624 625 bool isLifetimeExtended() const { return Value.getInt(); } 626 void endLifetime() { 627 *Value.getPointer() = APValue(); 628 } 629 }; 630 631 /// EvalInfo - This is a private struct used by the evaluator to capture 632 /// information about a subexpression as it is folded. It retains information 633 /// about the AST context, but also maintains information about the folded 634 /// expression. 635 /// 636 /// If an expression could be evaluated, it is still possible it is not a C 637 /// "integer constant expression" or constant expression. If not, this struct 638 /// captures information about how and why not. 639 /// 640 /// One bit of information passed *into* the request for constant folding 641 /// indicates whether the subexpression is "evaluated" or not according to C 642 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 643 /// evaluate the expression regardless of what the RHS is, but C only allows 644 /// certain things in certain situations. 645 struct EvalInfo { 646 ASTContext &Ctx; 647 648 /// EvalStatus - Contains information about the evaluation. 649 Expr::EvalStatus &EvalStatus; 650 651 /// CurrentCall - The top of the constexpr call stack. 652 CallStackFrame *CurrentCall; 653 654 /// CallStackDepth - The number of calls in the call stack right now. 655 unsigned CallStackDepth; 656 657 /// NextCallIndex - The next call index to assign. 658 unsigned NextCallIndex; 659 660 /// StepsLeft - The remaining number of evaluation steps we're permitted 661 /// to perform. This is essentially a limit for the number of statements 662 /// we will evaluate. 663 unsigned StepsLeft; 664 665 /// BottomFrame - The frame in which evaluation started. This must be 666 /// initialized after CurrentCall and CallStackDepth. 667 CallStackFrame BottomFrame; 668 669 /// A stack of values whose lifetimes end at the end of some surrounding 670 /// evaluation frame. 671 llvm::SmallVector<Cleanup, 16> CleanupStack; 672 673 /// EvaluatingDecl - This is the declaration whose initializer is being 674 /// evaluated, if any. 675 APValue::LValueBase EvaluatingDecl; 676 677 /// EvaluatingDeclValue - This is the value being constructed for the 678 /// declaration whose initializer is being evaluated, if any. 679 APValue *EvaluatingDeclValue; 680 681 /// EvaluatingObject - Pair of the AST node that an lvalue represents and 682 /// the call index that that lvalue was allocated in. 683 typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>> 684 EvaluatingObject; 685 686 /// EvaluatingConstructors - Set of objects that are currently being 687 /// constructed. 688 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors; 689 690 struct EvaluatingConstructorRAII { 691 EvalInfo &EI; 692 EvaluatingObject Object; 693 bool DidInsert; 694 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object) 695 : EI(EI), Object(Object) { 696 DidInsert = EI.EvaluatingConstructors.insert(Object).second; 697 } 698 ~EvaluatingConstructorRAII() { 699 if (DidInsert) EI.EvaluatingConstructors.erase(Object); 700 } 701 }; 702 703 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex, 704 unsigned Version) { 705 return EvaluatingConstructors.count( 706 EvaluatingObject(Decl, {CallIndex, Version})); 707 } 708 709 /// The current array initialization index, if we're performing array 710 /// initialization. 711 uint64_t ArrayInitIndex = -1; 712 713 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 714 /// notes attached to it will also be stored, otherwise they will not be. 715 bool HasActiveDiagnostic; 716 717 /// Have we emitted a diagnostic explaining why we couldn't constant 718 /// fold (not just why it's not strictly a constant expression)? 719 bool HasFoldFailureDiagnostic; 720 721 /// Whether or not we're currently speculatively evaluating. 722 bool IsSpeculativelyEvaluating; 723 724 enum EvaluationMode { 725 /// Evaluate as a constant expression. Stop if we find that the expression 726 /// is not a constant expression. 727 EM_ConstantExpression, 728 729 /// Evaluate as a potential constant expression. Keep going if we hit a 730 /// construct that we can't evaluate yet (because we don't yet know the 731 /// value of something) but stop if we hit something that could never be 732 /// a constant expression. 733 EM_PotentialConstantExpression, 734 735 /// Fold the expression to a constant. Stop if we hit a side-effect that 736 /// we can't model. 737 EM_ConstantFold, 738 739 /// Evaluate the expression looking for integer overflow and similar 740 /// issues. Don't worry about side-effects, and try to visit all 741 /// subexpressions. 742 EM_EvaluateForOverflow, 743 744 /// Evaluate in any way we know how. Don't worry about side-effects that 745 /// can't be modeled. 746 EM_IgnoreSideEffects, 747 748 /// Evaluate as a constant expression. Stop if we find that the expression 749 /// is not a constant expression. Some expressions can be retried in the 750 /// optimizer if we don't constant fold them here, but in an unevaluated 751 /// context we try to fold them immediately since the optimizer never 752 /// gets a chance to look at it. 753 EM_ConstantExpressionUnevaluated, 754 755 /// Evaluate as a potential constant expression. Keep going if we hit a 756 /// construct that we can't evaluate yet (because we don't yet know the 757 /// value of something) but stop if we hit something that could never be 758 /// a constant expression. Some expressions can be retried in the 759 /// optimizer if we don't constant fold them here, but in an unevaluated 760 /// context we try to fold them immediately since the optimizer never 761 /// gets a chance to look at it. 762 EM_PotentialConstantExpressionUnevaluated, 763 } EvalMode; 764 765 /// Are we checking whether the expression is a potential constant 766 /// expression? 767 bool checkingPotentialConstantExpression() const { 768 return EvalMode == EM_PotentialConstantExpression || 769 EvalMode == EM_PotentialConstantExpressionUnevaluated; 770 } 771 772 /// Are we checking an expression for overflow? 773 // FIXME: We should check for any kind of undefined or suspicious behavior 774 // in such constructs, not just overflow. 775 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; } 776 777 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 778 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 779 CallStackDepth(0), NextCallIndex(1), 780 StepsLeft(getLangOpts().ConstexprStepLimit), 781 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 782 EvaluatingDecl((const ValueDecl *)nullptr), 783 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 784 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false), 785 EvalMode(Mode) {} 786 787 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) { 788 EvaluatingDecl = Base; 789 EvaluatingDeclValue = &Value; 790 EvaluatingConstructors.insert({Base, {0, 0}}); 791 } 792 793 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); } 794 795 bool CheckCallLimit(SourceLocation Loc) { 796 // Don't perform any constexpr calls (other than the call we're checking) 797 // when checking a potential constant expression. 798 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 799 return false; 800 if (NextCallIndex == 0) { 801 // NextCallIndex has wrapped around. 802 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 803 return false; 804 } 805 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 806 return true; 807 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 808 << getLangOpts().ConstexprCallDepth; 809 return false; 810 } 811 812 CallStackFrame *getCallFrame(unsigned CallIndex) { 813 assert(CallIndex && "no call index in getCallFrame"); 814 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 815 // be null in this loop. 816 CallStackFrame *Frame = CurrentCall; 817 while (Frame->Index > CallIndex) 818 Frame = Frame->Caller; 819 return (Frame->Index == CallIndex) ? Frame : nullptr; 820 } 821 822 bool nextStep(const Stmt *S) { 823 if (!StepsLeft) { 824 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 825 return false; 826 } 827 --StepsLeft; 828 return true; 829 } 830 831 private: 832 /// Add a diagnostic to the diagnostics list. 833 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) { 834 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator()); 835 EvalStatus.Diag->push_back(std::make_pair(Loc, PD)); 836 return EvalStatus.Diag->back().second; 837 } 838 839 /// Add notes containing a call stack to the current point of evaluation. 840 void addCallStack(unsigned Limit); 841 842 private: 843 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId, 844 unsigned ExtraNotes, bool IsCCEDiag) { 845 846 if (EvalStatus.Diag) { 847 // If we have a prior diagnostic, it will be noting that the expression 848 // isn't a constant expression. This diagnostic is more important, 849 // unless we require this evaluation to produce a constant expression. 850 // 851 // FIXME: We might want to show both diagnostics to the user in 852 // EM_ConstantFold mode. 853 if (!EvalStatus.Diag->empty()) { 854 switch (EvalMode) { 855 case EM_ConstantFold: 856 case EM_IgnoreSideEffects: 857 case EM_EvaluateForOverflow: 858 if (!HasFoldFailureDiagnostic) 859 break; 860 // We've already failed to fold something. Keep that diagnostic. 861 LLVM_FALLTHROUGH; 862 case EM_ConstantExpression: 863 case EM_PotentialConstantExpression: 864 case EM_ConstantExpressionUnevaluated: 865 case EM_PotentialConstantExpressionUnevaluated: 866 HasActiveDiagnostic = false; 867 return OptionalDiagnostic(); 868 } 869 } 870 871 unsigned CallStackNotes = CallStackDepth - 1; 872 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit(); 873 if (Limit) 874 CallStackNotes = std::min(CallStackNotes, Limit + 1); 875 if (checkingPotentialConstantExpression()) 876 CallStackNotes = 0; 877 878 HasActiveDiagnostic = true; 879 HasFoldFailureDiagnostic = !IsCCEDiag; 880 EvalStatus.Diag->clear(); 881 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes); 882 addDiag(Loc, DiagId); 883 if (!checkingPotentialConstantExpression()) 884 addCallStack(Limit); 885 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second); 886 } 887 HasActiveDiagnostic = false; 888 return OptionalDiagnostic(); 889 } 890 public: 891 // Diagnose that the evaluation could not be folded (FF => FoldFailure) 892 OptionalDiagnostic 893 FFDiag(SourceLocation Loc, 894 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr, 895 unsigned ExtraNotes = 0) { 896 return Diag(Loc, DiagId, ExtraNotes, false); 897 } 898 899 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId 900 = diag::note_invalid_subexpr_in_const_expr, 901 unsigned ExtraNotes = 0) { 902 if (EvalStatus.Diag) 903 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false); 904 HasActiveDiagnostic = false; 905 return OptionalDiagnostic(); 906 } 907 908 /// Diagnose that the evaluation does not produce a C++11 core constant 909 /// expression. 910 /// 911 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or 912 /// EM_PotentialConstantExpression mode and we produce one of these. 913 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId 914 = diag::note_invalid_subexpr_in_const_expr, 915 unsigned ExtraNotes = 0) { 916 // Don't override a previous diagnostic. Don't bother collecting 917 // diagnostics if we're evaluating for overflow. 918 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) { 919 HasActiveDiagnostic = false; 920 return OptionalDiagnostic(); 921 } 922 return Diag(Loc, DiagId, ExtraNotes, true); 923 } 924 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId 925 = diag::note_invalid_subexpr_in_const_expr, 926 unsigned ExtraNotes = 0) { 927 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes); 928 } 929 /// Add a note to a prior diagnostic. 930 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) { 931 if (!HasActiveDiagnostic) 932 return OptionalDiagnostic(); 933 return OptionalDiagnostic(&addDiag(Loc, DiagId)); 934 } 935 936 /// Add a stack of notes to a prior diagnostic. 937 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) { 938 if (HasActiveDiagnostic) { 939 EvalStatus.Diag->insert(EvalStatus.Diag->end(), 940 Diags.begin(), Diags.end()); 941 } 942 } 943 944 /// Should we continue evaluation after encountering a side-effect that we 945 /// couldn't model? 946 bool keepEvaluatingAfterSideEffect() { 947 switch (EvalMode) { 948 case EM_PotentialConstantExpression: 949 case EM_PotentialConstantExpressionUnevaluated: 950 case EM_EvaluateForOverflow: 951 case EM_IgnoreSideEffects: 952 return true; 953 954 case EM_ConstantExpression: 955 case EM_ConstantExpressionUnevaluated: 956 case EM_ConstantFold: 957 return false; 958 } 959 llvm_unreachable("Missed EvalMode case"); 960 } 961 962 /// Note that we have had a side-effect, and determine whether we should 963 /// keep evaluating. 964 bool noteSideEffect() { 965 EvalStatus.HasSideEffects = true; 966 return keepEvaluatingAfterSideEffect(); 967 } 968 969 /// Should we continue evaluation after encountering undefined behavior? 970 bool keepEvaluatingAfterUndefinedBehavior() { 971 switch (EvalMode) { 972 case EM_EvaluateForOverflow: 973 case EM_IgnoreSideEffects: 974 case EM_ConstantFold: 975 return true; 976 977 case EM_PotentialConstantExpression: 978 case EM_PotentialConstantExpressionUnevaluated: 979 case EM_ConstantExpression: 980 case EM_ConstantExpressionUnevaluated: 981 return false; 982 } 983 llvm_unreachable("Missed EvalMode case"); 984 } 985 986 /// Note that we hit something that was technically undefined behavior, but 987 /// that we can evaluate past it (such as signed overflow or floating-point 988 /// division by zero.) 989 bool noteUndefinedBehavior() { 990 EvalStatus.HasUndefinedBehavior = true; 991 return keepEvaluatingAfterUndefinedBehavior(); 992 } 993 994 /// Should we continue evaluation as much as possible after encountering a 995 /// construct which can't be reduced to a value? 996 bool keepEvaluatingAfterFailure() { 997 if (!StepsLeft) 998 return false; 999 1000 switch (EvalMode) { 1001 case EM_PotentialConstantExpression: 1002 case EM_PotentialConstantExpressionUnevaluated: 1003 case EM_EvaluateForOverflow: 1004 return true; 1005 1006 case EM_ConstantExpression: 1007 case EM_ConstantExpressionUnevaluated: 1008 case EM_ConstantFold: 1009 case EM_IgnoreSideEffects: 1010 return false; 1011 } 1012 llvm_unreachable("Missed EvalMode case"); 1013 } 1014 1015 /// Notes that we failed to evaluate an expression that other expressions 1016 /// directly depend on, and determine if we should keep evaluating. This 1017 /// should only be called if we actually intend to keep evaluating. 1018 /// 1019 /// Call noteSideEffect() instead if we may be able to ignore the value that 1020 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1021 /// 1022 /// (Foo(), 1) // use noteSideEffect 1023 /// (Foo() || true) // use noteSideEffect 1024 /// Foo() + 1 // use noteFailure 1025 LLVM_NODISCARD bool noteFailure() { 1026 // Failure when evaluating some expression often means there is some 1027 // subexpression whose evaluation was skipped. Therefore, (because we 1028 // don't track whether we skipped an expression when unwinding after an 1029 // evaluation failure) every evaluation failure that bubbles up from a 1030 // subexpression implies that a side-effect has potentially happened. We 1031 // skip setting the HasSideEffects flag to true until we decide to 1032 // continue evaluating after that point, which happens here. 1033 bool KeepGoing = keepEvaluatingAfterFailure(); 1034 EvalStatus.HasSideEffects |= KeepGoing; 1035 return KeepGoing; 1036 } 1037 1038 class ArrayInitLoopIndex { 1039 EvalInfo &Info; 1040 uint64_t OuterIndex; 1041 1042 public: 1043 ArrayInitLoopIndex(EvalInfo &Info) 1044 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1045 Info.ArrayInitIndex = 0; 1046 } 1047 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1048 1049 operator uint64_t&() { return Info.ArrayInitIndex; } 1050 }; 1051 }; 1052 1053 /// Object used to treat all foldable expressions as constant expressions. 1054 struct FoldConstant { 1055 EvalInfo &Info; 1056 bool Enabled; 1057 bool HadNoPriorDiags; 1058 EvalInfo::EvaluationMode OldMode; 1059 1060 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1061 : Info(Info), 1062 Enabled(Enabled), 1063 HadNoPriorDiags(Info.EvalStatus.Diag && 1064 Info.EvalStatus.Diag->empty() && 1065 !Info.EvalStatus.HasSideEffects), 1066 OldMode(Info.EvalMode) { 1067 if (Enabled && 1068 (Info.EvalMode == EvalInfo::EM_ConstantExpression || 1069 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated)) 1070 Info.EvalMode = EvalInfo::EM_ConstantFold; 1071 } 1072 void keepDiagnostics() { Enabled = false; } 1073 ~FoldConstant() { 1074 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1075 !Info.EvalStatus.HasSideEffects) 1076 Info.EvalStatus.Diag->clear(); 1077 Info.EvalMode = OldMode; 1078 } 1079 }; 1080 1081 /// RAII object used to set the current evaluation mode to ignore 1082 /// side-effects. 1083 struct IgnoreSideEffectsRAII { 1084 EvalInfo &Info; 1085 EvalInfo::EvaluationMode OldMode; 1086 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1087 : Info(Info), OldMode(Info.EvalMode) { 1088 if (!Info.checkingPotentialConstantExpression()) 1089 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1090 } 1091 1092 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1093 }; 1094 1095 /// RAII object used to optionally suppress diagnostics and side-effects from 1096 /// a speculative evaluation. 1097 class SpeculativeEvaluationRAII { 1098 EvalInfo *Info = nullptr; 1099 Expr::EvalStatus OldStatus; 1100 bool OldIsSpeculativelyEvaluating; 1101 1102 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1103 Info = Other.Info; 1104 OldStatus = Other.OldStatus; 1105 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating; 1106 Other.Info = nullptr; 1107 } 1108 1109 void maybeRestoreState() { 1110 if (!Info) 1111 return; 1112 1113 Info->EvalStatus = OldStatus; 1114 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating; 1115 } 1116 1117 public: 1118 SpeculativeEvaluationRAII() = default; 1119 1120 SpeculativeEvaluationRAII( 1121 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1122 : Info(&Info), OldStatus(Info.EvalStatus), 1123 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) { 1124 Info.EvalStatus.Diag = NewDiag; 1125 Info.IsSpeculativelyEvaluating = true; 1126 } 1127 1128 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1129 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1130 moveFromAndCancel(std::move(Other)); 1131 } 1132 1133 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1134 maybeRestoreState(); 1135 moveFromAndCancel(std::move(Other)); 1136 return *this; 1137 } 1138 1139 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1140 }; 1141 1142 /// RAII object wrapping a full-expression or block scope, and handling 1143 /// the ending of the lifetime of temporaries created within it. 1144 template<bool IsFullExpression> 1145 class ScopeRAII { 1146 EvalInfo &Info; 1147 unsigned OldStackSize; 1148 public: 1149 ScopeRAII(EvalInfo &Info) 1150 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1151 // Push a new temporary version. This is needed to distinguish between 1152 // temporaries created in different iterations of a loop. 1153 Info.CurrentCall->pushTempVersion(); 1154 } 1155 ~ScopeRAII() { 1156 // Body moved to a static method to encourage the compiler to inline away 1157 // instances of this class. 1158 cleanup(Info, OldStackSize); 1159 Info.CurrentCall->popTempVersion(); 1160 } 1161 private: 1162 static void cleanup(EvalInfo &Info, unsigned OldStackSize) { 1163 unsigned NewEnd = OldStackSize; 1164 for (unsigned I = OldStackSize, N = Info.CleanupStack.size(); 1165 I != N; ++I) { 1166 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) { 1167 // Full-expression cleanup of a lifetime-extended temporary: nothing 1168 // to do, just move this cleanup to the right place in the stack. 1169 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]); 1170 ++NewEnd; 1171 } else { 1172 // End the lifetime of the object. 1173 Info.CleanupStack[I].endLifetime(); 1174 } 1175 } 1176 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd, 1177 Info.CleanupStack.end()); 1178 } 1179 }; 1180 typedef ScopeRAII<false> BlockScopeRAII; 1181 typedef ScopeRAII<true> FullExpressionRAII; 1182 } 1183 1184 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1185 CheckSubobjectKind CSK) { 1186 if (Invalid) 1187 return false; 1188 if (isOnePastTheEnd()) { 1189 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1190 << CSK; 1191 setInvalid(); 1192 return false; 1193 } 1194 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1195 // must actually be at least one array element; even a VLA cannot have a 1196 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1197 return true; 1198 } 1199 1200 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1201 const Expr *E) { 1202 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1203 // Do not set the designator as invalid: we can represent this situation, 1204 // and correct handling of __builtin_object_size requires us to do so. 1205 } 1206 1207 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1208 const Expr *E, 1209 const APSInt &N) { 1210 // If we're complaining, we must be able to statically determine the size of 1211 // the most derived array. 1212 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1213 Info.CCEDiag(E, diag::note_constexpr_array_index) 1214 << N << /*array*/ 0 1215 << static_cast<unsigned>(getMostDerivedArraySize()); 1216 else 1217 Info.CCEDiag(E, diag::note_constexpr_array_index) 1218 << N << /*non-array*/ 1; 1219 setInvalid(); 1220 } 1221 1222 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1223 const FunctionDecl *Callee, const LValue *This, 1224 APValue *Arguments) 1225 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1226 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1227 Info.CurrentCall = this; 1228 ++Info.CallStackDepth; 1229 } 1230 1231 CallStackFrame::~CallStackFrame() { 1232 assert(Info.CurrentCall == this && "calls retired out of order"); 1233 --Info.CallStackDepth; 1234 Info.CurrentCall = Caller; 1235 } 1236 1237 APValue &CallStackFrame::createTemporary(const void *Key, 1238 bool IsLifetimeExtended) { 1239 unsigned Version = Info.CurrentCall->getTempVersion(); 1240 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1241 assert(Result.isUninit() && "temporary created multiple times"); 1242 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended)); 1243 return Result; 1244 } 1245 1246 static void describeCall(CallStackFrame *Frame, raw_ostream &Out); 1247 1248 void EvalInfo::addCallStack(unsigned Limit) { 1249 // Determine which calls to skip, if any. 1250 unsigned ActiveCalls = CallStackDepth - 1; 1251 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart; 1252 if (Limit && Limit < ActiveCalls) { 1253 SkipStart = Limit / 2 + Limit % 2; 1254 SkipEnd = ActiveCalls - Limit / 2; 1255 } 1256 1257 // Walk the call stack and add the diagnostics. 1258 unsigned CallIdx = 0; 1259 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame; 1260 Frame = Frame->Caller, ++CallIdx) { 1261 // Skip this call? 1262 if (CallIdx >= SkipStart && CallIdx < SkipEnd) { 1263 if (CallIdx == SkipStart) { 1264 // Note that we're skipping calls. 1265 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed) 1266 << unsigned(ActiveCalls - Limit); 1267 } 1268 continue; 1269 } 1270 1271 // Use a different note for an inheriting constructor, because from the 1272 // user's perspective it's not really a function at all. 1273 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) { 1274 if (CD->isInheritingConstructor()) { 1275 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here) 1276 << CD->getParent(); 1277 continue; 1278 } 1279 } 1280 1281 SmallVector<char, 128> Buffer; 1282 llvm::raw_svector_ostream Out(Buffer); 1283 describeCall(Frame, Out); 1284 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str(); 1285 } 1286 } 1287 1288 namespace { 1289 struct ComplexValue { 1290 private: 1291 bool IsInt; 1292 1293 public: 1294 APSInt IntReal, IntImag; 1295 APFloat FloatReal, FloatImag; 1296 1297 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1298 1299 void makeComplexFloat() { IsInt = false; } 1300 bool isComplexFloat() const { return !IsInt; } 1301 APFloat &getComplexFloatReal() { return FloatReal; } 1302 APFloat &getComplexFloatImag() { return FloatImag; } 1303 1304 void makeComplexInt() { IsInt = true; } 1305 bool isComplexInt() const { return IsInt; } 1306 APSInt &getComplexIntReal() { return IntReal; } 1307 APSInt &getComplexIntImag() { return IntImag; } 1308 1309 void moveInto(APValue &v) const { 1310 if (isComplexFloat()) 1311 v = APValue(FloatReal, FloatImag); 1312 else 1313 v = APValue(IntReal, IntImag); 1314 } 1315 void setFrom(const APValue &v) { 1316 assert(v.isComplexFloat() || v.isComplexInt()); 1317 if (v.isComplexFloat()) { 1318 makeComplexFloat(); 1319 FloatReal = v.getComplexFloatReal(); 1320 FloatImag = v.getComplexFloatImag(); 1321 } else { 1322 makeComplexInt(); 1323 IntReal = v.getComplexIntReal(); 1324 IntImag = v.getComplexIntImag(); 1325 } 1326 } 1327 }; 1328 1329 struct LValue { 1330 APValue::LValueBase Base; 1331 CharUnits Offset; 1332 SubobjectDesignator Designator; 1333 bool IsNullPtr : 1; 1334 bool InvalidBase : 1; 1335 1336 const APValue::LValueBase getLValueBase() const { return Base; } 1337 CharUnits &getLValueOffset() { return Offset; } 1338 const CharUnits &getLValueOffset() const { return Offset; } 1339 SubobjectDesignator &getLValueDesignator() { return Designator; } 1340 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1341 bool isNullPointer() const { return IsNullPtr;} 1342 1343 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1344 unsigned getLValueVersion() const { return Base.getVersion(); } 1345 1346 void moveInto(APValue &V) const { 1347 if (Designator.Invalid) 1348 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1349 else { 1350 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1351 V = APValue(Base, Offset, Designator.Entries, 1352 Designator.IsOnePastTheEnd, IsNullPtr); 1353 } 1354 } 1355 void setFrom(ASTContext &Ctx, const APValue &V) { 1356 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1357 Base = V.getLValueBase(); 1358 Offset = V.getLValueOffset(); 1359 InvalidBase = false; 1360 Designator = SubobjectDesignator(Ctx, V); 1361 IsNullPtr = V.isNullPointer(); 1362 } 1363 1364 void set(APValue::LValueBase B, bool BInvalid = false) { 1365 #ifndef NDEBUG 1366 // We only allow a few types of invalid bases. Enforce that here. 1367 if (BInvalid) { 1368 const auto *E = B.get<const Expr *>(); 1369 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1370 "Unexpected type of invalid base"); 1371 } 1372 #endif 1373 1374 Base = B; 1375 Offset = CharUnits::fromQuantity(0); 1376 InvalidBase = BInvalid; 1377 Designator = SubobjectDesignator(getType(B)); 1378 IsNullPtr = false; 1379 } 1380 1381 void setNull(QualType PointerTy, uint64_t TargetVal) { 1382 Base = (Expr *)nullptr; 1383 Offset = CharUnits::fromQuantity(TargetVal); 1384 InvalidBase = false; 1385 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1386 IsNullPtr = true; 1387 } 1388 1389 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1390 set(B, true); 1391 } 1392 1393 // Check that this LValue is not based on a null pointer. If it is, produce 1394 // a diagnostic and mark the designator as invalid. 1395 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1396 CheckSubobjectKind CSK) { 1397 if (Designator.Invalid) 1398 return false; 1399 if (IsNullPtr) { 1400 Info.CCEDiag(E, diag::note_constexpr_null_subobject) 1401 << CSK; 1402 Designator.setInvalid(); 1403 return false; 1404 } 1405 return true; 1406 } 1407 1408 // Check this LValue refers to an object. If not, set the designator to be 1409 // invalid and emit a diagnostic. 1410 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1411 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1412 Designator.checkSubobject(Info, E, CSK); 1413 } 1414 1415 void addDecl(EvalInfo &Info, const Expr *E, 1416 const Decl *D, bool Virtual = false) { 1417 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1418 Designator.addDeclUnchecked(D, Virtual); 1419 } 1420 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1421 if (!Designator.Entries.empty()) { 1422 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1423 Designator.setInvalid(); 1424 return; 1425 } 1426 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1427 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1428 Designator.FirstEntryIsAnUnsizedArray = true; 1429 Designator.addUnsizedArrayUnchecked(ElemTy); 1430 } 1431 } 1432 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1433 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1434 Designator.addArrayUnchecked(CAT); 1435 } 1436 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1437 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1438 Designator.addComplexUnchecked(EltTy, Imag); 1439 } 1440 void clearIsNullPointer() { 1441 IsNullPtr = false; 1442 } 1443 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1444 const APSInt &Index, CharUnits ElementSize) { 1445 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1446 // but we're not required to diagnose it and it's valid in C++.) 1447 if (!Index) 1448 return; 1449 1450 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1451 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1452 // offsets. 1453 uint64_t Offset64 = Offset.getQuantity(); 1454 uint64_t ElemSize64 = ElementSize.getQuantity(); 1455 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1456 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1457 1458 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1459 Designator.adjustIndex(Info, E, Index); 1460 clearIsNullPointer(); 1461 } 1462 void adjustOffset(CharUnits N) { 1463 Offset += N; 1464 if (N.getQuantity()) 1465 clearIsNullPointer(); 1466 } 1467 }; 1468 1469 struct MemberPtr { 1470 MemberPtr() {} 1471 explicit MemberPtr(const ValueDecl *Decl) : 1472 DeclAndIsDerivedMember(Decl, false), Path() {} 1473 1474 /// The member or (direct or indirect) field referred to by this member 1475 /// pointer, or 0 if this is a null member pointer. 1476 const ValueDecl *getDecl() const { 1477 return DeclAndIsDerivedMember.getPointer(); 1478 } 1479 /// Is this actually a member of some type derived from the relevant class? 1480 bool isDerivedMember() const { 1481 return DeclAndIsDerivedMember.getInt(); 1482 } 1483 /// Get the class which the declaration actually lives in. 1484 const CXXRecordDecl *getContainingRecord() const { 1485 return cast<CXXRecordDecl>( 1486 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1487 } 1488 1489 void moveInto(APValue &V) const { 1490 V = APValue(getDecl(), isDerivedMember(), Path); 1491 } 1492 void setFrom(const APValue &V) { 1493 assert(V.isMemberPointer()); 1494 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1495 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1496 Path.clear(); 1497 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1498 Path.insert(Path.end(), P.begin(), P.end()); 1499 } 1500 1501 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1502 /// whether the member is a member of some class derived from the class type 1503 /// of the member pointer. 1504 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1505 /// Path - The path of base/derived classes from the member declaration's 1506 /// class (exclusive) to the class type of the member pointer (inclusive). 1507 SmallVector<const CXXRecordDecl*, 4> Path; 1508 1509 /// Perform a cast towards the class of the Decl (either up or down the 1510 /// hierarchy). 1511 bool castBack(const CXXRecordDecl *Class) { 1512 assert(!Path.empty()); 1513 const CXXRecordDecl *Expected; 1514 if (Path.size() >= 2) 1515 Expected = Path[Path.size() - 2]; 1516 else 1517 Expected = getContainingRecord(); 1518 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1519 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1520 // if B does not contain the original member and is not a base or 1521 // derived class of the class containing the original member, the result 1522 // of the cast is undefined. 1523 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1524 // (D::*). We consider that to be a language defect. 1525 return false; 1526 } 1527 Path.pop_back(); 1528 return true; 1529 } 1530 /// Perform a base-to-derived member pointer cast. 1531 bool castToDerived(const CXXRecordDecl *Derived) { 1532 if (!getDecl()) 1533 return true; 1534 if (!isDerivedMember()) { 1535 Path.push_back(Derived); 1536 return true; 1537 } 1538 if (!castBack(Derived)) 1539 return false; 1540 if (Path.empty()) 1541 DeclAndIsDerivedMember.setInt(false); 1542 return true; 1543 } 1544 /// Perform a derived-to-base member pointer cast. 1545 bool castToBase(const CXXRecordDecl *Base) { 1546 if (!getDecl()) 1547 return true; 1548 if (Path.empty()) 1549 DeclAndIsDerivedMember.setInt(true); 1550 if (isDerivedMember()) { 1551 Path.push_back(Base); 1552 return true; 1553 } 1554 return castBack(Base); 1555 } 1556 }; 1557 1558 /// Compare two member pointers, which are assumed to be of the same type. 1559 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1560 if (!LHS.getDecl() || !RHS.getDecl()) 1561 return !LHS.getDecl() && !RHS.getDecl(); 1562 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1563 return false; 1564 return LHS.Path == RHS.Path; 1565 } 1566 } 1567 1568 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1569 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1570 const LValue &This, const Expr *E, 1571 bool AllowNonLiteralTypes = false); 1572 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1573 bool InvalidBaseOK = false); 1574 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1575 bool InvalidBaseOK = false); 1576 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1577 EvalInfo &Info); 1578 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1579 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1580 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1581 EvalInfo &Info); 1582 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1583 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1584 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1585 EvalInfo &Info); 1586 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1587 1588 //===----------------------------------------------------------------------===// 1589 // Misc utilities 1590 //===----------------------------------------------------------------------===// 1591 1592 /// A helper function to create a temporary and set an LValue. 1593 template <class KeyTy> 1594 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended, 1595 LValue &LV, CallStackFrame &Frame) { 1596 LV.set({Key, Frame.Info.CurrentCall->Index, 1597 Frame.Info.CurrentCall->getTempVersion()}); 1598 return Frame.createTemporary(Key, IsLifetimeExtended); 1599 } 1600 1601 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1602 /// preserving its value (by extending by up to one bit as needed). 1603 static void negateAsSigned(APSInt &Int) { 1604 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1605 Int = Int.extend(Int.getBitWidth() + 1); 1606 Int.setIsSigned(true); 1607 } 1608 Int = -Int; 1609 } 1610 1611 /// Produce a string describing the given constexpr call. 1612 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) { 1613 unsigned ArgIndex = 0; 1614 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) && 1615 !isa<CXXConstructorDecl>(Frame->Callee) && 1616 cast<CXXMethodDecl>(Frame->Callee)->isInstance(); 1617 1618 if (!IsMemberCall) 1619 Out << *Frame->Callee << '('; 1620 1621 if (Frame->This && IsMemberCall) { 1622 APValue Val; 1623 Frame->This->moveInto(Val); 1624 Val.printPretty(Out, Frame->Info.Ctx, 1625 Frame->This->Designator.MostDerivedType); 1626 // FIXME: Add parens around Val if needed. 1627 Out << "->" << *Frame->Callee << '('; 1628 IsMemberCall = false; 1629 } 1630 1631 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(), 1632 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) { 1633 if (ArgIndex > (unsigned)IsMemberCall) 1634 Out << ", "; 1635 1636 const ParmVarDecl *Param = *I; 1637 const APValue &Arg = Frame->Arguments[ArgIndex]; 1638 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType()); 1639 1640 if (ArgIndex == 0 && IsMemberCall) 1641 Out << "->" << *Frame->Callee << '('; 1642 } 1643 1644 Out << ')'; 1645 } 1646 1647 /// Evaluate an expression to see if it had side-effects, and discard its 1648 /// result. 1649 /// \return \c true if the caller should keep evaluating. 1650 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1651 APValue Scratch; 1652 if (!Evaluate(Scratch, Info, E)) 1653 // We don't need the value, but we might have skipped a side effect here. 1654 return Info.noteSideEffect(); 1655 return true; 1656 } 1657 1658 /// Should this call expression be treated as a string literal? 1659 static bool IsStringLiteralCall(const CallExpr *E) { 1660 unsigned Builtin = E->getBuiltinCallee(); 1661 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1662 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1663 } 1664 1665 static bool IsGlobalLValue(APValue::LValueBase B) { 1666 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1667 // constant expression of pointer type that evaluates to... 1668 1669 // ... a null pointer value, or a prvalue core constant expression of type 1670 // std::nullptr_t. 1671 if (!B) return true; 1672 1673 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1674 // ... the address of an object with static storage duration, 1675 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1676 return VD->hasGlobalStorage(); 1677 // ... the address of a function, 1678 return isa<FunctionDecl>(D); 1679 } 1680 1681 const Expr *E = B.get<const Expr*>(); 1682 switch (E->getStmtClass()) { 1683 default: 1684 return false; 1685 case Expr::CompoundLiteralExprClass: { 1686 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1687 return CLE->isFileScope() && CLE->isLValue(); 1688 } 1689 case Expr::MaterializeTemporaryExprClass: 1690 // A materialized temporary might have been lifetime-extended to static 1691 // storage duration. 1692 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1693 // A string literal has static storage duration. 1694 case Expr::StringLiteralClass: 1695 case Expr::PredefinedExprClass: 1696 case Expr::ObjCStringLiteralClass: 1697 case Expr::ObjCEncodeExprClass: 1698 case Expr::CXXTypeidExprClass: 1699 case Expr::CXXUuidofExprClass: 1700 return true; 1701 case Expr::CallExprClass: 1702 return IsStringLiteralCall(cast<CallExpr>(E)); 1703 // For GCC compatibility, &&label has static storage duration. 1704 case Expr::AddrLabelExprClass: 1705 return true; 1706 // A Block literal expression may be used as the initialization value for 1707 // Block variables at global or local static scope. 1708 case Expr::BlockExprClass: 1709 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1710 case Expr::ImplicitValueInitExprClass: 1711 // FIXME: 1712 // We can never form an lvalue with an implicit value initialization as its 1713 // base through expression evaluation, so these only appear in one case: the 1714 // implicit variable declaration we invent when checking whether a constexpr 1715 // constructor can produce a constant expression. We must assume that such 1716 // an expression might be a global lvalue. 1717 return true; 1718 } 1719 } 1720 1721 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1722 return LVal.Base.dyn_cast<const ValueDecl*>(); 1723 } 1724 1725 static bool IsLiteralLValue(const LValue &Value) { 1726 if (Value.getLValueCallIndex()) 1727 return false; 1728 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1729 return E && !isa<MaterializeTemporaryExpr>(E); 1730 } 1731 1732 static bool IsWeakLValue(const LValue &Value) { 1733 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1734 return Decl && Decl->isWeak(); 1735 } 1736 1737 static bool isZeroSized(const LValue &Value) { 1738 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1739 if (Decl && isa<VarDecl>(Decl)) { 1740 QualType Ty = Decl->getType(); 1741 if (Ty->isArrayType()) 1742 return Ty->isIncompleteType() || 1743 Decl->getASTContext().getTypeSize(Ty) == 0; 1744 } 1745 return false; 1746 } 1747 1748 static bool HasSameBase(const LValue &A, const LValue &B) { 1749 if (!A.getLValueBase()) 1750 return !B.getLValueBase(); 1751 if (!B.getLValueBase()) 1752 return false; 1753 1754 if (A.getLValueBase().getOpaqueValue() != 1755 B.getLValueBase().getOpaqueValue()) { 1756 const Decl *ADecl = GetLValueBaseDecl(A); 1757 if (!ADecl) 1758 return false; 1759 const Decl *BDecl = GetLValueBaseDecl(B); 1760 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 1761 return false; 1762 } 1763 1764 return IsGlobalLValue(A.getLValueBase()) || 1765 (A.getLValueCallIndex() == B.getLValueCallIndex() && 1766 A.getLValueVersion() == B.getLValueVersion()); 1767 } 1768 1769 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1770 assert(Base && "no location for a null lvalue"); 1771 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1772 if (VD) 1773 Info.Note(VD->getLocation(), diag::note_declared_at); 1774 else 1775 Info.Note(Base.get<const Expr*>()->getExprLoc(), 1776 diag::note_constexpr_temporary_here); 1777 } 1778 1779 /// Check that this reference or pointer core constant expression is a valid 1780 /// value for an address or reference constant expression. Return true if we 1781 /// can fold this expression, whether or not it's a constant expression. 1782 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 1783 QualType Type, const LValue &LVal, 1784 Expr::ConstExprUsage Usage) { 1785 bool IsReferenceType = Type->isReferenceType(); 1786 1787 APValue::LValueBase Base = LVal.getLValueBase(); 1788 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 1789 1790 // Check that the object is a global. Note that the fake 'this' object we 1791 // manufacture when checking potential constant expressions is conservatively 1792 // assumed to be global here. 1793 if (!IsGlobalLValue(Base)) { 1794 if (Info.getLangOpts().CPlusPlus11) { 1795 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1796 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 1797 << IsReferenceType << !Designator.Entries.empty() 1798 << !!VD << VD; 1799 NoteLValueLocation(Info, Base); 1800 } else { 1801 Info.FFDiag(Loc); 1802 } 1803 // Don't allow references to temporaries to escape. 1804 return false; 1805 } 1806 assert((Info.checkingPotentialConstantExpression() || 1807 LVal.getLValueCallIndex() == 0) && 1808 "have call index for global lvalue"); 1809 1810 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 1811 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 1812 // Check if this is a thread-local variable. 1813 if (Var->getTLSKind()) 1814 return false; 1815 1816 // A dllimport variable never acts like a constant. 1817 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 1818 return false; 1819 } 1820 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 1821 // __declspec(dllimport) must be handled very carefully: 1822 // We must never initialize an expression with the thunk in C++. 1823 // Doing otherwise would allow the same id-expression to yield 1824 // different addresses for the same function in different translation 1825 // units. However, this means that we must dynamically initialize the 1826 // expression with the contents of the import address table at runtime. 1827 // 1828 // The C language has no notion of ODR; furthermore, it has no notion of 1829 // dynamic initialization. This means that we are permitted to 1830 // perform initialization with the address of the thunk. 1831 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 1832 FD->hasAttr<DLLImportAttr>()) 1833 return false; 1834 } 1835 } 1836 1837 // Allow address constant expressions to be past-the-end pointers. This is 1838 // an extension: the standard requires them to point to an object. 1839 if (!IsReferenceType) 1840 return true; 1841 1842 // A reference constant expression must refer to an object. 1843 if (!Base) { 1844 // FIXME: diagnostic 1845 Info.CCEDiag(Loc); 1846 return true; 1847 } 1848 1849 // Does this refer one past the end of some object? 1850 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 1851 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1852 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 1853 << !Designator.Entries.empty() << !!VD << VD; 1854 NoteLValueLocation(Info, Base); 1855 } 1856 1857 return true; 1858 } 1859 1860 /// Member pointers are constant expressions unless they point to a 1861 /// non-virtual dllimport member function. 1862 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 1863 SourceLocation Loc, 1864 QualType Type, 1865 const APValue &Value, 1866 Expr::ConstExprUsage Usage) { 1867 const ValueDecl *Member = Value.getMemberPointerDecl(); 1868 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 1869 if (!FD) 1870 return true; 1871 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 1872 !FD->hasAttr<DLLImportAttr>(); 1873 } 1874 1875 /// Check that this core constant expression is of literal type, and if not, 1876 /// produce an appropriate diagnostic. 1877 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 1878 const LValue *This = nullptr) { 1879 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 1880 return true; 1881 1882 // C++1y: A constant initializer for an object o [...] may also invoke 1883 // constexpr constructors for o and its subobjects even if those objects 1884 // are of non-literal class types. 1885 // 1886 // C++11 missed this detail for aggregates, so classes like this: 1887 // struct foo_t { union { int i; volatile int j; } u; }; 1888 // are not (obviously) initializable like so: 1889 // __attribute__((__require_constant_initialization__)) 1890 // static const foo_t x = {{0}}; 1891 // because "i" is a subobject with non-literal initialization (due to the 1892 // volatile member of the union). See: 1893 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 1894 // Therefore, we use the C++1y behavior. 1895 if (This && Info.EvaluatingDecl == This->getLValueBase()) 1896 return true; 1897 1898 // Prvalue constant expressions must be of literal types. 1899 if (Info.getLangOpts().CPlusPlus11) 1900 Info.FFDiag(E, diag::note_constexpr_nonliteral) 1901 << E->getType(); 1902 else 1903 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 1904 return false; 1905 } 1906 1907 /// Check that this core constant expression value is a valid value for a 1908 /// constant expression. If not, report an appropriate diagnostic. Does not 1909 /// check that the expression is of literal type. 1910 static bool 1911 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 1912 const APValue &Value, 1913 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) { 1914 if (Value.isUninit()) { 1915 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 1916 << true << Type; 1917 return false; 1918 } 1919 1920 // We allow _Atomic(T) to be initialized from anything that T can be 1921 // initialized from. 1922 if (const AtomicType *AT = Type->getAs<AtomicType>()) 1923 Type = AT->getValueType(); 1924 1925 // Core issue 1454: For a literal constant expression of array or class type, 1926 // each subobject of its value shall have been initialized by a constant 1927 // expression. 1928 if (Value.isArray()) { 1929 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 1930 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 1931 if (!CheckConstantExpression(Info, DiagLoc, EltTy, 1932 Value.getArrayInitializedElt(I), Usage)) 1933 return false; 1934 } 1935 if (!Value.hasArrayFiller()) 1936 return true; 1937 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(), 1938 Usage); 1939 } 1940 if (Value.isUnion() && Value.getUnionField()) { 1941 return CheckConstantExpression(Info, DiagLoc, 1942 Value.getUnionField()->getType(), 1943 Value.getUnionValue(), Usage); 1944 } 1945 if (Value.isStruct()) { 1946 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 1947 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 1948 unsigned BaseIndex = 0; 1949 for (const CXXBaseSpecifier &BS : CD->bases()) { 1950 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(), 1951 Value.getStructBase(BaseIndex), Usage)) 1952 return false; 1953 ++BaseIndex; 1954 } 1955 } 1956 for (const auto *I : RD->fields()) { 1957 if (I->isUnnamedBitfield()) 1958 continue; 1959 1960 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 1961 Value.getStructField(I->getFieldIndex()), 1962 Usage)) 1963 return false; 1964 } 1965 } 1966 1967 if (Value.isLValue()) { 1968 LValue LVal; 1969 LVal.setFrom(Info.Ctx, Value); 1970 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage); 1971 } 1972 1973 if (Value.isMemberPointer()) 1974 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 1975 1976 // Everything else is fine. 1977 return true; 1978 } 1979 1980 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 1981 // A null base expression indicates a null pointer. These are always 1982 // evaluatable, and they are false unless the offset is zero. 1983 if (!Value.getLValueBase()) { 1984 Result = !Value.getLValueOffset().isZero(); 1985 return true; 1986 } 1987 1988 // We have a non-null base. These are generally known to be true, but if it's 1989 // a weak declaration it can be null at runtime. 1990 Result = true; 1991 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 1992 return !Decl || !Decl->isWeak(); 1993 } 1994 1995 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 1996 switch (Val.getKind()) { 1997 case APValue::Uninitialized: 1998 return false; 1999 case APValue::Int: 2000 Result = Val.getInt().getBoolValue(); 2001 return true; 2002 case APValue::Float: 2003 Result = !Val.getFloat().isZero(); 2004 return true; 2005 case APValue::ComplexInt: 2006 Result = Val.getComplexIntReal().getBoolValue() || 2007 Val.getComplexIntImag().getBoolValue(); 2008 return true; 2009 case APValue::ComplexFloat: 2010 Result = !Val.getComplexFloatReal().isZero() || 2011 !Val.getComplexFloatImag().isZero(); 2012 return true; 2013 case APValue::LValue: 2014 return EvalPointerValueAsBool(Val, Result); 2015 case APValue::MemberPointer: 2016 Result = Val.getMemberPointerDecl(); 2017 return true; 2018 case APValue::Vector: 2019 case APValue::Array: 2020 case APValue::Struct: 2021 case APValue::Union: 2022 case APValue::AddrLabelDiff: 2023 return false; 2024 } 2025 2026 llvm_unreachable("unknown APValue kind"); 2027 } 2028 2029 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2030 EvalInfo &Info) { 2031 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2032 APValue Val; 2033 if (!Evaluate(Val, Info, E)) 2034 return false; 2035 return HandleConversionToBool(Val, Result); 2036 } 2037 2038 template<typename T> 2039 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2040 const T &SrcValue, QualType DestType) { 2041 Info.CCEDiag(E, diag::note_constexpr_overflow) 2042 << SrcValue << DestType; 2043 return Info.noteUndefinedBehavior(); 2044 } 2045 2046 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2047 QualType SrcType, const APFloat &Value, 2048 QualType DestType, APSInt &Result) { 2049 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2050 // Determine whether we are converting to unsigned or signed. 2051 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2052 2053 Result = APSInt(DestWidth, !DestSigned); 2054 bool ignored; 2055 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2056 & APFloat::opInvalidOp) 2057 return HandleOverflow(Info, E, Value, DestType); 2058 return true; 2059 } 2060 2061 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2062 QualType SrcType, QualType DestType, 2063 APFloat &Result) { 2064 APFloat Value = Result; 2065 bool ignored; 2066 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 2067 APFloat::rmNearestTiesToEven, &ignored) 2068 & APFloat::opOverflow) 2069 return HandleOverflow(Info, E, Value, DestType); 2070 return true; 2071 } 2072 2073 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2074 QualType DestType, QualType SrcType, 2075 const APSInt &Value) { 2076 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2077 // Figure out if this is a truncate, extend or noop cast. 2078 // If the input is signed, do a sign extend, noop, or truncate. 2079 APSInt Result = Value.extOrTrunc(DestWidth); 2080 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2081 if (DestType->isBooleanType()) 2082 Result = Value.getBoolValue(); 2083 return Result; 2084 } 2085 2086 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2087 QualType SrcType, const APSInt &Value, 2088 QualType DestType, APFloat &Result) { 2089 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2090 if (Result.convertFromAPInt(Value, Value.isSigned(), 2091 APFloat::rmNearestTiesToEven) 2092 & APFloat::opOverflow) 2093 return HandleOverflow(Info, E, Value, DestType); 2094 return true; 2095 } 2096 2097 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2098 APValue &Value, const FieldDecl *FD) { 2099 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2100 2101 if (!Value.isInt()) { 2102 // Trying to store a pointer-cast-to-integer into a bitfield. 2103 // FIXME: In this case, we should provide the diagnostic for casting 2104 // a pointer to an integer. 2105 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2106 Info.FFDiag(E); 2107 return false; 2108 } 2109 2110 APSInt &Int = Value.getInt(); 2111 unsigned OldBitWidth = Int.getBitWidth(); 2112 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2113 if (NewBitWidth < OldBitWidth) 2114 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2115 return true; 2116 } 2117 2118 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2119 llvm::APInt &Res) { 2120 APValue SVal; 2121 if (!Evaluate(SVal, Info, E)) 2122 return false; 2123 if (SVal.isInt()) { 2124 Res = SVal.getInt(); 2125 return true; 2126 } 2127 if (SVal.isFloat()) { 2128 Res = SVal.getFloat().bitcastToAPInt(); 2129 return true; 2130 } 2131 if (SVal.isVector()) { 2132 QualType VecTy = E->getType(); 2133 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2134 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2135 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2136 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2137 Res = llvm::APInt::getNullValue(VecSize); 2138 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2139 APValue &Elt = SVal.getVectorElt(i); 2140 llvm::APInt EltAsInt; 2141 if (Elt.isInt()) { 2142 EltAsInt = Elt.getInt(); 2143 } else if (Elt.isFloat()) { 2144 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2145 } else { 2146 // Don't try to handle vectors of anything other than int or float 2147 // (not sure if it's possible to hit this case). 2148 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2149 return false; 2150 } 2151 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2152 if (BigEndian) 2153 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2154 else 2155 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2156 } 2157 return true; 2158 } 2159 // Give up if the input isn't an int, float, or vector. For example, we 2160 // reject "(v4i16)(intptr_t)&a". 2161 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2162 return false; 2163 } 2164 2165 /// Perform the given integer operation, which is known to need at most BitWidth 2166 /// bits, and check for overflow in the original type (if that type was not an 2167 /// unsigned type). 2168 template<typename Operation> 2169 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2170 const APSInt &LHS, const APSInt &RHS, 2171 unsigned BitWidth, Operation Op, 2172 APSInt &Result) { 2173 if (LHS.isUnsigned()) { 2174 Result = Op(LHS, RHS); 2175 return true; 2176 } 2177 2178 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2179 Result = Value.trunc(LHS.getBitWidth()); 2180 if (Result.extend(BitWidth) != Value) { 2181 if (Info.checkingForOverflow()) 2182 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2183 diag::warn_integer_constant_overflow) 2184 << Result.toString(10) << E->getType(); 2185 else 2186 return HandleOverflow(Info, E, Value, E->getType()); 2187 } 2188 return true; 2189 } 2190 2191 /// Perform the given binary integer operation. 2192 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2193 BinaryOperatorKind Opcode, APSInt RHS, 2194 APSInt &Result) { 2195 switch (Opcode) { 2196 default: 2197 Info.FFDiag(E); 2198 return false; 2199 case BO_Mul: 2200 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2201 std::multiplies<APSInt>(), Result); 2202 case BO_Add: 2203 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2204 std::plus<APSInt>(), Result); 2205 case BO_Sub: 2206 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2207 std::minus<APSInt>(), Result); 2208 case BO_And: Result = LHS & RHS; return true; 2209 case BO_Xor: Result = LHS ^ RHS; return true; 2210 case BO_Or: Result = LHS | RHS; return true; 2211 case BO_Div: 2212 case BO_Rem: 2213 if (RHS == 0) { 2214 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2215 return false; 2216 } 2217 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2218 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2219 // this operation and gives the two's complement result. 2220 if (RHS.isNegative() && RHS.isAllOnesValue() && 2221 LHS.isSigned() && LHS.isMinSignedValue()) 2222 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2223 E->getType()); 2224 return true; 2225 case BO_Shl: { 2226 if (Info.getLangOpts().OpenCL) 2227 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2228 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2229 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2230 RHS.isUnsigned()); 2231 else if (RHS.isSigned() && RHS.isNegative()) { 2232 // During constant-folding, a negative shift is an opposite shift. Such 2233 // a shift is not a constant expression. 2234 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2235 RHS = -RHS; 2236 goto shift_right; 2237 } 2238 shift_left: 2239 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2240 // the shifted type. 2241 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2242 if (SA != RHS) { 2243 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2244 << RHS << E->getType() << LHS.getBitWidth(); 2245 } else if (LHS.isSigned()) { 2246 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2247 // operand, and must not overflow the corresponding unsigned type. 2248 if (LHS.isNegative()) 2249 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2250 else if (LHS.countLeadingZeros() < SA) 2251 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2252 } 2253 Result = LHS << SA; 2254 return true; 2255 } 2256 case BO_Shr: { 2257 if (Info.getLangOpts().OpenCL) 2258 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2259 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2260 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2261 RHS.isUnsigned()); 2262 else if (RHS.isSigned() && RHS.isNegative()) { 2263 // During constant-folding, a negative shift is an opposite shift. Such a 2264 // shift is not a constant expression. 2265 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2266 RHS = -RHS; 2267 goto shift_left; 2268 } 2269 shift_right: 2270 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2271 // shifted type. 2272 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2273 if (SA != RHS) 2274 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2275 << RHS << E->getType() << LHS.getBitWidth(); 2276 Result = LHS >> SA; 2277 return true; 2278 } 2279 2280 case BO_LT: Result = LHS < RHS; return true; 2281 case BO_GT: Result = LHS > RHS; return true; 2282 case BO_LE: Result = LHS <= RHS; return true; 2283 case BO_GE: Result = LHS >= RHS; return true; 2284 case BO_EQ: Result = LHS == RHS; return true; 2285 case BO_NE: Result = LHS != RHS; return true; 2286 case BO_Cmp: 2287 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2288 } 2289 } 2290 2291 /// Perform the given binary floating-point operation, in-place, on LHS. 2292 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2293 APFloat &LHS, BinaryOperatorKind Opcode, 2294 const APFloat &RHS) { 2295 switch (Opcode) { 2296 default: 2297 Info.FFDiag(E); 2298 return false; 2299 case BO_Mul: 2300 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2301 break; 2302 case BO_Add: 2303 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2304 break; 2305 case BO_Sub: 2306 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2307 break; 2308 case BO_Div: 2309 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2310 break; 2311 } 2312 2313 if (LHS.isInfinity() || LHS.isNaN()) { 2314 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2315 return Info.noteUndefinedBehavior(); 2316 } 2317 return true; 2318 } 2319 2320 /// Cast an lvalue referring to a base subobject to a derived class, by 2321 /// truncating the lvalue's path to the given length. 2322 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2323 const RecordDecl *TruncatedType, 2324 unsigned TruncatedElements) { 2325 SubobjectDesignator &D = Result.Designator; 2326 2327 // Check we actually point to a derived class object. 2328 if (TruncatedElements == D.Entries.size()) 2329 return true; 2330 assert(TruncatedElements >= D.MostDerivedPathLength && 2331 "not casting to a derived class"); 2332 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2333 return false; 2334 2335 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2336 const RecordDecl *RD = TruncatedType; 2337 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2338 if (RD->isInvalidDecl()) return false; 2339 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2340 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2341 if (isVirtualBaseClass(D.Entries[I])) 2342 Result.Offset -= Layout.getVBaseClassOffset(Base); 2343 else 2344 Result.Offset -= Layout.getBaseClassOffset(Base); 2345 RD = Base; 2346 } 2347 D.Entries.resize(TruncatedElements); 2348 return true; 2349 } 2350 2351 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2352 const CXXRecordDecl *Derived, 2353 const CXXRecordDecl *Base, 2354 const ASTRecordLayout *RL = nullptr) { 2355 if (!RL) { 2356 if (Derived->isInvalidDecl()) return false; 2357 RL = &Info.Ctx.getASTRecordLayout(Derived); 2358 } 2359 2360 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2361 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2362 return true; 2363 } 2364 2365 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2366 const CXXRecordDecl *DerivedDecl, 2367 const CXXBaseSpecifier *Base) { 2368 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2369 2370 if (!Base->isVirtual()) 2371 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2372 2373 SubobjectDesignator &D = Obj.Designator; 2374 if (D.Invalid) 2375 return false; 2376 2377 // Extract most-derived object and corresponding type. 2378 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2379 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2380 return false; 2381 2382 // Find the virtual base class. 2383 if (DerivedDecl->isInvalidDecl()) return false; 2384 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2385 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2386 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2387 return true; 2388 } 2389 2390 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2391 QualType Type, LValue &Result) { 2392 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2393 PathE = E->path_end(); 2394 PathI != PathE; ++PathI) { 2395 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2396 *PathI)) 2397 return false; 2398 Type = (*PathI)->getType(); 2399 } 2400 return true; 2401 } 2402 2403 /// Update LVal to refer to the given field, which must be a member of the type 2404 /// currently described by LVal. 2405 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2406 const FieldDecl *FD, 2407 const ASTRecordLayout *RL = nullptr) { 2408 if (!RL) { 2409 if (FD->getParent()->isInvalidDecl()) return false; 2410 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2411 } 2412 2413 unsigned I = FD->getFieldIndex(); 2414 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2415 LVal.addDecl(Info, E, FD); 2416 return true; 2417 } 2418 2419 /// Update LVal to refer to the given indirect field. 2420 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2421 LValue &LVal, 2422 const IndirectFieldDecl *IFD) { 2423 for (const auto *C : IFD->chain()) 2424 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2425 return false; 2426 return true; 2427 } 2428 2429 /// Get the size of the given type in char units. 2430 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2431 QualType Type, CharUnits &Size) { 2432 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2433 // extension. 2434 if (Type->isVoidType() || Type->isFunctionType()) { 2435 Size = CharUnits::One(); 2436 return true; 2437 } 2438 2439 if (Type->isDependentType()) { 2440 Info.FFDiag(Loc); 2441 return false; 2442 } 2443 2444 if (!Type->isConstantSizeType()) { 2445 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2446 // FIXME: Better diagnostic. 2447 Info.FFDiag(Loc); 2448 return false; 2449 } 2450 2451 Size = Info.Ctx.getTypeSizeInChars(Type); 2452 return true; 2453 } 2454 2455 /// Update a pointer value to model pointer arithmetic. 2456 /// \param Info - Information about the ongoing evaluation. 2457 /// \param E - The expression being evaluated, for diagnostic purposes. 2458 /// \param LVal - The pointer value to be updated. 2459 /// \param EltTy - The pointee type represented by LVal. 2460 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2461 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2462 LValue &LVal, QualType EltTy, 2463 APSInt Adjustment) { 2464 CharUnits SizeOfPointee; 2465 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2466 return false; 2467 2468 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2469 return true; 2470 } 2471 2472 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2473 LValue &LVal, QualType EltTy, 2474 int64_t Adjustment) { 2475 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 2476 APSInt::get(Adjustment)); 2477 } 2478 2479 /// Update an lvalue to refer to a component of a complex number. 2480 /// \param Info - Information about the ongoing evaluation. 2481 /// \param LVal - The lvalue to be updated. 2482 /// \param EltTy - The complex number's component type. 2483 /// \param Imag - False for the real component, true for the imaginary. 2484 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 2485 LValue &LVal, QualType EltTy, 2486 bool Imag) { 2487 if (Imag) { 2488 CharUnits SizeOfComponent; 2489 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 2490 return false; 2491 LVal.Offset += SizeOfComponent; 2492 } 2493 LVal.addComplex(Info, E, EltTy, Imag); 2494 return true; 2495 } 2496 2497 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 2498 QualType Type, const LValue &LVal, 2499 APValue &RVal); 2500 2501 /// Try to evaluate the initializer for a variable declaration. 2502 /// 2503 /// \param Info Information about the ongoing evaluation. 2504 /// \param E An expression to be used when printing diagnostics. 2505 /// \param VD The variable whose initializer should be obtained. 2506 /// \param Frame The frame in which the variable was created. Must be null 2507 /// if this variable is not local to the evaluation. 2508 /// \param Result Filled in with a pointer to the value of the variable. 2509 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 2510 const VarDecl *VD, CallStackFrame *Frame, 2511 APValue *&Result, const LValue *LVal) { 2512 2513 // If this is a parameter to an active constexpr function call, perform 2514 // argument substitution. 2515 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 2516 // Assume arguments of a potential constant expression are unknown 2517 // constant expressions. 2518 if (Info.checkingPotentialConstantExpression()) 2519 return false; 2520 if (!Frame || !Frame->Arguments) { 2521 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2522 return false; 2523 } 2524 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 2525 return true; 2526 } 2527 2528 // If this is a local variable, dig out its value. 2529 if (Frame) { 2530 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 2531 : Frame->getCurrentTemporary(VD); 2532 if (!Result) { 2533 // Assume variables referenced within a lambda's call operator that were 2534 // not declared within the call operator are captures and during checking 2535 // of a potential constant expression, assume they are unknown constant 2536 // expressions. 2537 assert(isLambdaCallOperator(Frame->Callee) && 2538 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 2539 "missing value for local variable"); 2540 if (Info.checkingPotentialConstantExpression()) 2541 return false; 2542 // FIXME: implement capture evaluation during constant expr evaluation. 2543 Info.FFDiag(E->getBeginLoc(), 2544 diag::note_unimplemented_constexpr_lambda_feature_ast) 2545 << "captures not currently allowed"; 2546 return false; 2547 } 2548 return true; 2549 } 2550 2551 // Dig out the initializer, and use the declaration which it's attached to. 2552 const Expr *Init = VD->getAnyInitializer(VD); 2553 if (!Init || Init->isValueDependent()) { 2554 // If we're checking a potential constant expression, the variable could be 2555 // initialized later. 2556 if (!Info.checkingPotentialConstantExpression()) 2557 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2558 return false; 2559 } 2560 2561 // If we're currently evaluating the initializer of this declaration, use that 2562 // in-flight value. 2563 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 2564 Result = Info.EvaluatingDeclValue; 2565 return true; 2566 } 2567 2568 // Never evaluate the initializer of a weak variable. We can't be sure that 2569 // this is the definition which will be used. 2570 if (VD->isWeak()) { 2571 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2572 return false; 2573 } 2574 2575 // Check that we can fold the initializer. In C++, we will have already done 2576 // this in the cases where it matters for conformance. 2577 SmallVector<PartialDiagnosticAt, 8> Notes; 2578 if (!VD->evaluateValue(Notes)) { 2579 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 2580 Notes.size() + 1) << VD; 2581 Info.Note(VD->getLocation(), diag::note_declared_at); 2582 Info.addNotes(Notes); 2583 return false; 2584 } else if (!VD->checkInitIsICE()) { 2585 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 2586 Notes.size() + 1) << VD; 2587 Info.Note(VD->getLocation(), diag::note_declared_at); 2588 Info.addNotes(Notes); 2589 } 2590 2591 Result = VD->getEvaluatedValue(); 2592 return true; 2593 } 2594 2595 static bool IsConstNonVolatile(QualType T) { 2596 Qualifiers Quals = T.getQualifiers(); 2597 return Quals.hasConst() && !Quals.hasVolatile(); 2598 } 2599 2600 /// Get the base index of the given base class within an APValue representing 2601 /// the given derived class. 2602 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 2603 const CXXRecordDecl *Base) { 2604 Base = Base->getCanonicalDecl(); 2605 unsigned Index = 0; 2606 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 2607 E = Derived->bases_end(); I != E; ++I, ++Index) { 2608 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 2609 return Index; 2610 } 2611 2612 llvm_unreachable("base class missing from derived class's bases list"); 2613 } 2614 2615 /// Extract the value of a character from a string literal. 2616 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 2617 uint64_t Index) { 2618 // FIXME: Support MakeStringConstant 2619 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 2620 std::string Str; 2621 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 2622 assert(Index <= Str.size() && "Index too large"); 2623 return APSInt::getUnsigned(Str.c_str()[Index]); 2624 } 2625 2626 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 2627 Lit = PE->getFunctionName(); 2628 const StringLiteral *S = cast<StringLiteral>(Lit); 2629 const ConstantArrayType *CAT = 2630 Info.Ctx.getAsConstantArrayType(S->getType()); 2631 assert(CAT && "string literal isn't an array"); 2632 QualType CharType = CAT->getElementType(); 2633 assert(CharType->isIntegerType() && "unexpected character type"); 2634 2635 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2636 CharType->isUnsignedIntegerType()); 2637 if (Index < S->getLength()) 2638 Value = S->getCodeUnit(Index); 2639 return Value; 2640 } 2641 2642 // Expand a string literal into an array of characters. 2643 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit, 2644 APValue &Result) { 2645 const StringLiteral *S = cast<StringLiteral>(Lit); 2646 const ConstantArrayType *CAT = 2647 Info.Ctx.getAsConstantArrayType(S->getType()); 2648 assert(CAT && "string literal isn't an array"); 2649 QualType CharType = CAT->getElementType(); 2650 assert(CharType->isIntegerType() && "unexpected character type"); 2651 2652 unsigned Elts = CAT->getSize().getZExtValue(); 2653 Result = APValue(APValue::UninitArray(), 2654 std::min(S->getLength(), Elts), Elts); 2655 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2656 CharType->isUnsignedIntegerType()); 2657 if (Result.hasArrayFiller()) 2658 Result.getArrayFiller() = APValue(Value); 2659 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 2660 Value = S->getCodeUnit(I); 2661 Result.getArrayInitializedElt(I) = APValue(Value); 2662 } 2663 } 2664 2665 // Expand an array so that it has more than Index filled elements. 2666 static void expandArray(APValue &Array, unsigned Index) { 2667 unsigned Size = Array.getArraySize(); 2668 assert(Index < Size); 2669 2670 // Always at least double the number of elements for which we store a value. 2671 unsigned OldElts = Array.getArrayInitializedElts(); 2672 unsigned NewElts = std::max(Index+1, OldElts * 2); 2673 NewElts = std::min(Size, std::max(NewElts, 8u)); 2674 2675 // Copy the data across. 2676 APValue NewValue(APValue::UninitArray(), NewElts, Size); 2677 for (unsigned I = 0; I != OldElts; ++I) 2678 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 2679 for (unsigned I = OldElts; I != NewElts; ++I) 2680 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 2681 if (NewValue.hasArrayFiller()) 2682 NewValue.getArrayFiller() = Array.getArrayFiller(); 2683 Array.swap(NewValue); 2684 } 2685 2686 /// Determine whether a type would actually be read by an lvalue-to-rvalue 2687 /// conversion. If it's of class type, we may assume that the copy operation 2688 /// is trivial. Note that this is never true for a union type with fields 2689 /// (because the copy always "reads" the active member) and always true for 2690 /// a non-class type. 2691 static bool isReadByLvalueToRvalueConversion(QualType T) { 2692 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2693 if (!RD || (RD->isUnion() && !RD->field_empty())) 2694 return true; 2695 if (RD->isEmpty()) 2696 return false; 2697 2698 for (auto *Field : RD->fields()) 2699 if (isReadByLvalueToRvalueConversion(Field->getType())) 2700 return true; 2701 2702 for (auto &BaseSpec : RD->bases()) 2703 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 2704 return true; 2705 2706 return false; 2707 } 2708 2709 /// Diagnose an attempt to read from any unreadable field within the specified 2710 /// type, which might be a class type. 2711 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E, 2712 QualType T) { 2713 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2714 if (!RD) 2715 return false; 2716 2717 if (!RD->hasMutableFields()) 2718 return false; 2719 2720 for (auto *Field : RD->fields()) { 2721 // If we're actually going to read this field in some way, then it can't 2722 // be mutable. If we're in a union, then assigning to a mutable field 2723 // (even an empty one) can change the active member, so that's not OK. 2724 // FIXME: Add core issue number for the union case. 2725 if (Field->isMutable() && 2726 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 2727 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field; 2728 Info.Note(Field->getLocation(), diag::note_declared_at); 2729 return true; 2730 } 2731 2732 if (diagnoseUnreadableFields(Info, E, Field->getType())) 2733 return true; 2734 } 2735 2736 for (auto &BaseSpec : RD->bases()) 2737 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType())) 2738 return true; 2739 2740 // All mutable fields were empty, and thus not actually read. 2741 return false; 2742 } 2743 2744 /// Kinds of access we can perform on an object, for diagnostics. 2745 enum AccessKinds { 2746 AK_Read, 2747 AK_Assign, 2748 AK_Increment, 2749 AK_Decrement 2750 }; 2751 2752 namespace { 2753 /// A handle to a complete object (an object that is not a subobject of 2754 /// another object). 2755 struct CompleteObject { 2756 /// The value of the complete object. 2757 APValue *Value; 2758 /// The type of the complete object. 2759 QualType Type; 2760 bool LifetimeStartedInEvaluation; 2761 2762 CompleteObject() : Value(nullptr) {} 2763 CompleteObject(APValue *Value, QualType Type, 2764 bool LifetimeStartedInEvaluation) 2765 : Value(Value), Type(Type), 2766 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) { 2767 assert(Value && "missing value for complete object"); 2768 } 2769 2770 explicit operator bool() const { return Value; } 2771 }; 2772 } // end anonymous namespace 2773 2774 /// Find the designated sub-object of an rvalue. 2775 template<typename SubobjectHandler> 2776 typename SubobjectHandler::result_type 2777 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 2778 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 2779 if (Sub.Invalid) 2780 // A diagnostic will have already been produced. 2781 return handler.failed(); 2782 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 2783 if (Info.getLangOpts().CPlusPlus11) 2784 Info.FFDiag(E, Sub.isOnePastTheEnd() 2785 ? diag::note_constexpr_access_past_end 2786 : diag::note_constexpr_access_unsized_array) 2787 << handler.AccessKind; 2788 else 2789 Info.FFDiag(E); 2790 return handler.failed(); 2791 } 2792 2793 APValue *O = Obj.Value; 2794 QualType ObjType = Obj.Type; 2795 const FieldDecl *LastField = nullptr; 2796 const bool MayReadMutableMembers = 2797 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14; 2798 2799 // Walk the designator's path to find the subobject. 2800 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 2801 if (O->isUninit()) { 2802 if (!Info.checkingPotentialConstantExpression()) 2803 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind; 2804 return handler.failed(); 2805 } 2806 2807 if (I == N) { 2808 // If we are reading an object of class type, there may still be more 2809 // things we need to check: if there are any mutable subobjects, we 2810 // cannot perform this read. (This only happens when performing a trivial 2811 // copy or assignment.) 2812 if (ObjType->isRecordType() && handler.AccessKind == AK_Read && 2813 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType)) 2814 return handler.failed(); 2815 2816 if (!handler.found(*O, ObjType)) 2817 return false; 2818 2819 // If we modified a bit-field, truncate it to the right width. 2820 if (handler.AccessKind != AK_Read && 2821 LastField && LastField->isBitField() && 2822 !truncateBitfieldValue(Info, E, *O, LastField)) 2823 return false; 2824 2825 return true; 2826 } 2827 2828 LastField = nullptr; 2829 if (ObjType->isArrayType()) { 2830 // Next subobject is an array element. 2831 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 2832 assert(CAT && "vla in literal type?"); 2833 uint64_t Index = Sub.Entries[I].ArrayIndex; 2834 if (CAT->getSize().ule(Index)) { 2835 // Note, it should not be possible to form a pointer with a valid 2836 // designator which points more than one past the end of the array. 2837 if (Info.getLangOpts().CPlusPlus11) 2838 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2839 << handler.AccessKind; 2840 else 2841 Info.FFDiag(E); 2842 return handler.failed(); 2843 } 2844 2845 ObjType = CAT->getElementType(); 2846 2847 // An array object is represented as either an Array APValue or as an 2848 // LValue which refers to a string literal. 2849 if (O->isLValue()) { 2850 assert(I == N - 1 && "extracting subobject of character?"); 2851 assert(!O->hasLValuePath() || O->getLValuePath().empty()); 2852 if (handler.AccessKind != AK_Read) 2853 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(), 2854 *O); 2855 else 2856 return handler.foundString(*O, ObjType, Index); 2857 } 2858 2859 if (O->getArrayInitializedElts() > Index) 2860 O = &O->getArrayInitializedElt(Index); 2861 else if (handler.AccessKind != AK_Read) { 2862 expandArray(*O, Index); 2863 O = &O->getArrayInitializedElt(Index); 2864 } else 2865 O = &O->getArrayFiller(); 2866 } else if (ObjType->isAnyComplexType()) { 2867 // Next subobject is a complex number. 2868 uint64_t Index = Sub.Entries[I].ArrayIndex; 2869 if (Index > 1) { 2870 if (Info.getLangOpts().CPlusPlus11) 2871 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2872 << handler.AccessKind; 2873 else 2874 Info.FFDiag(E); 2875 return handler.failed(); 2876 } 2877 2878 bool WasConstQualified = ObjType.isConstQualified(); 2879 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 2880 if (WasConstQualified) 2881 ObjType.addConst(); 2882 2883 assert(I == N - 1 && "extracting subobject of scalar?"); 2884 if (O->isComplexInt()) { 2885 return handler.found(Index ? O->getComplexIntImag() 2886 : O->getComplexIntReal(), ObjType); 2887 } else { 2888 assert(O->isComplexFloat()); 2889 return handler.found(Index ? O->getComplexFloatImag() 2890 : O->getComplexFloatReal(), ObjType); 2891 } 2892 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 2893 // In C++14 onwards, it is permitted to read a mutable member whose 2894 // lifetime began within the evaluation. 2895 // FIXME: Should we also allow this in C++11? 2896 if (Field->isMutable() && handler.AccessKind == AK_Read && 2897 !MayReadMutableMembers) { 2898 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) 2899 << Field; 2900 Info.Note(Field->getLocation(), diag::note_declared_at); 2901 return handler.failed(); 2902 } 2903 2904 // Next subobject is a class, struct or union field. 2905 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 2906 if (RD->isUnion()) { 2907 const FieldDecl *UnionField = O->getUnionField(); 2908 if (!UnionField || 2909 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 2910 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 2911 << handler.AccessKind << Field << !UnionField << UnionField; 2912 return handler.failed(); 2913 } 2914 O = &O->getUnionValue(); 2915 } else 2916 O = &O->getStructField(Field->getFieldIndex()); 2917 2918 bool WasConstQualified = ObjType.isConstQualified(); 2919 ObjType = Field->getType(); 2920 if (WasConstQualified && !Field->isMutable()) 2921 ObjType.addConst(); 2922 2923 if (ObjType.isVolatileQualified()) { 2924 if (Info.getLangOpts().CPlusPlus) { 2925 // FIXME: Include a description of the path to the volatile subobject. 2926 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 2927 << handler.AccessKind << 2 << Field; 2928 Info.Note(Field->getLocation(), diag::note_declared_at); 2929 } else { 2930 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2931 } 2932 return handler.failed(); 2933 } 2934 2935 LastField = Field; 2936 } else { 2937 // Next subobject is a base class. 2938 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 2939 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 2940 O = &O->getStructBase(getBaseIndex(Derived, Base)); 2941 2942 bool WasConstQualified = ObjType.isConstQualified(); 2943 ObjType = Info.Ctx.getRecordType(Base); 2944 if (WasConstQualified) 2945 ObjType.addConst(); 2946 } 2947 } 2948 } 2949 2950 namespace { 2951 struct ExtractSubobjectHandler { 2952 EvalInfo &Info; 2953 APValue &Result; 2954 2955 static const AccessKinds AccessKind = AK_Read; 2956 2957 typedef bool result_type; 2958 bool failed() { return false; } 2959 bool found(APValue &Subobj, QualType SubobjType) { 2960 Result = Subobj; 2961 return true; 2962 } 2963 bool found(APSInt &Value, QualType SubobjType) { 2964 Result = APValue(Value); 2965 return true; 2966 } 2967 bool found(APFloat &Value, QualType SubobjType) { 2968 Result = APValue(Value); 2969 return true; 2970 } 2971 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 2972 Result = APValue(extractStringLiteralCharacter( 2973 Info, Subobj.getLValueBase().get<const Expr *>(), Character)); 2974 return true; 2975 } 2976 }; 2977 } // end anonymous namespace 2978 2979 const AccessKinds ExtractSubobjectHandler::AccessKind; 2980 2981 /// Extract the designated sub-object of an rvalue. 2982 static bool extractSubobject(EvalInfo &Info, const Expr *E, 2983 const CompleteObject &Obj, 2984 const SubobjectDesignator &Sub, 2985 APValue &Result) { 2986 ExtractSubobjectHandler Handler = { Info, Result }; 2987 return findSubobject(Info, E, Obj, Sub, Handler); 2988 } 2989 2990 namespace { 2991 struct ModifySubobjectHandler { 2992 EvalInfo &Info; 2993 APValue &NewVal; 2994 const Expr *E; 2995 2996 typedef bool result_type; 2997 static const AccessKinds AccessKind = AK_Assign; 2998 2999 bool checkConst(QualType QT) { 3000 // Assigning to a const object has undefined behavior. 3001 if (QT.isConstQualified()) { 3002 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3003 return false; 3004 } 3005 return true; 3006 } 3007 3008 bool failed() { return false; } 3009 bool found(APValue &Subobj, QualType SubobjType) { 3010 if (!checkConst(SubobjType)) 3011 return false; 3012 // We've been given ownership of NewVal, so just swap it in. 3013 Subobj.swap(NewVal); 3014 return true; 3015 } 3016 bool found(APSInt &Value, QualType SubobjType) { 3017 if (!checkConst(SubobjType)) 3018 return false; 3019 if (!NewVal.isInt()) { 3020 // Maybe trying to write a cast pointer value into a complex? 3021 Info.FFDiag(E); 3022 return false; 3023 } 3024 Value = NewVal.getInt(); 3025 return true; 3026 } 3027 bool found(APFloat &Value, QualType SubobjType) { 3028 if (!checkConst(SubobjType)) 3029 return false; 3030 Value = NewVal.getFloat(); 3031 return true; 3032 } 3033 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3034 llvm_unreachable("shouldn't encounter string elements with ExpandArrays"); 3035 } 3036 }; 3037 } // end anonymous namespace 3038 3039 const AccessKinds ModifySubobjectHandler::AccessKind; 3040 3041 /// Update the designated sub-object of an rvalue to the given value. 3042 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3043 const CompleteObject &Obj, 3044 const SubobjectDesignator &Sub, 3045 APValue &NewVal) { 3046 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3047 return findSubobject(Info, E, Obj, Sub, Handler); 3048 } 3049 3050 /// Find the position where two subobject designators diverge, or equivalently 3051 /// the length of the common initial subsequence. 3052 static unsigned FindDesignatorMismatch(QualType ObjType, 3053 const SubobjectDesignator &A, 3054 const SubobjectDesignator &B, 3055 bool &WasArrayIndex) { 3056 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3057 for (/**/; I != N; ++I) { 3058 if (!ObjType.isNull() && 3059 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3060 // Next subobject is an array element. 3061 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) { 3062 WasArrayIndex = true; 3063 return I; 3064 } 3065 if (ObjType->isAnyComplexType()) 3066 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3067 else 3068 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3069 } else { 3070 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) { 3071 WasArrayIndex = false; 3072 return I; 3073 } 3074 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3075 // Next subobject is a field. 3076 ObjType = FD->getType(); 3077 else 3078 // Next subobject is a base class. 3079 ObjType = QualType(); 3080 } 3081 } 3082 WasArrayIndex = false; 3083 return I; 3084 } 3085 3086 /// Determine whether the given subobject designators refer to elements of the 3087 /// same array object. 3088 static bool AreElementsOfSameArray(QualType ObjType, 3089 const SubobjectDesignator &A, 3090 const SubobjectDesignator &B) { 3091 if (A.Entries.size() != B.Entries.size()) 3092 return false; 3093 3094 bool IsArray = A.MostDerivedIsArrayElement; 3095 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3096 // A is a subobject of the array element. 3097 return false; 3098 3099 // If A (and B) designates an array element, the last entry will be the array 3100 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3101 // of length 1' case, and the entire path must match. 3102 bool WasArrayIndex; 3103 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3104 return CommonLength >= A.Entries.size() - IsArray; 3105 } 3106 3107 /// Find the complete object to which an LValue refers. 3108 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3109 AccessKinds AK, const LValue &LVal, 3110 QualType LValType) { 3111 if (!LVal.Base) { 3112 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3113 return CompleteObject(); 3114 } 3115 3116 CallStackFrame *Frame = nullptr; 3117 if (LVal.getLValueCallIndex()) { 3118 Frame = Info.getCallFrame(LVal.getLValueCallIndex()); 3119 if (!Frame) { 3120 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3121 << AK << LVal.Base.is<const ValueDecl*>(); 3122 NoteLValueLocation(Info, LVal.Base); 3123 return CompleteObject(); 3124 } 3125 } 3126 3127 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3128 // is not a constant expression (even if the object is non-volatile). We also 3129 // apply this rule to C++98, in order to conform to the expected 'volatile' 3130 // semantics. 3131 if (LValType.isVolatileQualified()) { 3132 if (Info.getLangOpts().CPlusPlus) 3133 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3134 << AK << LValType; 3135 else 3136 Info.FFDiag(E); 3137 return CompleteObject(); 3138 } 3139 3140 // Compute value storage location and type of base object. 3141 APValue *BaseVal = nullptr; 3142 QualType BaseType = getType(LVal.Base); 3143 bool LifetimeStartedInEvaluation = Frame; 3144 3145 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 3146 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3147 // In C++11, constexpr, non-volatile variables initialized with constant 3148 // expressions are constant expressions too. Inside constexpr functions, 3149 // parameters are constant expressions even if they're non-const. 3150 // In C++1y, objects local to a constant expression (those with a Frame) are 3151 // both readable and writable inside constant expressions. 3152 // In C, such things can also be folded, although they are not ICEs. 3153 const VarDecl *VD = dyn_cast<VarDecl>(D); 3154 if (VD) { 3155 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3156 VD = VDef; 3157 } 3158 if (!VD || VD->isInvalidDecl()) { 3159 Info.FFDiag(E); 3160 return CompleteObject(); 3161 } 3162 3163 // Accesses of volatile-qualified objects are not allowed. 3164 if (BaseType.isVolatileQualified()) { 3165 if (Info.getLangOpts().CPlusPlus) { 3166 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3167 << AK << 1 << VD; 3168 Info.Note(VD->getLocation(), diag::note_declared_at); 3169 } else { 3170 Info.FFDiag(E); 3171 } 3172 return CompleteObject(); 3173 } 3174 3175 // Unless we're looking at a local variable or argument in a constexpr call, 3176 // the variable we're reading must be const. 3177 if (!Frame) { 3178 if (Info.getLangOpts().CPlusPlus14 && 3179 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) { 3180 // OK, we can read and modify an object if we're in the process of 3181 // evaluating its initializer, because its lifetime began in this 3182 // evaluation. 3183 } else if (AK != AK_Read) { 3184 // All the remaining cases only permit reading. 3185 Info.FFDiag(E, diag::note_constexpr_modify_global); 3186 return CompleteObject(); 3187 } else if (VD->isConstexpr()) { 3188 // OK, we can read this variable. 3189 } else if (BaseType->isIntegralOrEnumerationType()) { 3190 // In OpenCL if a variable is in constant address space it is a const value. 3191 if (!(BaseType.isConstQualified() || 3192 (Info.getLangOpts().OpenCL && 3193 BaseType.getAddressSpace() == LangAS::opencl_constant))) { 3194 if (Info.getLangOpts().CPlusPlus) { 3195 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3196 Info.Note(VD->getLocation(), diag::note_declared_at); 3197 } else { 3198 Info.FFDiag(E); 3199 } 3200 return CompleteObject(); 3201 } 3202 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { 3203 // We support folding of const floating-point types, in order to make 3204 // static const data members of such types (supported as an extension) 3205 // more useful. 3206 if (Info.getLangOpts().CPlusPlus11) { 3207 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3208 Info.Note(VD->getLocation(), diag::note_declared_at); 3209 } else { 3210 Info.CCEDiag(E); 3211 } 3212 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { 3213 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; 3214 // Keep evaluating to see what we can do. 3215 } else { 3216 // FIXME: Allow folding of values of any literal type in all languages. 3217 if (Info.checkingPotentialConstantExpression() && 3218 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { 3219 // The definition of this variable could be constexpr. We can't 3220 // access it right now, but may be able to in future. 3221 } else if (Info.getLangOpts().CPlusPlus11) { 3222 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3223 Info.Note(VD->getLocation(), diag::note_declared_at); 3224 } else { 3225 Info.FFDiag(E); 3226 } 3227 return CompleteObject(); 3228 } 3229 } 3230 3231 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3232 return CompleteObject(); 3233 } else { 3234 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3235 3236 if (!Frame) { 3237 if (const MaterializeTemporaryExpr *MTE = 3238 dyn_cast<MaterializeTemporaryExpr>(Base)) { 3239 assert(MTE->getStorageDuration() == SD_Static && 3240 "should have a frame for a non-global materialized temporary"); 3241 3242 // Per C++1y [expr.const]p2: 3243 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3244 // - a [...] glvalue of integral or enumeration type that refers to 3245 // a non-volatile const object [...] 3246 // [...] 3247 // - a [...] glvalue of literal type that refers to a non-volatile 3248 // object whose lifetime began within the evaluation of e. 3249 // 3250 // C++11 misses the 'began within the evaluation of e' check and 3251 // instead allows all temporaries, including things like: 3252 // int &&r = 1; 3253 // int x = ++r; 3254 // constexpr int k = r; 3255 // Therefore we use the C++14 rules in C++11 too. 3256 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3257 const ValueDecl *ED = MTE->getExtendingDecl(); 3258 if (!(BaseType.isConstQualified() && 3259 BaseType->isIntegralOrEnumerationType()) && 3260 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) { 3261 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3262 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3263 return CompleteObject(); 3264 } 3265 3266 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false); 3267 assert(BaseVal && "got reference to unevaluated temporary"); 3268 LifetimeStartedInEvaluation = true; 3269 } else { 3270 Info.FFDiag(E); 3271 return CompleteObject(); 3272 } 3273 } else { 3274 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 3275 assert(BaseVal && "missing value for temporary"); 3276 } 3277 3278 // Volatile temporary objects cannot be accessed in constant expressions. 3279 if (BaseType.isVolatileQualified()) { 3280 if (Info.getLangOpts().CPlusPlus) { 3281 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3282 << AK << 0; 3283 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here); 3284 } else { 3285 Info.FFDiag(E); 3286 } 3287 return CompleteObject(); 3288 } 3289 } 3290 3291 // During the construction of an object, it is not yet 'const'. 3292 // FIXME: This doesn't do quite the right thing for const subobjects of the 3293 // object under construction. 3294 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), 3295 LVal.getLValueCallIndex(), 3296 LVal.getLValueVersion())) { 3297 BaseType = Info.Ctx.getCanonicalType(BaseType); 3298 BaseType.removeLocalConst(); 3299 LifetimeStartedInEvaluation = true; 3300 } 3301 3302 // In C++14, we can't safely access any mutable state when we might be 3303 // evaluating after an unmodeled side effect. 3304 // 3305 // FIXME: Not all local state is mutable. Allow local constant subobjects 3306 // to be read here (but take care with 'mutable' fields). 3307 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3308 Info.EvalStatus.HasSideEffects) || 3309 (AK != AK_Read && Info.IsSpeculativelyEvaluating)) 3310 return CompleteObject(); 3311 3312 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation); 3313 } 3314 3315 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 3316 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3317 /// glvalue referred to by an entity of reference type. 3318 /// 3319 /// \param Info - Information about the ongoing evaluation. 3320 /// \param Conv - The expression for which we are performing the conversion. 3321 /// Used for diagnostics. 3322 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 3323 /// case of a non-class type). 3324 /// \param LVal - The glvalue on which we are attempting to perform this action. 3325 /// \param RVal - The produced value will be placed here. 3326 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 3327 QualType Type, 3328 const LValue &LVal, APValue &RVal) { 3329 if (LVal.Designator.Invalid) 3330 return false; 3331 3332 // Check for special cases where there is no existing APValue to look at. 3333 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3334 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 3335 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 3336 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 3337 // initializer until now for such expressions. Such an expression can't be 3338 // an ICE in C, so this only matters for fold. 3339 if (Type.isVolatileQualified()) { 3340 Info.FFDiag(Conv); 3341 return false; 3342 } 3343 APValue Lit; 3344 if (!Evaluate(Lit, Info, CLE->getInitializer())) 3345 return false; 3346 CompleteObject LitObj(&Lit, Base->getType(), false); 3347 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal); 3348 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 3349 // We represent a string literal array as an lvalue pointing at the 3350 // corresponding expression, rather than building an array of chars. 3351 // FIXME: Support ObjCEncodeExpr, MakeStringConstant 3352 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0); 3353 CompleteObject StrObj(&Str, Base->getType(), false); 3354 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal); 3355 } 3356 } 3357 3358 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type); 3359 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal); 3360 } 3361 3362 /// Perform an assignment of Val to LVal. Takes ownership of Val. 3363 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 3364 QualType LValType, APValue &Val) { 3365 if (LVal.Designator.Invalid) 3366 return false; 3367 3368 if (!Info.getLangOpts().CPlusPlus14) { 3369 Info.FFDiag(E); 3370 return false; 3371 } 3372 3373 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3374 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 3375 } 3376 3377 namespace { 3378 struct CompoundAssignSubobjectHandler { 3379 EvalInfo &Info; 3380 const Expr *E; 3381 QualType PromotedLHSType; 3382 BinaryOperatorKind Opcode; 3383 const APValue &RHS; 3384 3385 static const AccessKinds AccessKind = AK_Assign; 3386 3387 typedef bool result_type; 3388 3389 bool checkConst(QualType QT) { 3390 // Assigning to a const object has undefined behavior. 3391 if (QT.isConstQualified()) { 3392 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3393 return false; 3394 } 3395 return true; 3396 } 3397 3398 bool failed() { return false; } 3399 bool found(APValue &Subobj, QualType SubobjType) { 3400 switch (Subobj.getKind()) { 3401 case APValue::Int: 3402 return found(Subobj.getInt(), SubobjType); 3403 case APValue::Float: 3404 return found(Subobj.getFloat(), SubobjType); 3405 case APValue::ComplexInt: 3406 case APValue::ComplexFloat: 3407 // FIXME: Implement complex compound assignment. 3408 Info.FFDiag(E); 3409 return false; 3410 case APValue::LValue: 3411 return foundPointer(Subobj, SubobjType); 3412 default: 3413 // FIXME: can this happen? 3414 Info.FFDiag(E); 3415 return false; 3416 } 3417 } 3418 bool found(APSInt &Value, QualType SubobjType) { 3419 if (!checkConst(SubobjType)) 3420 return false; 3421 3422 if (!SubobjType->isIntegerType() || !RHS.isInt()) { 3423 // We don't support compound assignment on integer-cast-to-pointer 3424 // values. 3425 Info.FFDiag(E); 3426 return false; 3427 } 3428 3429 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType, 3430 SubobjType, Value); 3431 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 3432 return false; 3433 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 3434 return true; 3435 } 3436 bool found(APFloat &Value, QualType SubobjType) { 3437 return checkConst(SubobjType) && 3438 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 3439 Value) && 3440 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 3441 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 3442 } 3443 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3444 if (!checkConst(SubobjType)) 3445 return false; 3446 3447 QualType PointeeType; 3448 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3449 PointeeType = PT->getPointeeType(); 3450 3451 if (PointeeType.isNull() || !RHS.isInt() || 3452 (Opcode != BO_Add && Opcode != BO_Sub)) { 3453 Info.FFDiag(E); 3454 return false; 3455 } 3456 3457 APSInt Offset = RHS.getInt(); 3458 if (Opcode == BO_Sub) 3459 negateAsSigned(Offset); 3460 3461 LValue LVal; 3462 LVal.setFrom(Info.Ctx, Subobj); 3463 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 3464 return false; 3465 LVal.moveInto(Subobj); 3466 return true; 3467 } 3468 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3469 llvm_unreachable("shouldn't encounter string elements here"); 3470 } 3471 }; 3472 } // end anonymous namespace 3473 3474 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 3475 3476 /// Perform a compound assignment of LVal <op>= RVal. 3477 static bool handleCompoundAssignment( 3478 EvalInfo &Info, const Expr *E, 3479 const LValue &LVal, QualType LValType, QualType PromotedLValType, 3480 BinaryOperatorKind Opcode, const APValue &RVal) { 3481 if (LVal.Designator.Invalid) 3482 return false; 3483 3484 if (!Info.getLangOpts().CPlusPlus14) { 3485 Info.FFDiag(E); 3486 return false; 3487 } 3488 3489 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3490 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 3491 RVal }; 3492 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3493 } 3494 3495 namespace { 3496 struct IncDecSubobjectHandler { 3497 EvalInfo &Info; 3498 const UnaryOperator *E; 3499 AccessKinds AccessKind; 3500 APValue *Old; 3501 3502 typedef bool result_type; 3503 3504 bool checkConst(QualType QT) { 3505 // Assigning to a const object has undefined behavior. 3506 if (QT.isConstQualified()) { 3507 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3508 return false; 3509 } 3510 return true; 3511 } 3512 3513 bool failed() { return false; } 3514 bool found(APValue &Subobj, QualType SubobjType) { 3515 // Stash the old value. Also clear Old, so we don't clobber it later 3516 // if we're post-incrementing a complex. 3517 if (Old) { 3518 *Old = Subobj; 3519 Old = nullptr; 3520 } 3521 3522 switch (Subobj.getKind()) { 3523 case APValue::Int: 3524 return found(Subobj.getInt(), SubobjType); 3525 case APValue::Float: 3526 return found(Subobj.getFloat(), SubobjType); 3527 case APValue::ComplexInt: 3528 return found(Subobj.getComplexIntReal(), 3529 SubobjType->castAs<ComplexType>()->getElementType() 3530 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3531 case APValue::ComplexFloat: 3532 return found(Subobj.getComplexFloatReal(), 3533 SubobjType->castAs<ComplexType>()->getElementType() 3534 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3535 case APValue::LValue: 3536 return foundPointer(Subobj, SubobjType); 3537 default: 3538 // FIXME: can this happen? 3539 Info.FFDiag(E); 3540 return false; 3541 } 3542 } 3543 bool found(APSInt &Value, QualType SubobjType) { 3544 if (!checkConst(SubobjType)) 3545 return false; 3546 3547 if (!SubobjType->isIntegerType()) { 3548 // We don't support increment / decrement on integer-cast-to-pointer 3549 // values. 3550 Info.FFDiag(E); 3551 return false; 3552 } 3553 3554 if (Old) *Old = APValue(Value); 3555 3556 // bool arithmetic promotes to int, and the conversion back to bool 3557 // doesn't reduce mod 2^n, so special-case it. 3558 if (SubobjType->isBooleanType()) { 3559 if (AccessKind == AK_Increment) 3560 Value = 1; 3561 else 3562 Value = !Value; 3563 return true; 3564 } 3565 3566 bool WasNegative = Value.isNegative(); 3567 if (AccessKind == AK_Increment) { 3568 ++Value; 3569 3570 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 3571 APSInt ActualValue(Value, /*IsUnsigned*/true); 3572 return HandleOverflow(Info, E, ActualValue, SubobjType); 3573 } 3574 } else { 3575 --Value; 3576 3577 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 3578 unsigned BitWidth = Value.getBitWidth(); 3579 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 3580 ActualValue.setBit(BitWidth); 3581 return HandleOverflow(Info, E, ActualValue, SubobjType); 3582 } 3583 } 3584 return true; 3585 } 3586 bool found(APFloat &Value, QualType SubobjType) { 3587 if (!checkConst(SubobjType)) 3588 return false; 3589 3590 if (Old) *Old = APValue(Value); 3591 3592 APFloat One(Value.getSemantics(), 1); 3593 if (AccessKind == AK_Increment) 3594 Value.add(One, APFloat::rmNearestTiesToEven); 3595 else 3596 Value.subtract(One, APFloat::rmNearestTiesToEven); 3597 return true; 3598 } 3599 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3600 if (!checkConst(SubobjType)) 3601 return false; 3602 3603 QualType PointeeType; 3604 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3605 PointeeType = PT->getPointeeType(); 3606 else { 3607 Info.FFDiag(E); 3608 return false; 3609 } 3610 3611 LValue LVal; 3612 LVal.setFrom(Info.Ctx, Subobj); 3613 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 3614 AccessKind == AK_Increment ? 1 : -1)) 3615 return false; 3616 LVal.moveInto(Subobj); 3617 return true; 3618 } 3619 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3620 llvm_unreachable("shouldn't encounter string elements here"); 3621 } 3622 }; 3623 } // end anonymous namespace 3624 3625 /// Perform an increment or decrement on LVal. 3626 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 3627 QualType LValType, bool IsIncrement, APValue *Old) { 3628 if (LVal.Designator.Invalid) 3629 return false; 3630 3631 if (!Info.getLangOpts().CPlusPlus14) { 3632 Info.FFDiag(E); 3633 return false; 3634 } 3635 3636 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 3637 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 3638 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 3639 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3640 } 3641 3642 /// Build an lvalue for the object argument of a member function call. 3643 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 3644 LValue &This) { 3645 if (Object->getType()->isPointerType()) 3646 return EvaluatePointer(Object, This, Info); 3647 3648 if (Object->isGLValue()) 3649 return EvaluateLValue(Object, This, Info); 3650 3651 if (Object->getType()->isLiteralType(Info.Ctx)) 3652 return EvaluateTemporary(Object, This, Info); 3653 3654 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 3655 return false; 3656 } 3657 3658 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 3659 /// lvalue referring to the result. 3660 /// 3661 /// \param Info - Information about the ongoing evaluation. 3662 /// \param LV - An lvalue referring to the base of the member pointer. 3663 /// \param RHS - The member pointer expression. 3664 /// \param IncludeMember - Specifies whether the member itself is included in 3665 /// the resulting LValue subobject designator. This is not possible when 3666 /// creating a bound member function. 3667 /// \return The field or method declaration to which the member pointer refers, 3668 /// or 0 if evaluation fails. 3669 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3670 QualType LVType, 3671 LValue &LV, 3672 const Expr *RHS, 3673 bool IncludeMember = true) { 3674 MemberPtr MemPtr; 3675 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 3676 return nullptr; 3677 3678 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 3679 // member value, the behavior is undefined. 3680 if (!MemPtr.getDecl()) { 3681 // FIXME: Specific diagnostic. 3682 Info.FFDiag(RHS); 3683 return nullptr; 3684 } 3685 3686 if (MemPtr.isDerivedMember()) { 3687 // This is a member of some derived class. Truncate LV appropriately. 3688 // The end of the derived-to-base path for the base object must match the 3689 // derived-to-base path for the member pointer. 3690 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 3691 LV.Designator.Entries.size()) { 3692 Info.FFDiag(RHS); 3693 return nullptr; 3694 } 3695 unsigned PathLengthToMember = 3696 LV.Designator.Entries.size() - MemPtr.Path.size(); 3697 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 3698 const CXXRecordDecl *LVDecl = getAsBaseClass( 3699 LV.Designator.Entries[PathLengthToMember + I]); 3700 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 3701 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 3702 Info.FFDiag(RHS); 3703 return nullptr; 3704 } 3705 } 3706 3707 // Truncate the lvalue to the appropriate derived class. 3708 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 3709 PathLengthToMember)) 3710 return nullptr; 3711 } else if (!MemPtr.Path.empty()) { 3712 // Extend the LValue path with the member pointer's path. 3713 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 3714 MemPtr.Path.size() + IncludeMember); 3715 3716 // Walk down to the appropriate base class. 3717 if (const PointerType *PT = LVType->getAs<PointerType>()) 3718 LVType = PT->getPointeeType(); 3719 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 3720 assert(RD && "member pointer access on non-class-type expression"); 3721 // The first class in the path is that of the lvalue. 3722 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 3723 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 3724 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 3725 return nullptr; 3726 RD = Base; 3727 } 3728 // Finally cast to the class containing the member. 3729 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 3730 MemPtr.getContainingRecord())) 3731 return nullptr; 3732 } 3733 3734 // Add the member. Note that we cannot build bound member functions here. 3735 if (IncludeMember) { 3736 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 3737 if (!HandleLValueMember(Info, RHS, LV, FD)) 3738 return nullptr; 3739 } else if (const IndirectFieldDecl *IFD = 3740 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 3741 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 3742 return nullptr; 3743 } else { 3744 llvm_unreachable("can't construct reference to bound member function"); 3745 } 3746 } 3747 3748 return MemPtr.getDecl(); 3749 } 3750 3751 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3752 const BinaryOperator *BO, 3753 LValue &LV, 3754 bool IncludeMember = true) { 3755 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 3756 3757 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 3758 if (Info.noteFailure()) { 3759 MemberPtr MemPtr; 3760 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 3761 } 3762 return nullptr; 3763 } 3764 3765 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 3766 BO->getRHS(), IncludeMember); 3767 } 3768 3769 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 3770 /// the provided lvalue, which currently refers to the base object. 3771 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 3772 LValue &Result) { 3773 SubobjectDesignator &D = Result.Designator; 3774 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 3775 return false; 3776 3777 QualType TargetQT = E->getType(); 3778 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 3779 TargetQT = PT->getPointeeType(); 3780 3781 // Check this cast lands within the final derived-to-base subobject path. 3782 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 3783 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3784 << D.MostDerivedType << TargetQT; 3785 return false; 3786 } 3787 3788 // Check the type of the final cast. We don't need to check the path, 3789 // since a cast can only be formed if the path is unique. 3790 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 3791 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 3792 const CXXRecordDecl *FinalType; 3793 if (NewEntriesSize == D.MostDerivedPathLength) 3794 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 3795 else 3796 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 3797 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 3798 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3799 << D.MostDerivedType << TargetQT; 3800 return false; 3801 } 3802 3803 // Truncate the lvalue to the appropriate derived class. 3804 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 3805 } 3806 3807 namespace { 3808 enum EvalStmtResult { 3809 /// Evaluation failed. 3810 ESR_Failed, 3811 /// Hit a 'return' statement. 3812 ESR_Returned, 3813 /// Evaluation succeeded. 3814 ESR_Succeeded, 3815 /// Hit a 'continue' statement. 3816 ESR_Continue, 3817 /// Hit a 'break' statement. 3818 ESR_Break, 3819 /// Still scanning for 'case' or 'default' statement. 3820 ESR_CaseNotFound 3821 }; 3822 } 3823 3824 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 3825 // We don't need to evaluate the initializer for a static local. 3826 if (!VD->hasLocalStorage()) 3827 return true; 3828 3829 LValue Result; 3830 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall); 3831 3832 const Expr *InitE = VD->getInit(); 3833 if (!InitE) { 3834 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized) 3835 << false << VD->getType(); 3836 Val = APValue(); 3837 return false; 3838 } 3839 3840 if (InitE->isValueDependent()) 3841 return false; 3842 3843 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 3844 // Wipe out any partially-computed value, to allow tracking that this 3845 // evaluation failed. 3846 Val = APValue(); 3847 return false; 3848 } 3849 3850 return true; 3851 } 3852 3853 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 3854 bool OK = true; 3855 3856 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 3857 OK &= EvaluateVarDecl(Info, VD); 3858 3859 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 3860 for (auto *BD : DD->bindings()) 3861 if (auto *VD = BD->getHoldingVar()) 3862 OK &= EvaluateDecl(Info, VD); 3863 3864 return OK; 3865 } 3866 3867 3868 /// Evaluate a condition (either a variable declaration or an expression). 3869 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 3870 const Expr *Cond, bool &Result) { 3871 FullExpressionRAII Scope(Info); 3872 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 3873 return false; 3874 return EvaluateAsBooleanCondition(Cond, Result, Info); 3875 } 3876 3877 namespace { 3878 /// A location where the result (returned value) of evaluating a 3879 /// statement should be stored. 3880 struct StmtResult { 3881 /// The APValue that should be filled in with the returned value. 3882 APValue &Value; 3883 /// The location containing the result, if any (used to support RVO). 3884 const LValue *Slot; 3885 }; 3886 3887 struct TempVersionRAII { 3888 CallStackFrame &Frame; 3889 3890 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 3891 Frame.pushTempVersion(); 3892 } 3893 3894 ~TempVersionRAII() { 3895 Frame.popTempVersion(); 3896 } 3897 }; 3898 3899 } 3900 3901 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 3902 const Stmt *S, 3903 const SwitchCase *SC = nullptr); 3904 3905 /// Evaluate the body of a loop, and translate the result as appropriate. 3906 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 3907 const Stmt *Body, 3908 const SwitchCase *Case = nullptr) { 3909 BlockScopeRAII Scope(Info); 3910 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) { 3911 case ESR_Break: 3912 return ESR_Succeeded; 3913 case ESR_Succeeded: 3914 case ESR_Continue: 3915 return ESR_Continue; 3916 case ESR_Failed: 3917 case ESR_Returned: 3918 case ESR_CaseNotFound: 3919 return ESR; 3920 } 3921 llvm_unreachable("Invalid EvalStmtResult!"); 3922 } 3923 3924 /// Evaluate a switch statement. 3925 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 3926 const SwitchStmt *SS) { 3927 BlockScopeRAII Scope(Info); 3928 3929 // Evaluate the switch condition. 3930 APSInt Value; 3931 { 3932 FullExpressionRAII Scope(Info); 3933 if (const Stmt *Init = SS->getInit()) { 3934 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 3935 if (ESR != ESR_Succeeded) 3936 return ESR; 3937 } 3938 if (SS->getConditionVariable() && 3939 !EvaluateDecl(Info, SS->getConditionVariable())) 3940 return ESR_Failed; 3941 if (!EvaluateInteger(SS->getCond(), Value, Info)) 3942 return ESR_Failed; 3943 } 3944 3945 // Find the switch case corresponding to the value of the condition. 3946 // FIXME: Cache this lookup. 3947 const SwitchCase *Found = nullptr; 3948 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 3949 SC = SC->getNextSwitchCase()) { 3950 if (isa<DefaultStmt>(SC)) { 3951 Found = SC; 3952 continue; 3953 } 3954 3955 const CaseStmt *CS = cast<CaseStmt>(SC); 3956 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 3957 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 3958 : LHS; 3959 if (LHS <= Value && Value <= RHS) { 3960 Found = SC; 3961 break; 3962 } 3963 } 3964 3965 if (!Found) 3966 return ESR_Succeeded; 3967 3968 // Search the switch body for the switch case and evaluate it from there. 3969 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) { 3970 case ESR_Break: 3971 return ESR_Succeeded; 3972 case ESR_Succeeded: 3973 case ESR_Continue: 3974 case ESR_Failed: 3975 case ESR_Returned: 3976 return ESR; 3977 case ESR_CaseNotFound: 3978 // This can only happen if the switch case is nested within a statement 3979 // expression. We have no intention of supporting that. 3980 Info.FFDiag(Found->getBeginLoc(), 3981 diag::note_constexpr_stmt_expr_unsupported); 3982 return ESR_Failed; 3983 } 3984 llvm_unreachable("Invalid EvalStmtResult!"); 3985 } 3986 3987 // Evaluate a statement. 3988 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 3989 const Stmt *S, const SwitchCase *Case) { 3990 if (!Info.nextStep(S)) 3991 return ESR_Failed; 3992 3993 // If we're hunting down a 'case' or 'default' label, recurse through 3994 // substatements until we hit the label. 3995 if (Case) { 3996 // FIXME: We don't start the lifetime of objects whose initialization we 3997 // jump over. However, such objects must be of class type with a trivial 3998 // default constructor that initialize all subobjects, so must be empty, 3999 // so this almost never matters. 4000 switch (S->getStmtClass()) { 4001 case Stmt::CompoundStmtClass: 4002 // FIXME: Precompute which substatement of a compound statement we 4003 // would jump to, and go straight there rather than performing a 4004 // linear scan each time. 4005 case Stmt::LabelStmtClass: 4006 case Stmt::AttributedStmtClass: 4007 case Stmt::DoStmtClass: 4008 break; 4009 4010 case Stmt::CaseStmtClass: 4011 case Stmt::DefaultStmtClass: 4012 if (Case == S) 4013 Case = nullptr; 4014 break; 4015 4016 case Stmt::IfStmtClass: { 4017 // FIXME: Precompute which side of an 'if' we would jump to, and go 4018 // straight there rather than scanning both sides. 4019 const IfStmt *IS = cast<IfStmt>(S); 4020 4021 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4022 // preceded by our switch label. 4023 BlockScopeRAII Scope(Info); 4024 4025 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4026 if (ESR != ESR_CaseNotFound || !IS->getElse()) 4027 return ESR; 4028 return EvaluateStmt(Result, Info, IS->getElse(), Case); 4029 } 4030 4031 case Stmt::WhileStmtClass: { 4032 EvalStmtResult ESR = 4033 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4034 if (ESR != ESR_Continue) 4035 return ESR; 4036 break; 4037 } 4038 4039 case Stmt::ForStmtClass: { 4040 const ForStmt *FS = cast<ForStmt>(S); 4041 EvalStmtResult ESR = 4042 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4043 if (ESR != ESR_Continue) 4044 return ESR; 4045 if (FS->getInc()) { 4046 FullExpressionRAII IncScope(Info); 4047 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4048 return ESR_Failed; 4049 } 4050 break; 4051 } 4052 4053 case Stmt::DeclStmtClass: 4054 // FIXME: If the variable has initialization that can't be jumped over, 4055 // bail out of any immediately-surrounding compound-statement too. 4056 default: 4057 return ESR_CaseNotFound; 4058 } 4059 } 4060 4061 switch (S->getStmtClass()) { 4062 default: 4063 if (const Expr *E = dyn_cast<Expr>(S)) { 4064 // Don't bother evaluating beyond an expression-statement which couldn't 4065 // be evaluated. 4066 FullExpressionRAII Scope(Info); 4067 if (!EvaluateIgnoredValue(Info, E)) 4068 return ESR_Failed; 4069 return ESR_Succeeded; 4070 } 4071 4072 Info.FFDiag(S->getBeginLoc()); 4073 return ESR_Failed; 4074 4075 case Stmt::NullStmtClass: 4076 return ESR_Succeeded; 4077 4078 case Stmt::DeclStmtClass: { 4079 const DeclStmt *DS = cast<DeclStmt>(S); 4080 for (const auto *DclIt : DS->decls()) { 4081 // Each declaration initialization is its own full-expression. 4082 // FIXME: This isn't quite right; if we're performing aggregate 4083 // initialization, each braced subexpression is its own full-expression. 4084 FullExpressionRAII Scope(Info); 4085 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure()) 4086 return ESR_Failed; 4087 } 4088 return ESR_Succeeded; 4089 } 4090 4091 case Stmt::ReturnStmtClass: { 4092 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4093 FullExpressionRAII Scope(Info); 4094 if (RetExpr && 4095 !(Result.Slot 4096 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4097 : Evaluate(Result.Value, Info, RetExpr))) 4098 return ESR_Failed; 4099 return ESR_Returned; 4100 } 4101 4102 case Stmt::CompoundStmtClass: { 4103 BlockScopeRAII Scope(Info); 4104 4105 const CompoundStmt *CS = cast<CompoundStmt>(S); 4106 for (const auto *BI : CS->body()) { 4107 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4108 if (ESR == ESR_Succeeded) 4109 Case = nullptr; 4110 else if (ESR != ESR_CaseNotFound) 4111 return ESR; 4112 } 4113 return Case ? ESR_CaseNotFound : ESR_Succeeded; 4114 } 4115 4116 case Stmt::IfStmtClass: { 4117 const IfStmt *IS = cast<IfStmt>(S); 4118 4119 // Evaluate the condition, as either a var decl or as an expression. 4120 BlockScopeRAII Scope(Info); 4121 if (const Stmt *Init = IS->getInit()) { 4122 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4123 if (ESR != ESR_Succeeded) 4124 return ESR; 4125 } 4126 bool Cond; 4127 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 4128 return ESR_Failed; 4129 4130 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 4131 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 4132 if (ESR != ESR_Succeeded) 4133 return ESR; 4134 } 4135 return ESR_Succeeded; 4136 } 4137 4138 case Stmt::WhileStmtClass: { 4139 const WhileStmt *WS = cast<WhileStmt>(S); 4140 while (true) { 4141 BlockScopeRAII Scope(Info); 4142 bool Continue; 4143 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 4144 Continue)) 4145 return ESR_Failed; 4146 if (!Continue) 4147 break; 4148 4149 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 4150 if (ESR != ESR_Continue) 4151 return ESR; 4152 } 4153 return ESR_Succeeded; 4154 } 4155 4156 case Stmt::DoStmtClass: { 4157 const DoStmt *DS = cast<DoStmt>(S); 4158 bool Continue; 4159 do { 4160 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 4161 if (ESR != ESR_Continue) 4162 return ESR; 4163 Case = nullptr; 4164 4165 FullExpressionRAII CondScope(Info); 4166 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info)) 4167 return ESR_Failed; 4168 } while (Continue); 4169 return ESR_Succeeded; 4170 } 4171 4172 case Stmt::ForStmtClass: { 4173 const ForStmt *FS = cast<ForStmt>(S); 4174 BlockScopeRAII Scope(Info); 4175 if (FS->getInit()) { 4176 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4177 if (ESR != ESR_Succeeded) 4178 return ESR; 4179 } 4180 while (true) { 4181 BlockScopeRAII Scope(Info); 4182 bool Continue = true; 4183 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 4184 FS->getCond(), Continue)) 4185 return ESR_Failed; 4186 if (!Continue) 4187 break; 4188 4189 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4190 if (ESR != ESR_Continue) 4191 return ESR; 4192 4193 if (FS->getInc()) { 4194 FullExpressionRAII IncScope(Info); 4195 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4196 return ESR_Failed; 4197 } 4198 } 4199 return ESR_Succeeded; 4200 } 4201 4202 case Stmt::CXXForRangeStmtClass: { 4203 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 4204 BlockScopeRAII Scope(Info); 4205 4206 // Evaluate the init-statement if present. 4207 if (FS->getInit()) { 4208 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4209 if (ESR != ESR_Succeeded) 4210 return ESR; 4211 } 4212 4213 // Initialize the __range variable. 4214 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 4215 if (ESR != ESR_Succeeded) 4216 return ESR; 4217 4218 // Create the __begin and __end iterators. 4219 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 4220 if (ESR != ESR_Succeeded) 4221 return ESR; 4222 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 4223 if (ESR != ESR_Succeeded) 4224 return ESR; 4225 4226 while (true) { 4227 // Condition: __begin != __end. 4228 { 4229 bool Continue = true; 4230 FullExpressionRAII CondExpr(Info); 4231 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 4232 return ESR_Failed; 4233 if (!Continue) 4234 break; 4235 } 4236 4237 // User's variable declaration, initialized by *__begin. 4238 BlockScopeRAII InnerScope(Info); 4239 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 4240 if (ESR != ESR_Succeeded) 4241 return ESR; 4242 4243 // Loop body. 4244 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4245 if (ESR != ESR_Continue) 4246 return ESR; 4247 4248 // Increment: ++__begin 4249 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4250 return ESR_Failed; 4251 } 4252 4253 return ESR_Succeeded; 4254 } 4255 4256 case Stmt::SwitchStmtClass: 4257 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 4258 4259 case Stmt::ContinueStmtClass: 4260 return ESR_Continue; 4261 4262 case Stmt::BreakStmtClass: 4263 return ESR_Break; 4264 4265 case Stmt::LabelStmtClass: 4266 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 4267 4268 case Stmt::AttributedStmtClass: 4269 // As a general principle, C++11 attributes can be ignored without 4270 // any semantic impact. 4271 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 4272 Case); 4273 4274 case Stmt::CaseStmtClass: 4275 case Stmt::DefaultStmtClass: 4276 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 4277 } 4278 } 4279 4280 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 4281 /// default constructor. If so, we'll fold it whether or not it's marked as 4282 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 4283 /// so we need special handling. 4284 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 4285 const CXXConstructorDecl *CD, 4286 bool IsValueInitialization) { 4287 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 4288 return false; 4289 4290 // Value-initialization does not call a trivial default constructor, so such a 4291 // call is a core constant expression whether or not the constructor is 4292 // constexpr. 4293 if (!CD->isConstexpr() && !IsValueInitialization) { 4294 if (Info.getLangOpts().CPlusPlus11) { 4295 // FIXME: If DiagDecl is an implicitly-declared special member function, 4296 // we should be much more explicit about why it's not constexpr. 4297 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 4298 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 4299 Info.Note(CD->getLocation(), diag::note_declared_at); 4300 } else { 4301 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 4302 } 4303 } 4304 return true; 4305 } 4306 4307 /// CheckConstexprFunction - Check that a function can be called in a constant 4308 /// expression. 4309 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 4310 const FunctionDecl *Declaration, 4311 const FunctionDecl *Definition, 4312 const Stmt *Body) { 4313 // Potential constant expressions can contain calls to declared, but not yet 4314 // defined, constexpr functions. 4315 if (Info.checkingPotentialConstantExpression() && !Definition && 4316 Declaration->isConstexpr()) 4317 return false; 4318 4319 // Bail out if the function declaration itself is invalid. We will 4320 // have produced a relevant diagnostic while parsing it, so just 4321 // note the problematic sub-expression. 4322 if (Declaration->isInvalidDecl()) { 4323 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4324 return false; 4325 } 4326 4327 // Can we evaluate this function call? 4328 if (Definition && Definition->isConstexpr() && 4329 !Definition->isInvalidDecl() && Body) 4330 return true; 4331 4332 if (Info.getLangOpts().CPlusPlus11) { 4333 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 4334 4335 // If this function is not constexpr because it is an inherited 4336 // non-constexpr constructor, diagnose that directly. 4337 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 4338 if (CD && CD->isInheritingConstructor()) { 4339 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 4340 if (!Inherited->isConstexpr()) 4341 DiagDecl = CD = Inherited; 4342 } 4343 4344 // FIXME: If DiagDecl is an implicitly-declared special member function 4345 // or an inheriting constructor, we should be much more explicit about why 4346 // it's not constexpr. 4347 if (CD && CD->isInheritingConstructor()) 4348 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 4349 << CD->getInheritedConstructor().getConstructor()->getParent(); 4350 else 4351 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 4352 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 4353 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 4354 } else { 4355 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4356 } 4357 return false; 4358 } 4359 4360 /// Determine if a class has any fields that might need to be copied by a 4361 /// trivial copy or move operation. 4362 static bool hasFields(const CXXRecordDecl *RD) { 4363 if (!RD || RD->isEmpty()) 4364 return false; 4365 for (auto *FD : RD->fields()) { 4366 if (FD->isUnnamedBitfield()) 4367 continue; 4368 return true; 4369 } 4370 for (auto &Base : RD->bases()) 4371 if (hasFields(Base.getType()->getAsCXXRecordDecl())) 4372 return true; 4373 return false; 4374 } 4375 4376 namespace { 4377 typedef SmallVector<APValue, 8> ArgVector; 4378 } 4379 4380 /// EvaluateArgs - Evaluate the arguments to a function call. 4381 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues, 4382 EvalInfo &Info) { 4383 bool Success = true; 4384 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 4385 I != E; ++I) { 4386 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) { 4387 // If we're checking for a potential constant expression, evaluate all 4388 // initializers even if some of them fail. 4389 if (!Info.noteFailure()) 4390 return false; 4391 Success = false; 4392 } 4393 } 4394 return Success; 4395 } 4396 4397 /// Evaluate a function call. 4398 static bool HandleFunctionCall(SourceLocation CallLoc, 4399 const FunctionDecl *Callee, const LValue *This, 4400 ArrayRef<const Expr*> Args, const Stmt *Body, 4401 EvalInfo &Info, APValue &Result, 4402 const LValue *ResultSlot) { 4403 ArgVector ArgValues(Args.size()); 4404 if (!EvaluateArgs(Args, ArgValues, Info)) 4405 return false; 4406 4407 if (!Info.CheckCallLimit(CallLoc)) 4408 return false; 4409 4410 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 4411 4412 // For a trivial copy or move assignment, perform an APValue copy. This is 4413 // essential for unions, where the operations performed by the assignment 4414 // operator cannot be represented as statements. 4415 // 4416 // Skip this for non-union classes with no fields; in that case, the defaulted 4417 // copy/move does not actually read the object. 4418 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 4419 if (MD && MD->isDefaulted() && 4420 (MD->getParent()->isUnion() || 4421 (MD->isTrivial() && hasFields(MD->getParent())))) { 4422 assert(This && 4423 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 4424 LValue RHS; 4425 RHS.setFrom(Info.Ctx, ArgValues[0]); 4426 APValue RHSValue; 4427 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), 4428 RHS, RHSValue)) 4429 return false; 4430 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx), 4431 RHSValue)) 4432 return false; 4433 This->moveInto(Result); 4434 return true; 4435 } else if (MD && isLambdaCallOperator(MD)) { 4436 // We're in a lambda; determine the lambda capture field maps unless we're 4437 // just constexpr checking a lambda's call operator. constexpr checking is 4438 // done before the captures have been added to the closure object (unless 4439 // we're inferring constexpr-ness), so we don't have access to them in this 4440 // case. But since we don't need the captures to constexpr check, we can 4441 // just ignore them. 4442 if (!Info.checkingPotentialConstantExpression()) 4443 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 4444 Frame.LambdaThisCaptureField); 4445 } 4446 4447 StmtResult Ret = {Result, ResultSlot}; 4448 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 4449 if (ESR == ESR_Succeeded) { 4450 if (Callee->getReturnType()->isVoidType()) 4451 return true; 4452 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 4453 } 4454 return ESR == ESR_Returned; 4455 } 4456 4457 /// Evaluate a constructor call. 4458 static bool HandleConstructorCall(const Expr *E, const LValue &This, 4459 APValue *ArgValues, 4460 const CXXConstructorDecl *Definition, 4461 EvalInfo &Info, APValue &Result) { 4462 SourceLocation CallLoc = E->getExprLoc(); 4463 if (!Info.CheckCallLimit(CallLoc)) 4464 return false; 4465 4466 const CXXRecordDecl *RD = Definition->getParent(); 4467 if (RD->getNumVBases()) { 4468 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 4469 return false; 4470 } 4471 4472 EvalInfo::EvaluatingConstructorRAII EvalObj( 4473 Info, {This.getLValueBase(), 4474 {This.getLValueCallIndex(), This.getLValueVersion()}}); 4475 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 4476 4477 // FIXME: Creating an APValue just to hold a nonexistent return value is 4478 // wasteful. 4479 APValue RetVal; 4480 StmtResult Ret = {RetVal, nullptr}; 4481 4482 // If it's a delegating constructor, delegate. 4483 if (Definition->isDelegatingConstructor()) { 4484 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 4485 { 4486 FullExpressionRAII InitScope(Info); 4487 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit())) 4488 return false; 4489 } 4490 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 4491 } 4492 4493 // For a trivial copy or move constructor, perform an APValue copy. This is 4494 // essential for unions (or classes with anonymous union members), where the 4495 // operations performed by the constructor cannot be represented by 4496 // ctor-initializers. 4497 // 4498 // Skip this for empty non-union classes; we should not perform an 4499 // lvalue-to-rvalue conversion on them because their copy constructor does not 4500 // actually read them. 4501 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 4502 (Definition->getParent()->isUnion() || 4503 (Definition->isTrivial() && hasFields(Definition->getParent())))) { 4504 LValue RHS; 4505 RHS.setFrom(Info.Ctx, ArgValues[0]); 4506 return handleLValueToRValueConversion( 4507 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 4508 RHS, Result); 4509 } 4510 4511 // Reserve space for the struct members. 4512 if (!RD->isUnion() && Result.isUninit()) 4513 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4514 std::distance(RD->field_begin(), RD->field_end())); 4515 4516 if (RD->isInvalidDecl()) return false; 4517 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 4518 4519 // A scope for temporaries lifetime-extended by reference members. 4520 BlockScopeRAII LifetimeExtendedScope(Info); 4521 4522 bool Success = true; 4523 unsigned BasesSeen = 0; 4524 #ifndef NDEBUG 4525 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 4526 #endif 4527 for (const auto *I : Definition->inits()) { 4528 LValue Subobject = This; 4529 LValue SubobjectParent = This; 4530 APValue *Value = &Result; 4531 4532 // Determine the subobject to initialize. 4533 FieldDecl *FD = nullptr; 4534 if (I->isBaseInitializer()) { 4535 QualType BaseType(I->getBaseClass(), 0); 4536 #ifndef NDEBUG 4537 // Non-virtual base classes are initialized in the order in the class 4538 // definition. We have already checked for virtual base classes. 4539 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 4540 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 4541 "base class initializers not in expected order"); 4542 ++BaseIt; 4543 #endif 4544 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 4545 BaseType->getAsCXXRecordDecl(), &Layout)) 4546 return false; 4547 Value = &Result.getStructBase(BasesSeen++); 4548 } else if ((FD = I->getMember())) { 4549 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 4550 return false; 4551 if (RD->isUnion()) { 4552 Result = APValue(FD); 4553 Value = &Result.getUnionValue(); 4554 } else { 4555 Value = &Result.getStructField(FD->getFieldIndex()); 4556 } 4557 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 4558 // Walk the indirect field decl's chain to find the object to initialize, 4559 // and make sure we've initialized every step along it. 4560 auto IndirectFieldChain = IFD->chain(); 4561 for (auto *C : IndirectFieldChain) { 4562 FD = cast<FieldDecl>(C); 4563 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 4564 // Switch the union field if it differs. This happens if we had 4565 // preceding zero-initialization, and we're now initializing a union 4566 // subobject other than the first. 4567 // FIXME: In this case, the values of the other subobjects are 4568 // specified, since zero-initialization sets all padding bits to zero. 4569 if (Value->isUninit() || 4570 (Value->isUnion() && Value->getUnionField() != FD)) { 4571 if (CD->isUnion()) 4572 *Value = APValue(FD); 4573 else 4574 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(), 4575 std::distance(CD->field_begin(), CD->field_end())); 4576 } 4577 // Store Subobject as its parent before updating it for the last element 4578 // in the chain. 4579 if (C == IndirectFieldChain.back()) 4580 SubobjectParent = Subobject; 4581 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 4582 return false; 4583 if (CD->isUnion()) 4584 Value = &Value->getUnionValue(); 4585 else 4586 Value = &Value->getStructField(FD->getFieldIndex()); 4587 } 4588 } else { 4589 llvm_unreachable("unknown base initializer kind"); 4590 } 4591 4592 // Need to override This for implicit field initializers as in this case 4593 // This refers to innermost anonymous struct/union containing initializer, 4594 // not to currently constructed class. 4595 const Expr *Init = I->getInit(); 4596 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 4597 isa<CXXDefaultInitExpr>(Init)); 4598 FullExpressionRAII InitScope(Info); 4599 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 4600 (FD && FD->isBitField() && 4601 !truncateBitfieldValue(Info, Init, *Value, FD))) { 4602 // If we're checking for a potential constant expression, evaluate all 4603 // initializers even if some of them fail. 4604 if (!Info.noteFailure()) 4605 return false; 4606 Success = false; 4607 } 4608 } 4609 4610 return Success && 4611 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 4612 } 4613 4614 static bool HandleConstructorCall(const Expr *E, const LValue &This, 4615 ArrayRef<const Expr*> Args, 4616 const CXXConstructorDecl *Definition, 4617 EvalInfo &Info, APValue &Result) { 4618 ArgVector ArgValues(Args.size()); 4619 if (!EvaluateArgs(Args, ArgValues, Info)) 4620 return false; 4621 4622 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 4623 Info, Result); 4624 } 4625 4626 //===----------------------------------------------------------------------===// 4627 // Generic Evaluation 4628 //===----------------------------------------------------------------------===// 4629 namespace { 4630 4631 template <class Derived> 4632 class ExprEvaluatorBase 4633 : public ConstStmtVisitor<Derived, bool> { 4634 private: 4635 Derived &getDerived() { return static_cast<Derived&>(*this); } 4636 bool DerivedSuccess(const APValue &V, const Expr *E) { 4637 return getDerived().Success(V, E); 4638 } 4639 bool DerivedZeroInitialization(const Expr *E) { 4640 return getDerived().ZeroInitialization(E); 4641 } 4642 4643 // Check whether a conditional operator with a non-constant condition is a 4644 // potential constant expression. If neither arm is a potential constant 4645 // expression, then the conditional operator is not either. 4646 template<typename ConditionalOperator> 4647 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 4648 assert(Info.checkingPotentialConstantExpression()); 4649 4650 // Speculatively evaluate both arms. 4651 SmallVector<PartialDiagnosticAt, 8> Diag; 4652 { 4653 SpeculativeEvaluationRAII Speculate(Info, &Diag); 4654 StmtVisitorTy::Visit(E->getFalseExpr()); 4655 if (Diag.empty()) 4656 return; 4657 } 4658 4659 { 4660 SpeculativeEvaluationRAII Speculate(Info, &Diag); 4661 Diag.clear(); 4662 StmtVisitorTy::Visit(E->getTrueExpr()); 4663 if (Diag.empty()) 4664 return; 4665 } 4666 4667 Error(E, diag::note_constexpr_conditional_never_const); 4668 } 4669 4670 4671 template<typename ConditionalOperator> 4672 bool HandleConditionalOperator(const ConditionalOperator *E) { 4673 bool BoolResult; 4674 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 4675 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 4676 CheckPotentialConstantConditional(E); 4677 return false; 4678 } 4679 if (Info.noteFailure()) { 4680 StmtVisitorTy::Visit(E->getTrueExpr()); 4681 StmtVisitorTy::Visit(E->getFalseExpr()); 4682 } 4683 return false; 4684 } 4685 4686 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 4687 return StmtVisitorTy::Visit(EvalExpr); 4688 } 4689 4690 protected: 4691 EvalInfo &Info; 4692 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 4693 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 4694 4695 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 4696 return Info.CCEDiag(E, D); 4697 } 4698 4699 bool ZeroInitialization(const Expr *E) { return Error(E); } 4700 4701 public: 4702 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 4703 4704 EvalInfo &getEvalInfo() { return Info; } 4705 4706 /// Report an evaluation error. This should only be called when an error is 4707 /// first discovered. When propagating an error, just return false. 4708 bool Error(const Expr *E, diag::kind D) { 4709 Info.FFDiag(E, D); 4710 return false; 4711 } 4712 bool Error(const Expr *E) { 4713 return Error(E, diag::note_invalid_subexpr_in_const_expr); 4714 } 4715 4716 bool VisitStmt(const Stmt *) { 4717 llvm_unreachable("Expression evaluator should not be called on stmts"); 4718 } 4719 bool VisitExpr(const Expr *E) { 4720 return Error(E); 4721 } 4722 4723 bool VisitConstantExpr(const ConstantExpr *E) 4724 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4725 bool VisitParenExpr(const ParenExpr *E) 4726 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4727 bool VisitUnaryExtension(const UnaryOperator *E) 4728 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4729 bool VisitUnaryPlus(const UnaryOperator *E) 4730 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4731 bool VisitChooseExpr(const ChooseExpr *E) 4732 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 4733 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 4734 { return StmtVisitorTy::Visit(E->getResultExpr()); } 4735 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 4736 { return StmtVisitorTy::Visit(E->getReplacement()); } 4737 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 4738 TempVersionRAII RAII(*Info.CurrentCall); 4739 return StmtVisitorTy::Visit(E->getExpr()); 4740 } 4741 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 4742 TempVersionRAII RAII(*Info.CurrentCall); 4743 // The initializer may not have been parsed yet, or might be erroneous. 4744 if (!E->getExpr()) 4745 return Error(E); 4746 return StmtVisitorTy::Visit(E->getExpr()); 4747 } 4748 // We cannot create any objects for which cleanups are required, so there is 4749 // nothing to do here; all cleanups must come from unevaluated subexpressions. 4750 bool VisitExprWithCleanups(const ExprWithCleanups *E) 4751 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4752 4753 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 4754 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 4755 return static_cast<Derived*>(this)->VisitCastExpr(E); 4756 } 4757 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 4758 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 4759 return static_cast<Derived*>(this)->VisitCastExpr(E); 4760 } 4761 4762 bool VisitBinaryOperator(const BinaryOperator *E) { 4763 switch (E->getOpcode()) { 4764 default: 4765 return Error(E); 4766 4767 case BO_Comma: 4768 VisitIgnoredValue(E->getLHS()); 4769 return StmtVisitorTy::Visit(E->getRHS()); 4770 4771 case BO_PtrMemD: 4772 case BO_PtrMemI: { 4773 LValue Obj; 4774 if (!HandleMemberPointerAccess(Info, E, Obj)) 4775 return false; 4776 APValue Result; 4777 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 4778 return false; 4779 return DerivedSuccess(Result, E); 4780 } 4781 } 4782 } 4783 4784 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 4785 // Evaluate and cache the common expression. We treat it as a temporary, 4786 // even though it's not quite the same thing. 4787 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false), 4788 Info, E->getCommon())) 4789 return false; 4790 4791 return HandleConditionalOperator(E); 4792 } 4793 4794 bool VisitConditionalOperator(const ConditionalOperator *E) { 4795 bool IsBcpCall = false; 4796 // If the condition (ignoring parens) is a __builtin_constant_p call, 4797 // the result is a constant expression if it can be folded without 4798 // side-effects. This is an important GNU extension. See GCC PR38377 4799 // for discussion. 4800 if (const CallExpr *CallCE = 4801 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 4802 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 4803 IsBcpCall = true; 4804 4805 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 4806 // constant expression; we can't check whether it's potentially foldable. 4807 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 4808 return false; 4809 4810 FoldConstant Fold(Info, IsBcpCall); 4811 if (!HandleConditionalOperator(E)) { 4812 Fold.keepDiagnostics(); 4813 return false; 4814 } 4815 4816 return true; 4817 } 4818 4819 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 4820 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 4821 return DerivedSuccess(*Value, E); 4822 4823 const Expr *Source = E->getSourceExpr(); 4824 if (!Source) 4825 return Error(E); 4826 if (Source == E) { // sanity checking. 4827 assert(0 && "OpaqueValueExpr recursively refers to itself"); 4828 return Error(E); 4829 } 4830 return StmtVisitorTy::Visit(Source); 4831 } 4832 4833 bool VisitCallExpr(const CallExpr *E) { 4834 APValue Result; 4835 if (!handleCallExpr(E, Result, nullptr)) 4836 return false; 4837 return DerivedSuccess(Result, E); 4838 } 4839 4840 bool handleCallExpr(const CallExpr *E, APValue &Result, 4841 const LValue *ResultSlot) { 4842 const Expr *Callee = E->getCallee()->IgnoreParens(); 4843 QualType CalleeType = Callee->getType(); 4844 4845 const FunctionDecl *FD = nullptr; 4846 LValue *This = nullptr, ThisVal; 4847 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 4848 bool HasQualifier = false; 4849 4850 // Extract function decl and 'this' pointer from the callee. 4851 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 4852 const ValueDecl *Member = nullptr; 4853 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 4854 // Explicit bound member calls, such as x.f() or p->g(); 4855 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 4856 return false; 4857 Member = ME->getMemberDecl(); 4858 This = &ThisVal; 4859 HasQualifier = ME->hasQualifier(); 4860 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 4861 // Indirect bound member calls ('.*' or '->*'). 4862 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false); 4863 if (!Member) return false; 4864 This = &ThisVal; 4865 } else 4866 return Error(Callee); 4867 4868 FD = dyn_cast<FunctionDecl>(Member); 4869 if (!FD) 4870 return Error(Callee); 4871 } else if (CalleeType->isFunctionPointerType()) { 4872 LValue Call; 4873 if (!EvaluatePointer(Callee, Call, Info)) 4874 return false; 4875 4876 if (!Call.getLValueOffset().isZero()) 4877 return Error(Callee); 4878 FD = dyn_cast_or_null<FunctionDecl>( 4879 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 4880 if (!FD) 4881 return Error(Callee); 4882 // Don't call function pointers which have been cast to some other type. 4883 // Per DR (no number yet), the caller and callee can differ in noexcept. 4884 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 4885 CalleeType->getPointeeType(), FD->getType())) { 4886 return Error(E); 4887 } 4888 4889 // Overloaded operator calls to member functions are represented as normal 4890 // calls with '*this' as the first argument. 4891 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 4892 if (MD && !MD->isStatic()) { 4893 // FIXME: When selecting an implicit conversion for an overloaded 4894 // operator delete, we sometimes try to evaluate calls to conversion 4895 // operators without a 'this' parameter! 4896 if (Args.empty()) 4897 return Error(E); 4898 4899 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 4900 return false; 4901 This = &ThisVal; 4902 Args = Args.slice(1); 4903 } else if (MD && MD->isLambdaStaticInvoker()) { 4904 // Map the static invoker for the lambda back to the call operator. 4905 // Conveniently, we don't have to slice out the 'this' argument (as is 4906 // being done for the non-static case), since a static member function 4907 // doesn't have an implicit argument passed in. 4908 const CXXRecordDecl *ClosureClass = MD->getParent(); 4909 assert( 4910 ClosureClass->captures_begin() == ClosureClass->captures_end() && 4911 "Number of captures must be zero for conversion to function-ptr"); 4912 4913 const CXXMethodDecl *LambdaCallOp = 4914 ClosureClass->getLambdaCallOperator(); 4915 4916 // Set 'FD', the function that will be called below, to the call 4917 // operator. If the closure object represents a generic lambda, find 4918 // the corresponding specialization of the call operator. 4919 4920 if (ClosureClass->isGenericLambda()) { 4921 assert(MD->isFunctionTemplateSpecialization() && 4922 "A generic lambda's static-invoker function must be a " 4923 "template specialization"); 4924 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 4925 FunctionTemplateDecl *CallOpTemplate = 4926 LambdaCallOp->getDescribedFunctionTemplate(); 4927 void *InsertPos = nullptr; 4928 FunctionDecl *CorrespondingCallOpSpecialization = 4929 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 4930 assert(CorrespondingCallOpSpecialization && 4931 "We must always have a function call operator specialization " 4932 "that corresponds to our static invoker specialization"); 4933 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 4934 } else 4935 FD = LambdaCallOp; 4936 } 4937 4938 4939 } else 4940 return Error(E); 4941 4942 if (This && !This->checkSubobject(Info, E, CSK_This)) 4943 return false; 4944 4945 // DR1358 allows virtual constexpr functions in some cases. Don't allow 4946 // calls to such functions in constant expressions. 4947 if (This && !HasQualifier && 4948 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual()) 4949 return Error(E, diag::note_constexpr_virtual_call); 4950 4951 const FunctionDecl *Definition = nullptr; 4952 Stmt *Body = FD->getBody(Definition); 4953 4954 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 4955 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 4956 Result, ResultSlot)) 4957 return false; 4958 4959 return true; 4960 } 4961 4962 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 4963 return StmtVisitorTy::Visit(E->getInitializer()); 4964 } 4965 bool VisitInitListExpr(const InitListExpr *E) { 4966 if (E->getNumInits() == 0) 4967 return DerivedZeroInitialization(E); 4968 if (E->getNumInits() == 1) 4969 return StmtVisitorTy::Visit(E->getInit(0)); 4970 return Error(E); 4971 } 4972 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 4973 return DerivedZeroInitialization(E); 4974 } 4975 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 4976 return DerivedZeroInitialization(E); 4977 } 4978 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 4979 return DerivedZeroInitialization(E); 4980 } 4981 4982 /// A member expression where the object is a prvalue is itself a prvalue. 4983 bool VisitMemberExpr(const MemberExpr *E) { 4984 assert(!E->isArrow() && "missing call to bound member function?"); 4985 4986 APValue Val; 4987 if (!Evaluate(Val, Info, E->getBase())) 4988 return false; 4989 4990 QualType BaseTy = E->getBase()->getType(); 4991 4992 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 4993 if (!FD) return Error(E); 4994 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 4995 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 4996 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 4997 4998 CompleteObject Obj(&Val, BaseTy, true); 4999 SubobjectDesignator Designator(BaseTy); 5000 Designator.addDeclUnchecked(FD); 5001 5002 APValue Result; 5003 return extractSubobject(Info, E, Obj, Designator, Result) && 5004 DerivedSuccess(Result, E); 5005 } 5006 5007 bool VisitCastExpr(const CastExpr *E) { 5008 switch (E->getCastKind()) { 5009 default: 5010 break; 5011 5012 case CK_AtomicToNonAtomic: { 5013 APValue AtomicVal; 5014 // This does not need to be done in place even for class/array types: 5015 // atomic-to-non-atomic conversion implies copying the object 5016 // representation. 5017 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 5018 return false; 5019 return DerivedSuccess(AtomicVal, E); 5020 } 5021 5022 case CK_NoOp: 5023 case CK_UserDefinedConversion: 5024 return StmtVisitorTy::Visit(E->getSubExpr()); 5025 5026 case CK_LValueToRValue: { 5027 LValue LVal; 5028 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 5029 return false; 5030 APValue RVal; 5031 // Note, we use the subexpression's type in order to retain cv-qualifiers. 5032 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 5033 LVal, RVal)) 5034 return false; 5035 return DerivedSuccess(RVal, E); 5036 } 5037 } 5038 5039 return Error(E); 5040 } 5041 5042 bool VisitUnaryPostInc(const UnaryOperator *UO) { 5043 return VisitUnaryPostIncDec(UO); 5044 } 5045 bool VisitUnaryPostDec(const UnaryOperator *UO) { 5046 return VisitUnaryPostIncDec(UO); 5047 } 5048 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 5049 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5050 return Error(UO); 5051 5052 LValue LVal; 5053 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 5054 return false; 5055 APValue RVal; 5056 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 5057 UO->isIncrementOp(), &RVal)) 5058 return false; 5059 return DerivedSuccess(RVal, UO); 5060 } 5061 5062 bool VisitStmtExpr(const StmtExpr *E) { 5063 // We will have checked the full-expressions inside the statement expression 5064 // when they were completed, and don't need to check them again now. 5065 if (Info.checkingForOverflow()) 5066 return Error(E); 5067 5068 BlockScopeRAII Scope(Info); 5069 const CompoundStmt *CS = E->getSubStmt(); 5070 if (CS->body_empty()) 5071 return true; 5072 5073 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 5074 BE = CS->body_end(); 5075 /**/; ++BI) { 5076 if (BI + 1 == BE) { 5077 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 5078 if (!FinalExpr) { 5079 Info.FFDiag((*BI)->getBeginLoc(), 5080 diag::note_constexpr_stmt_expr_unsupported); 5081 return false; 5082 } 5083 return this->Visit(FinalExpr); 5084 } 5085 5086 APValue ReturnValue; 5087 StmtResult Result = { ReturnValue, nullptr }; 5088 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 5089 if (ESR != ESR_Succeeded) { 5090 // FIXME: If the statement-expression terminated due to 'return', 5091 // 'break', or 'continue', it would be nice to propagate that to 5092 // the outer statement evaluation rather than bailing out. 5093 if (ESR != ESR_Failed) 5094 Info.FFDiag((*BI)->getBeginLoc(), 5095 diag::note_constexpr_stmt_expr_unsupported); 5096 return false; 5097 } 5098 } 5099 5100 llvm_unreachable("Return from function from the loop above."); 5101 } 5102 5103 /// Visit a value which is evaluated, but whose value is ignored. 5104 void VisitIgnoredValue(const Expr *E) { 5105 EvaluateIgnoredValue(Info, E); 5106 } 5107 5108 /// Potentially visit a MemberExpr's base expression. 5109 void VisitIgnoredBaseExpression(const Expr *E) { 5110 // While MSVC doesn't evaluate the base expression, it does diagnose the 5111 // presence of side-effecting behavior. 5112 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 5113 return; 5114 VisitIgnoredValue(E); 5115 } 5116 }; 5117 5118 } // namespace 5119 5120 //===----------------------------------------------------------------------===// 5121 // Common base class for lvalue and temporary evaluation. 5122 //===----------------------------------------------------------------------===// 5123 namespace { 5124 template<class Derived> 5125 class LValueExprEvaluatorBase 5126 : public ExprEvaluatorBase<Derived> { 5127 protected: 5128 LValue &Result; 5129 bool InvalidBaseOK; 5130 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 5131 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 5132 5133 bool Success(APValue::LValueBase B) { 5134 Result.set(B); 5135 return true; 5136 } 5137 5138 bool evaluatePointer(const Expr *E, LValue &Result) { 5139 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 5140 } 5141 5142 public: 5143 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 5144 : ExprEvaluatorBaseTy(Info), Result(Result), 5145 InvalidBaseOK(InvalidBaseOK) {} 5146 5147 bool Success(const APValue &V, const Expr *E) { 5148 Result.setFrom(this->Info.Ctx, V); 5149 return true; 5150 } 5151 5152 bool VisitMemberExpr(const MemberExpr *E) { 5153 // Handle non-static data members. 5154 QualType BaseTy; 5155 bool EvalOK; 5156 if (E->isArrow()) { 5157 EvalOK = evaluatePointer(E->getBase(), Result); 5158 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 5159 } else if (E->getBase()->isRValue()) { 5160 assert(E->getBase()->getType()->isRecordType()); 5161 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 5162 BaseTy = E->getBase()->getType(); 5163 } else { 5164 EvalOK = this->Visit(E->getBase()); 5165 BaseTy = E->getBase()->getType(); 5166 } 5167 if (!EvalOK) { 5168 if (!InvalidBaseOK) 5169 return false; 5170 Result.setInvalid(E); 5171 return true; 5172 } 5173 5174 const ValueDecl *MD = E->getMemberDecl(); 5175 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 5176 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 5177 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 5178 (void)BaseTy; 5179 if (!HandleLValueMember(this->Info, E, Result, FD)) 5180 return false; 5181 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 5182 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 5183 return false; 5184 } else 5185 return this->Error(E); 5186 5187 if (MD->getType()->isReferenceType()) { 5188 APValue RefValue; 5189 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 5190 RefValue)) 5191 return false; 5192 return Success(RefValue, E); 5193 } 5194 return true; 5195 } 5196 5197 bool VisitBinaryOperator(const BinaryOperator *E) { 5198 switch (E->getOpcode()) { 5199 default: 5200 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5201 5202 case BO_PtrMemD: 5203 case BO_PtrMemI: 5204 return HandleMemberPointerAccess(this->Info, E, Result); 5205 } 5206 } 5207 5208 bool VisitCastExpr(const CastExpr *E) { 5209 switch (E->getCastKind()) { 5210 default: 5211 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5212 5213 case CK_DerivedToBase: 5214 case CK_UncheckedDerivedToBase: 5215 if (!this->Visit(E->getSubExpr())) 5216 return false; 5217 5218 // Now figure out the necessary offset to add to the base LV to get from 5219 // the derived class to the base class. 5220 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 5221 Result); 5222 } 5223 } 5224 }; 5225 } 5226 5227 //===----------------------------------------------------------------------===// 5228 // LValue Evaluation 5229 // 5230 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 5231 // function designators (in C), decl references to void objects (in C), and 5232 // temporaries (if building with -Wno-address-of-temporary). 5233 // 5234 // LValue evaluation produces values comprising a base expression of one of the 5235 // following types: 5236 // - Declarations 5237 // * VarDecl 5238 // * FunctionDecl 5239 // - Literals 5240 // * CompoundLiteralExpr in C (and in global scope in C++) 5241 // * StringLiteral 5242 // * CXXTypeidExpr 5243 // * PredefinedExpr 5244 // * ObjCStringLiteralExpr 5245 // * ObjCEncodeExpr 5246 // * AddrLabelExpr 5247 // * BlockExpr 5248 // * CallExpr for a MakeStringConstant builtin 5249 // - Locals and temporaries 5250 // * MaterializeTemporaryExpr 5251 // * Any Expr, with a CallIndex indicating the function in which the temporary 5252 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 5253 // from the AST (FIXME). 5254 // * A MaterializeTemporaryExpr that has static storage duration, with no 5255 // CallIndex, for a lifetime-extended temporary. 5256 // plus an offset in bytes. 5257 //===----------------------------------------------------------------------===// 5258 namespace { 5259 class LValueExprEvaluator 5260 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 5261 public: 5262 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 5263 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 5264 5265 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 5266 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 5267 5268 bool VisitDeclRefExpr(const DeclRefExpr *E); 5269 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 5270 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 5271 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 5272 bool VisitMemberExpr(const MemberExpr *E); 5273 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 5274 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 5275 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 5276 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 5277 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 5278 bool VisitUnaryDeref(const UnaryOperator *E); 5279 bool VisitUnaryReal(const UnaryOperator *E); 5280 bool VisitUnaryImag(const UnaryOperator *E); 5281 bool VisitUnaryPreInc(const UnaryOperator *UO) { 5282 return VisitUnaryPreIncDec(UO); 5283 } 5284 bool VisitUnaryPreDec(const UnaryOperator *UO) { 5285 return VisitUnaryPreIncDec(UO); 5286 } 5287 bool VisitBinAssign(const BinaryOperator *BO); 5288 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 5289 5290 bool VisitCastExpr(const CastExpr *E) { 5291 switch (E->getCastKind()) { 5292 default: 5293 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 5294 5295 case CK_LValueBitCast: 5296 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5297 if (!Visit(E->getSubExpr())) 5298 return false; 5299 Result.Designator.setInvalid(); 5300 return true; 5301 5302 case CK_BaseToDerived: 5303 if (!Visit(E->getSubExpr())) 5304 return false; 5305 return HandleBaseToDerivedCast(Info, E, Result); 5306 } 5307 } 5308 }; 5309 } // end anonymous namespace 5310 5311 /// Evaluate an expression as an lvalue. This can be legitimately called on 5312 /// expressions which are not glvalues, in three cases: 5313 /// * function designators in C, and 5314 /// * "extern void" objects 5315 /// * @selector() expressions in Objective-C 5316 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 5317 bool InvalidBaseOK) { 5318 assert(E->isGLValue() || E->getType()->isFunctionType() || 5319 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 5320 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 5321 } 5322 5323 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 5324 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 5325 return Success(FD); 5326 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 5327 return VisitVarDecl(E, VD); 5328 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 5329 return Visit(BD->getBinding()); 5330 return Error(E); 5331 } 5332 5333 5334 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 5335 5336 // If we are within a lambda's call operator, check whether the 'VD' referred 5337 // to within 'E' actually represents a lambda-capture that maps to a 5338 // data-member/field within the closure object, and if so, evaluate to the 5339 // field or what the field refers to. 5340 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 5341 isa<DeclRefExpr>(E) && 5342 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 5343 // We don't always have a complete capture-map when checking or inferring if 5344 // the function call operator meets the requirements of a constexpr function 5345 // - but we don't need to evaluate the captures to determine constexprness 5346 // (dcl.constexpr C++17). 5347 if (Info.checkingPotentialConstantExpression()) 5348 return false; 5349 5350 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 5351 // Start with 'Result' referring to the complete closure object... 5352 Result = *Info.CurrentCall->This; 5353 // ... then update it to refer to the field of the closure object 5354 // that represents the capture. 5355 if (!HandleLValueMember(Info, E, Result, FD)) 5356 return false; 5357 // And if the field is of reference type, update 'Result' to refer to what 5358 // the field refers to. 5359 if (FD->getType()->isReferenceType()) { 5360 APValue RVal; 5361 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 5362 RVal)) 5363 return false; 5364 Result.setFrom(Info.Ctx, RVal); 5365 } 5366 return true; 5367 } 5368 } 5369 CallStackFrame *Frame = nullptr; 5370 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 5371 // Only if a local variable was declared in the function currently being 5372 // evaluated, do we expect to be able to find its value in the current 5373 // frame. (Otherwise it was likely declared in an enclosing context and 5374 // could either have a valid evaluatable value (for e.g. a constexpr 5375 // variable) or be ill-formed (and trigger an appropriate evaluation 5376 // diagnostic)). 5377 if (Info.CurrentCall->Callee && 5378 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 5379 Frame = Info.CurrentCall; 5380 } 5381 } 5382 5383 if (!VD->getType()->isReferenceType()) { 5384 if (Frame) { 5385 Result.set({VD, Frame->Index, 5386 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 5387 return true; 5388 } 5389 return Success(VD); 5390 } 5391 5392 APValue *V; 5393 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 5394 return false; 5395 if (V->isUninit()) { 5396 if (!Info.checkingPotentialConstantExpression()) 5397 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 5398 return false; 5399 } 5400 return Success(*V, E); 5401 } 5402 5403 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 5404 const MaterializeTemporaryExpr *E) { 5405 // Walk through the expression to find the materialized temporary itself. 5406 SmallVector<const Expr *, 2> CommaLHSs; 5407 SmallVector<SubobjectAdjustment, 2> Adjustments; 5408 const Expr *Inner = E->GetTemporaryExpr()-> 5409 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 5410 5411 // If we passed any comma operators, evaluate their LHSs. 5412 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 5413 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 5414 return false; 5415 5416 // A materialized temporary with static storage duration can appear within the 5417 // result of a constant expression evaluation, so we need to preserve its 5418 // value for use outside this evaluation. 5419 APValue *Value; 5420 if (E->getStorageDuration() == SD_Static) { 5421 Value = Info.Ctx.getMaterializedTemporaryValue(E, true); 5422 *Value = APValue(); 5423 Result.set(E); 5424 } else { 5425 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result, 5426 *Info.CurrentCall); 5427 } 5428 5429 QualType Type = Inner->getType(); 5430 5431 // Materialize the temporary itself. 5432 if (!EvaluateInPlace(*Value, Info, Result, Inner) || 5433 (E->getStorageDuration() == SD_Static && 5434 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) { 5435 *Value = APValue(); 5436 return false; 5437 } 5438 5439 // Adjust our lvalue to refer to the desired subobject. 5440 for (unsigned I = Adjustments.size(); I != 0; /**/) { 5441 --I; 5442 switch (Adjustments[I].Kind) { 5443 case SubobjectAdjustment::DerivedToBaseAdjustment: 5444 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 5445 Type, Result)) 5446 return false; 5447 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 5448 break; 5449 5450 case SubobjectAdjustment::FieldAdjustment: 5451 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 5452 return false; 5453 Type = Adjustments[I].Field->getType(); 5454 break; 5455 5456 case SubobjectAdjustment::MemberPointerAdjustment: 5457 if (!HandleMemberPointerAccess(this->Info, Type, Result, 5458 Adjustments[I].Ptr.RHS)) 5459 return false; 5460 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 5461 break; 5462 } 5463 } 5464 5465 return true; 5466 } 5467 5468 bool 5469 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 5470 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 5471 "lvalue compound literal in c++?"); 5472 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 5473 // only see this when folding in C, so there's no standard to follow here. 5474 return Success(E); 5475 } 5476 5477 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 5478 if (!E->isPotentiallyEvaluated()) 5479 return Success(E); 5480 5481 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic) 5482 << E->getExprOperand()->getType() 5483 << E->getExprOperand()->getSourceRange(); 5484 return false; 5485 } 5486 5487 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 5488 return Success(E); 5489 } 5490 5491 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 5492 // Handle static data members. 5493 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 5494 VisitIgnoredBaseExpression(E->getBase()); 5495 return VisitVarDecl(E, VD); 5496 } 5497 5498 // Handle static member functions. 5499 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 5500 if (MD->isStatic()) { 5501 VisitIgnoredBaseExpression(E->getBase()); 5502 return Success(MD); 5503 } 5504 } 5505 5506 // Handle non-static data members. 5507 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 5508 } 5509 5510 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 5511 // FIXME: Deal with vectors as array subscript bases. 5512 if (E->getBase()->getType()->isVectorType()) 5513 return Error(E); 5514 5515 bool Success = true; 5516 if (!evaluatePointer(E->getBase(), Result)) { 5517 if (!Info.noteFailure()) 5518 return false; 5519 Success = false; 5520 } 5521 5522 APSInt Index; 5523 if (!EvaluateInteger(E->getIdx(), Index, Info)) 5524 return false; 5525 5526 return Success && 5527 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 5528 } 5529 5530 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 5531 return evaluatePointer(E->getSubExpr(), Result); 5532 } 5533 5534 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 5535 if (!Visit(E->getSubExpr())) 5536 return false; 5537 // __real is a no-op on scalar lvalues. 5538 if (E->getSubExpr()->getType()->isAnyComplexType()) 5539 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 5540 return true; 5541 } 5542 5543 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 5544 assert(E->getSubExpr()->getType()->isAnyComplexType() && 5545 "lvalue __imag__ on scalar?"); 5546 if (!Visit(E->getSubExpr())) 5547 return false; 5548 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 5549 return true; 5550 } 5551 5552 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 5553 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5554 return Error(UO); 5555 5556 if (!this->Visit(UO->getSubExpr())) 5557 return false; 5558 5559 return handleIncDec( 5560 this->Info, UO, Result, UO->getSubExpr()->getType(), 5561 UO->isIncrementOp(), nullptr); 5562 } 5563 5564 bool LValueExprEvaluator::VisitCompoundAssignOperator( 5565 const CompoundAssignOperator *CAO) { 5566 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5567 return Error(CAO); 5568 5569 APValue RHS; 5570 5571 // The overall lvalue result is the result of evaluating the LHS. 5572 if (!this->Visit(CAO->getLHS())) { 5573 if (Info.noteFailure()) 5574 Evaluate(RHS, this->Info, CAO->getRHS()); 5575 return false; 5576 } 5577 5578 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 5579 return false; 5580 5581 return handleCompoundAssignment( 5582 this->Info, CAO, 5583 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 5584 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 5585 } 5586 5587 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 5588 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5589 return Error(E); 5590 5591 APValue NewVal; 5592 5593 if (!this->Visit(E->getLHS())) { 5594 if (Info.noteFailure()) 5595 Evaluate(NewVal, this->Info, E->getRHS()); 5596 return false; 5597 } 5598 5599 if (!Evaluate(NewVal, this->Info, E->getRHS())) 5600 return false; 5601 5602 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 5603 NewVal); 5604 } 5605 5606 //===----------------------------------------------------------------------===// 5607 // Pointer Evaluation 5608 //===----------------------------------------------------------------------===// 5609 5610 /// Attempts to compute the number of bytes available at the pointer 5611 /// returned by a function with the alloc_size attribute. Returns true if we 5612 /// were successful. Places an unsigned number into `Result`. 5613 /// 5614 /// This expects the given CallExpr to be a call to a function with an 5615 /// alloc_size attribute. 5616 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 5617 const CallExpr *Call, 5618 llvm::APInt &Result) { 5619 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 5620 5621 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 5622 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 5623 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 5624 if (Call->getNumArgs() <= SizeArgNo) 5625 return false; 5626 5627 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 5628 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects)) 5629 return false; 5630 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 5631 return false; 5632 Into = Into.zextOrSelf(BitsInSizeT); 5633 return true; 5634 }; 5635 5636 APSInt SizeOfElem; 5637 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 5638 return false; 5639 5640 if (!AllocSize->getNumElemsParam().isValid()) { 5641 Result = std::move(SizeOfElem); 5642 return true; 5643 } 5644 5645 APSInt NumberOfElems; 5646 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 5647 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 5648 return false; 5649 5650 bool Overflow; 5651 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 5652 if (Overflow) 5653 return false; 5654 5655 Result = std::move(BytesAvailable); 5656 return true; 5657 } 5658 5659 /// Convenience function. LVal's base must be a call to an alloc_size 5660 /// function. 5661 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 5662 const LValue &LVal, 5663 llvm::APInt &Result) { 5664 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 5665 "Can't get the size of a non alloc_size function"); 5666 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 5667 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 5668 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 5669 } 5670 5671 /// Attempts to evaluate the given LValueBase as the result of a call to 5672 /// a function with the alloc_size attribute. If it was possible to do so, this 5673 /// function will return true, make Result's Base point to said function call, 5674 /// and mark Result's Base as invalid. 5675 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 5676 LValue &Result) { 5677 if (Base.isNull()) 5678 return false; 5679 5680 // Because we do no form of static analysis, we only support const variables. 5681 // 5682 // Additionally, we can't support parameters, nor can we support static 5683 // variables (in the latter case, use-before-assign isn't UB; in the former, 5684 // we have no clue what they'll be assigned to). 5685 const auto *VD = 5686 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 5687 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 5688 return false; 5689 5690 const Expr *Init = VD->getAnyInitializer(); 5691 if (!Init) 5692 return false; 5693 5694 const Expr *E = Init->IgnoreParens(); 5695 if (!tryUnwrapAllocSizeCall(E)) 5696 return false; 5697 5698 // Store E instead of E unwrapped so that the type of the LValue's base is 5699 // what the user wanted. 5700 Result.setInvalid(E); 5701 5702 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 5703 Result.addUnsizedArray(Info, E, Pointee); 5704 return true; 5705 } 5706 5707 namespace { 5708 class PointerExprEvaluator 5709 : public ExprEvaluatorBase<PointerExprEvaluator> { 5710 LValue &Result; 5711 bool InvalidBaseOK; 5712 5713 bool Success(const Expr *E) { 5714 Result.set(E); 5715 return true; 5716 } 5717 5718 bool evaluateLValue(const Expr *E, LValue &Result) { 5719 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 5720 } 5721 5722 bool evaluatePointer(const Expr *E, LValue &Result) { 5723 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 5724 } 5725 5726 bool visitNonBuiltinCallExpr(const CallExpr *E); 5727 public: 5728 5729 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 5730 : ExprEvaluatorBaseTy(info), Result(Result), 5731 InvalidBaseOK(InvalidBaseOK) {} 5732 5733 bool Success(const APValue &V, const Expr *E) { 5734 Result.setFrom(Info.Ctx, V); 5735 return true; 5736 } 5737 bool ZeroInitialization(const Expr *E) { 5738 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); 5739 Result.setNull(E->getType(), TargetVal); 5740 return true; 5741 } 5742 5743 bool VisitBinaryOperator(const BinaryOperator *E); 5744 bool VisitCastExpr(const CastExpr* E); 5745 bool VisitUnaryAddrOf(const UnaryOperator *E); 5746 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 5747 { return Success(E); } 5748 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 5749 if (Info.noteFailure()) 5750 EvaluateIgnoredValue(Info, E->getSubExpr()); 5751 return Error(E); 5752 } 5753 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 5754 { return Success(E); } 5755 bool VisitCallExpr(const CallExpr *E); 5756 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 5757 bool VisitBlockExpr(const BlockExpr *E) { 5758 if (!E->getBlockDecl()->hasCaptures()) 5759 return Success(E); 5760 return Error(E); 5761 } 5762 bool VisitCXXThisExpr(const CXXThisExpr *E) { 5763 // Can't look at 'this' when checking a potential constant expression. 5764 if (Info.checkingPotentialConstantExpression()) 5765 return false; 5766 if (!Info.CurrentCall->This) { 5767 if (Info.getLangOpts().CPlusPlus11) 5768 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 5769 else 5770 Info.FFDiag(E); 5771 return false; 5772 } 5773 Result = *Info.CurrentCall->This; 5774 // If we are inside a lambda's call operator, the 'this' expression refers 5775 // to the enclosing '*this' object (either by value or reference) which is 5776 // either copied into the closure object's field that represents the '*this' 5777 // or refers to '*this'. 5778 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 5779 // Update 'Result' to refer to the data member/field of the closure object 5780 // that represents the '*this' capture. 5781 if (!HandleLValueMember(Info, E, Result, 5782 Info.CurrentCall->LambdaThisCaptureField)) 5783 return false; 5784 // If we captured '*this' by reference, replace the field with its referent. 5785 if (Info.CurrentCall->LambdaThisCaptureField->getType() 5786 ->isPointerType()) { 5787 APValue RVal; 5788 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 5789 RVal)) 5790 return false; 5791 5792 Result.setFrom(Info.Ctx, RVal); 5793 } 5794 } 5795 return true; 5796 } 5797 5798 // FIXME: Missing: @protocol, @selector 5799 }; 5800 } // end anonymous namespace 5801 5802 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 5803 bool InvalidBaseOK) { 5804 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 5805 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 5806 } 5807 5808 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 5809 if (E->getOpcode() != BO_Add && 5810 E->getOpcode() != BO_Sub) 5811 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5812 5813 const Expr *PExp = E->getLHS(); 5814 const Expr *IExp = E->getRHS(); 5815 if (IExp->getType()->isPointerType()) 5816 std::swap(PExp, IExp); 5817 5818 bool EvalPtrOK = evaluatePointer(PExp, Result); 5819 if (!EvalPtrOK && !Info.noteFailure()) 5820 return false; 5821 5822 llvm::APSInt Offset; 5823 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 5824 return false; 5825 5826 if (E->getOpcode() == BO_Sub) 5827 negateAsSigned(Offset); 5828 5829 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 5830 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 5831 } 5832 5833 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 5834 return evaluateLValue(E->getSubExpr(), Result); 5835 } 5836 5837 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 5838 const Expr *SubExpr = E->getSubExpr(); 5839 5840 switch (E->getCastKind()) { 5841 default: 5842 break; 5843 5844 case CK_BitCast: 5845 case CK_CPointerToObjCPointerCast: 5846 case CK_BlockPointerToObjCPointerCast: 5847 case CK_AnyPointerToBlockPointerCast: 5848 case CK_AddressSpaceConversion: 5849 if (!Visit(SubExpr)) 5850 return false; 5851 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 5852 // permitted in constant expressions in C++11. Bitcasts from cv void* are 5853 // also static_casts, but we disallow them as a resolution to DR1312. 5854 if (!E->getType()->isVoidPointerType()) { 5855 Result.Designator.setInvalid(); 5856 if (SubExpr->getType()->isVoidPointerType()) 5857 CCEDiag(E, diag::note_constexpr_invalid_cast) 5858 << 3 << SubExpr->getType(); 5859 else 5860 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5861 } 5862 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 5863 ZeroInitialization(E); 5864 return true; 5865 5866 case CK_DerivedToBase: 5867 case CK_UncheckedDerivedToBase: 5868 if (!evaluatePointer(E->getSubExpr(), Result)) 5869 return false; 5870 if (!Result.Base && Result.Offset.isZero()) 5871 return true; 5872 5873 // Now figure out the necessary offset to add to the base LV to get from 5874 // the derived class to the base class. 5875 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 5876 castAs<PointerType>()->getPointeeType(), 5877 Result); 5878 5879 case CK_BaseToDerived: 5880 if (!Visit(E->getSubExpr())) 5881 return false; 5882 if (!Result.Base && Result.Offset.isZero()) 5883 return true; 5884 return HandleBaseToDerivedCast(Info, E, Result); 5885 5886 case CK_NullToPointer: 5887 VisitIgnoredValue(E->getSubExpr()); 5888 return ZeroInitialization(E); 5889 5890 case CK_IntegralToPointer: { 5891 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5892 5893 APValue Value; 5894 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 5895 break; 5896 5897 if (Value.isInt()) { 5898 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 5899 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 5900 Result.Base = (Expr*)nullptr; 5901 Result.InvalidBase = false; 5902 Result.Offset = CharUnits::fromQuantity(N); 5903 Result.Designator.setInvalid(); 5904 Result.IsNullPtr = false; 5905 return true; 5906 } else { 5907 // Cast is of an lvalue, no need to change value. 5908 Result.setFrom(Info.Ctx, Value); 5909 return true; 5910 } 5911 } 5912 5913 case CK_ArrayToPointerDecay: { 5914 if (SubExpr->isGLValue()) { 5915 if (!evaluateLValue(SubExpr, Result)) 5916 return false; 5917 } else { 5918 APValue &Value = createTemporary(SubExpr, false, Result, 5919 *Info.CurrentCall); 5920 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 5921 return false; 5922 } 5923 // The result is a pointer to the first element of the array. 5924 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 5925 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 5926 Result.addArray(Info, E, CAT); 5927 else 5928 Result.addUnsizedArray(Info, E, AT->getElementType()); 5929 return true; 5930 } 5931 5932 case CK_FunctionToPointerDecay: 5933 return evaluateLValue(SubExpr, Result); 5934 5935 case CK_LValueToRValue: { 5936 LValue LVal; 5937 if (!evaluateLValue(E->getSubExpr(), LVal)) 5938 return false; 5939 5940 APValue RVal; 5941 // Note, we use the subexpression's type in order to retain cv-qualifiers. 5942 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 5943 LVal, RVal)) 5944 return InvalidBaseOK && 5945 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 5946 return Success(RVal, E); 5947 } 5948 } 5949 5950 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5951 } 5952 5953 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 5954 UnaryExprOrTypeTrait ExprKind) { 5955 // C++ [expr.alignof]p3: 5956 // When alignof is applied to a reference type, the result is the 5957 // alignment of the referenced type. 5958 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 5959 T = Ref->getPointeeType(); 5960 5961 if (T.getQualifiers().hasUnaligned()) 5962 return CharUnits::One(); 5963 5964 const bool AlignOfReturnsPreferred = 5965 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 5966 5967 // __alignof is defined to return the preferred alignment. 5968 // Before 8, clang returned the preferred alignment for alignof and _Alignof 5969 // as well. 5970 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 5971 return Info.Ctx.toCharUnitsFromBits( 5972 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 5973 // alignof and _Alignof are defined to return the ABI alignment. 5974 else if (ExprKind == UETT_AlignOf) 5975 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 5976 else 5977 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 5978 } 5979 5980 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 5981 UnaryExprOrTypeTrait ExprKind) { 5982 E = E->IgnoreParens(); 5983 5984 // The kinds of expressions that we have special-case logic here for 5985 // should be kept up to date with the special checks for those 5986 // expressions in Sema. 5987 5988 // alignof decl is always accepted, even if it doesn't make sense: we default 5989 // to 1 in those cases. 5990 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 5991 return Info.Ctx.getDeclAlign(DRE->getDecl(), 5992 /*RefAsPointee*/true); 5993 5994 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 5995 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 5996 /*RefAsPointee*/true); 5997 5998 return GetAlignOfType(Info, E->getType(), ExprKind); 5999 } 6000 6001 // To be clear: this happily visits unsupported builtins. Better name welcomed. 6002 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 6003 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 6004 return true; 6005 6006 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 6007 return false; 6008 6009 Result.setInvalid(E); 6010 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 6011 Result.addUnsizedArray(Info, E, PointeeTy); 6012 return true; 6013 } 6014 6015 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 6016 if (IsStringLiteralCall(E)) 6017 return Success(E); 6018 6019 if (unsigned BuiltinOp = E->getBuiltinCallee()) 6020 return VisitBuiltinCallExpr(E, BuiltinOp); 6021 6022 return visitNonBuiltinCallExpr(E); 6023 } 6024 6025 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 6026 unsigned BuiltinOp) { 6027 switch (BuiltinOp) { 6028 case Builtin::BI__builtin_addressof: 6029 return evaluateLValue(E->getArg(0), Result); 6030 case Builtin::BI__builtin_assume_aligned: { 6031 // We need to be very careful here because: if the pointer does not have the 6032 // asserted alignment, then the behavior is undefined, and undefined 6033 // behavior is non-constant. 6034 if (!evaluatePointer(E->getArg(0), Result)) 6035 return false; 6036 6037 LValue OffsetResult(Result); 6038 APSInt Alignment; 6039 if (!EvaluateInteger(E->getArg(1), Alignment, Info)) 6040 return false; 6041 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 6042 6043 if (E->getNumArgs() > 2) { 6044 APSInt Offset; 6045 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 6046 return false; 6047 6048 int64_t AdditionalOffset = -Offset.getZExtValue(); 6049 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 6050 } 6051 6052 // If there is a base object, then it must have the correct alignment. 6053 if (OffsetResult.Base) { 6054 CharUnits BaseAlignment; 6055 if (const ValueDecl *VD = 6056 OffsetResult.Base.dyn_cast<const ValueDecl*>()) { 6057 BaseAlignment = Info.Ctx.getDeclAlign(VD); 6058 } else { 6059 BaseAlignment = GetAlignOfExpr( 6060 Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf); 6061 } 6062 6063 if (BaseAlignment < Align) { 6064 Result.Designator.setInvalid(); 6065 // FIXME: Add support to Diagnostic for long / long long. 6066 CCEDiag(E->getArg(0), 6067 diag::note_constexpr_baa_insufficient_alignment) << 0 6068 << (unsigned)BaseAlignment.getQuantity() 6069 << (unsigned)Align.getQuantity(); 6070 return false; 6071 } 6072 } 6073 6074 // The offset must also have the correct alignment. 6075 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 6076 Result.Designator.setInvalid(); 6077 6078 (OffsetResult.Base 6079 ? CCEDiag(E->getArg(0), 6080 diag::note_constexpr_baa_insufficient_alignment) << 1 6081 : CCEDiag(E->getArg(0), 6082 diag::note_constexpr_baa_value_insufficient_alignment)) 6083 << (int)OffsetResult.Offset.getQuantity() 6084 << (unsigned)Align.getQuantity(); 6085 return false; 6086 } 6087 6088 return true; 6089 } 6090 6091 case Builtin::BIstrchr: 6092 case Builtin::BIwcschr: 6093 case Builtin::BImemchr: 6094 case Builtin::BIwmemchr: 6095 if (Info.getLangOpts().CPlusPlus11) 6096 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 6097 << /*isConstexpr*/0 << /*isConstructor*/0 6098 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 6099 else 6100 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 6101 LLVM_FALLTHROUGH; 6102 case Builtin::BI__builtin_strchr: 6103 case Builtin::BI__builtin_wcschr: 6104 case Builtin::BI__builtin_memchr: 6105 case Builtin::BI__builtin_char_memchr: 6106 case Builtin::BI__builtin_wmemchr: { 6107 if (!Visit(E->getArg(0))) 6108 return false; 6109 APSInt Desired; 6110 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 6111 return false; 6112 uint64_t MaxLength = uint64_t(-1); 6113 if (BuiltinOp != Builtin::BIstrchr && 6114 BuiltinOp != Builtin::BIwcschr && 6115 BuiltinOp != Builtin::BI__builtin_strchr && 6116 BuiltinOp != Builtin::BI__builtin_wcschr) { 6117 APSInt N; 6118 if (!EvaluateInteger(E->getArg(2), N, Info)) 6119 return false; 6120 MaxLength = N.getExtValue(); 6121 } 6122 6123 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 6124 6125 // Figure out what value we're actually looking for (after converting to 6126 // the corresponding unsigned type if necessary). 6127 uint64_t DesiredVal; 6128 bool StopAtNull = false; 6129 switch (BuiltinOp) { 6130 case Builtin::BIstrchr: 6131 case Builtin::BI__builtin_strchr: 6132 // strchr compares directly to the passed integer, and therefore 6133 // always fails if given an int that is not a char. 6134 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 6135 E->getArg(1)->getType(), 6136 Desired), 6137 Desired)) 6138 return ZeroInitialization(E); 6139 StopAtNull = true; 6140 LLVM_FALLTHROUGH; 6141 case Builtin::BImemchr: 6142 case Builtin::BI__builtin_memchr: 6143 case Builtin::BI__builtin_char_memchr: 6144 // memchr compares by converting both sides to unsigned char. That's also 6145 // correct for strchr if we get this far (to cope with plain char being 6146 // unsigned in the strchr case). 6147 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 6148 break; 6149 6150 case Builtin::BIwcschr: 6151 case Builtin::BI__builtin_wcschr: 6152 StopAtNull = true; 6153 LLVM_FALLTHROUGH; 6154 case Builtin::BIwmemchr: 6155 case Builtin::BI__builtin_wmemchr: 6156 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 6157 DesiredVal = Desired.getZExtValue(); 6158 break; 6159 } 6160 6161 for (; MaxLength; --MaxLength) { 6162 APValue Char; 6163 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 6164 !Char.isInt()) 6165 return false; 6166 if (Char.getInt().getZExtValue() == DesiredVal) 6167 return true; 6168 if (StopAtNull && !Char.getInt()) 6169 break; 6170 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 6171 return false; 6172 } 6173 // Not found: return nullptr. 6174 return ZeroInitialization(E); 6175 } 6176 6177 case Builtin::BImemcpy: 6178 case Builtin::BImemmove: 6179 case Builtin::BIwmemcpy: 6180 case Builtin::BIwmemmove: 6181 if (Info.getLangOpts().CPlusPlus11) 6182 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 6183 << /*isConstexpr*/0 << /*isConstructor*/0 6184 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 6185 else 6186 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 6187 LLVM_FALLTHROUGH; 6188 case Builtin::BI__builtin_memcpy: 6189 case Builtin::BI__builtin_memmove: 6190 case Builtin::BI__builtin_wmemcpy: 6191 case Builtin::BI__builtin_wmemmove: { 6192 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 6193 BuiltinOp == Builtin::BIwmemmove || 6194 BuiltinOp == Builtin::BI__builtin_wmemcpy || 6195 BuiltinOp == Builtin::BI__builtin_wmemmove; 6196 bool Move = BuiltinOp == Builtin::BImemmove || 6197 BuiltinOp == Builtin::BIwmemmove || 6198 BuiltinOp == Builtin::BI__builtin_memmove || 6199 BuiltinOp == Builtin::BI__builtin_wmemmove; 6200 6201 // The result of mem* is the first argument. 6202 if (!Visit(E->getArg(0))) 6203 return false; 6204 LValue Dest = Result; 6205 6206 LValue Src; 6207 if (!EvaluatePointer(E->getArg(1), Src, Info)) 6208 return false; 6209 6210 APSInt N; 6211 if (!EvaluateInteger(E->getArg(2), N, Info)) 6212 return false; 6213 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 6214 6215 // If the size is zero, we treat this as always being a valid no-op. 6216 // (Even if one of the src and dest pointers is null.) 6217 if (!N) 6218 return true; 6219 6220 // Otherwise, if either of the operands is null, we can't proceed. Don't 6221 // try to determine the type of the copied objects, because there aren't 6222 // any. 6223 if (!Src.Base || !Dest.Base) { 6224 APValue Val; 6225 (!Src.Base ? Src : Dest).moveInto(Val); 6226 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 6227 << Move << WChar << !!Src.Base 6228 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 6229 return false; 6230 } 6231 if (Src.Designator.Invalid || Dest.Designator.Invalid) 6232 return false; 6233 6234 // We require that Src and Dest are both pointers to arrays of 6235 // trivially-copyable type. (For the wide version, the designator will be 6236 // invalid if the designated object is not a wchar_t.) 6237 QualType T = Dest.Designator.getType(Info.Ctx); 6238 QualType SrcT = Src.Designator.getType(Info.Ctx); 6239 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 6240 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 6241 return false; 6242 } 6243 if (T->isIncompleteType()) { 6244 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 6245 return false; 6246 } 6247 if (!T.isTriviallyCopyableType(Info.Ctx)) { 6248 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 6249 return false; 6250 } 6251 6252 // Figure out how many T's we're copying. 6253 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 6254 if (!WChar) { 6255 uint64_t Remainder; 6256 llvm::APInt OrigN = N; 6257 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 6258 if (Remainder) { 6259 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 6260 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 6261 << (unsigned)TSize; 6262 return false; 6263 } 6264 } 6265 6266 // Check that the copying will remain within the arrays, just so that we 6267 // can give a more meaningful diagnostic. This implicitly also checks that 6268 // N fits into 64 bits. 6269 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 6270 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 6271 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 6272 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 6273 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 6274 << N.toString(10, /*Signed*/false); 6275 return false; 6276 } 6277 uint64_t NElems = N.getZExtValue(); 6278 uint64_t NBytes = NElems * TSize; 6279 6280 // Check for overlap. 6281 int Direction = 1; 6282 if (HasSameBase(Src, Dest)) { 6283 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 6284 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 6285 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 6286 // Dest is inside the source region. 6287 if (!Move) { 6288 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 6289 return false; 6290 } 6291 // For memmove and friends, copy backwards. 6292 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 6293 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 6294 return false; 6295 Direction = -1; 6296 } else if (!Move && SrcOffset >= DestOffset && 6297 SrcOffset - DestOffset < NBytes) { 6298 // Src is inside the destination region for memcpy: invalid. 6299 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 6300 return false; 6301 } 6302 } 6303 6304 while (true) { 6305 APValue Val; 6306 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 6307 !handleAssignment(Info, E, Dest, T, Val)) 6308 return false; 6309 // Do not iterate past the last element; if we're copying backwards, that 6310 // might take us off the start of the array. 6311 if (--NElems == 0) 6312 return true; 6313 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 6314 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 6315 return false; 6316 } 6317 } 6318 6319 default: 6320 return visitNonBuiltinCallExpr(E); 6321 } 6322 } 6323 6324 //===----------------------------------------------------------------------===// 6325 // Member Pointer Evaluation 6326 //===----------------------------------------------------------------------===// 6327 6328 namespace { 6329 class MemberPointerExprEvaluator 6330 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 6331 MemberPtr &Result; 6332 6333 bool Success(const ValueDecl *D) { 6334 Result = MemberPtr(D); 6335 return true; 6336 } 6337 public: 6338 6339 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 6340 : ExprEvaluatorBaseTy(Info), Result(Result) {} 6341 6342 bool Success(const APValue &V, const Expr *E) { 6343 Result.setFrom(V); 6344 return true; 6345 } 6346 bool ZeroInitialization(const Expr *E) { 6347 return Success((const ValueDecl*)nullptr); 6348 } 6349 6350 bool VisitCastExpr(const CastExpr *E); 6351 bool VisitUnaryAddrOf(const UnaryOperator *E); 6352 }; 6353 } // end anonymous namespace 6354 6355 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 6356 EvalInfo &Info) { 6357 assert(E->isRValue() && E->getType()->isMemberPointerType()); 6358 return MemberPointerExprEvaluator(Info, Result).Visit(E); 6359 } 6360 6361 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 6362 switch (E->getCastKind()) { 6363 default: 6364 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6365 6366 case CK_NullToMemberPointer: 6367 VisitIgnoredValue(E->getSubExpr()); 6368 return ZeroInitialization(E); 6369 6370 case CK_BaseToDerivedMemberPointer: { 6371 if (!Visit(E->getSubExpr())) 6372 return false; 6373 if (E->path_empty()) 6374 return true; 6375 // Base-to-derived member pointer casts store the path in derived-to-base 6376 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 6377 // the wrong end of the derived->base arc, so stagger the path by one class. 6378 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 6379 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 6380 PathI != PathE; ++PathI) { 6381 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 6382 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 6383 if (!Result.castToDerived(Derived)) 6384 return Error(E); 6385 } 6386 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 6387 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 6388 return Error(E); 6389 return true; 6390 } 6391 6392 case CK_DerivedToBaseMemberPointer: 6393 if (!Visit(E->getSubExpr())) 6394 return false; 6395 for (CastExpr::path_const_iterator PathI = E->path_begin(), 6396 PathE = E->path_end(); PathI != PathE; ++PathI) { 6397 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 6398 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 6399 if (!Result.castToBase(Base)) 6400 return Error(E); 6401 } 6402 return true; 6403 } 6404 } 6405 6406 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 6407 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 6408 // member can be formed. 6409 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 6410 } 6411 6412 //===----------------------------------------------------------------------===// 6413 // Record Evaluation 6414 //===----------------------------------------------------------------------===// 6415 6416 namespace { 6417 class RecordExprEvaluator 6418 : public ExprEvaluatorBase<RecordExprEvaluator> { 6419 const LValue &This; 6420 APValue &Result; 6421 public: 6422 6423 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 6424 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 6425 6426 bool Success(const APValue &V, const Expr *E) { 6427 Result = V; 6428 return true; 6429 } 6430 bool ZeroInitialization(const Expr *E) { 6431 return ZeroInitialization(E, E->getType()); 6432 } 6433 bool ZeroInitialization(const Expr *E, QualType T); 6434 6435 bool VisitCallExpr(const CallExpr *E) { 6436 return handleCallExpr(E, Result, &This); 6437 } 6438 bool VisitCastExpr(const CastExpr *E); 6439 bool VisitInitListExpr(const InitListExpr *E); 6440 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 6441 return VisitCXXConstructExpr(E, E->getType()); 6442 } 6443 bool VisitLambdaExpr(const LambdaExpr *E); 6444 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 6445 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 6446 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 6447 6448 bool VisitBinCmp(const BinaryOperator *E); 6449 }; 6450 } 6451 6452 /// Perform zero-initialization on an object of non-union class type. 6453 /// C++11 [dcl.init]p5: 6454 /// To zero-initialize an object or reference of type T means: 6455 /// [...] 6456 /// -- if T is a (possibly cv-qualified) non-union class type, 6457 /// each non-static data member and each base-class subobject is 6458 /// zero-initialized 6459 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 6460 const RecordDecl *RD, 6461 const LValue &This, APValue &Result) { 6462 assert(!RD->isUnion() && "Expected non-union class type"); 6463 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 6464 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 6465 std::distance(RD->field_begin(), RD->field_end())); 6466 6467 if (RD->isInvalidDecl()) return false; 6468 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6469 6470 if (CD) { 6471 unsigned Index = 0; 6472 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 6473 End = CD->bases_end(); I != End; ++I, ++Index) { 6474 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 6475 LValue Subobject = This; 6476 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 6477 return false; 6478 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 6479 Result.getStructBase(Index))) 6480 return false; 6481 } 6482 } 6483 6484 for (const auto *I : RD->fields()) { 6485 // -- if T is a reference type, no initialization is performed. 6486 if (I->getType()->isReferenceType()) 6487 continue; 6488 6489 LValue Subobject = This; 6490 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 6491 return false; 6492 6493 ImplicitValueInitExpr VIE(I->getType()); 6494 if (!EvaluateInPlace( 6495 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 6496 return false; 6497 } 6498 6499 return true; 6500 } 6501 6502 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 6503 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 6504 if (RD->isInvalidDecl()) return false; 6505 if (RD->isUnion()) { 6506 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 6507 // object's first non-static named data member is zero-initialized 6508 RecordDecl::field_iterator I = RD->field_begin(); 6509 if (I == RD->field_end()) { 6510 Result = APValue((const FieldDecl*)nullptr); 6511 return true; 6512 } 6513 6514 LValue Subobject = This; 6515 if (!HandleLValueMember(Info, E, Subobject, *I)) 6516 return false; 6517 Result = APValue(*I); 6518 ImplicitValueInitExpr VIE(I->getType()); 6519 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 6520 } 6521 6522 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 6523 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 6524 return false; 6525 } 6526 6527 return HandleClassZeroInitialization(Info, E, RD, This, Result); 6528 } 6529 6530 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 6531 switch (E->getCastKind()) { 6532 default: 6533 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6534 6535 case CK_ConstructorConversion: 6536 return Visit(E->getSubExpr()); 6537 6538 case CK_DerivedToBase: 6539 case CK_UncheckedDerivedToBase: { 6540 APValue DerivedObject; 6541 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 6542 return false; 6543 if (!DerivedObject.isStruct()) 6544 return Error(E->getSubExpr()); 6545 6546 // Derived-to-base rvalue conversion: just slice off the derived part. 6547 APValue *Value = &DerivedObject; 6548 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 6549 for (CastExpr::path_const_iterator PathI = E->path_begin(), 6550 PathE = E->path_end(); PathI != PathE; ++PathI) { 6551 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 6552 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 6553 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 6554 RD = Base; 6555 } 6556 Result = *Value; 6557 return true; 6558 } 6559 } 6560 } 6561 6562 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6563 if (E->isTransparent()) 6564 return Visit(E->getInit(0)); 6565 6566 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 6567 if (RD->isInvalidDecl()) return false; 6568 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6569 6570 if (RD->isUnion()) { 6571 const FieldDecl *Field = E->getInitializedFieldInUnion(); 6572 Result = APValue(Field); 6573 if (!Field) 6574 return true; 6575 6576 // If the initializer list for a union does not contain any elements, the 6577 // first element of the union is value-initialized. 6578 // FIXME: The element should be initialized from an initializer list. 6579 // Is this difference ever observable for initializer lists which 6580 // we don't build? 6581 ImplicitValueInitExpr VIE(Field->getType()); 6582 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 6583 6584 LValue Subobject = This; 6585 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 6586 return false; 6587 6588 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 6589 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 6590 isa<CXXDefaultInitExpr>(InitExpr)); 6591 6592 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 6593 } 6594 6595 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 6596 if (Result.isUninit()) 6597 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 6598 std::distance(RD->field_begin(), RD->field_end())); 6599 unsigned ElementNo = 0; 6600 bool Success = true; 6601 6602 // Initialize base classes. 6603 if (CXXRD) { 6604 for (const auto &Base : CXXRD->bases()) { 6605 assert(ElementNo < E->getNumInits() && "missing init for base class"); 6606 const Expr *Init = E->getInit(ElementNo); 6607 6608 LValue Subobject = This; 6609 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 6610 return false; 6611 6612 APValue &FieldVal = Result.getStructBase(ElementNo); 6613 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 6614 if (!Info.noteFailure()) 6615 return false; 6616 Success = false; 6617 } 6618 ++ElementNo; 6619 } 6620 } 6621 6622 // Initialize members. 6623 for (const auto *Field : RD->fields()) { 6624 // Anonymous bit-fields are not considered members of the class for 6625 // purposes of aggregate initialization. 6626 if (Field->isUnnamedBitfield()) 6627 continue; 6628 6629 LValue Subobject = This; 6630 6631 bool HaveInit = ElementNo < E->getNumInits(); 6632 6633 // FIXME: Diagnostics here should point to the end of the initializer 6634 // list, not the start. 6635 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 6636 Subobject, Field, &Layout)) 6637 return false; 6638 6639 // Perform an implicit value-initialization for members beyond the end of 6640 // the initializer list. 6641 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 6642 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 6643 6644 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 6645 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 6646 isa<CXXDefaultInitExpr>(Init)); 6647 6648 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 6649 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 6650 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 6651 FieldVal, Field))) { 6652 if (!Info.noteFailure()) 6653 return false; 6654 Success = false; 6655 } 6656 } 6657 6658 return Success; 6659 } 6660 6661 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 6662 QualType T) { 6663 // Note that E's type is not necessarily the type of our class here; we might 6664 // be initializing an array element instead. 6665 const CXXConstructorDecl *FD = E->getConstructor(); 6666 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 6667 6668 bool ZeroInit = E->requiresZeroInitialization(); 6669 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 6670 // If we've already performed zero-initialization, we're already done. 6671 if (!Result.isUninit()) 6672 return true; 6673 6674 // We can get here in two different ways: 6675 // 1) We're performing value-initialization, and should zero-initialize 6676 // the object, or 6677 // 2) We're performing default-initialization of an object with a trivial 6678 // constexpr default constructor, in which case we should start the 6679 // lifetimes of all the base subobjects (there can be no data member 6680 // subobjects in this case) per [basic.life]p1. 6681 // Either way, ZeroInitialization is appropriate. 6682 return ZeroInitialization(E, T); 6683 } 6684 6685 const FunctionDecl *Definition = nullptr; 6686 auto Body = FD->getBody(Definition); 6687 6688 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 6689 return false; 6690 6691 // Avoid materializing a temporary for an elidable copy/move constructor. 6692 if (E->isElidable() && !ZeroInit) 6693 if (const MaterializeTemporaryExpr *ME 6694 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 6695 return Visit(ME->GetTemporaryExpr()); 6696 6697 if (ZeroInit && !ZeroInitialization(E, T)) 6698 return false; 6699 6700 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 6701 return HandleConstructorCall(E, This, Args, 6702 cast<CXXConstructorDecl>(Definition), Info, 6703 Result); 6704 } 6705 6706 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 6707 const CXXInheritedCtorInitExpr *E) { 6708 if (!Info.CurrentCall) { 6709 assert(Info.checkingPotentialConstantExpression()); 6710 return false; 6711 } 6712 6713 const CXXConstructorDecl *FD = E->getConstructor(); 6714 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 6715 return false; 6716 6717 const FunctionDecl *Definition = nullptr; 6718 auto Body = FD->getBody(Definition); 6719 6720 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 6721 return false; 6722 6723 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 6724 cast<CXXConstructorDecl>(Definition), Info, 6725 Result); 6726 } 6727 6728 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 6729 const CXXStdInitializerListExpr *E) { 6730 const ConstantArrayType *ArrayType = 6731 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 6732 6733 LValue Array; 6734 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 6735 return false; 6736 6737 // Get a pointer to the first element of the array. 6738 Array.addArray(Info, E, ArrayType); 6739 6740 // FIXME: Perform the checks on the field types in SemaInit. 6741 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 6742 RecordDecl::field_iterator Field = Record->field_begin(); 6743 if (Field == Record->field_end()) 6744 return Error(E); 6745 6746 // Start pointer. 6747 if (!Field->getType()->isPointerType() || 6748 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 6749 ArrayType->getElementType())) 6750 return Error(E); 6751 6752 // FIXME: What if the initializer_list type has base classes, etc? 6753 Result = APValue(APValue::UninitStruct(), 0, 2); 6754 Array.moveInto(Result.getStructField(0)); 6755 6756 if (++Field == Record->field_end()) 6757 return Error(E); 6758 6759 if (Field->getType()->isPointerType() && 6760 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 6761 ArrayType->getElementType())) { 6762 // End pointer. 6763 if (!HandleLValueArrayAdjustment(Info, E, Array, 6764 ArrayType->getElementType(), 6765 ArrayType->getSize().getZExtValue())) 6766 return false; 6767 Array.moveInto(Result.getStructField(1)); 6768 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 6769 // Length. 6770 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 6771 else 6772 return Error(E); 6773 6774 if (++Field != Record->field_end()) 6775 return Error(E); 6776 6777 return true; 6778 } 6779 6780 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 6781 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 6782 if (ClosureClass->isInvalidDecl()) return false; 6783 6784 if (Info.checkingPotentialConstantExpression()) return true; 6785 6786 const size_t NumFields = 6787 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 6788 6789 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 6790 E->capture_init_end()) && 6791 "The number of lambda capture initializers should equal the number of " 6792 "fields within the closure type"); 6793 6794 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 6795 // Iterate through all the lambda's closure object's fields and initialize 6796 // them. 6797 auto *CaptureInitIt = E->capture_init_begin(); 6798 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 6799 bool Success = true; 6800 for (const auto *Field : ClosureClass->fields()) { 6801 assert(CaptureInitIt != E->capture_init_end()); 6802 // Get the initializer for this field 6803 Expr *const CurFieldInit = *CaptureInitIt++; 6804 6805 // If there is no initializer, either this is a VLA or an error has 6806 // occurred. 6807 if (!CurFieldInit) 6808 return Error(E); 6809 6810 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 6811 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 6812 if (!Info.keepEvaluatingAfterFailure()) 6813 return false; 6814 Success = false; 6815 } 6816 ++CaptureIt; 6817 } 6818 return Success; 6819 } 6820 6821 static bool EvaluateRecord(const Expr *E, const LValue &This, 6822 APValue &Result, EvalInfo &Info) { 6823 assert(E->isRValue() && E->getType()->isRecordType() && 6824 "can't evaluate expression as a record rvalue"); 6825 return RecordExprEvaluator(Info, This, Result).Visit(E); 6826 } 6827 6828 //===----------------------------------------------------------------------===// 6829 // Temporary Evaluation 6830 // 6831 // Temporaries are represented in the AST as rvalues, but generally behave like 6832 // lvalues. The full-object of which the temporary is a subobject is implicitly 6833 // materialized so that a reference can bind to it. 6834 //===----------------------------------------------------------------------===// 6835 namespace { 6836 class TemporaryExprEvaluator 6837 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 6838 public: 6839 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 6840 LValueExprEvaluatorBaseTy(Info, Result, false) {} 6841 6842 /// Visit an expression which constructs the value of this temporary. 6843 bool VisitConstructExpr(const Expr *E) { 6844 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall); 6845 return EvaluateInPlace(Value, Info, Result, E); 6846 } 6847 6848 bool VisitCastExpr(const CastExpr *E) { 6849 switch (E->getCastKind()) { 6850 default: 6851 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 6852 6853 case CK_ConstructorConversion: 6854 return VisitConstructExpr(E->getSubExpr()); 6855 } 6856 } 6857 bool VisitInitListExpr(const InitListExpr *E) { 6858 return VisitConstructExpr(E); 6859 } 6860 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 6861 return VisitConstructExpr(E); 6862 } 6863 bool VisitCallExpr(const CallExpr *E) { 6864 return VisitConstructExpr(E); 6865 } 6866 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 6867 return VisitConstructExpr(E); 6868 } 6869 bool VisitLambdaExpr(const LambdaExpr *E) { 6870 return VisitConstructExpr(E); 6871 } 6872 }; 6873 } // end anonymous namespace 6874 6875 /// Evaluate an expression of record type as a temporary. 6876 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 6877 assert(E->isRValue() && E->getType()->isRecordType()); 6878 return TemporaryExprEvaluator(Info, Result).Visit(E); 6879 } 6880 6881 //===----------------------------------------------------------------------===// 6882 // Vector Evaluation 6883 //===----------------------------------------------------------------------===// 6884 6885 namespace { 6886 class VectorExprEvaluator 6887 : public ExprEvaluatorBase<VectorExprEvaluator> { 6888 APValue &Result; 6889 public: 6890 6891 VectorExprEvaluator(EvalInfo &info, APValue &Result) 6892 : ExprEvaluatorBaseTy(info), Result(Result) {} 6893 6894 bool Success(ArrayRef<APValue> V, const Expr *E) { 6895 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 6896 // FIXME: remove this APValue copy. 6897 Result = APValue(V.data(), V.size()); 6898 return true; 6899 } 6900 bool Success(const APValue &V, const Expr *E) { 6901 assert(V.isVector()); 6902 Result = V; 6903 return true; 6904 } 6905 bool ZeroInitialization(const Expr *E); 6906 6907 bool VisitUnaryReal(const UnaryOperator *E) 6908 { return Visit(E->getSubExpr()); } 6909 bool VisitCastExpr(const CastExpr* E); 6910 bool VisitInitListExpr(const InitListExpr *E); 6911 bool VisitUnaryImag(const UnaryOperator *E); 6912 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 6913 // binary comparisons, binary and/or/xor, 6914 // shufflevector, ExtVectorElementExpr 6915 }; 6916 } // end anonymous namespace 6917 6918 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 6919 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 6920 return VectorExprEvaluator(Info, Result).Visit(E); 6921 } 6922 6923 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 6924 const VectorType *VTy = E->getType()->castAs<VectorType>(); 6925 unsigned NElts = VTy->getNumElements(); 6926 6927 const Expr *SE = E->getSubExpr(); 6928 QualType SETy = SE->getType(); 6929 6930 switch (E->getCastKind()) { 6931 case CK_VectorSplat: { 6932 APValue Val = APValue(); 6933 if (SETy->isIntegerType()) { 6934 APSInt IntResult; 6935 if (!EvaluateInteger(SE, IntResult, Info)) 6936 return false; 6937 Val = APValue(std::move(IntResult)); 6938 } else if (SETy->isRealFloatingType()) { 6939 APFloat FloatResult(0.0); 6940 if (!EvaluateFloat(SE, FloatResult, Info)) 6941 return false; 6942 Val = APValue(std::move(FloatResult)); 6943 } else { 6944 return Error(E); 6945 } 6946 6947 // Splat and create vector APValue. 6948 SmallVector<APValue, 4> Elts(NElts, Val); 6949 return Success(Elts, E); 6950 } 6951 case CK_BitCast: { 6952 // Evaluate the operand into an APInt we can extract from. 6953 llvm::APInt SValInt; 6954 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 6955 return false; 6956 // Extract the elements 6957 QualType EltTy = VTy->getElementType(); 6958 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 6959 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 6960 SmallVector<APValue, 4> Elts; 6961 if (EltTy->isRealFloatingType()) { 6962 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 6963 unsigned FloatEltSize = EltSize; 6964 if (&Sem == &APFloat::x87DoubleExtended()) 6965 FloatEltSize = 80; 6966 for (unsigned i = 0; i < NElts; i++) { 6967 llvm::APInt Elt; 6968 if (BigEndian) 6969 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 6970 else 6971 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 6972 Elts.push_back(APValue(APFloat(Sem, Elt))); 6973 } 6974 } else if (EltTy->isIntegerType()) { 6975 for (unsigned i = 0; i < NElts; i++) { 6976 llvm::APInt Elt; 6977 if (BigEndian) 6978 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 6979 else 6980 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 6981 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 6982 } 6983 } else { 6984 return Error(E); 6985 } 6986 return Success(Elts, E); 6987 } 6988 default: 6989 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6990 } 6991 } 6992 6993 bool 6994 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6995 const VectorType *VT = E->getType()->castAs<VectorType>(); 6996 unsigned NumInits = E->getNumInits(); 6997 unsigned NumElements = VT->getNumElements(); 6998 6999 QualType EltTy = VT->getElementType(); 7000 SmallVector<APValue, 4> Elements; 7001 7002 // The number of initializers can be less than the number of 7003 // vector elements. For OpenCL, this can be due to nested vector 7004 // initialization. For GCC compatibility, missing trailing elements 7005 // should be initialized with zeroes. 7006 unsigned CountInits = 0, CountElts = 0; 7007 while (CountElts < NumElements) { 7008 // Handle nested vector initialization. 7009 if (CountInits < NumInits 7010 && E->getInit(CountInits)->getType()->isVectorType()) { 7011 APValue v; 7012 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 7013 return Error(E); 7014 unsigned vlen = v.getVectorLength(); 7015 for (unsigned j = 0; j < vlen; j++) 7016 Elements.push_back(v.getVectorElt(j)); 7017 CountElts += vlen; 7018 } else if (EltTy->isIntegerType()) { 7019 llvm::APSInt sInt(32); 7020 if (CountInits < NumInits) { 7021 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 7022 return false; 7023 } else // trailing integer zero. 7024 sInt = Info.Ctx.MakeIntValue(0, EltTy); 7025 Elements.push_back(APValue(sInt)); 7026 CountElts++; 7027 } else { 7028 llvm::APFloat f(0.0); 7029 if (CountInits < NumInits) { 7030 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 7031 return false; 7032 } else // trailing float zero. 7033 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 7034 Elements.push_back(APValue(f)); 7035 CountElts++; 7036 } 7037 CountInits++; 7038 } 7039 return Success(Elements, E); 7040 } 7041 7042 bool 7043 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 7044 const VectorType *VT = E->getType()->getAs<VectorType>(); 7045 QualType EltTy = VT->getElementType(); 7046 APValue ZeroElement; 7047 if (EltTy->isIntegerType()) 7048 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 7049 else 7050 ZeroElement = 7051 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 7052 7053 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 7054 return Success(Elements, E); 7055 } 7056 7057 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 7058 VisitIgnoredValue(E->getSubExpr()); 7059 return ZeroInitialization(E); 7060 } 7061 7062 //===----------------------------------------------------------------------===// 7063 // Array Evaluation 7064 //===----------------------------------------------------------------------===// 7065 7066 namespace { 7067 class ArrayExprEvaluator 7068 : public ExprEvaluatorBase<ArrayExprEvaluator> { 7069 const LValue &This; 7070 APValue &Result; 7071 public: 7072 7073 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 7074 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 7075 7076 bool Success(const APValue &V, const Expr *E) { 7077 assert((V.isArray() || V.isLValue()) && 7078 "expected array or string literal"); 7079 Result = V; 7080 return true; 7081 } 7082 7083 bool ZeroInitialization(const Expr *E) { 7084 const ConstantArrayType *CAT = 7085 Info.Ctx.getAsConstantArrayType(E->getType()); 7086 if (!CAT) 7087 return Error(E); 7088 7089 Result = APValue(APValue::UninitArray(), 0, 7090 CAT->getSize().getZExtValue()); 7091 if (!Result.hasArrayFiller()) return true; 7092 7093 // Zero-initialize all elements. 7094 LValue Subobject = This; 7095 Subobject.addArray(Info, E, CAT); 7096 ImplicitValueInitExpr VIE(CAT->getElementType()); 7097 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 7098 } 7099 7100 bool VisitCallExpr(const CallExpr *E) { 7101 return handleCallExpr(E, Result, &This); 7102 } 7103 bool VisitInitListExpr(const InitListExpr *E); 7104 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 7105 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 7106 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 7107 const LValue &Subobject, 7108 APValue *Value, QualType Type); 7109 }; 7110 } // end anonymous namespace 7111 7112 static bool EvaluateArray(const Expr *E, const LValue &This, 7113 APValue &Result, EvalInfo &Info) { 7114 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 7115 return ArrayExprEvaluator(Info, This, Result).Visit(E); 7116 } 7117 7118 // Return true iff the given array filler may depend on the element index. 7119 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 7120 // For now, just whitelist non-class value-initialization and initialization 7121 // lists comprised of them. 7122 if (isa<ImplicitValueInitExpr>(FillerExpr)) 7123 return false; 7124 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 7125 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 7126 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 7127 return true; 7128 } 7129 return false; 7130 } 7131 return true; 7132 } 7133 7134 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 7135 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 7136 if (!CAT) 7137 return Error(E); 7138 7139 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 7140 // an appropriately-typed string literal enclosed in braces. 7141 if (E->isStringLiteralInit()) { 7142 LValue LV; 7143 if (!EvaluateLValue(E->getInit(0), LV, Info)) 7144 return false; 7145 APValue Val; 7146 LV.moveInto(Val); 7147 return Success(Val, E); 7148 } 7149 7150 bool Success = true; 7151 7152 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 7153 "zero-initialized array shouldn't have any initialized elts"); 7154 APValue Filler; 7155 if (Result.isArray() && Result.hasArrayFiller()) 7156 Filler = Result.getArrayFiller(); 7157 7158 unsigned NumEltsToInit = E->getNumInits(); 7159 unsigned NumElts = CAT->getSize().getZExtValue(); 7160 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 7161 7162 // If the initializer might depend on the array index, run it for each 7163 // array element. 7164 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 7165 NumEltsToInit = NumElts; 7166 7167 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 7168 << NumEltsToInit << ".\n"); 7169 7170 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 7171 7172 // If the array was previously zero-initialized, preserve the 7173 // zero-initialized values. 7174 if (!Filler.isUninit()) { 7175 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 7176 Result.getArrayInitializedElt(I) = Filler; 7177 if (Result.hasArrayFiller()) 7178 Result.getArrayFiller() = Filler; 7179 } 7180 7181 LValue Subobject = This; 7182 Subobject.addArray(Info, E, CAT); 7183 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 7184 const Expr *Init = 7185 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 7186 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 7187 Info, Subobject, Init) || 7188 !HandleLValueArrayAdjustment(Info, Init, Subobject, 7189 CAT->getElementType(), 1)) { 7190 if (!Info.noteFailure()) 7191 return false; 7192 Success = false; 7193 } 7194 } 7195 7196 if (!Result.hasArrayFiller()) 7197 return Success; 7198 7199 // If we get here, we have a trivial filler, which we can just evaluate 7200 // once and splat over the rest of the array elements. 7201 assert(FillerExpr && "no array filler for incomplete init list"); 7202 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 7203 FillerExpr) && Success; 7204 } 7205 7206 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 7207 if (E->getCommonExpr() && 7208 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false), 7209 Info, E->getCommonExpr()->getSourceExpr())) 7210 return false; 7211 7212 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 7213 7214 uint64_t Elements = CAT->getSize().getZExtValue(); 7215 Result = APValue(APValue::UninitArray(), Elements, Elements); 7216 7217 LValue Subobject = This; 7218 Subobject.addArray(Info, E, CAT); 7219 7220 bool Success = true; 7221 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 7222 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 7223 Info, Subobject, E->getSubExpr()) || 7224 !HandleLValueArrayAdjustment(Info, E, Subobject, 7225 CAT->getElementType(), 1)) { 7226 if (!Info.noteFailure()) 7227 return false; 7228 Success = false; 7229 } 7230 } 7231 7232 return Success; 7233 } 7234 7235 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 7236 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 7237 } 7238 7239 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 7240 const LValue &Subobject, 7241 APValue *Value, 7242 QualType Type) { 7243 bool HadZeroInit = !Value->isUninit(); 7244 7245 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 7246 unsigned N = CAT->getSize().getZExtValue(); 7247 7248 // Preserve the array filler if we had prior zero-initialization. 7249 APValue Filler = 7250 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 7251 : APValue(); 7252 7253 *Value = APValue(APValue::UninitArray(), N, N); 7254 7255 if (HadZeroInit) 7256 for (unsigned I = 0; I != N; ++I) 7257 Value->getArrayInitializedElt(I) = Filler; 7258 7259 // Initialize the elements. 7260 LValue ArrayElt = Subobject; 7261 ArrayElt.addArray(Info, E, CAT); 7262 for (unsigned I = 0; I != N; ++I) 7263 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 7264 CAT->getElementType()) || 7265 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 7266 CAT->getElementType(), 1)) 7267 return false; 7268 7269 return true; 7270 } 7271 7272 if (!Type->isRecordType()) 7273 return Error(E); 7274 7275 return RecordExprEvaluator(Info, Subobject, *Value) 7276 .VisitCXXConstructExpr(E, Type); 7277 } 7278 7279 //===----------------------------------------------------------------------===// 7280 // Integer Evaluation 7281 // 7282 // As a GNU extension, we support casting pointers to sufficiently-wide integer 7283 // types and back in constant folding. Integer values are thus represented 7284 // either as an integer-valued APValue, or as an lvalue-valued APValue. 7285 //===----------------------------------------------------------------------===// 7286 7287 namespace { 7288 class IntExprEvaluator 7289 : public ExprEvaluatorBase<IntExprEvaluator> { 7290 APValue &Result; 7291 public: 7292 IntExprEvaluator(EvalInfo &info, APValue &result) 7293 : ExprEvaluatorBaseTy(info), Result(result) {} 7294 7295 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 7296 assert(E->getType()->isIntegralOrEnumerationType() && 7297 "Invalid evaluation result."); 7298 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 7299 "Invalid evaluation result."); 7300 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7301 "Invalid evaluation result."); 7302 Result = APValue(SI); 7303 return true; 7304 } 7305 bool Success(const llvm::APSInt &SI, const Expr *E) { 7306 return Success(SI, E, Result); 7307 } 7308 7309 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 7310 assert(E->getType()->isIntegralOrEnumerationType() && 7311 "Invalid evaluation result."); 7312 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7313 "Invalid evaluation result."); 7314 Result = APValue(APSInt(I)); 7315 Result.getInt().setIsUnsigned( 7316 E->getType()->isUnsignedIntegerOrEnumerationType()); 7317 return true; 7318 } 7319 bool Success(const llvm::APInt &I, const Expr *E) { 7320 return Success(I, E, Result); 7321 } 7322 7323 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 7324 assert(E->getType()->isIntegralOrEnumerationType() && 7325 "Invalid evaluation result."); 7326 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 7327 return true; 7328 } 7329 bool Success(uint64_t Value, const Expr *E) { 7330 return Success(Value, E, Result); 7331 } 7332 7333 bool Success(CharUnits Size, const Expr *E) { 7334 return Success(Size.getQuantity(), E); 7335 } 7336 7337 bool Success(const APValue &V, const Expr *E) { 7338 if (V.isLValue() || V.isAddrLabelDiff()) { 7339 Result = V; 7340 return true; 7341 } 7342 return Success(V.getInt(), E); 7343 } 7344 7345 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 7346 7347 //===--------------------------------------------------------------------===// 7348 // Visitor Methods 7349 //===--------------------------------------------------------------------===// 7350 7351 bool VisitIntegerLiteral(const IntegerLiteral *E) { 7352 return Success(E->getValue(), E); 7353 } 7354 bool VisitCharacterLiteral(const CharacterLiteral *E) { 7355 return Success(E->getValue(), E); 7356 } 7357 7358 bool CheckReferencedDecl(const Expr *E, const Decl *D); 7359 bool VisitDeclRefExpr(const DeclRefExpr *E) { 7360 if (CheckReferencedDecl(E, E->getDecl())) 7361 return true; 7362 7363 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 7364 } 7365 bool VisitMemberExpr(const MemberExpr *E) { 7366 if (CheckReferencedDecl(E, E->getMemberDecl())) { 7367 VisitIgnoredBaseExpression(E->getBase()); 7368 return true; 7369 } 7370 7371 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 7372 } 7373 7374 bool VisitCallExpr(const CallExpr *E); 7375 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 7376 bool VisitBinaryOperator(const BinaryOperator *E); 7377 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 7378 bool VisitUnaryOperator(const UnaryOperator *E); 7379 7380 bool VisitCastExpr(const CastExpr* E); 7381 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 7382 7383 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 7384 return Success(E->getValue(), E); 7385 } 7386 7387 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 7388 return Success(E->getValue(), E); 7389 } 7390 7391 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 7392 if (Info.ArrayInitIndex == uint64_t(-1)) { 7393 // We were asked to evaluate this subexpression independent of the 7394 // enclosing ArrayInitLoopExpr. We can't do that. 7395 Info.FFDiag(E); 7396 return false; 7397 } 7398 return Success(Info.ArrayInitIndex, E); 7399 } 7400 7401 // Note, GNU defines __null as an integer, not a pointer. 7402 bool VisitGNUNullExpr(const GNUNullExpr *E) { 7403 return ZeroInitialization(E); 7404 } 7405 7406 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 7407 return Success(E->getValue(), E); 7408 } 7409 7410 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 7411 return Success(E->getValue(), E); 7412 } 7413 7414 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 7415 return Success(E->getValue(), E); 7416 } 7417 7418 bool VisitUnaryReal(const UnaryOperator *E); 7419 bool VisitUnaryImag(const UnaryOperator *E); 7420 7421 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 7422 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 7423 7424 // FIXME: Missing: array subscript of vector, member of vector 7425 }; 7426 7427 class FixedPointExprEvaluator 7428 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 7429 APValue &Result; 7430 7431 public: 7432 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 7433 : ExprEvaluatorBaseTy(info), Result(result) {} 7434 7435 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 7436 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 7437 assert(SI.isSigned() == E->getType()->isSignedFixedPointType() && 7438 "Invalid evaluation result."); 7439 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7440 "Invalid evaluation result."); 7441 Result = APValue(SI); 7442 return true; 7443 } 7444 bool Success(const llvm::APSInt &SI, const Expr *E) { 7445 return Success(SI, E, Result); 7446 } 7447 7448 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 7449 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 7450 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7451 "Invalid evaluation result."); 7452 Result = APValue(APSInt(I)); 7453 Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType()); 7454 return true; 7455 } 7456 bool Success(const llvm::APInt &I, const Expr *E) { 7457 return Success(I, E, Result); 7458 } 7459 7460 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 7461 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 7462 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 7463 return true; 7464 } 7465 bool Success(uint64_t Value, const Expr *E) { 7466 return Success(Value, E, Result); 7467 } 7468 7469 bool Success(CharUnits Size, const Expr *E) { 7470 return Success(Size.getQuantity(), E); 7471 } 7472 7473 bool Success(const APValue &V, const Expr *E) { 7474 if (V.isLValue() || V.isAddrLabelDiff()) { 7475 Result = V; 7476 return true; 7477 } 7478 return Success(V.getInt(), E); 7479 } 7480 7481 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 7482 7483 //===--------------------------------------------------------------------===// 7484 // Visitor Methods 7485 //===--------------------------------------------------------------------===// 7486 7487 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 7488 return Success(E->getValue(), E); 7489 } 7490 7491 bool VisitUnaryOperator(const UnaryOperator *E); 7492 }; 7493 } // end anonymous namespace 7494 7495 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 7496 /// produce either the integer value or a pointer. 7497 /// 7498 /// GCC has a heinous extension which folds casts between pointer types and 7499 /// pointer-sized integral types. We support this by allowing the evaluation of 7500 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 7501 /// Some simple arithmetic on such values is supported (they are treated much 7502 /// like char*). 7503 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 7504 EvalInfo &Info) { 7505 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 7506 return IntExprEvaluator(Info, Result).Visit(E); 7507 } 7508 7509 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 7510 APValue Val; 7511 if (!EvaluateIntegerOrLValue(E, Val, Info)) 7512 return false; 7513 if (!Val.isInt()) { 7514 // FIXME: It would be better to produce the diagnostic for casting 7515 // a pointer to an integer. 7516 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 7517 return false; 7518 } 7519 Result = Val.getInt(); 7520 return true; 7521 } 7522 7523 /// Check whether the given declaration can be directly converted to an integral 7524 /// rvalue. If not, no diagnostic is produced; there are other things we can 7525 /// try. 7526 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 7527 // Enums are integer constant exprs. 7528 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 7529 // Check for signedness/width mismatches between E type and ECD value. 7530 bool SameSign = (ECD->getInitVal().isSigned() 7531 == E->getType()->isSignedIntegerOrEnumerationType()); 7532 bool SameWidth = (ECD->getInitVal().getBitWidth() 7533 == Info.Ctx.getIntWidth(E->getType())); 7534 if (SameSign && SameWidth) 7535 return Success(ECD->getInitVal(), E); 7536 else { 7537 // Get rid of mismatch (otherwise Success assertions will fail) 7538 // by computing a new value matching the type of E. 7539 llvm::APSInt Val = ECD->getInitVal(); 7540 if (!SameSign) 7541 Val.setIsSigned(!ECD->getInitVal().isSigned()); 7542 if (!SameWidth) 7543 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 7544 return Success(Val, E); 7545 } 7546 } 7547 return false; 7548 } 7549 7550 /// Values returned by __builtin_classify_type, chosen to match the values 7551 /// produced by GCC's builtin. 7552 enum class GCCTypeClass { 7553 None = -1, 7554 Void = 0, 7555 Integer = 1, 7556 // GCC reserves 2 for character types, but instead classifies them as 7557 // integers. 7558 Enum = 3, 7559 Bool = 4, 7560 Pointer = 5, 7561 // GCC reserves 6 for references, but appears to never use it (because 7562 // expressions never have reference type, presumably). 7563 PointerToDataMember = 7, 7564 RealFloat = 8, 7565 Complex = 9, 7566 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 7567 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 7568 // GCC claims to reserve 11 for pointers to member functions, but *actually* 7569 // uses 12 for that purpose, same as for a class or struct. Maybe it 7570 // internally implements a pointer to member as a struct? Who knows. 7571 PointerToMemberFunction = 12, // Not a bug, see above. 7572 ClassOrStruct = 12, 7573 Union = 13, 7574 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 7575 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 7576 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 7577 // literals. 7578 }; 7579 7580 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 7581 /// as GCC. 7582 static GCCTypeClass 7583 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 7584 assert(!T->isDependentType() && "unexpected dependent type"); 7585 7586 QualType CanTy = T.getCanonicalType(); 7587 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 7588 7589 switch (CanTy->getTypeClass()) { 7590 #define TYPE(ID, BASE) 7591 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 7592 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 7593 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 7594 #include "clang/AST/TypeNodes.def" 7595 case Type::Auto: 7596 case Type::DeducedTemplateSpecialization: 7597 llvm_unreachable("unexpected non-canonical or dependent type"); 7598 7599 case Type::Builtin: 7600 switch (BT->getKind()) { 7601 #define BUILTIN_TYPE(ID, SINGLETON_ID) 7602 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 7603 case BuiltinType::ID: return GCCTypeClass::Integer; 7604 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 7605 case BuiltinType::ID: return GCCTypeClass::RealFloat; 7606 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 7607 case BuiltinType::ID: break; 7608 #include "clang/AST/BuiltinTypes.def" 7609 case BuiltinType::Void: 7610 return GCCTypeClass::Void; 7611 7612 case BuiltinType::Bool: 7613 return GCCTypeClass::Bool; 7614 7615 case BuiltinType::Char_U: 7616 case BuiltinType::UChar: 7617 case BuiltinType::WChar_U: 7618 case BuiltinType::Char8: 7619 case BuiltinType::Char16: 7620 case BuiltinType::Char32: 7621 case BuiltinType::UShort: 7622 case BuiltinType::UInt: 7623 case BuiltinType::ULong: 7624 case BuiltinType::ULongLong: 7625 case BuiltinType::UInt128: 7626 return GCCTypeClass::Integer; 7627 7628 case BuiltinType::UShortAccum: 7629 case BuiltinType::UAccum: 7630 case BuiltinType::ULongAccum: 7631 case BuiltinType::UShortFract: 7632 case BuiltinType::UFract: 7633 case BuiltinType::ULongFract: 7634 case BuiltinType::SatUShortAccum: 7635 case BuiltinType::SatUAccum: 7636 case BuiltinType::SatULongAccum: 7637 case BuiltinType::SatUShortFract: 7638 case BuiltinType::SatUFract: 7639 case BuiltinType::SatULongFract: 7640 return GCCTypeClass::None; 7641 7642 case BuiltinType::NullPtr: 7643 7644 case BuiltinType::ObjCId: 7645 case BuiltinType::ObjCClass: 7646 case BuiltinType::ObjCSel: 7647 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7648 case BuiltinType::Id: 7649 #include "clang/Basic/OpenCLImageTypes.def" 7650 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 7651 case BuiltinType::Id: 7652 #include "clang/Basic/OpenCLExtensionTypes.def" 7653 case BuiltinType::OCLSampler: 7654 case BuiltinType::OCLEvent: 7655 case BuiltinType::OCLClkEvent: 7656 case BuiltinType::OCLQueue: 7657 case BuiltinType::OCLReserveID: 7658 return GCCTypeClass::None; 7659 7660 case BuiltinType::Dependent: 7661 llvm_unreachable("unexpected dependent type"); 7662 }; 7663 llvm_unreachable("unexpected placeholder type"); 7664 7665 case Type::Enum: 7666 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 7667 7668 case Type::Pointer: 7669 case Type::ConstantArray: 7670 case Type::VariableArray: 7671 case Type::IncompleteArray: 7672 case Type::FunctionNoProto: 7673 case Type::FunctionProto: 7674 return GCCTypeClass::Pointer; 7675 7676 case Type::MemberPointer: 7677 return CanTy->isMemberDataPointerType() 7678 ? GCCTypeClass::PointerToDataMember 7679 : GCCTypeClass::PointerToMemberFunction; 7680 7681 case Type::Complex: 7682 return GCCTypeClass::Complex; 7683 7684 case Type::Record: 7685 return CanTy->isUnionType() ? GCCTypeClass::Union 7686 : GCCTypeClass::ClassOrStruct; 7687 7688 case Type::Atomic: 7689 // GCC classifies _Atomic T the same as T. 7690 return EvaluateBuiltinClassifyType( 7691 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 7692 7693 case Type::BlockPointer: 7694 case Type::Vector: 7695 case Type::ExtVector: 7696 case Type::ObjCObject: 7697 case Type::ObjCInterface: 7698 case Type::ObjCObjectPointer: 7699 case Type::Pipe: 7700 // GCC classifies vectors as None. We follow its lead and classify all 7701 // other types that don't fit into the regular classification the same way. 7702 return GCCTypeClass::None; 7703 7704 case Type::LValueReference: 7705 case Type::RValueReference: 7706 llvm_unreachable("invalid type for expression"); 7707 } 7708 7709 llvm_unreachable("unexpected type class"); 7710 } 7711 7712 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 7713 /// as GCC. 7714 static GCCTypeClass 7715 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 7716 // If no argument was supplied, default to None. This isn't 7717 // ideal, however it is what gcc does. 7718 if (E->getNumArgs() == 0) 7719 return GCCTypeClass::None; 7720 7721 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 7722 // being an ICE, but still folds it to a constant using the type of the first 7723 // argument. 7724 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 7725 } 7726 7727 /// EvaluateBuiltinConstantPForLValue - Determine the result of 7728 /// __builtin_constant_p when applied to the given lvalue. 7729 /// 7730 /// An lvalue is only "constant" if it is a pointer or reference to the first 7731 /// character of a string literal. 7732 template<typename LValue> 7733 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) { 7734 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>(); 7735 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero(); 7736 } 7737 7738 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 7739 /// GCC as we can manage. 7740 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) { 7741 QualType ArgType = Arg->getType(); 7742 7743 // __builtin_constant_p always has one operand. The rules which gcc follows 7744 // are not precisely documented, but are as follows: 7745 // 7746 // - If the operand is of integral, floating, complex or enumeration type, 7747 // and can be folded to a known value of that type, it returns 1. 7748 // - If the operand and can be folded to a pointer to the first character 7749 // of a string literal (or such a pointer cast to an integral type), it 7750 // returns 1. 7751 // 7752 // Otherwise, it returns 0. 7753 // 7754 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 7755 // its support for this does not currently work. 7756 if (ArgType->isIntegralOrEnumerationType()) { 7757 Expr::EvalResult Result; 7758 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects) 7759 return false; 7760 7761 APValue &V = Result.Val; 7762 if (V.getKind() == APValue::Int) 7763 return true; 7764 if (V.getKind() == APValue::LValue) 7765 return EvaluateBuiltinConstantPForLValue(V); 7766 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) { 7767 return Arg->isEvaluatable(Ctx); 7768 } else if (ArgType->isPointerType() || Arg->isGLValue()) { 7769 LValue LV; 7770 Expr::EvalStatus Status; 7771 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 7772 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info) 7773 : EvaluatePointer(Arg, LV, Info)) && 7774 !Status.HasSideEffects) 7775 return EvaluateBuiltinConstantPForLValue(LV); 7776 } 7777 7778 // Anything else isn't considered to be sufficiently constant. 7779 return false; 7780 } 7781 7782 /// Retrieves the "underlying object type" of the given expression, 7783 /// as used by __builtin_object_size. 7784 static QualType getObjectType(APValue::LValueBase B) { 7785 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 7786 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 7787 return VD->getType(); 7788 } else if (const Expr *E = B.get<const Expr*>()) { 7789 if (isa<CompoundLiteralExpr>(E)) 7790 return E->getType(); 7791 } 7792 7793 return QualType(); 7794 } 7795 7796 /// A more selective version of E->IgnoreParenCasts for 7797 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 7798 /// to change the type of E. 7799 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 7800 /// 7801 /// Always returns an RValue with a pointer representation. 7802 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 7803 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 7804 7805 auto *NoParens = E->IgnoreParens(); 7806 auto *Cast = dyn_cast<CastExpr>(NoParens); 7807 if (Cast == nullptr) 7808 return NoParens; 7809 7810 // We only conservatively allow a few kinds of casts, because this code is 7811 // inherently a simple solution that seeks to support the common case. 7812 auto CastKind = Cast->getCastKind(); 7813 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 7814 CastKind != CK_AddressSpaceConversion) 7815 return NoParens; 7816 7817 auto *SubExpr = Cast->getSubExpr(); 7818 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 7819 return NoParens; 7820 return ignorePointerCastsAndParens(SubExpr); 7821 } 7822 7823 /// Checks to see if the given LValue's Designator is at the end of the LValue's 7824 /// record layout. e.g. 7825 /// struct { struct { int a, b; } fst, snd; } obj; 7826 /// obj.fst // no 7827 /// obj.snd // yes 7828 /// obj.fst.a // no 7829 /// obj.fst.b // no 7830 /// obj.snd.a // no 7831 /// obj.snd.b // yes 7832 /// 7833 /// Please note: this function is specialized for how __builtin_object_size 7834 /// views "objects". 7835 /// 7836 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 7837 /// correct result, it will always return true. 7838 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 7839 assert(!LVal.Designator.Invalid); 7840 7841 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 7842 const RecordDecl *Parent = FD->getParent(); 7843 Invalid = Parent->isInvalidDecl(); 7844 if (Invalid || Parent->isUnion()) 7845 return true; 7846 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 7847 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 7848 }; 7849 7850 auto &Base = LVal.getLValueBase(); 7851 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 7852 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 7853 bool Invalid; 7854 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 7855 return Invalid; 7856 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 7857 for (auto *FD : IFD->chain()) { 7858 bool Invalid; 7859 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 7860 return Invalid; 7861 } 7862 } 7863 } 7864 7865 unsigned I = 0; 7866 QualType BaseType = getType(Base); 7867 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 7868 // If we don't know the array bound, conservatively assume we're looking at 7869 // the final array element. 7870 ++I; 7871 if (BaseType->isIncompleteArrayType()) 7872 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 7873 else 7874 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 7875 } 7876 7877 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 7878 const auto &Entry = LVal.Designator.Entries[I]; 7879 if (BaseType->isArrayType()) { 7880 // Because __builtin_object_size treats arrays as objects, we can ignore 7881 // the index iff this is the last array in the Designator. 7882 if (I + 1 == E) 7883 return true; 7884 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 7885 uint64_t Index = Entry.ArrayIndex; 7886 if (Index + 1 != CAT->getSize()) 7887 return false; 7888 BaseType = CAT->getElementType(); 7889 } else if (BaseType->isAnyComplexType()) { 7890 const auto *CT = BaseType->castAs<ComplexType>(); 7891 uint64_t Index = Entry.ArrayIndex; 7892 if (Index != 1) 7893 return false; 7894 BaseType = CT->getElementType(); 7895 } else if (auto *FD = getAsField(Entry)) { 7896 bool Invalid; 7897 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 7898 return Invalid; 7899 BaseType = FD->getType(); 7900 } else { 7901 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 7902 return false; 7903 } 7904 } 7905 return true; 7906 } 7907 7908 /// Tests to see if the LValue has a user-specified designator (that isn't 7909 /// necessarily valid). Note that this always returns 'true' if the LValue has 7910 /// an unsized array as its first designator entry, because there's currently no 7911 /// way to tell if the user typed *foo or foo[0]. 7912 static bool refersToCompleteObject(const LValue &LVal) { 7913 if (LVal.Designator.Invalid) 7914 return false; 7915 7916 if (!LVal.Designator.Entries.empty()) 7917 return LVal.Designator.isMostDerivedAnUnsizedArray(); 7918 7919 if (!LVal.InvalidBase) 7920 return true; 7921 7922 // If `E` is a MemberExpr, then the first part of the designator is hiding in 7923 // the LValueBase. 7924 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 7925 return !E || !isa<MemberExpr>(E); 7926 } 7927 7928 /// Attempts to detect a user writing into a piece of memory that's impossible 7929 /// to figure out the size of by just using types. 7930 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 7931 const SubobjectDesignator &Designator = LVal.Designator; 7932 // Notes: 7933 // - Users can only write off of the end when we have an invalid base. Invalid 7934 // bases imply we don't know where the memory came from. 7935 // - We used to be a bit more aggressive here; we'd only be conservative if 7936 // the array at the end was flexible, or if it had 0 or 1 elements. This 7937 // broke some common standard library extensions (PR30346), but was 7938 // otherwise seemingly fine. It may be useful to reintroduce this behavior 7939 // with some sort of whitelist. OTOH, it seems that GCC is always 7940 // conservative with the last element in structs (if it's an array), so our 7941 // current behavior is more compatible than a whitelisting approach would 7942 // be. 7943 return LVal.InvalidBase && 7944 Designator.Entries.size() == Designator.MostDerivedPathLength && 7945 Designator.MostDerivedIsArrayElement && 7946 isDesignatorAtObjectEnd(Ctx, LVal); 7947 } 7948 7949 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 7950 /// Fails if the conversion would cause loss of precision. 7951 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 7952 CharUnits &Result) { 7953 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 7954 if (Int.ugt(CharUnitsMax)) 7955 return false; 7956 Result = CharUnits::fromQuantity(Int.getZExtValue()); 7957 return true; 7958 } 7959 7960 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 7961 /// determine how many bytes exist from the beginning of the object to either 7962 /// the end of the current subobject, or the end of the object itself, depending 7963 /// on what the LValue looks like + the value of Type. 7964 /// 7965 /// If this returns false, the value of Result is undefined. 7966 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 7967 unsigned Type, const LValue &LVal, 7968 CharUnits &EndOffset) { 7969 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 7970 7971 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 7972 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 7973 return false; 7974 return HandleSizeof(Info, ExprLoc, Ty, Result); 7975 }; 7976 7977 // We want to evaluate the size of the entire object. This is a valid fallback 7978 // for when Type=1 and the designator is invalid, because we're asked for an 7979 // upper-bound. 7980 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 7981 // Type=3 wants a lower bound, so we can't fall back to this. 7982 if (Type == 3 && !DetermineForCompleteObject) 7983 return false; 7984 7985 llvm::APInt APEndOffset; 7986 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 7987 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 7988 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 7989 7990 if (LVal.InvalidBase) 7991 return false; 7992 7993 QualType BaseTy = getObjectType(LVal.getLValueBase()); 7994 return CheckedHandleSizeof(BaseTy, EndOffset); 7995 } 7996 7997 // We want to evaluate the size of a subobject. 7998 const SubobjectDesignator &Designator = LVal.Designator; 7999 8000 // The following is a moderately common idiom in C: 8001 // 8002 // struct Foo { int a; char c[1]; }; 8003 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 8004 // strcpy(&F->c[0], Bar); 8005 // 8006 // In order to not break too much legacy code, we need to support it. 8007 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 8008 // If we can resolve this to an alloc_size call, we can hand that back, 8009 // because we know for certain how many bytes there are to write to. 8010 llvm::APInt APEndOffset; 8011 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8012 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 8013 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 8014 8015 // If we cannot determine the size of the initial allocation, then we can't 8016 // given an accurate upper-bound. However, we are still able to give 8017 // conservative lower-bounds for Type=3. 8018 if (Type == 1) 8019 return false; 8020 } 8021 8022 CharUnits BytesPerElem; 8023 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 8024 return false; 8025 8026 // According to the GCC documentation, we want the size of the subobject 8027 // denoted by the pointer. But that's not quite right -- what we actually 8028 // want is the size of the immediately-enclosing array, if there is one. 8029 int64_t ElemsRemaining; 8030 if (Designator.MostDerivedIsArrayElement && 8031 Designator.Entries.size() == Designator.MostDerivedPathLength) { 8032 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 8033 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex; 8034 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 8035 } else { 8036 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 8037 } 8038 8039 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 8040 return true; 8041 } 8042 8043 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 8044 /// returns true and stores the result in @p Size. 8045 /// 8046 /// If @p WasError is non-null, this will report whether the failure to evaluate 8047 /// is to be treated as an Error in IntExprEvaluator. 8048 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 8049 EvalInfo &Info, uint64_t &Size) { 8050 // Determine the denoted object. 8051 LValue LVal; 8052 { 8053 // The operand of __builtin_object_size is never evaluated for side-effects. 8054 // If there are any, but we can determine the pointed-to object anyway, then 8055 // ignore the side-effects. 8056 SpeculativeEvaluationRAII SpeculativeEval(Info); 8057 IgnoreSideEffectsRAII Fold(Info); 8058 8059 if (E->isGLValue()) { 8060 // It's possible for us to be given GLValues if we're called via 8061 // Expr::tryEvaluateObjectSize. 8062 APValue RVal; 8063 if (!EvaluateAsRValue(Info, E, RVal)) 8064 return false; 8065 LVal.setFrom(Info.Ctx, RVal); 8066 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 8067 /*InvalidBaseOK=*/true)) 8068 return false; 8069 } 8070 8071 // If we point to before the start of the object, there are no accessible 8072 // bytes. 8073 if (LVal.getLValueOffset().isNegative()) { 8074 Size = 0; 8075 return true; 8076 } 8077 8078 CharUnits EndOffset; 8079 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 8080 return false; 8081 8082 // If we've fallen outside of the end offset, just pretend there's nothing to 8083 // write to/read from. 8084 if (EndOffset <= LVal.getLValueOffset()) 8085 Size = 0; 8086 else 8087 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 8088 return true; 8089 } 8090 8091 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 8092 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8093 return VisitBuiltinCallExpr(E, BuiltinOp); 8094 8095 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8096 } 8097 8098 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8099 unsigned BuiltinOp) { 8100 switch (unsigned BuiltinOp = E->getBuiltinCallee()) { 8101 default: 8102 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8103 8104 case Builtin::BI__builtin_object_size: { 8105 // The type was checked when we built the expression. 8106 unsigned Type = 8107 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 8108 assert(Type <= 3 && "unexpected type"); 8109 8110 uint64_t Size; 8111 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 8112 return Success(Size, E); 8113 8114 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 8115 return Success((Type & 2) ? 0 : -1, E); 8116 8117 // Expression had no side effects, but we couldn't statically determine the 8118 // size of the referenced object. 8119 switch (Info.EvalMode) { 8120 case EvalInfo::EM_ConstantExpression: 8121 case EvalInfo::EM_PotentialConstantExpression: 8122 case EvalInfo::EM_ConstantFold: 8123 case EvalInfo::EM_EvaluateForOverflow: 8124 case EvalInfo::EM_IgnoreSideEffects: 8125 // Leave it to IR generation. 8126 return Error(E); 8127 case EvalInfo::EM_ConstantExpressionUnevaluated: 8128 case EvalInfo::EM_PotentialConstantExpressionUnevaluated: 8129 // Reduce it to a constant now. 8130 return Success((Type & 2) ? 0 : -1, E); 8131 } 8132 8133 llvm_unreachable("unexpected EvalMode"); 8134 } 8135 8136 case Builtin::BI__builtin_os_log_format_buffer_size: { 8137 analyze_os_log::OSLogBufferLayout Layout; 8138 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 8139 return Success(Layout.size().getQuantity(), E); 8140 } 8141 8142 case Builtin::BI__builtin_bswap16: 8143 case Builtin::BI__builtin_bswap32: 8144 case Builtin::BI__builtin_bswap64: { 8145 APSInt Val; 8146 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8147 return false; 8148 8149 return Success(Val.byteSwap(), E); 8150 } 8151 8152 case Builtin::BI__builtin_classify_type: 8153 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 8154 8155 case Builtin::BI__builtin_clrsb: 8156 case Builtin::BI__builtin_clrsbl: 8157 case Builtin::BI__builtin_clrsbll: { 8158 APSInt Val; 8159 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8160 return false; 8161 8162 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 8163 } 8164 8165 case Builtin::BI__builtin_clz: 8166 case Builtin::BI__builtin_clzl: 8167 case Builtin::BI__builtin_clzll: 8168 case Builtin::BI__builtin_clzs: { 8169 APSInt Val; 8170 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8171 return false; 8172 if (!Val) 8173 return Error(E); 8174 8175 return Success(Val.countLeadingZeros(), E); 8176 } 8177 8178 case Builtin::BI__builtin_constant_p: 8179 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E); 8180 8181 case Builtin::BI__builtin_ctz: 8182 case Builtin::BI__builtin_ctzl: 8183 case Builtin::BI__builtin_ctzll: 8184 case Builtin::BI__builtin_ctzs: { 8185 APSInt Val; 8186 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8187 return false; 8188 if (!Val) 8189 return Error(E); 8190 8191 return Success(Val.countTrailingZeros(), E); 8192 } 8193 8194 case Builtin::BI__builtin_eh_return_data_regno: { 8195 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 8196 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 8197 return Success(Operand, E); 8198 } 8199 8200 case Builtin::BI__builtin_expect: 8201 return Visit(E->getArg(0)); 8202 8203 case Builtin::BI__builtin_ffs: 8204 case Builtin::BI__builtin_ffsl: 8205 case Builtin::BI__builtin_ffsll: { 8206 APSInt Val; 8207 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8208 return false; 8209 8210 unsigned N = Val.countTrailingZeros(); 8211 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 8212 } 8213 8214 case Builtin::BI__builtin_fpclassify: { 8215 APFloat Val(0.0); 8216 if (!EvaluateFloat(E->getArg(5), Val, Info)) 8217 return false; 8218 unsigned Arg; 8219 switch (Val.getCategory()) { 8220 case APFloat::fcNaN: Arg = 0; break; 8221 case APFloat::fcInfinity: Arg = 1; break; 8222 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 8223 case APFloat::fcZero: Arg = 4; break; 8224 } 8225 return Visit(E->getArg(Arg)); 8226 } 8227 8228 case Builtin::BI__builtin_isinf_sign: { 8229 APFloat Val(0.0); 8230 return EvaluateFloat(E->getArg(0), Val, Info) && 8231 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 8232 } 8233 8234 case Builtin::BI__builtin_isinf: { 8235 APFloat Val(0.0); 8236 return EvaluateFloat(E->getArg(0), Val, Info) && 8237 Success(Val.isInfinity() ? 1 : 0, E); 8238 } 8239 8240 case Builtin::BI__builtin_isfinite: { 8241 APFloat Val(0.0); 8242 return EvaluateFloat(E->getArg(0), Val, Info) && 8243 Success(Val.isFinite() ? 1 : 0, E); 8244 } 8245 8246 case Builtin::BI__builtin_isnan: { 8247 APFloat Val(0.0); 8248 return EvaluateFloat(E->getArg(0), Val, Info) && 8249 Success(Val.isNaN() ? 1 : 0, E); 8250 } 8251 8252 case Builtin::BI__builtin_isnormal: { 8253 APFloat Val(0.0); 8254 return EvaluateFloat(E->getArg(0), Val, Info) && 8255 Success(Val.isNormal() ? 1 : 0, E); 8256 } 8257 8258 case Builtin::BI__builtin_parity: 8259 case Builtin::BI__builtin_parityl: 8260 case Builtin::BI__builtin_parityll: { 8261 APSInt Val; 8262 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8263 return false; 8264 8265 return Success(Val.countPopulation() % 2, E); 8266 } 8267 8268 case Builtin::BI__builtin_popcount: 8269 case Builtin::BI__builtin_popcountl: 8270 case Builtin::BI__builtin_popcountll: { 8271 APSInt Val; 8272 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8273 return false; 8274 8275 return Success(Val.countPopulation(), E); 8276 } 8277 8278 case Builtin::BIstrlen: 8279 case Builtin::BIwcslen: 8280 // A call to strlen is not a constant expression. 8281 if (Info.getLangOpts().CPlusPlus11) 8282 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8283 << /*isConstexpr*/0 << /*isConstructor*/0 8284 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8285 else 8286 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8287 LLVM_FALLTHROUGH; 8288 case Builtin::BI__builtin_strlen: 8289 case Builtin::BI__builtin_wcslen: { 8290 // As an extension, we support __builtin_strlen() as a constant expression, 8291 // and support folding strlen() to a constant. 8292 LValue String; 8293 if (!EvaluatePointer(E->getArg(0), String, Info)) 8294 return false; 8295 8296 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 8297 8298 // Fast path: if it's a string literal, search the string value. 8299 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 8300 String.getLValueBase().dyn_cast<const Expr *>())) { 8301 // The string literal may have embedded null characters. Find the first 8302 // one and truncate there. 8303 StringRef Str = S->getBytes(); 8304 int64_t Off = String.Offset.getQuantity(); 8305 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 8306 S->getCharByteWidth() == 1 && 8307 // FIXME: Add fast-path for wchar_t too. 8308 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 8309 Str = Str.substr(Off); 8310 8311 StringRef::size_type Pos = Str.find(0); 8312 if (Pos != StringRef::npos) 8313 Str = Str.substr(0, Pos); 8314 8315 return Success(Str.size(), E); 8316 } 8317 8318 // Fall through to slow path to issue appropriate diagnostic. 8319 } 8320 8321 // Slow path: scan the bytes of the string looking for the terminating 0. 8322 for (uint64_t Strlen = 0; /**/; ++Strlen) { 8323 APValue Char; 8324 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 8325 !Char.isInt()) 8326 return false; 8327 if (!Char.getInt()) 8328 return Success(Strlen, E); 8329 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 8330 return false; 8331 } 8332 } 8333 8334 case Builtin::BIstrcmp: 8335 case Builtin::BIwcscmp: 8336 case Builtin::BIstrncmp: 8337 case Builtin::BIwcsncmp: 8338 case Builtin::BImemcmp: 8339 case Builtin::BIwmemcmp: 8340 // A call to strlen is not a constant expression. 8341 if (Info.getLangOpts().CPlusPlus11) 8342 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8343 << /*isConstexpr*/0 << /*isConstructor*/0 8344 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8345 else 8346 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8347 LLVM_FALLTHROUGH; 8348 case Builtin::BI__builtin_strcmp: 8349 case Builtin::BI__builtin_wcscmp: 8350 case Builtin::BI__builtin_strncmp: 8351 case Builtin::BI__builtin_wcsncmp: 8352 case Builtin::BI__builtin_memcmp: 8353 case Builtin::BI__builtin_wmemcmp: { 8354 LValue String1, String2; 8355 if (!EvaluatePointer(E->getArg(0), String1, Info) || 8356 !EvaluatePointer(E->getArg(1), String2, Info)) 8357 return false; 8358 8359 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 8360 8361 uint64_t MaxLength = uint64_t(-1); 8362 if (BuiltinOp != Builtin::BIstrcmp && 8363 BuiltinOp != Builtin::BIwcscmp && 8364 BuiltinOp != Builtin::BI__builtin_strcmp && 8365 BuiltinOp != Builtin::BI__builtin_wcscmp) { 8366 APSInt N; 8367 if (!EvaluateInteger(E->getArg(2), N, Info)) 8368 return false; 8369 MaxLength = N.getExtValue(); 8370 } 8371 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp && 8372 BuiltinOp != Builtin::BIwmemcmp && 8373 BuiltinOp != Builtin::BI__builtin_memcmp && 8374 BuiltinOp != Builtin::BI__builtin_wmemcmp); 8375 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 8376 BuiltinOp == Builtin::BIwcsncmp || 8377 BuiltinOp == Builtin::BIwmemcmp || 8378 BuiltinOp == Builtin::BI__builtin_wcscmp || 8379 BuiltinOp == Builtin::BI__builtin_wcsncmp || 8380 BuiltinOp == Builtin::BI__builtin_wmemcmp; 8381 for (; MaxLength; --MaxLength) { 8382 APValue Char1, Char2; 8383 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) || 8384 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) || 8385 !Char1.isInt() || !Char2.isInt()) 8386 return false; 8387 if (Char1.getInt() != Char2.getInt()) { 8388 if (IsWide) // wmemcmp compares with wchar_t signedness. 8389 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 8390 // memcmp always compares unsigned chars. 8391 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 8392 } 8393 if (StopAtNull && !Char1.getInt()) 8394 return Success(0, E); 8395 assert(!(StopAtNull && !Char2.getInt())); 8396 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) || 8397 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1)) 8398 return false; 8399 } 8400 // We hit the strncmp / memcmp limit. 8401 return Success(0, E); 8402 } 8403 8404 case Builtin::BI__atomic_always_lock_free: 8405 case Builtin::BI__atomic_is_lock_free: 8406 case Builtin::BI__c11_atomic_is_lock_free: { 8407 APSInt SizeVal; 8408 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 8409 return false; 8410 8411 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 8412 // of two less than the maximum inline atomic width, we know it is 8413 // lock-free. If the size isn't a power of two, or greater than the 8414 // maximum alignment where we promote atomics, we know it is not lock-free 8415 // (at least not in the sense of atomic_is_lock_free). Otherwise, 8416 // the answer can only be determined at runtime; for example, 16-byte 8417 // atomics have lock-free implementations on some, but not all, 8418 // x86-64 processors. 8419 8420 // Check power-of-two. 8421 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 8422 if (Size.isPowerOfTwo()) { 8423 // Check against inlining width. 8424 unsigned InlineWidthBits = 8425 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 8426 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 8427 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 8428 Size == CharUnits::One() || 8429 E->getArg(1)->isNullPointerConstant(Info.Ctx, 8430 Expr::NPC_NeverValueDependent)) 8431 // OK, we will inline appropriately-aligned operations of this size, 8432 // and _Atomic(T) is appropriately-aligned. 8433 return Success(1, E); 8434 8435 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 8436 castAs<PointerType>()->getPointeeType(); 8437 if (!PointeeType->isIncompleteType() && 8438 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 8439 // OK, we will inline operations on this object. 8440 return Success(1, E); 8441 } 8442 } 8443 } 8444 8445 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 8446 Success(0, E) : Error(E); 8447 } 8448 case Builtin::BIomp_is_initial_device: 8449 // We can decide statically which value the runtime would return if called. 8450 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 8451 case Builtin::BI__builtin_add_overflow: 8452 case Builtin::BI__builtin_sub_overflow: 8453 case Builtin::BI__builtin_mul_overflow: 8454 case Builtin::BI__builtin_sadd_overflow: 8455 case Builtin::BI__builtin_uadd_overflow: 8456 case Builtin::BI__builtin_uaddl_overflow: 8457 case Builtin::BI__builtin_uaddll_overflow: 8458 case Builtin::BI__builtin_usub_overflow: 8459 case Builtin::BI__builtin_usubl_overflow: 8460 case Builtin::BI__builtin_usubll_overflow: 8461 case Builtin::BI__builtin_umul_overflow: 8462 case Builtin::BI__builtin_umull_overflow: 8463 case Builtin::BI__builtin_umulll_overflow: 8464 case Builtin::BI__builtin_saddl_overflow: 8465 case Builtin::BI__builtin_saddll_overflow: 8466 case Builtin::BI__builtin_ssub_overflow: 8467 case Builtin::BI__builtin_ssubl_overflow: 8468 case Builtin::BI__builtin_ssubll_overflow: 8469 case Builtin::BI__builtin_smul_overflow: 8470 case Builtin::BI__builtin_smull_overflow: 8471 case Builtin::BI__builtin_smulll_overflow: { 8472 LValue ResultLValue; 8473 APSInt LHS, RHS; 8474 8475 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 8476 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 8477 !EvaluateInteger(E->getArg(1), RHS, Info) || 8478 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 8479 return false; 8480 8481 APSInt Result; 8482 bool DidOverflow = false; 8483 8484 // If the types don't have to match, enlarge all 3 to the largest of them. 8485 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 8486 BuiltinOp == Builtin::BI__builtin_sub_overflow || 8487 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 8488 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 8489 ResultType->isSignedIntegerOrEnumerationType(); 8490 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 8491 ResultType->isSignedIntegerOrEnumerationType(); 8492 uint64_t LHSSize = LHS.getBitWidth(); 8493 uint64_t RHSSize = RHS.getBitWidth(); 8494 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 8495 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 8496 8497 // Add an additional bit if the signedness isn't uniformly agreed to. We 8498 // could do this ONLY if there is a signed and an unsigned that both have 8499 // MaxBits, but the code to check that is pretty nasty. The issue will be 8500 // caught in the shrink-to-result later anyway. 8501 if (IsSigned && !AllSigned) 8502 ++MaxBits; 8503 8504 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits), 8505 !IsSigned); 8506 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits), 8507 !IsSigned); 8508 Result = APSInt(MaxBits, !IsSigned); 8509 } 8510 8511 // Find largest int. 8512 switch (BuiltinOp) { 8513 default: 8514 llvm_unreachable("Invalid value for BuiltinOp"); 8515 case Builtin::BI__builtin_add_overflow: 8516 case Builtin::BI__builtin_sadd_overflow: 8517 case Builtin::BI__builtin_saddl_overflow: 8518 case Builtin::BI__builtin_saddll_overflow: 8519 case Builtin::BI__builtin_uadd_overflow: 8520 case Builtin::BI__builtin_uaddl_overflow: 8521 case Builtin::BI__builtin_uaddll_overflow: 8522 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 8523 : LHS.uadd_ov(RHS, DidOverflow); 8524 break; 8525 case Builtin::BI__builtin_sub_overflow: 8526 case Builtin::BI__builtin_ssub_overflow: 8527 case Builtin::BI__builtin_ssubl_overflow: 8528 case Builtin::BI__builtin_ssubll_overflow: 8529 case Builtin::BI__builtin_usub_overflow: 8530 case Builtin::BI__builtin_usubl_overflow: 8531 case Builtin::BI__builtin_usubll_overflow: 8532 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 8533 : LHS.usub_ov(RHS, DidOverflow); 8534 break; 8535 case Builtin::BI__builtin_mul_overflow: 8536 case Builtin::BI__builtin_smul_overflow: 8537 case Builtin::BI__builtin_smull_overflow: 8538 case Builtin::BI__builtin_smulll_overflow: 8539 case Builtin::BI__builtin_umul_overflow: 8540 case Builtin::BI__builtin_umull_overflow: 8541 case Builtin::BI__builtin_umulll_overflow: 8542 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 8543 : LHS.umul_ov(RHS, DidOverflow); 8544 break; 8545 } 8546 8547 // In the case where multiple sizes are allowed, truncate and see if 8548 // the values are the same. 8549 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 8550 BuiltinOp == Builtin::BI__builtin_sub_overflow || 8551 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 8552 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 8553 // since it will give us the behavior of a TruncOrSelf in the case where 8554 // its parameter <= its size. We previously set Result to be at least the 8555 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 8556 // will work exactly like TruncOrSelf. 8557 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 8558 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 8559 8560 if (!APSInt::isSameValue(Temp, Result)) 8561 DidOverflow = true; 8562 Result = Temp; 8563 } 8564 8565 APValue APV{Result}; 8566 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 8567 return false; 8568 return Success(DidOverflow, E); 8569 } 8570 } 8571 } 8572 8573 /// Determine whether this is a pointer past the end of the complete 8574 /// object referred to by the lvalue. 8575 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 8576 const LValue &LV) { 8577 // A null pointer can be viewed as being "past the end" but we don't 8578 // choose to look at it that way here. 8579 if (!LV.getLValueBase()) 8580 return false; 8581 8582 // If the designator is valid and refers to a subobject, we're not pointing 8583 // past the end. 8584 if (!LV.getLValueDesignator().Invalid && 8585 !LV.getLValueDesignator().isOnePastTheEnd()) 8586 return false; 8587 8588 // A pointer to an incomplete type might be past-the-end if the type's size is 8589 // zero. We cannot tell because the type is incomplete. 8590 QualType Ty = getType(LV.getLValueBase()); 8591 if (Ty->isIncompleteType()) 8592 return true; 8593 8594 // We're a past-the-end pointer if we point to the byte after the object, 8595 // no matter what our type or path is. 8596 auto Size = Ctx.getTypeSizeInChars(Ty); 8597 return LV.getLValueOffset() == Size; 8598 } 8599 8600 namespace { 8601 8602 /// Data recursive integer evaluator of certain binary operators. 8603 /// 8604 /// We use a data recursive algorithm for binary operators so that we are able 8605 /// to handle extreme cases of chained binary operators without causing stack 8606 /// overflow. 8607 class DataRecursiveIntBinOpEvaluator { 8608 struct EvalResult { 8609 APValue Val; 8610 bool Failed; 8611 8612 EvalResult() : Failed(false) { } 8613 8614 void swap(EvalResult &RHS) { 8615 Val.swap(RHS.Val); 8616 Failed = RHS.Failed; 8617 RHS.Failed = false; 8618 } 8619 }; 8620 8621 struct Job { 8622 const Expr *E; 8623 EvalResult LHSResult; // meaningful only for binary operator expression. 8624 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 8625 8626 Job() = default; 8627 Job(Job &&) = default; 8628 8629 void startSpeculativeEval(EvalInfo &Info) { 8630 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 8631 } 8632 8633 private: 8634 SpeculativeEvaluationRAII SpecEvalRAII; 8635 }; 8636 8637 SmallVector<Job, 16> Queue; 8638 8639 IntExprEvaluator &IntEval; 8640 EvalInfo &Info; 8641 APValue &FinalResult; 8642 8643 public: 8644 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 8645 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 8646 8647 /// True if \param E is a binary operator that we are going to handle 8648 /// data recursively. 8649 /// We handle binary operators that are comma, logical, or that have operands 8650 /// with integral or enumeration type. 8651 static bool shouldEnqueue(const BinaryOperator *E) { 8652 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 8653 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 8654 E->getLHS()->getType()->isIntegralOrEnumerationType() && 8655 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8656 } 8657 8658 bool Traverse(const BinaryOperator *E) { 8659 enqueue(E); 8660 EvalResult PrevResult; 8661 while (!Queue.empty()) 8662 process(PrevResult); 8663 8664 if (PrevResult.Failed) return false; 8665 8666 FinalResult.swap(PrevResult.Val); 8667 return true; 8668 } 8669 8670 private: 8671 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 8672 return IntEval.Success(Value, E, Result); 8673 } 8674 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 8675 return IntEval.Success(Value, E, Result); 8676 } 8677 bool Error(const Expr *E) { 8678 return IntEval.Error(E); 8679 } 8680 bool Error(const Expr *E, diag::kind D) { 8681 return IntEval.Error(E, D); 8682 } 8683 8684 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 8685 return Info.CCEDiag(E, D); 8686 } 8687 8688 // Returns true if visiting the RHS is necessary, false otherwise. 8689 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 8690 bool &SuppressRHSDiags); 8691 8692 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 8693 const BinaryOperator *E, APValue &Result); 8694 8695 void EvaluateExpr(const Expr *E, EvalResult &Result) { 8696 Result.Failed = !Evaluate(Result.Val, Info, E); 8697 if (Result.Failed) 8698 Result.Val = APValue(); 8699 } 8700 8701 void process(EvalResult &Result); 8702 8703 void enqueue(const Expr *E) { 8704 E = E->IgnoreParens(); 8705 Queue.resize(Queue.size()+1); 8706 Queue.back().E = E; 8707 Queue.back().Kind = Job::AnyExprKind; 8708 } 8709 }; 8710 8711 } 8712 8713 bool DataRecursiveIntBinOpEvaluator:: 8714 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 8715 bool &SuppressRHSDiags) { 8716 if (E->getOpcode() == BO_Comma) { 8717 // Ignore LHS but note if we could not evaluate it. 8718 if (LHSResult.Failed) 8719 return Info.noteSideEffect(); 8720 return true; 8721 } 8722 8723 if (E->isLogicalOp()) { 8724 bool LHSAsBool; 8725 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 8726 // We were able to evaluate the LHS, see if we can get away with not 8727 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 8728 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 8729 Success(LHSAsBool, E, LHSResult.Val); 8730 return false; // Ignore RHS 8731 } 8732 } else { 8733 LHSResult.Failed = true; 8734 8735 // Since we weren't able to evaluate the left hand side, it 8736 // might have had side effects. 8737 if (!Info.noteSideEffect()) 8738 return false; 8739 8740 // We can't evaluate the LHS; however, sometimes the result 8741 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 8742 // Don't ignore RHS and suppress diagnostics from this arm. 8743 SuppressRHSDiags = true; 8744 } 8745 8746 return true; 8747 } 8748 8749 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 8750 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8751 8752 if (LHSResult.Failed && !Info.noteFailure()) 8753 return false; // Ignore RHS; 8754 8755 return true; 8756 } 8757 8758 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 8759 bool IsSub) { 8760 // Compute the new offset in the appropriate width, wrapping at 64 bits. 8761 // FIXME: When compiling for a 32-bit target, we should use 32-bit 8762 // offsets. 8763 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 8764 CharUnits &Offset = LVal.getLValueOffset(); 8765 uint64_t Offset64 = Offset.getQuantity(); 8766 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 8767 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 8768 : Offset64 + Index64); 8769 } 8770 8771 bool DataRecursiveIntBinOpEvaluator:: 8772 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 8773 const BinaryOperator *E, APValue &Result) { 8774 if (E->getOpcode() == BO_Comma) { 8775 if (RHSResult.Failed) 8776 return false; 8777 Result = RHSResult.Val; 8778 return true; 8779 } 8780 8781 if (E->isLogicalOp()) { 8782 bool lhsResult, rhsResult; 8783 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 8784 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 8785 8786 if (LHSIsOK) { 8787 if (RHSIsOK) { 8788 if (E->getOpcode() == BO_LOr) 8789 return Success(lhsResult || rhsResult, E, Result); 8790 else 8791 return Success(lhsResult && rhsResult, E, Result); 8792 } 8793 } else { 8794 if (RHSIsOK) { 8795 // We can't evaluate the LHS; however, sometimes the result 8796 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 8797 if (rhsResult == (E->getOpcode() == BO_LOr)) 8798 return Success(rhsResult, E, Result); 8799 } 8800 } 8801 8802 return false; 8803 } 8804 8805 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 8806 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8807 8808 if (LHSResult.Failed || RHSResult.Failed) 8809 return false; 8810 8811 const APValue &LHSVal = LHSResult.Val; 8812 const APValue &RHSVal = RHSResult.Val; 8813 8814 // Handle cases like (unsigned long)&a + 4. 8815 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 8816 Result = LHSVal; 8817 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 8818 return true; 8819 } 8820 8821 // Handle cases like 4 + (unsigned long)&a 8822 if (E->getOpcode() == BO_Add && 8823 RHSVal.isLValue() && LHSVal.isInt()) { 8824 Result = RHSVal; 8825 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 8826 return true; 8827 } 8828 8829 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 8830 // Handle (intptr_t)&&A - (intptr_t)&&B. 8831 if (!LHSVal.getLValueOffset().isZero() || 8832 !RHSVal.getLValueOffset().isZero()) 8833 return false; 8834 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 8835 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 8836 if (!LHSExpr || !RHSExpr) 8837 return false; 8838 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 8839 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 8840 if (!LHSAddrExpr || !RHSAddrExpr) 8841 return false; 8842 // Make sure both labels come from the same function. 8843 if (LHSAddrExpr->getLabel()->getDeclContext() != 8844 RHSAddrExpr->getLabel()->getDeclContext()) 8845 return false; 8846 Result = APValue(LHSAddrExpr, RHSAddrExpr); 8847 return true; 8848 } 8849 8850 // All the remaining cases expect both operands to be an integer 8851 if (!LHSVal.isInt() || !RHSVal.isInt()) 8852 return Error(E); 8853 8854 // Set up the width and signedness manually, in case it can't be deduced 8855 // from the operation we're performing. 8856 // FIXME: Don't do this in the cases where we can deduce it. 8857 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 8858 E->getType()->isUnsignedIntegerOrEnumerationType()); 8859 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 8860 RHSVal.getInt(), Value)) 8861 return false; 8862 return Success(Value, E, Result); 8863 } 8864 8865 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 8866 Job &job = Queue.back(); 8867 8868 switch (job.Kind) { 8869 case Job::AnyExprKind: { 8870 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 8871 if (shouldEnqueue(Bop)) { 8872 job.Kind = Job::BinOpKind; 8873 enqueue(Bop->getLHS()); 8874 return; 8875 } 8876 } 8877 8878 EvaluateExpr(job.E, Result); 8879 Queue.pop_back(); 8880 return; 8881 } 8882 8883 case Job::BinOpKind: { 8884 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 8885 bool SuppressRHSDiags = false; 8886 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 8887 Queue.pop_back(); 8888 return; 8889 } 8890 if (SuppressRHSDiags) 8891 job.startSpeculativeEval(Info); 8892 job.LHSResult.swap(Result); 8893 job.Kind = Job::BinOpVisitedLHSKind; 8894 enqueue(Bop->getRHS()); 8895 return; 8896 } 8897 8898 case Job::BinOpVisitedLHSKind: { 8899 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 8900 EvalResult RHS; 8901 RHS.swap(Result); 8902 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 8903 Queue.pop_back(); 8904 return; 8905 } 8906 } 8907 8908 llvm_unreachable("Invalid Job::Kind!"); 8909 } 8910 8911 namespace { 8912 /// Used when we determine that we should fail, but can keep evaluating prior to 8913 /// noting that we had a failure. 8914 class DelayedNoteFailureRAII { 8915 EvalInfo &Info; 8916 bool NoteFailure; 8917 8918 public: 8919 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 8920 : Info(Info), NoteFailure(NoteFailure) {} 8921 ~DelayedNoteFailureRAII() { 8922 if (NoteFailure) { 8923 bool ContinueAfterFailure = Info.noteFailure(); 8924 (void)ContinueAfterFailure; 8925 assert(ContinueAfterFailure && 8926 "Shouldn't have kept evaluating on failure."); 8927 } 8928 } 8929 }; 8930 } 8931 8932 template <class SuccessCB, class AfterCB> 8933 static bool 8934 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 8935 SuccessCB &&Success, AfterCB &&DoAfter) { 8936 assert(E->isComparisonOp() && "expected comparison operator"); 8937 assert((E->getOpcode() == BO_Cmp || 8938 E->getType()->isIntegralOrEnumerationType()) && 8939 "unsupported binary expression evaluation"); 8940 auto Error = [&](const Expr *E) { 8941 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 8942 return false; 8943 }; 8944 8945 using CCR = ComparisonCategoryResult; 8946 bool IsRelational = E->isRelationalOp(); 8947 bool IsEquality = E->isEqualityOp(); 8948 if (E->getOpcode() == BO_Cmp) { 8949 const ComparisonCategoryInfo &CmpInfo = 8950 Info.Ctx.CompCategories.getInfoForType(E->getType()); 8951 IsRelational = CmpInfo.isOrdered(); 8952 IsEquality = CmpInfo.isEquality(); 8953 } 8954 8955 QualType LHSTy = E->getLHS()->getType(); 8956 QualType RHSTy = E->getRHS()->getType(); 8957 8958 if (LHSTy->isIntegralOrEnumerationType() && 8959 RHSTy->isIntegralOrEnumerationType()) { 8960 APSInt LHS, RHS; 8961 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 8962 if (!LHSOK && !Info.noteFailure()) 8963 return false; 8964 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 8965 return false; 8966 if (LHS < RHS) 8967 return Success(CCR::Less, E); 8968 if (LHS > RHS) 8969 return Success(CCR::Greater, E); 8970 return Success(CCR::Equal, E); 8971 } 8972 8973 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 8974 ComplexValue LHS, RHS; 8975 bool LHSOK; 8976 if (E->isAssignmentOp()) { 8977 LValue LV; 8978 EvaluateLValue(E->getLHS(), LV, Info); 8979 LHSOK = false; 8980 } else if (LHSTy->isRealFloatingType()) { 8981 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 8982 if (LHSOK) { 8983 LHS.makeComplexFloat(); 8984 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 8985 } 8986 } else { 8987 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 8988 } 8989 if (!LHSOK && !Info.noteFailure()) 8990 return false; 8991 8992 if (E->getRHS()->getType()->isRealFloatingType()) { 8993 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 8994 return false; 8995 RHS.makeComplexFloat(); 8996 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 8997 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 8998 return false; 8999 9000 if (LHS.isComplexFloat()) { 9001 APFloat::cmpResult CR_r = 9002 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 9003 APFloat::cmpResult CR_i = 9004 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 9005 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 9006 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 9007 } else { 9008 assert(IsEquality && "invalid complex comparison"); 9009 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 9010 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 9011 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 9012 } 9013 } 9014 9015 if (LHSTy->isRealFloatingType() && 9016 RHSTy->isRealFloatingType()) { 9017 APFloat RHS(0.0), LHS(0.0); 9018 9019 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 9020 if (!LHSOK && !Info.noteFailure()) 9021 return false; 9022 9023 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 9024 return false; 9025 9026 assert(E->isComparisonOp() && "Invalid binary operator!"); 9027 auto GetCmpRes = [&]() { 9028 switch (LHS.compare(RHS)) { 9029 case APFloat::cmpEqual: 9030 return CCR::Equal; 9031 case APFloat::cmpLessThan: 9032 return CCR::Less; 9033 case APFloat::cmpGreaterThan: 9034 return CCR::Greater; 9035 case APFloat::cmpUnordered: 9036 return CCR::Unordered; 9037 } 9038 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 9039 }; 9040 return Success(GetCmpRes(), E); 9041 } 9042 9043 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 9044 LValue LHSValue, RHSValue; 9045 9046 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 9047 if (!LHSOK && !Info.noteFailure()) 9048 return false; 9049 9050 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 9051 return false; 9052 9053 // Reject differing bases from the normal codepath; we special-case 9054 // comparisons to null. 9055 if (!HasSameBase(LHSValue, RHSValue)) { 9056 // Inequalities and subtractions between unrelated pointers have 9057 // unspecified or undefined behavior. 9058 if (!IsEquality) 9059 return Error(E); 9060 // A constant address may compare equal to the address of a symbol. 9061 // The one exception is that address of an object cannot compare equal 9062 // to a null pointer constant. 9063 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 9064 (!RHSValue.Base && !RHSValue.Offset.isZero())) 9065 return Error(E); 9066 // It's implementation-defined whether distinct literals will have 9067 // distinct addresses. In clang, the result of such a comparison is 9068 // unspecified, so it is not a constant expression. However, we do know 9069 // that the address of a literal will be non-null. 9070 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 9071 LHSValue.Base && RHSValue.Base) 9072 return Error(E); 9073 // We can't tell whether weak symbols will end up pointing to the same 9074 // object. 9075 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 9076 return Error(E); 9077 // We can't compare the address of the start of one object with the 9078 // past-the-end address of another object, per C++ DR1652. 9079 if ((LHSValue.Base && LHSValue.Offset.isZero() && 9080 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 9081 (RHSValue.Base && RHSValue.Offset.isZero() && 9082 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 9083 return Error(E); 9084 // We can't tell whether an object is at the same address as another 9085 // zero sized object. 9086 if ((RHSValue.Base && isZeroSized(LHSValue)) || 9087 (LHSValue.Base && isZeroSized(RHSValue))) 9088 return Error(E); 9089 return Success(CCR::Nonequal, E); 9090 } 9091 9092 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 9093 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 9094 9095 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 9096 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 9097 9098 // C++11 [expr.rel]p3: 9099 // Pointers to void (after pointer conversions) can be compared, with a 9100 // result defined as follows: If both pointers represent the same 9101 // address or are both the null pointer value, the result is true if the 9102 // operator is <= or >= and false otherwise; otherwise the result is 9103 // unspecified. 9104 // We interpret this as applying to pointers to *cv* void. 9105 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 9106 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 9107 9108 // C++11 [expr.rel]p2: 9109 // - If two pointers point to non-static data members of the same object, 9110 // or to subobjects or array elements fo such members, recursively, the 9111 // pointer to the later declared member compares greater provided the 9112 // two members have the same access control and provided their class is 9113 // not a union. 9114 // [...] 9115 // - Otherwise pointer comparisons are unspecified. 9116 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 9117 bool WasArrayIndex; 9118 unsigned Mismatch = FindDesignatorMismatch( 9119 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 9120 // At the point where the designators diverge, the comparison has a 9121 // specified value if: 9122 // - we are comparing array indices 9123 // - we are comparing fields of a union, or fields with the same access 9124 // Otherwise, the result is unspecified and thus the comparison is not a 9125 // constant expression. 9126 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 9127 Mismatch < RHSDesignator.Entries.size()) { 9128 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 9129 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 9130 if (!LF && !RF) 9131 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 9132 else if (!LF) 9133 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 9134 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 9135 << RF->getParent() << RF; 9136 else if (!RF) 9137 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 9138 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 9139 << LF->getParent() << LF; 9140 else if (!LF->getParent()->isUnion() && 9141 LF->getAccess() != RF->getAccess()) 9142 Info.CCEDiag(E, 9143 diag::note_constexpr_pointer_comparison_differing_access) 9144 << LF << LF->getAccess() << RF << RF->getAccess() 9145 << LF->getParent(); 9146 } 9147 } 9148 9149 // The comparison here must be unsigned, and performed with the same 9150 // width as the pointer. 9151 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 9152 uint64_t CompareLHS = LHSOffset.getQuantity(); 9153 uint64_t CompareRHS = RHSOffset.getQuantity(); 9154 assert(PtrSize <= 64 && "Unexpected pointer width"); 9155 uint64_t Mask = ~0ULL >> (64 - PtrSize); 9156 CompareLHS &= Mask; 9157 CompareRHS &= Mask; 9158 9159 // If there is a base and this is a relational operator, we can only 9160 // compare pointers within the object in question; otherwise, the result 9161 // depends on where the object is located in memory. 9162 if (!LHSValue.Base.isNull() && IsRelational) { 9163 QualType BaseTy = getType(LHSValue.Base); 9164 if (BaseTy->isIncompleteType()) 9165 return Error(E); 9166 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 9167 uint64_t OffsetLimit = Size.getQuantity(); 9168 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 9169 return Error(E); 9170 } 9171 9172 if (CompareLHS < CompareRHS) 9173 return Success(CCR::Less, E); 9174 if (CompareLHS > CompareRHS) 9175 return Success(CCR::Greater, E); 9176 return Success(CCR::Equal, E); 9177 } 9178 9179 if (LHSTy->isMemberPointerType()) { 9180 assert(IsEquality && "unexpected member pointer operation"); 9181 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 9182 9183 MemberPtr LHSValue, RHSValue; 9184 9185 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 9186 if (!LHSOK && !Info.noteFailure()) 9187 return false; 9188 9189 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 9190 return false; 9191 9192 // C++11 [expr.eq]p2: 9193 // If both operands are null, they compare equal. Otherwise if only one is 9194 // null, they compare unequal. 9195 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 9196 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 9197 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 9198 } 9199 9200 // Otherwise if either is a pointer to a virtual member function, the 9201 // result is unspecified. 9202 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 9203 if (MD->isVirtual()) 9204 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 9205 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 9206 if (MD->isVirtual()) 9207 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 9208 9209 // Otherwise they compare equal if and only if they would refer to the 9210 // same member of the same most derived object or the same subobject if 9211 // they were dereferenced with a hypothetical object of the associated 9212 // class type. 9213 bool Equal = LHSValue == RHSValue; 9214 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 9215 } 9216 9217 if (LHSTy->isNullPtrType()) { 9218 assert(E->isComparisonOp() && "unexpected nullptr operation"); 9219 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 9220 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 9221 // are compared, the result is true of the operator is <=, >= or ==, and 9222 // false otherwise. 9223 return Success(CCR::Equal, E); 9224 } 9225 9226 return DoAfter(); 9227 } 9228 9229 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 9230 if (!CheckLiteralType(Info, E)) 9231 return false; 9232 9233 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 9234 const BinaryOperator *E) { 9235 // Evaluation succeeded. Lookup the information for the comparison category 9236 // type and fetch the VarDecl for the result. 9237 const ComparisonCategoryInfo &CmpInfo = 9238 Info.Ctx.CompCategories.getInfoForType(E->getType()); 9239 const VarDecl *VD = 9240 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD; 9241 // Check and evaluate the result as a constant expression. 9242 LValue LV; 9243 LV.set(VD); 9244 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 9245 return false; 9246 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 9247 }; 9248 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 9249 return ExprEvaluatorBaseTy::VisitBinCmp(E); 9250 }); 9251 } 9252 9253 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9254 // We don't call noteFailure immediately because the assignment happens after 9255 // we evaluate LHS and RHS. 9256 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 9257 return Error(E); 9258 9259 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 9260 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 9261 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 9262 9263 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 9264 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 9265 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 9266 9267 if (E->isComparisonOp()) { 9268 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way 9269 // comparisons and then translating the result. 9270 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 9271 const BinaryOperator *E) { 9272 using CCR = ComparisonCategoryResult; 9273 bool IsEqual = ResKind == CCR::Equal, 9274 IsLess = ResKind == CCR::Less, 9275 IsGreater = ResKind == CCR::Greater; 9276 auto Op = E->getOpcode(); 9277 switch (Op) { 9278 default: 9279 llvm_unreachable("unsupported binary operator"); 9280 case BO_EQ: 9281 case BO_NE: 9282 return Success(IsEqual == (Op == BO_EQ), E); 9283 case BO_LT: return Success(IsLess, E); 9284 case BO_GT: return Success(IsGreater, E); 9285 case BO_LE: return Success(IsEqual || IsLess, E); 9286 case BO_GE: return Success(IsEqual || IsGreater, E); 9287 } 9288 }; 9289 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 9290 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9291 }); 9292 } 9293 9294 QualType LHSTy = E->getLHS()->getType(); 9295 QualType RHSTy = E->getRHS()->getType(); 9296 9297 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 9298 E->getOpcode() == BO_Sub) { 9299 LValue LHSValue, RHSValue; 9300 9301 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 9302 if (!LHSOK && !Info.noteFailure()) 9303 return false; 9304 9305 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 9306 return false; 9307 9308 // Reject differing bases from the normal codepath; we special-case 9309 // comparisons to null. 9310 if (!HasSameBase(LHSValue, RHSValue)) { 9311 // Handle &&A - &&B. 9312 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 9313 return Error(E); 9314 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 9315 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 9316 if (!LHSExpr || !RHSExpr) 9317 return Error(E); 9318 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 9319 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 9320 if (!LHSAddrExpr || !RHSAddrExpr) 9321 return Error(E); 9322 // Make sure both labels come from the same function. 9323 if (LHSAddrExpr->getLabel()->getDeclContext() != 9324 RHSAddrExpr->getLabel()->getDeclContext()) 9325 return Error(E); 9326 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 9327 } 9328 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 9329 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 9330 9331 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 9332 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 9333 9334 // C++11 [expr.add]p6: 9335 // Unless both pointers point to elements of the same array object, or 9336 // one past the last element of the array object, the behavior is 9337 // undefined. 9338 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 9339 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 9340 RHSDesignator)) 9341 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 9342 9343 QualType Type = E->getLHS()->getType(); 9344 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 9345 9346 CharUnits ElementSize; 9347 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 9348 return false; 9349 9350 // As an extension, a type may have zero size (empty struct or union in 9351 // C, array of zero length). Pointer subtraction in such cases has 9352 // undefined behavior, so is not constant. 9353 if (ElementSize.isZero()) { 9354 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 9355 << ElementType; 9356 return false; 9357 } 9358 9359 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 9360 // and produce incorrect results when it overflows. Such behavior 9361 // appears to be non-conforming, but is common, so perhaps we should 9362 // assume the standard intended for such cases to be undefined behavior 9363 // and check for them. 9364 9365 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 9366 // overflow in the final conversion to ptrdiff_t. 9367 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 9368 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 9369 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 9370 false); 9371 APSInt TrueResult = (LHS - RHS) / ElemSize; 9372 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 9373 9374 if (Result.extend(65) != TrueResult && 9375 !HandleOverflow(Info, E, TrueResult, E->getType())) 9376 return false; 9377 return Success(Result, E); 9378 } 9379 9380 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9381 } 9382 9383 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 9384 /// a result as the expression's type. 9385 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 9386 const UnaryExprOrTypeTraitExpr *E) { 9387 switch(E->getKind()) { 9388 case UETT_PreferredAlignOf: 9389 case UETT_AlignOf: { 9390 if (E->isArgumentType()) 9391 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 9392 E); 9393 else 9394 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 9395 E); 9396 } 9397 9398 case UETT_VecStep: { 9399 QualType Ty = E->getTypeOfArgument(); 9400 9401 if (Ty->isVectorType()) { 9402 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 9403 9404 // The vec_step built-in functions that take a 3-component 9405 // vector return 4. (OpenCL 1.1 spec 6.11.12) 9406 if (n == 3) 9407 n = 4; 9408 9409 return Success(n, E); 9410 } else 9411 return Success(1, E); 9412 } 9413 9414 case UETT_SizeOf: { 9415 QualType SrcTy = E->getTypeOfArgument(); 9416 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 9417 // the result is the size of the referenced type." 9418 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 9419 SrcTy = Ref->getPointeeType(); 9420 9421 CharUnits Sizeof; 9422 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 9423 return false; 9424 return Success(Sizeof, E); 9425 } 9426 case UETT_OpenMPRequiredSimdAlign: 9427 assert(E->isArgumentType()); 9428 return Success( 9429 Info.Ctx.toCharUnitsFromBits( 9430 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 9431 .getQuantity(), 9432 E); 9433 } 9434 9435 llvm_unreachable("unknown expr/type trait"); 9436 } 9437 9438 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 9439 CharUnits Result; 9440 unsigned n = OOE->getNumComponents(); 9441 if (n == 0) 9442 return Error(OOE); 9443 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 9444 for (unsigned i = 0; i != n; ++i) { 9445 OffsetOfNode ON = OOE->getComponent(i); 9446 switch (ON.getKind()) { 9447 case OffsetOfNode::Array: { 9448 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 9449 APSInt IdxResult; 9450 if (!EvaluateInteger(Idx, IdxResult, Info)) 9451 return false; 9452 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 9453 if (!AT) 9454 return Error(OOE); 9455 CurrentType = AT->getElementType(); 9456 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 9457 Result += IdxResult.getSExtValue() * ElementSize; 9458 break; 9459 } 9460 9461 case OffsetOfNode::Field: { 9462 FieldDecl *MemberDecl = ON.getField(); 9463 const RecordType *RT = CurrentType->getAs<RecordType>(); 9464 if (!RT) 9465 return Error(OOE); 9466 RecordDecl *RD = RT->getDecl(); 9467 if (RD->isInvalidDecl()) return false; 9468 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 9469 unsigned i = MemberDecl->getFieldIndex(); 9470 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 9471 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 9472 CurrentType = MemberDecl->getType().getNonReferenceType(); 9473 break; 9474 } 9475 9476 case OffsetOfNode::Identifier: 9477 llvm_unreachable("dependent __builtin_offsetof"); 9478 9479 case OffsetOfNode::Base: { 9480 CXXBaseSpecifier *BaseSpec = ON.getBase(); 9481 if (BaseSpec->isVirtual()) 9482 return Error(OOE); 9483 9484 // Find the layout of the class whose base we are looking into. 9485 const RecordType *RT = CurrentType->getAs<RecordType>(); 9486 if (!RT) 9487 return Error(OOE); 9488 RecordDecl *RD = RT->getDecl(); 9489 if (RD->isInvalidDecl()) return false; 9490 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 9491 9492 // Find the base class itself. 9493 CurrentType = BaseSpec->getType(); 9494 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 9495 if (!BaseRT) 9496 return Error(OOE); 9497 9498 // Add the offset to the base. 9499 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 9500 break; 9501 } 9502 } 9503 } 9504 return Success(Result, OOE); 9505 } 9506 9507 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9508 switch (E->getOpcode()) { 9509 default: 9510 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 9511 // See C99 6.6p3. 9512 return Error(E); 9513 case UO_Extension: 9514 // FIXME: Should extension allow i-c-e extension expressions in its scope? 9515 // If so, we could clear the diagnostic ID. 9516 return Visit(E->getSubExpr()); 9517 case UO_Plus: 9518 // The result is just the value. 9519 return Visit(E->getSubExpr()); 9520 case UO_Minus: { 9521 if (!Visit(E->getSubExpr())) 9522 return false; 9523 if (!Result.isInt()) return Error(E); 9524 const APSInt &Value = Result.getInt(); 9525 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 9526 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 9527 E->getType())) 9528 return false; 9529 return Success(-Value, E); 9530 } 9531 case UO_Not: { 9532 if (!Visit(E->getSubExpr())) 9533 return false; 9534 if (!Result.isInt()) return Error(E); 9535 return Success(~Result.getInt(), E); 9536 } 9537 case UO_LNot: { 9538 bool bres; 9539 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 9540 return false; 9541 return Success(!bres, E); 9542 } 9543 } 9544 } 9545 9546 /// HandleCast - This is used to evaluate implicit or explicit casts where the 9547 /// result type is integer. 9548 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 9549 const Expr *SubExpr = E->getSubExpr(); 9550 QualType DestType = E->getType(); 9551 QualType SrcType = SubExpr->getType(); 9552 9553 switch (E->getCastKind()) { 9554 case CK_BaseToDerived: 9555 case CK_DerivedToBase: 9556 case CK_UncheckedDerivedToBase: 9557 case CK_Dynamic: 9558 case CK_ToUnion: 9559 case CK_ArrayToPointerDecay: 9560 case CK_FunctionToPointerDecay: 9561 case CK_NullToPointer: 9562 case CK_NullToMemberPointer: 9563 case CK_BaseToDerivedMemberPointer: 9564 case CK_DerivedToBaseMemberPointer: 9565 case CK_ReinterpretMemberPointer: 9566 case CK_ConstructorConversion: 9567 case CK_IntegralToPointer: 9568 case CK_ToVoid: 9569 case CK_VectorSplat: 9570 case CK_IntegralToFloating: 9571 case CK_FloatingCast: 9572 case CK_CPointerToObjCPointerCast: 9573 case CK_BlockPointerToObjCPointerCast: 9574 case CK_AnyPointerToBlockPointerCast: 9575 case CK_ObjCObjectLValueCast: 9576 case CK_FloatingRealToComplex: 9577 case CK_FloatingComplexToReal: 9578 case CK_FloatingComplexCast: 9579 case CK_FloatingComplexToIntegralComplex: 9580 case CK_IntegralRealToComplex: 9581 case CK_IntegralComplexCast: 9582 case CK_IntegralComplexToFloatingComplex: 9583 case CK_BuiltinFnToFnPtr: 9584 case CK_ZeroToOCLOpaqueType: 9585 case CK_NonAtomicToAtomic: 9586 case CK_AddressSpaceConversion: 9587 case CK_IntToOCLSampler: 9588 case CK_FixedPointCast: 9589 llvm_unreachable("invalid cast kind for integral value"); 9590 9591 case CK_BitCast: 9592 case CK_Dependent: 9593 case CK_LValueBitCast: 9594 case CK_ARCProduceObject: 9595 case CK_ARCConsumeObject: 9596 case CK_ARCReclaimReturnedObject: 9597 case CK_ARCExtendBlockObject: 9598 case CK_CopyAndAutoreleaseBlockObject: 9599 return Error(E); 9600 9601 case CK_UserDefinedConversion: 9602 case CK_LValueToRValue: 9603 case CK_AtomicToNonAtomic: 9604 case CK_NoOp: 9605 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9606 9607 case CK_MemberPointerToBoolean: 9608 case CK_PointerToBoolean: 9609 case CK_IntegralToBoolean: 9610 case CK_FloatingToBoolean: 9611 case CK_BooleanToSignedIntegral: 9612 case CK_FloatingComplexToBoolean: 9613 case CK_IntegralComplexToBoolean: { 9614 bool BoolResult; 9615 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 9616 return false; 9617 uint64_t IntResult = BoolResult; 9618 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 9619 IntResult = (uint64_t)-1; 9620 return Success(IntResult, E); 9621 } 9622 9623 case CK_FixedPointToBoolean: { 9624 // Unsigned padding does not affect this. 9625 APValue Val; 9626 if (!Evaluate(Val, Info, SubExpr)) 9627 return false; 9628 return Success(Val.getInt().getBoolValue(), E); 9629 } 9630 9631 case CK_IntegralCast: { 9632 if (!Visit(SubExpr)) 9633 return false; 9634 9635 if (!Result.isInt()) { 9636 // Allow casts of address-of-label differences if they are no-ops 9637 // or narrowing. (The narrowing case isn't actually guaranteed to 9638 // be constant-evaluatable except in some narrow cases which are hard 9639 // to detect here. We let it through on the assumption the user knows 9640 // what they are doing.) 9641 if (Result.isAddrLabelDiff()) 9642 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 9643 // Only allow casts of lvalues if they are lossless. 9644 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 9645 } 9646 9647 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 9648 Result.getInt()), E); 9649 } 9650 9651 case CK_PointerToIntegral: { 9652 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 9653 9654 LValue LV; 9655 if (!EvaluatePointer(SubExpr, LV, Info)) 9656 return false; 9657 9658 if (LV.getLValueBase()) { 9659 // Only allow based lvalue casts if they are lossless. 9660 // FIXME: Allow a larger integer size than the pointer size, and allow 9661 // narrowing back down to pointer width in subsequent integral casts. 9662 // FIXME: Check integer type's active bits, not its type size. 9663 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 9664 return Error(E); 9665 9666 LV.Designator.setInvalid(); 9667 LV.moveInto(Result); 9668 return true; 9669 } 9670 9671 uint64_t V; 9672 if (LV.isNullPointer()) 9673 V = Info.Ctx.getTargetNullPointerValue(SrcType); 9674 else 9675 V = LV.getLValueOffset().getQuantity(); 9676 9677 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType); 9678 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 9679 } 9680 9681 case CK_IntegralComplexToReal: { 9682 ComplexValue C; 9683 if (!EvaluateComplex(SubExpr, C, Info)) 9684 return false; 9685 return Success(C.getComplexIntReal(), E); 9686 } 9687 9688 case CK_FloatingToIntegral: { 9689 APFloat F(0.0); 9690 if (!EvaluateFloat(SubExpr, F, Info)) 9691 return false; 9692 9693 APSInt Value; 9694 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 9695 return false; 9696 return Success(Value, E); 9697 } 9698 } 9699 9700 llvm_unreachable("unknown cast resulting in integral value"); 9701 } 9702 9703 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 9704 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9705 ComplexValue LV; 9706 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 9707 return false; 9708 if (!LV.isComplexInt()) 9709 return Error(E); 9710 return Success(LV.getComplexIntReal(), E); 9711 } 9712 9713 return Visit(E->getSubExpr()); 9714 } 9715 9716 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9717 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 9718 ComplexValue LV; 9719 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 9720 return false; 9721 if (!LV.isComplexInt()) 9722 return Error(E); 9723 return Success(LV.getComplexIntImag(), E); 9724 } 9725 9726 VisitIgnoredValue(E->getSubExpr()); 9727 return Success(0, E); 9728 } 9729 9730 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 9731 return Success(E->getPackLength(), E); 9732 } 9733 9734 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 9735 return Success(E->getValue(), E); 9736 } 9737 9738 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9739 switch (E->getOpcode()) { 9740 default: 9741 // Invalid unary operators 9742 return Error(E); 9743 case UO_Plus: 9744 // The result is just the value. 9745 return Visit(E->getSubExpr()); 9746 case UO_Minus: { 9747 if (!Visit(E->getSubExpr())) return false; 9748 if (!Result.isInt()) return Error(E); 9749 const APSInt &Value = Result.getInt(); 9750 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) { 9751 SmallString<64> S; 9752 FixedPointValueToString(S, Value, 9753 Info.Ctx.getTypeInfo(E->getType()).Width); 9754 Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType(); 9755 if (Info.noteUndefinedBehavior()) return false; 9756 } 9757 return Success(-Value, E); 9758 } 9759 case UO_LNot: { 9760 bool bres; 9761 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 9762 return false; 9763 return Success(!bres, E); 9764 } 9765 } 9766 } 9767 9768 //===----------------------------------------------------------------------===// 9769 // Float Evaluation 9770 //===----------------------------------------------------------------------===// 9771 9772 namespace { 9773 class FloatExprEvaluator 9774 : public ExprEvaluatorBase<FloatExprEvaluator> { 9775 APFloat &Result; 9776 public: 9777 FloatExprEvaluator(EvalInfo &info, APFloat &result) 9778 : ExprEvaluatorBaseTy(info), Result(result) {} 9779 9780 bool Success(const APValue &V, const Expr *e) { 9781 Result = V.getFloat(); 9782 return true; 9783 } 9784 9785 bool ZeroInitialization(const Expr *E) { 9786 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 9787 return true; 9788 } 9789 9790 bool VisitCallExpr(const CallExpr *E); 9791 9792 bool VisitUnaryOperator(const UnaryOperator *E); 9793 bool VisitBinaryOperator(const BinaryOperator *E); 9794 bool VisitFloatingLiteral(const FloatingLiteral *E); 9795 bool VisitCastExpr(const CastExpr *E); 9796 9797 bool VisitUnaryReal(const UnaryOperator *E); 9798 bool VisitUnaryImag(const UnaryOperator *E); 9799 9800 // FIXME: Missing: array subscript of vector, member of vector 9801 }; 9802 } // end anonymous namespace 9803 9804 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 9805 assert(E->isRValue() && E->getType()->isRealFloatingType()); 9806 return FloatExprEvaluator(Info, Result).Visit(E); 9807 } 9808 9809 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 9810 QualType ResultTy, 9811 const Expr *Arg, 9812 bool SNaN, 9813 llvm::APFloat &Result) { 9814 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 9815 if (!S) return false; 9816 9817 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 9818 9819 llvm::APInt fill; 9820 9821 // Treat empty strings as if they were zero. 9822 if (S->getString().empty()) 9823 fill = llvm::APInt(32, 0); 9824 else if (S->getString().getAsInteger(0, fill)) 9825 return false; 9826 9827 if (Context.getTargetInfo().isNan2008()) { 9828 if (SNaN) 9829 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 9830 else 9831 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 9832 } else { 9833 // Prior to IEEE 754-2008, architectures were allowed to choose whether 9834 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 9835 // a different encoding to what became a standard in 2008, and for pre- 9836 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 9837 // sNaN. This is now known as "legacy NaN" encoding. 9838 if (SNaN) 9839 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 9840 else 9841 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 9842 } 9843 9844 return true; 9845 } 9846 9847 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 9848 switch (E->getBuiltinCallee()) { 9849 default: 9850 return ExprEvaluatorBaseTy::VisitCallExpr(E); 9851 9852 case Builtin::BI__builtin_huge_val: 9853 case Builtin::BI__builtin_huge_valf: 9854 case Builtin::BI__builtin_huge_vall: 9855 case Builtin::BI__builtin_huge_valf128: 9856 case Builtin::BI__builtin_inf: 9857 case Builtin::BI__builtin_inff: 9858 case Builtin::BI__builtin_infl: 9859 case Builtin::BI__builtin_inff128: { 9860 const llvm::fltSemantics &Sem = 9861 Info.Ctx.getFloatTypeSemantics(E->getType()); 9862 Result = llvm::APFloat::getInf(Sem); 9863 return true; 9864 } 9865 9866 case Builtin::BI__builtin_nans: 9867 case Builtin::BI__builtin_nansf: 9868 case Builtin::BI__builtin_nansl: 9869 case Builtin::BI__builtin_nansf128: 9870 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 9871 true, Result)) 9872 return Error(E); 9873 return true; 9874 9875 case Builtin::BI__builtin_nan: 9876 case Builtin::BI__builtin_nanf: 9877 case Builtin::BI__builtin_nanl: 9878 case Builtin::BI__builtin_nanf128: 9879 // If this is __builtin_nan() turn this into a nan, otherwise we 9880 // can't constant fold it. 9881 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 9882 false, Result)) 9883 return Error(E); 9884 return true; 9885 9886 case Builtin::BI__builtin_fabs: 9887 case Builtin::BI__builtin_fabsf: 9888 case Builtin::BI__builtin_fabsl: 9889 case Builtin::BI__builtin_fabsf128: 9890 if (!EvaluateFloat(E->getArg(0), Result, Info)) 9891 return false; 9892 9893 if (Result.isNegative()) 9894 Result.changeSign(); 9895 return true; 9896 9897 // FIXME: Builtin::BI__builtin_powi 9898 // FIXME: Builtin::BI__builtin_powif 9899 // FIXME: Builtin::BI__builtin_powil 9900 9901 case Builtin::BI__builtin_copysign: 9902 case Builtin::BI__builtin_copysignf: 9903 case Builtin::BI__builtin_copysignl: 9904 case Builtin::BI__builtin_copysignf128: { 9905 APFloat RHS(0.); 9906 if (!EvaluateFloat(E->getArg(0), Result, Info) || 9907 !EvaluateFloat(E->getArg(1), RHS, Info)) 9908 return false; 9909 Result.copySign(RHS); 9910 return true; 9911 } 9912 } 9913 } 9914 9915 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 9916 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9917 ComplexValue CV; 9918 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 9919 return false; 9920 Result = CV.FloatReal; 9921 return true; 9922 } 9923 9924 return Visit(E->getSubExpr()); 9925 } 9926 9927 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9928 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9929 ComplexValue CV; 9930 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 9931 return false; 9932 Result = CV.FloatImag; 9933 return true; 9934 } 9935 9936 VisitIgnoredValue(E->getSubExpr()); 9937 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 9938 Result = llvm::APFloat::getZero(Sem); 9939 return true; 9940 } 9941 9942 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9943 switch (E->getOpcode()) { 9944 default: return Error(E); 9945 case UO_Plus: 9946 return EvaluateFloat(E->getSubExpr(), Result, Info); 9947 case UO_Minus: 9948 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 9949 return false; 9950 Result.changeSign(); 9951 return true; 9952 } 9953 } 9954 9955 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9956 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 9957 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9958 9959 APFloat RHS(0.0); 9960 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 9961 if (!LHSOK && !Info.noteFailure()) 9962 return false; 9963 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 9964 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 9965 } 9966 9967 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 9968 Result = E->getValue(); 9969 return true; 9970 } 9971 9972 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 9973 const Expr* SubExpr = E->getSubExpr(); 9974 9975 switch (E->getCastKind()) { 9976 default: 9977 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9978 9979 case CK_IntegralToFloating: { 9980 APSInt IntResult; 9981 return EvaluateInteger(SubExpr, IntResult, Info) && 9982 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 9983 E->getType(), Result); 9984 } 9985 9986 case CK_FloatingCast: { 9987 if (!Visit(SubExpr)) 9988 return false; 9989 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 9990 Result); 9991 } 9992 9993 case CK_FloatingComplexToReal: { 9994 ComplexValue V; 9995 if (!EvaluateComplex(SubExpr, V, Info)) 9996 return false; 9997 Result = V.getComplexFloatReal(); 9998 return true; 9999 } 10000 } 10001 } 10002 10003 //===----------------------------------------------------------------------===// 10004 // Complex Evaluation (for float and integer) 10005 //===----------------------------------------------------------------------===// 10006 10007 namespace { 10008 class ComplexExprEvaluator 10009 : public ExprEvaluatorBase<ComplexExprEvaluator> { 10010 ComplexValue &Result; 10011 10012 public: 10013 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 10014 : ExprEvaluatorBaseTy(info), Result(Result) {} 10015 10016 bool Success(const APValue &V, const Expr *e) { 10017 Result.setFrom(V); 10018 return true; 10019 } 10020 10021 bool ZeroInitialization(const Expr *E); 10022 10023 //===--------------------------------------------------------------------===// 10024 // Visitor Methods 10025 //===--------------------------------------------------------------------===// 10026 10027 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 10028 bool VisitCastExpr(const CastExpr *E); 10029 bool VisitBinaryOperator(const BinaryOperator *E); 10030 bool VisitUnaryOperator(const UnaryOperator *E); 10031 bool VisitInitListExpr(const InitListExpr *E); 10032 }; 10033 } // end anonymous namespace 10034 10035 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 10036 EvalInfo &Info) { 10037 assert(E->isRValue() && E->getType()->isAnyComplexType()); 10038 return ComplexExprEvaluator(Info, Result).Visit(E); 10039 } 10040 10041 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 10042 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 10043 if (ElemTy->isRealFloatingType()) { 10044 Result.makeComplexFloat(); 10045 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 10046 Result.FloatReal = Zero; 10047 Result.FloatImag = Zero; 10048 } else { 10049 Result.makeComplexInt(); 10050 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 10051 Result.IntReal = Zero; 10052 Result.IntImag = Zero; 10053 } 10054 return true; 10055 } 10056 10057 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 10058 const Expr* SubExpr = E->getSubExpr(); 10059 10060 if (SubExpr->getType()->isRealFloatingType()) { 10061 Result.makeComplexFloat(); 10062 APFloat &Imag = Result.FloatImag; 10063 if (!EvaluateFloat(SubExpr, Imag, Info)) 10064 return false; 10065 10066 Result.FloatReal = APFloat(Imag.getSemantics()); 10067 return true; 10068 } else { 10069 assert(SubExpr->getType()->isIntegerType() && 10070 "Unexpected imaginary literal."); 10071 10072 Result.makeComplexInt(); 10073 APSInt &Imag = Result.IntImag; 10074 if (!EvaluateInteger(SubExpr, Imag, Info)) 10075 return false; 10076 10077 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 10078 return true; 10079 } 10080 } 10081 10082 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 10083 10084 switch (E->getCastKind()) { 10085 case CK_BitCast: 10086 case CK_BaseToDerived: 10087 case CK_DerivedToBase: 10088 case CK_UncheckedDerivedToBase: 10089 case CK_Dynamic: 10090 case CK_ToUnion: 10091 case CK_ArrayToPointerDecay: 10092 case CK_FunctionToPointerDecay: 10093 case CK_NullToPointer: 10094 case CK_NullToMemberPointer: 10095 case CK_BaseToDerivedMemberPointer: 10096 case CK_DerivedToBaseMemberPointer: 10097 case CK_MemberPointerToBoolean: 10098 case CK_ReinterpretMemberPointer: 10099 case CK_ConstructorConversion: 10100 case CK_IntegralToPointer: 10101 case CK_PointerToIntegral: 10102 case CK_PointerToBoolean: 10103 case CK_ToVoid: 10104 case CK_VectorSplat: 10105 case CK_IntegralCast: 10106 case CK_BooleanToSignedIntegral: 10107 case CK_IntegralToBoolean: 10108 case CK_IntegralToFloating: 10109 case CK_FloatingToIntegral: 10110 case CK_FloatingToBoolean: 10111 case CK_FloatingCast: 10112 case CK_CPointerToObjCPointerCast: 10113 case CK_BlockPointerToObjCPointerCast: 10114 case CK_AnyPointerToBlockPointerCast: 10115 case CK_ObjCObjectLValueCast: 10116 case CK_FloatingComplexToReal: 10117 case CK_FloatingComplexToBoolean: 10118 case CK_IntegralComplexToReal: 10119 case CK_IntegralComplexToBoolean: 10120 case CK_ARCProduceObject: 10121 case CK_ARCConsumeObject: 10122 case CK_ARCReclaimReturnedObject: 10123 case CK_ARCExtendBlockObject: 10124 case CK_CopyAndAutoreleaseBlockObject: 10125 case CK_BuiltinFnToFnPtr: 10126 case CK_ZeroToOCLOpaqueType: 10127 case CK_NonAtomicToAtomic: 10128 case CK_AddressSpaceConversion: 10129 case CK_IntToOCLSampler: 10130 case CK_FixedPointCast: 10131 case CK_FixedPointToBoolean: 10132 llvm_unreachable("invalid cast kind for complex value"); 10133 10134 case CK_LValueToRValue: 10135 case CK_AtomicToNonAtomic: 10136 case CK_NoOp: 10137 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10138 10139 case CK_Dependent: 10140 case CK_LValueBitCast: 10141 case CK_UserDefinedConversion: 10142 return Error(E); 10143 10144 case CK_FloatingRealToComplex: { 10145 APFloat &Real = Result.FloatReal; 10146 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 10147 return false; 10148 10149 Result.makeComplexFloat(); 10150 Result.FloatImag = APFloat(Real.getSemantics()); 10151 return true; 10152 } 10153 10154 case CK_FloatingComplexCast: { 10155 if (!Visit(E->getSubExpr())) 10156 return false; 10157 10158 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 10159 QualType From 10160 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 10161 10162 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 10163 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 10164 } 10165 10166 case CK_FloatingComplexToIntegralComplex: { 10167 if (!Visit(E->getSubExpr())) 10168 return false; 10169 10170 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 10171 QualType From 10172 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 10173 Result.makeComplexInt(); 10174 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 10175 To, Result.IntReal) && 10176 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 10177 To, Result.IntImag); 10178 } 10179 10180 case CK_IntegralRealToComplex: { 10181 APSInt &Real = Result.IntReal; 10182 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 10183 return false; 10184 10185 Result.makeComplexInt(); 10186 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 10187 return true; 10188 } 10189 10190 case CK_IntegralComplexCast: { 10191 if (!Visit(E->getSubExpr())) 10192 return false; 10193 10194 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 10195 QualType From 10196 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 10197 10198 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 10199 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 10200 return true; 10201 } 10202 10203 case CK_IntegralComplexToFloatingComplex: { 10204 if (!Visit(E->getSubExpr())) 10205 return false; 10206 10207 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 10208 QualType From 10209 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 10210 Result.makeComplexFloat(); 10211 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 10212 To, Result.FloatReal) && 10213 HandleIntToFloatCast(Info, E, From, Result.IntImag, 10214 To, Result.FloatImag); 10215 } 10216 } 10217 10218 llvm_unreachable("unknown cast resulting in complex value"); 10219 } 10220 10221 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10222 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 10223 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10224 10225 // Track whether the LHS or RHS is real at the type system level. When this is 10226 // the case we can simplify our evaluation strategy. 10227 bool LHSReal = false, RHSReal = false; 10228 10229 bool LHSOK; 10230 if (E->getLHS()->getType()->isRealFloatingType()) { 10231 LHSReal = true; 10232 APFloat &Real = Result.FloatReal; 10233 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 10234 if (LHSOK) { 10235 Result.makeComplexFloat(); 10236 Result.FloatImag = APFloat(Real.getSemantics()); 10237 } 10238 } else { 10239 LHSOK = Visit(E->getLHS()); 10240 } 10241 if (!LHSOK && !Info.noteFailure()) 10242 return false; 10243 10244 ComplexValue RHS; 10245 if (E->getRHS()->getType()->isRealFloatingType()) { 10246 RHSReal = true; 10247 APFloat &Real = RHS.FloatReal; 10248 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 10249 return false; 10250 RHS.makeComplexFloat(); 10251 RHS.FloatImag = APFloat(Real.getSemantics()); 10252 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 10253 return false; 10254 10255 assert(!(LHSReal && RHSReal) && 10256 "Cannot have both operands of a complex operation be real."); 10257 switch (E->getOpcode()) { 10258 default: return Error(E); 10259 case BO_Add: 10260 if (Result.isComplexFloat()) { 10261 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 10262 APFloat::rmNearestTiesToEven); 10263 if (LHSReal) 10264 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 10265 else if (!RHSReal) 10266 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 10267 APFloat::rmNearestTiesToEven); 10268 } else { 10269 Result.getComplexIntReal() += RHS.getComplexIntReal(); 10270 Result.getComplexIntImag() += RHS.getComplexIntImag(); 10271 } 10272 break; 10273 case BO_Sub: 10274 if (Result.isComplexFloat()) { 10275 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 10276 APFloat::rmNearestTiesToEven); 10277 if (LHSReal) { 10278 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 10279 Result.getComplexFloatImag().changeSign(); 10280 } else if (!RHSReal) { 10281 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 10282 APFloat::rmNearestTiesToEven); 10283 } 10284 } else { 10285 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 10286 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 10287 } 10288 break; 10289 case BO_Mul: 10290 if (Result.isComplexFloat()) { 10291 // This is an implementation of complex multiplication according to the 10292 // constraints laid out in C11 Annex G. The implemention uses the 10293 // following naming scheme: 10294 // (a + ib) * (c + id) 10295 ComplexValue LHS = Result; 10296 APFloat &A = LHS.getComplexFloatReal(); 10297 APFloat &B = LHS.getComplexFloatImag(); 10298 APFloat &C = RHS.getComplexFloatReal(); 10299 APFloat &D = RHS.getComplexFloatImag(); 10300 APFloat &ResR = Result.getComplexFloatReal(); 10301 APFloat &ResI = Result.getComplexFloatImag(); 10302 if (LHSReal) { 10303 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 10304 ResR = A * C; 10305 ResI = A * D; 10306 } else if (RHSReal) { 10307 ResR = C * A; 10308 ResI = C * B; 10309 } else { 10310 // In the fully general case, we need to handle NaNs and infinities 10311 // robustly. 10312 APFloat AC = A * C; 10313 APFloat BD = B * D; 10314 APFloat AD = A * D; 10315 APFloat BC = B * C; 10316 ResR = AC - BD; 10317 ResI = AD + BC; 10318 if (ResR.isNaN() && ResI.isNaN()) { 10319 bool Recalc = false; 10320 if (A.isInfinity() || B.isInfinity()) { 10321 A = APFloat::copySign( 10322 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 10323 B = APFloat::copySign( 10324 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 10325 if (C.isNaN()) 10326 C = APFloat::copySign(APFloat(C.getSemantics()), C); 10327 if (D.isNaN()) 10328 D = APFloat::copySign(APFloat(D.getSemantics()), D); 10329 Recalc = true; 10330 } 10331 if (C.isInfinity() || D.isInfinity()) { 10332 C = APFloat::copySign( 10333 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 10334 D = APFloat::copySign( 10335 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 10336 if (A.isNaN()) 10337 A = APFloat::copySign(APFloat(A.getSemantics()), A); 10338 if (B.isNaN()) 10339 B = APFloat::copySign(APFloat(B.getSemantics()), B); 10340 Recalc = true; 10341 } 10342 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 10343 AD.isInfinity() || BC.isInfinity())) { 10344 if (A.isNaN()) 10345 A = APFloat::copySign(APFloat(A.getSemantics()), A); 10346 if (B.isNaN()) 10347 B = APFloat::copySign(APFloat(B.getSemantics()), B); 10348 if (C.isNaN()) 10349 C = APFloat::copySign(APFloat(C.getSemantics()), C); 10350 if (D.isNaN()) 10351 D = APFloat::copySign(APFloat(D.getSemantics()), D); 10352 Recalc = true; 10353 } 10354 if (Recalc) { 10355 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 10356 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 10357 } 10358 } 10359 } 10360 } else { 10361 ComplexValue LHS = Result; 10362 Result.getComplexIntReal() = 10363 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 10364 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 10365 Result.getComplexIntImag() = 10366 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 10367 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 10368 } 10369 break; 10370 case BO_Div: 10371 if (Result.isComplexFloat()) { 10372 // This is an implementation of complex division according to the 10373 // constraints laid out in C11 Annex G. The implemention uses the 10374 // following naming scheme: 10375 // (a + ib) / (c + id) 10376 ComplexValue LHS = Result; 10377 APFloat &A = LHS.getComplexFloatReal(); 10378 APFloat &B = LHS.getComplexFloatImag(); 10379 APFloat &C = RHS.getComplexFloatReal(); 10380 APFloat &D = RHS.getComplexFloatImag(); 10381 APFloat &ResR = Result.getComplexFloatReal(); 10382 APFloat &ResI = Result.getComplexFloatImag(); 10383 if (RHSReal) { 10384 ResR = A / C; 10385 ResI = B / C; 10386 } else { 10387 if (LHSReal) { 10388 // No real optimizations we can do here, stub out with zero. 10389 B = APFloat::getZero(A.getSemantics()); 10390 } 10391 int DenomLogB = 0; 10392 APFloat MaxCD = maxnum(abs(C), abs(D)); 10393 if (MaxCD.isFinite()) { 10394 DenomLogB = ilogb(MaxCD); 10395 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 10396 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 10397 } 10398 APFloat Denom = C * C + D * D; 10399 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 10400 APFloat::rmNearestTiesToEven); 10401 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 10402 APFloat::rmNearestTiesToEven); 10403 if (ResR.isNaN() && ResI.isNaN()) { 10404 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 10405 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 10406 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 10407 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 10408 D.isFinite()) { 10409 A = APFloat::copySign( 10410 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 10411 B = APFloat::copySign( 10412 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 10413 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 10414 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 10415 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 10416 C = APFloat::copySign( 10417 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 10418 D = APFloat::copySign( 10419 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 10420 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 10421 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 10422 } 10423 } 10424 } 10425 } else { 10426 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 10427 return Error(E, diag::note_expr_divide_by_zero); 10428 10429 ComplexValue LHS = Result; 10430 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 10431 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 10432 Result.getComplexIntReal() = 10433 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 10434 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 10435 Result.getComplexIntImag() = 10436 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 10437 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 10438 } 10439 break; 10440 } 10441 10442 return true; 10443 } 10444 10445 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10446 // Get the operand value into 'Result'. 10447 if (!Visit(E->getSubExpr())) 10448 return false; 10449 10450 switch (E->getOpcode()) { 10451 default: 10452 return Error(E); 10453 case UO_Extension: 10454 return true; 10455 case UO_Plus: 10456 // The result is always just the subexpr. 10457 return true; 10458 case UO_Minus: 10459 if (Result.isComplexFloat()) { 10460 Result.getComplexFloatReal().changeSign(); 10461 Result.getComplexFloatImag().changeSign(); 10462 } 10463 else { 10464 Result.getComplexIntReal() = -Result.getComplexIntReal(); 10465 Result.getComplexIntImag() = -Result.getComplexIntImag(); 10466 } 10467 return true; 10468 case UO_Not: 10469 if (Result.isComplexFloat()) 10470 Result.getComplexFloatImag().changeSign(); 10471 else 10472 Result.getComplexIntImag() = -Result.getComplexIntImag(); 10473 return true; 10474 } 10475 } 10476 10477 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10478 if (E->getNumInits() == 2) { 10479 if (E->getType()->isComplexType()) { 10480 Result.makeComplexFloat(); 10481 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 10482 return false; 10483 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 10484 return false; 10485 } else { 10486 Result.makeComplexInt(); 10487 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 10488 return false; 10489 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 10490 return false; 10491 } 10492 return true; 10493 } 10494 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 10495 } 10496 10497 //===----------------------------------------------------------------------===// 10498 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 10499 // implicit conversion. 10500 //===----------------------------------------------------------------------===// 10501 10502 namespace { 10503 class AtomicExprEvaluator : 10504 public ExprEvaluatorBase<AtomicExprEvaluator> { 10505 const LValue *This; 10506 APValue &Result; 10507 public: 10508 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 10509 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10510 10511 bool Success(const APValue &V, const Expr *E) { 10512 Result = V; 10513 return true; 10514 } 10515 10516 bool ZeroInitialization(const Expr *E) { 10517 ImplicitValueInitExpr VIE( 10518 E->getType()->castAs<AtomicType>()->getValueType()); 10519 // For atomic-qualified class (and array) types in C++, initialize the 10520 // _Atomic-wrapped subobject directly, in-place. 10521 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 10522 : Evaluate(Result, Info, &VIE); 10523 } 10524 10525 bool VisitCastExpr(const CastExpr *E) { 10526 switch (E->getCastKind()) { 10527 default: 10528 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10529 case CK_NonAtomicToAtomic: 10530 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 10531 : Evaluate(Result, Info, E->getSubExpr()); 10532 } 10533 } 10534 }; 10535 } // end anonymous namespace 10536 10537 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 10538 EvalInfo &Info) { 10539 assert(E->isRValue() && E->getType()->isAtomicType()); 10540 return AtomicExprEvaluator(Info, This, Result).Visit(E); 10541 } 10542 10543 //===----------------------------------------------------------------------===// 10544 // Void expression evaluation, primarily for a cast to void on the LHS of a 10545 // comma operator 10546 //===----------------------------------------------------------------------===// 10547 10548 namespace { 10549 class VoidExprEvaluator 10550 : public ExprEvaluatorBase<VoidExprEvaluator> { 10551 public: 10552 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 10553 10554 bool Success(const APValue &V, const Expr *e) { return true; } 10555 10556 bool ZeroInitialization(const Expr *E) { return true; } 10557 10558 bool VisitCastExpr(const CastExpr *E) { 10559 switch (E->getCastKind()) { 10560 default: 10561 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10562 case CK_ToVoid: 10563 VisitIgnoredValue(E->getSubExpr()); 10564 return true; 10565 } 10566 } 10567 10568 bool VisitCallExpr(const CallExpr *E) { 10569 switch (E->getBuiltinCallee()) { 10570 default: 10571 return ExprEvaluatorBaseTy::VisitCallExpr(E); 10572 case Builtin::BI__assume: 10573 case Builtin::BI__builtin_assume: 10574 // The argument is not evaluated! 10575 return true; 10576 } 10577 } 10578 }; 10579 } // end anonymous namespace 10580 10581 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 10582 assert(E->isRValue() && E->getType()->isVoidType()); 10583 return VoidExprEvaluator(Info).Visit(E); 10584 } 10585 10586 //===----------------------------------------------------------------------===// 10587 // Top level Expr::EvaluateAsRValue method. 10588 //===----------------------------------------------------------------------===// 10589 10590 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 10591 // In C, function designators are not lvalues, but we evaluate them as if they 10592 // are. 10593 QualType T = E->getType(); 10594 if (E->isGLValue() || T->isFunctionType()) { 10595 LValue LV; 10596 if (!EvaluateLValue(E, LV, Info)) 10597 return false; 10598 LV.moveInto(Result); 10599 } else if (T->isVectorType()) { 10600 if (!EvaluateVector(E, Result, Info)) 10601 return false; 10602 } else if (T->isIntegralOrEnumerationType()) { 10603 if (!IntExprEvaluator(Info, Result).Visit(E)) 10604 return false; 10605 } else if (T->hasPointerRepresentation()) { 10606 LValue LV; 10607 if (!EvaluatePointer(E, LV, Info)) 10608 return false; 10609 LV.moveInto(Result); 10610 } else if (T->isRealFloatingType()) { 10611 llvm::APFloat F(0.0); 10612 if (!EvaluateFloat(E, F, Info)) 10613 return false; 10614 Result = APValue(F); 10615 } else if (T->isAnyComplexType()) { 10616 ComplexValue C; 10617 if (!EvaluateComplex(E, C, Info)) 10618 return false; 10619 C.moveInto(Result); 10620 } else if (T->isFixedPointType()) { 10621 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 10622 } else if (T->isMemberPointerType()) { 10623 MemberPtr P; 10624 if (!EvaluateMemberPointer(E, P, Info)) 10625 return false; 10626 P.moveInto(Result); 10627 return true; 10628 } else if (T->isArrayType()) { 10629 LValue LV; 10630 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 10631 if (!EvaluateArray(E, LV, Value, Info)) 10632 return false; 10633 Result = Value; 10634 } else if (T->isRecordType()) { 10635 LValue LV; 10636 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 10637 if (!EvaluateRecord(E, LV, Value, Info)) 10638 return false; 10639 Result = Value; 10640 } else if (T->isVoidType()) { 10641 if (!Info.getLangOpts().CPlusPlus11) 10642 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 10643 << E->getType(); 10644 if (!EvaluateVoid(E, Info)) 10645 return false; 10646 } else if (T->isAtomicType()) { 10647 QualType Unqual = T.getAtomicUnqualifiedType(); 10648 if (Unqual->isArrayType() || Unqual->isRecordType()) { 10649 LValue LV; 10650 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 10651 if (!EvaluateAtomic(E, &LV, Value, Info)) 10652 return false; 10653 } else { 10654 if (!EvaluateAtomic(E, nullptr, Result, Info)) 10655 return false; 10656 } 10657 } else if (Info.getLangOpts().CPlusPlus11) { 10658 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 10659 return false; 10660 } else { 10661 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10662 return false; 10663 } 10664 10665 return true; 10666 } 10667 10668 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 10669 /// cases, the in-place evaluation is essential, since later initializers for 10670 /// an object can indirectly refer to subobjects which were initialized earlier. 10671 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 10672 const Expr *E, bool AllowNonLiteralTypes) { 10673 assert(!E->isValueDependent()); 10674 10675 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 10676 return false; 10677 10678 if (E->isRValue()) { 10679 // Evaluate arrays and record types in-place, so that later initializers can 10680 // refer to earlier-initialized members of the object. 10681 QualType T = E->getType(); 10682 if (T->isArrayType()) 10683 return EvaluateArray(E, This, Result, Info); 10684 else if (T->isRecordType()) 10685 return EvaluateRecord(E, This, Result, Info); 10686 else if (T->isAtomicType()) { 10687 QualType Unqual = T.getAtomicUnqualifiedType(); 10688 if (Unqual->isArrayType() || Unqual->isRecordType()) 10689 return EvaluateAtomic(E, &This, Result, Info); 10690 } 10691 } 10692 10693 // For any other type, in-place evaluation is unimportant. 10694 return Evaluate(Result, Info, E); 10695 } 10696 10697 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 10698 /// lvalue-to-rvalue cast if it is an lvalue. 10699 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 10700 if (E->getType().isNull()) 10701 return false; 10702 10703 if (!CheckLiteralType(Info, E)) 10704 return false; 10705 10706 if (!::Evaluate(Result, Info, E)) 10707 return false; 10708 10709 if (E->isGLValue()) { 10710 LValue LV; 10711 LV.setFrom(Info.Ctx, Result); 10712 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 10713 return false; 10714 } 10715 10716 // Check this core constant expression is a constant expression. 10717 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 10718 } 10719 10720 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 10721 const ASTContext &Ctx, bool &IsConst) { 10722 // Fast-path evaluations of integer literals, since we sometimes see files 10723 // containing vast quantities of these. 10724 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 10725 Result.Val = APValue(APSInt(L->getValue(), 10726 L->getType()->isUnsignedIntegerType())); 10727 IsConst = true; 10728 return true; 10729 } 10730 10731 // This case should be rare, but we need to check it before we check on 10732 // the type below. 10733 if (Exp->getType().isNull()) { 10734 IsConst = false; 10735 return true; 10736 } 10737 10738 // FIXME: Evaluating values of large array and record types can cause 10739 // performance problems. Only do so in C++11 for now. 10740 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 10741 Exp->getType()->isRecordType()) && 10742 !Ctx.getLangOpts().CPlusPlus11) { 10743 IsConst = false; 10744 return true; 10745 } 10746 return false; 10747 } 10748 10749 10750 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 10751 /// any crazy technique (that has nothing to do with language standards) that 10752 /// we want to. If this function returns true, it returns the folded constant 10753 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 10754 /// will be applied to the result. 10755 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const { 10756 bool IsConst; 10757 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst)) 10758 return IsConst; 10759 10760 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 10761 return ::EvaluateAsRValue(Info, this, Result.Val); 10762 } 10763 10764 bool Expr::EvaluateAsBooleanCondition(bool &Result, 10765 const ASTContext &Ctx) const { 10766 EvalResult Scratch; 10767 return EvaluateAsRValue(Scratch, Ctx) && 10768 HandleConversionToBool(Scratch.Val, Result); 10769 } 10770 10771 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 10772 Expr::SideEffectsKind SEK) { 10773 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 10774 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 10775 } 10776 10777 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx, 10778 SideEffectsKind AllowSideEffects) const { 10779 if (!getType()->isIntegralOrEnumerationType()) 10780 return false; 10781 10782 EvalResult ExprResult; 10783 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() || 10784 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 10785 return false; 10786 10787 Result = ExprResult.Val.getInt(); 10788 return true; 10789 } 10790 10791 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 10792 SideEffectsKind AllowSideEffects) const { 10793 if (!getType()->isRealFloatingType()) 10794 return false; 10795 10796 EvalResult ExprResult; 10797 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() || 10798 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 10799 return false; 10800 10801 Result = ExprResult.Val.getFloat(); 10802 return true; 10803 } 10804 10805 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const { 10806 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 10807 10808 LValue LV; 10809 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects || 10810 !CheckLValueConstantExpression(Info, getExprLoc(), 10811 Ctx.getLValueReferenceType(getType()), LV, 10812 Expr::EvaluateForCodeGen)) 10813 return false; 10814 10815 LV.moveInto(Result.Val); 10816 return true; 10817 } 10818 10819 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 10820 const ASTContext &Ctx) const { 10821 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 10822 EvalInfo Info(Ctx, Result, EM); 10823 if (!::Evaluate(Result.Val, Info, this)) 10824 return false; 10825 10826 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val, 10827 Usage); 10828 } 10829 10830 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 10831 const VarDecl *VD, 10832 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 10833 // FIXME: Evaluating initializers for large array and record types can cause 10834 // performance problems. Only do so in C++11 for now. 10835 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 10836 !Ctx.getLangOpts().CPlusPlus11) 10837 return false; 10838 10839 Expr::EvalStatus EStatus; 10840 EStatus.Diag = &Notes; 10841 10842 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr() 10843 ? EvalInfo::EM_ConstantExpression 10844 : EvalInfo::EM_ConstantFold); 10845 InitInfo.setEvaluatingDecl(VD, Value); 10846 10847 LValue LVal; 10848 LVal.set(VD); 10849 10850 // C++11 [basic.start.init]p2: 10851 // Variables with static storage duration or thread storage duration shall be 10852 // zero-initialized before any other initialization takes place. 10853 // This behavior is not present in C. 10854 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && 10855 !VD->getType()->isReferenceType()) { 10856 ImplicitValueInitExpr VIE(VD->getType()); 10857 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, 10858 /*AllowNonLiteralTypes=*/true)) 10859 return false; 10860 } 10861 10862 if (!EvaluateInPlace(Value, InitInfo, LVal, this, 10863 /*AllowNonLiteralTypes=*/true) || 10864 EStatus.HasSideEffects) 10865 return false; 10866 10867 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(), 10868 Value); 10869 } 10870 10871 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 10872 /// constant folded, but discard the result. 10873 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 10874 EvalResult Result; 10875 return EvaluateAsRValue(Result, Ctx) && 10876 !hasUnacceptableSideEffect(Result, SEK); 10877 } 10878 10879 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 10880 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 10881 EvalResult EvalResult; 10882 EvalResult.Diag = Diag; 10883 bool Result = EvaluateAsRValue(EvalResult, Ctx); 10884 (void)Result; 10885 assert(Result && "Could not evaluate expression"); 10886 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer"); 10887 10888 return EvalResult.Val.getInt(); 10889 } 10890 10891 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 10892 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 10893 EvalResult EvalResult; 10894 EvalResult.Diag = Diag; 10895 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow); 10896 bool Result = ::EvaluateAsRValue(Info, this, EvalResult.Val); 10897 (void)Result; 10898 assert(Result && "Could not evaluate expression"); 10899 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer"); 10900 10901 return EvalResult.Val.getInt(); 10902 } 10903 10904 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 10905 bool IsConst; 10906 EvalResult EvalResult; 10907 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) { 10908 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow); 10909 (void)::EvaluateAsRValue(Info, this, EvalResult.Val); 10910 } 10911 } 10912 10913 bool Expr::EvalResult::isGlobalLValue() const { 10914 assert(Val.isLValue()); 10915 return IsGlobalLValue(Val.getLValueBase()); 10916 } 10917 10918 10919 /// isIntegerConstantExpr - this recursive routine will test if an expression is 10920 /// an integer constant expression. 10921 10922 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 10923 /// comma, etc 10924 10925 // CheckICE - This function does the fundamental ICE checking: the returned 10926 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 10927 // and a (possibly null) SourceLocation indicating the location of the problem. 10928 // 10929 // Note that to reduce code duplication, this helper does no evaluation 10930 // itself; the caller checks whether the expression is evaluatable, and 10931 // in the rare cases where CheckICE actually cares about the evaluated 10932 // value, it calls into Evaluate. 10933 10934 namespace { 10935 10936 enum ICEKind { 10937 /// This expression is an ICE. 10938 IK_ICE, 10939 /// This expression is not an ICE, but if it isn't evaluated, it's 10940 /// a legal subexpression for an ICE. This return value is used to handle 10941 /// the comma operator in C99 mode, and non-constant subexpressions. 10942 IK_ICEIfUnevaluated, 10943 /// This expression is not an ICE, and is not a legal subexpression for one. 10944 IK_NotICE 10945 }; 10946 10947 struct ICEDiag { 10948 ICEKind Kind; 10949 SourceLocation Loc; 10950 10951 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 10952 }; 10953 10954 } 10955 10956 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 10957 10958 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 10959 10960 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 10961 Expr::EvalResult EVResult; 10962 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects || 10963 !EVResult.Val.isInt()) 10964 return ICEDiag(IK_NotICE, E->getBeginLoc()); 10965 10966 return NoDiag(); 10967 } 10968 10969 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 10970 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 10971 if (!E->getType()->isIntegralOrEnumerationType()) 10972 return ICEDiag(IK_NotICE, E->getBeginLoc()); 10973 10974 switch (E->getStmtClass()) { 10975 #define ABSTRACT_STMT(Node) 10976 #define STMT(Node, Base) case Expr::Node##Class: 10977 #define EXPR(Node, Base) 10978 #include "clang/AST/StmtNodes.inc" 10979 case Expr::PredefinedExprClass: 10980 case Expr::FloatingLiteralClass: 10981 case Expr::ImaginaryLiteralClass: 10982 case Expr::StringLiteralClass: 10983 case Expr::ArraySubscriptExprClass: 10984 case Expr::OMPArraySectionExprClass: 10985 case Expr::MemberExprClass: 10986 case Expr::CompoundAssignOperatorClass: 10987 case Expr::CompoundLiteralExprClass: 10988 case Expr::ExtVectorElementExprClass: 10989 case Expr::DesignatedInitExprClass: 10990 case Expr::ArrayInitLoopExprClass: 10991 case Expr::ArrayInitIndexExprClass: 10992 case Expr::NoInitExprClass: 10993 case Expr::DesignatedInitUpdateExprClass: 10994 case Expr::ImplicitValueInitExprClass: 10995 case Expr::ParenListExprClass: 10996 case Expr::VAArgExprClass: 10997 case Expr::AddrLabelExprClass: 10998 case Expr::StmtExprClass: 10999 case Expr::CXXMemberCallExprClass: 11000 case Expr::CUDAKernelCallExprClass: 11001 case Expr::CXXDynamicCastExprClass: 11002 case Expr::CXXTypeidExprClass: 11003 case Expr::CXXUuidofExprClass: 11004 case Expr::MSPropertyRefExprClass: 11005 case Expr::MSPropertySubscriptExprClass: 11006 case Expr::CXXNullPtrLiteralExprClass: 11007 case Expr::UserDefinedLiteralClass: 11008 case Expr::CXXThisExprClass: 11009 case Expr::CXXThrowExprClass: 11010 case Expr::CXXNewExprClass: 11011 case Expr::CXXDeleteExprClass: 11012 case Expr::CXXPseudoDestructorExprClass: 11013 case Expr::UnresolvedLookupExprClass: 11014 case Expr::TypoExprClass: 11015 case Expr::DependentScopeDeclRefExprClass: 11016 case Expr::CXXConstructExprClass: 11017 case Expr::CXXInheritedCtorInitExprClass: 11018 case Expr::CXXStdInitializerListExprClass: 11019 case Expr::CXXBindTemporaryExprClass: 11020 case Expr::ExprWithCleanupsClass: 11021 case Expr::CXXTemporaryObjectExprClass: 11022 case Expr::CXXUnresolvedConstructExprClass: 11023 case Expr::CXXDependentScopeMemberExprClass: 11024 case Expr::UnresolvedMemberExprClass: 11025 case Expr::ObjCStringLiteralClass: 11026 case Expr::ObjCBoxedExprClass: 11027 case Expr::ObjCArrayLiteralClass: 11028 case Expr::ObjCDictionaryLiteralClass: 11029 case Expr::ObjCEncodeExprClass: 11030 case Expr::ObjCMessageExprClass: 11031 case Expr::ObjCSelectorExprClass: 11032 case Expr::ObjCProtocolExprClass: 11033 case Expr::ObjCIvarRefExprClass: 11034 case Expr::ObjCPropertyRefExprClass: 11035 case Expr::ObjCSubscriptRefExprClass: 11036 case Expr::ObjCIsaExprClass: 11037 case Expr::ObjCAvailabilityCheckExprClass: 11038 case Expr::ShuffleVectorExprClass: 11039 case Expr::ConvertVectorExprClass: 11040 case Expr::BlockExprClass: 11041 case Expr::NoStmtClass: 11042 case Expr::OpaqueValueExprClass: 11043 case Expr::PackExpansionExprClass: 11044 case Expr::SubstNonTypeTemplateParmPackExprClass: 11045 case Expr::FunctionParmPackExprClass: 11046 case Expr::AsTypeExprClass: 11047 case Expr::ObjCIndirectCopyRestoreExprClass: 11048 case Expr::MaterializeTemporaryExprClass: 11049 case Expr::PseudoObjectExprClass: 11050 case Expr::AtomicExprClass: 11051 case Expr::LambdaExprClass: 11052 case Expr::CXXFoldExprClass: 11053 case Expr::CoawaitExprClass: 11054 case Expr::DependentCoawaitExprClass: 11055 case Expr::CoyieldExprClass: 11056 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11057 11058 case Expr::InitListExprClass: { 11059 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 11060 // form "T x = { a };" is equivalent to "T x = a;". 11061 // Unless we're initializing a reference, T is a scalar as it is known to be 11062 // of integral or enumeration type. 11063 if (E->isRValue()) 11064 if (cast<InitListExpr>(E)->getNumInits() == 1) 11065 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 11066 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11067 } 11068 11069 case Expr::SizeOfPackExprClass: 11070 case Expr::GNUNullExprClass: 11071 // GCC considers the GNU __null value to be an integral constant expression. 11072 return NoDiag(); 11073 11074 case Expr::SubstNonTypeTemplateParmExprClass: 11075 return 11076 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 11077 11078 case Expr::ConstantExprClass: 11079 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 11080 11081 case Expr::ParenExprClass: 11082 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 11083 case Expr::GenericSelectionExprClass: 11084 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 11085 case Expr::IntegerLiteralClass: 11086 case Expr::FixedPointLiteralClass: 11087 case Expr::CharacterLiteralClass: 11088 case Expr::ObjCBoolLiteralExprClass: 11089 case Expr::CXXBoolLiteralExprClass: 11090 case Expr::CXXScalarValueInitExprClass: 11091 case Expr::TypeTraitExprClass: 11092 case Expr::ArrayTypeTraitExprClass: 11093 case Expr::ExpressionTraitExprClass: 11094 case Expr::CXXNoexceptExprClass: 11095 return NoDiag(); 11096 case Expr::CallExprClass: 11097 case Expr::CXXOperatorCallExprClass: { 11098 // C99 6.6/3 allows function calls within unevaluated subexpressions of 11099 // constant expressions, but they can never be ICEs because an ICE cannot 11100 // contain an operand of (pointer to) function type. 11101 const CallExpr *CE = cast<CallExpr>(E); 11102 if (CE->getBuiltinCallee()) 11103 return CheckEvalInICE(E, Ctx); 11104 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11105 } 11106 case Expr::DeclRefExprClass: { 11107 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 11108 return NoDiag(); 11109 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 11110 if (Ctx.getLangOpts().CPlusPlus && 11111 D && IsConstNonVolatile(D->getType())) { 11112 // Parameter variables are never constants. Without this check, 11113 // getAnyInitializer() can find a default argument, which leads 11114 // to chaos. 11115 if (isa<ParmVarDecl>(D)) 11116 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 11117 11118 // C++ 7.1.5.1p2 11119 // A variable of non-volatile const-qualified integral or enumeration 11120 // type initialized by an ICE can be used in ICEs. 11121 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 11122 if (!Dcl->getType()->isIntegralOrEnumerationType()) 11123 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 11124 11125 const VarDecl *VD; 11126 // Look for a declaration of this variable that has an initializer, and 11127 // check whether it is an ICE. 11128 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 11129 return NoDiag(); 11130 else 11131 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 11132 } 11133 } 11134 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11135 } 11136 case Expr::UnaryOperatorClass: { 11137 const UnaryOperator *Exp = cast<UnaryOperator>(E); 11138 switch (Exp->getOpcode()) { 11139 case UO_PostInc: 11140 case UO_PostDec: 11141 case UO_PreInc: 11142 case UO_PreDec: 11143 case UO_AddrOf: 11144 case UO_Deref: 11145 case UO_Coawait: 11146 // C99 6.6/3 allows increment and decrement within unevaluated 11147 // subexpressions of constant expressions, but they can never be ICEs 11148 // because an ICE cannot contain an lvalue operand. 11149 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11150 case UO_Extension: 11151 case UO_LNot: 11152 case UO_Plus: 11153 case UO_Minus: 11154 case UO_Not: 11155 case UO_Real: 11156 case UO_Imag: 11157 return CheckICE(Exp->getSubExpr(), Ctx); 11158 } 11159 llvm_unreachable("invalid unary operator class"); 11160 } 11161 case Expr::OffsetOfExprClass: { 11162 // Note that per C99, offsetof must be an ICE. And AFAIK, using 11163 // EvaluateAsRValue matches the proposed gcc behavior for cases like 11164 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 11165 // compliance: we should warn earlier for offsetof expressions with 11166 // array subscripts that aren't ICEs, and if the array subscripts 11167 // are ICEs, the value of the offsetof must be an integer constant. 11168 return CheckEvalInICE(E, Ctx); 11169 } 11170 case Expr::UnaryExprOrTypeTraitExprClass: { 11171 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 11172 if ((Exp->getKind() == UETT_SizeOf) && 11173 Exp->getTypeOfArgument()->isVariableArrayType()) 11174 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11175 return NoDiag(); 11176 } 11177 case Expr::BinaryOperatorClass: { 11178 const BinaryOperator *Exp = cast<BinaryOperator>(E); 11179 switch (Exp->getOpcode()) { 11180 case BO_PtrMemD: 11181 case BO_PtrMemI: 11182 case BO_Assign: 11183 case BO_MulAssign: 11184 case BO_DivAssign: 11185 case BO_RemAssign: 11186 case BO_AddAssign: 11187 case BO_SubAssign: 11188 case BO_ShlAssign: 11189 case BO_ShrAssign: 11190 case BO_AndAssign: 11191 case BO_XorAssign: 11192 case BO_OrAssign: 11193 // C99 6.6/3 allows assignments within unevaluated subexpressions of 11194 // constant expressions, but they can never be ICEs because an ICE cannot 11195 // contain an lvalue operand. 11196 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11197 11198 case BO_Mul: 11199 case BO_Div: 11200 case BO_Rem: 11201 case BO_Add: 11202 case BO_Sub: 11203 case BO_Shl: 11204 case BO_Shr: 11205 case BO_LT: 11206 case BO_GT: 11207 case BO_LE: 11208 case BO_GE: 11209 case BO_EQ: 11210 case BO_NE: 11211 case BO_And: 11212 case BO_Xor: 11213 case BO_Or: 11214 case BO_Comma: 11215 case BO_Cmp: { 11216 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 11217 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 11218 if (Exp->getOpcode() == BO_Div || 11219 Exp->getOpcode() == BO_Rem) { 11220 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 11221 // we don't evaluate one. 11222 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 11223 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 11224 if (REval == 0) 11225 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 11226 if (REval.isSigned() && REval.isAllOnesValue()) { 11227 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 11228 if (LEval.isMinSignedValue()) 11229 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 11230 } 11231 } 11232 } 11233 if (Exp->getOpcode() == BO_Comma) { 11234 if (Ctx.getLangOpts().C99) { 11235 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 11236 // if it isn't evaluated. 11237 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 11238 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 11239 } else { 11240 // In both C89 and C++, commas in ICEs are illegal. 11241 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11242 } 11243 } 11244 return Worst(LHSResult, RHSResult); 11245 } 11246 case BO_LAnd: 11247 case BO_LOr: { 11248 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 11249 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 11250 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 11251 // Rare case where the RHS has a comma "side-effect"; we need 11252 // to actually check the condition to see whether the side 11253 // with the comma is evaluated. 11254 if ((Exp->getOpcode() == BO_LAnd) != 11255 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 11256 return RHSResult; 11257 return NoDiag(); 11258 } 11259 11260 return Worst(LHSResult, RHSResult); 11261 } 11262 } 11263 llvm_unreachable("invalid binary operator kind"); 11264 } 11265 case Expr::ImplicitCastExprClass: 11266 case Expr::CStyleCastExprClass: 11267 case Expr::CXXFunctionalCastExprClass: 11268 case Expr::CXXStaticCastExprClass: 11269 case Expr::CXXReinterpretCastExprClass: 11270 case Expr::CXXConstCastExprClass: 11271 case Expr::ObjCBridgedCastExprClass: { 11272 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 11273 if (isa<ExplicitCastExpr>(E)) { 11274 if (const FloatingLiteral *FL 11275 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 11276 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 11277 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 11278 APSInt IgnoredVal(DestWidth, !DestSigned); 11279 bool Ignored; 11280 // If the value does not fit in the destination type, the behavior is 11281 // undefined, so we are not required to treat it as a constant 11282 // expression. 11283 if (FL->getValue().convertToInteger(IgnoredVal, 11284 llvm::APFloat::rmTowardZero, 11285 &Ignored) & APFloat::opInvalidOp) 11286 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11287 return NoDiag(); 11288 } 11289 } 11290 switch (cast<CastExpr>(E)->getCastKind()) { 11291 case CK_LValueToRValue: 11292 case CK_AtomicToNonAtomic: 11293 case CK_NonAtomicToAtomic: 11294 case CK_NoOp: 11295 case CK_IntegralToBoolean: 11296 case CK_IntegralCast: 11297 return CheckICE(SubExpr, Ctx); 11298 default: 11299 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11300 } 11301 } 11302 case Expr::BinaryConditionalOperatorClass: { 11303 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 11304 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 11305 if (CommonResult.Kind == IK_NotICE) return CommonResult; 11306 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 11307 if (FalseResult.Kind == IK_NotICE) return FalseResult; 11308 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 11309 if (FalseResult.Kind == IK_ICEIfUnevaluated && 11310 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 11311 return FalseResult; 11312 } 11313 case Expr::ConditionalOperatorClass: { 11314 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 11315 // If the condition (ignoring parens) is a __builtin_constant_p call, 11316 // then only the true side is actually considered in an integer constant 11317 // expression, and it is fully evaluated. This is an important GNU 11318 // extension. See GCC PR38377 for discussion. 11319 if (const CallExpr *CallCE 11320 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 11321 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 11322 return CheckEvalInICE(E, Ctx); 11323 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 11324 if (CondResult.Kind == IK_NotICE) 11325 return CondResult; 11326 11327 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 11328 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 11329 11330 if (TrueResult.Kind == IK_NotICE) 11331 return TrueResult; 11332 if (FalseResult.Kind == IK_NotICE) 11333 return FalseResult; 11334 if (CondResult.Kind == IK_ICEIfUnevaluated) 11335 return CondResult; 11336 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 11337 return NoDiag(); 11338 // Rare case where the diagnostics depend on which side is evaluated 11339 // Note that if we get here, CondResult is 0, and at least one of 11340 // TrueResult and FalseResult is non-zero. 11341 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 11342 return FalseResult; 11343 return TrueResult; 11344 } 11345 case Expr::CXXDefaultArgExprClass: 11346 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 11347 case Expr::CXXDefaultInitExprClass: 11348 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 11349 case Expr::ChooseExprClass: { 11350 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 11351 } 11352 } 11353 11354 llvm_unreachable("Invalid StmtClass!"); 11355 } 11356 11357 /// Evaluate an expression as a C++11 integral constant expression. 11358 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 11359 const Expr *E, 11360 llvm::APSInt *Value, 11361 SourceLocation *Loc) { 11362 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 11363 if (Loc) *Loc = E->getExprLoc(); 11364 return false; 11365 } 11366 11367 APValue Result; 11368 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 11369 return false; 11370 11371 if (!Result.isInt()) { 11372 if (Loc) *Loc = E->getExprLoc(); 11373 return false; 11374 } 11375 11376 if (Value) *Value = Result.getInt(); 11377 return true; 11378 } 11379 11380 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 11381 SourceLocation *Loc) const { 11382 if (Ctx.getLangOpts().CPlusPlus11) 11383 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 11384 11385 ICEDiag D = CheckICE(this, Ctx); 11386 if (D.Kind != IK_ICE) { 11387 if (Loc) *Loc = D.Loc; 11388 return false; 11389 } 11390 return true; 11391 } 11392 11393 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, 11394 SourceLocation *Loc, bool isEvaluated) const { 11395 if (Ctx.getLangOpts().CPlusPlus11) 11396 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 11397 11398 if (!isIntegerConstantExpr(Ctx, Loc)) 11399 return false; 11400 // The only possible side-effects here are due to UB discovered in the 11401 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 11402 // required to treat the expression as an ICE, so we produce the folded 11403 // value. 11404 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects)) 11405 llvm_unreachable("ICE cannot be evaluated!"); 11406 return true; 11407 } 11408 11409 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 11410 return CheckICE(this, Ctx).Kind == IK_ICE; 11411 } 11412 11413 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 11414 SourceLocation *Loc) const { 11415 // We support this checking in C++98 mode in order to diagnose compatibility 11416 // issues. 11417 assert(Ctx.getLangOpts().CPlusPlus); 11418 11419 // Build evaluation settings. 11420 Expr::EvalStatus Status; 11421 SmallVector<PartialDiagnosticAt, 8> Diags; 11422 Status.Diag = &Diags; 11423 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 11424 11425 APValue Scratch; 11426 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch); 11427 11428 if (!Diags.empty()) { 11429 IsConstExpr = false; 11430 if (Loc) *Loc = Diags[0].first; 11431 } else if (!IsConstExpr) { 11432 // FIXME: This shouldn't happen. 11433 if (Loc) *Loc = getExprLoc(); 11434 } 11435 11436 return IsConstExpr; 11437 } 11438 11439 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 11440 const FunctionDecl *Callee, 11441 ArrayRef<const Expr*> Args, 11442 const Expr *This) const { 11443 Expr::EvalStatus Status; 11444 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 11445 11446 LValue ThisVal; 11447 const LValue *ThisPtr = nullptr; 11448 if (This) { 11449 #ifndef NDEBUG 11450 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 11451 assert(MD && "Don't provide `this` for non-methods."); 11452 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 11453 #endif 11454 if (EvaluateObjectArgument(Info, This, ThisVal)) 11455 ThisPtr = &ThisVal; 11456 if (Info.EvalStatus.HasSideEffects) 11457 return false; 11458 } 11459 11460 ArgVector ArgValues(Args.size()); 11461 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 11462 I != E; ++I) { 11463 if ((*I)->isValueDependent() || 11464 !Evaluate(ArgValues[I - Args.begin()], Info, *I)) 11465 // If evaluation fails, throw away the argument entirely. 11466 ArgValues[I - Args.begin()] = APValue(); 11467 if (Info.EvalStatus.HasSideEffects) 11468 return false; 11469 } 11470 11471 // Build fake call to Callee. 11472 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 11473 ArgValues.data()); 11474 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects; 11475 } 11476 11477 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 11478 SmallVectorImpl< 11479 PartialDiagnosticAt> &Diags) { 11480 // FIXME: It would be useful to check constexpr function templates, but at the 11481 // moment the constant expression evaluator cannot cope with the non-rigorous 11482 // ASTs which we build for dependent expressions. 11483 if (FD->isDependentContext()) 11484 return true; 11485 11486 Expr::EvalStatus Status; 11487 Status.Diag = &Diags; 11488 11489 EvalInfo Info(FD->getASTContext(), Status, 11490 EvalInfo::EM_PotentialConstantExpression); 11491 11492 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 11493 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 11494 11495 // Fabricate an arbitrary expression on the stack and pretend that it 11496 // is a temporary being used as the 'this' pointer. 11497 LValue This; 11498 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 11499 This.set({&VIE, Info.CurrentCall->Index}); 11500 11501 ArrayRef<const Expr*> Args; 11502 11503 APValue Scratch; 11504 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 11505 // Evaluate the call as a constant initializer, to allow the construction 11506 // of objects of non-literal types. 11507 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 11508 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 11509 } else { 11510 SourceLocation Loc = FD->getLocation(); 11511 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 11512 Args, FD->getBody(), Info, Scratch, nullptr); 11513 } 11514 11515 return Diags.empty(); 11516 } 11517 11518 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 11519 const FunctionDecl *FD, 11520 SmallVectorImpl< 11521 PartialDiagnosticAt> &Diags) { 11522 Expr::EvalStatus Status; 11523 Status.Diag = &Diags; 11524 11525 EvalInfo Info(FD->getASTContext(), Status, 11526 EvalInfo::EM_PotentialConstantExpressionUnevaluated); 11527 11528 // Fabricate a call stack frame to give the arguments a plausible cover story. 11529 ArrayRef<const Expr*> Args; 11530 ArgVector ArgValues(0); 11531 bool Success = EvaluateArgs(Args, ArgValues, Info); 11532 (void)Success; 11533 assert(Success && 11534 "Failed to set up arguments for potential constant evaluation"); 11535 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 11536 11537 APValue ResultScratch; 11538 Evaluate(ResultScratch, Info, E); 11539 return Diags.empty(); 11540 } 11541 11542 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 11543 unsigned Type) const { 11544 if (!getType()->isPointerType()) 11545 return false; 11546 11547 Expr::EvalStatus Status; 11548 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 11549 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 11550 } 11551