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/RecordLayout.h" 43 #include "clang/AST/StmtVisitor.h" 44 #include "clang/AST/TypeLoc.h" 45 #include "clang/Basic/Builtins.h" 46 #include "clang/Basic/TargetInfo.h" 47 #include "llvm/Support/raw_ostream.h" 48 #include <cstring> 49 #include <functional> 50 51 using namespace clang; 52 using llvm::APSInt; 53 using llvm::APFloat; 54 55 static bool IsGlobalLValue(APValue::LValueBase B); 56 57 namespace { 58 struct LValue; 59 struct CallStackFrame; 60 struct EvalInfo; 61 62 static QualType getType(APValue::LValueBase B) { 63 if (!B) return QualType(); 64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) 65 return D->getType(); 66 67 const Expr *Base = B.get<const Expr*>(); 68 69 // For a materialized temporary, the type of the temporary we materialized 70 // may not be the type of the expression. 71 if (const MaterializeTemporaryExpr *MTE = 72 dyn_cast<MaterializeTemporaryExpr>(Base)) { 73 SmallVector<const Expr *, 2> CommaLHSs; 74 SmallVector<SubobjectAdjustment, 2> Adjustments; 75 const Expr *Temp = MTE->GetTemporaryExpr(); 76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 77 Adjustments); 78 // Keep any cv-qualifiers from the reference if we generated a temporary 79 // for it directly. Otherwise use the type after adjustment. 80 if (!Adjustments.empty()) 81 return Inner->getType(); 82 } 83 84 return Base->getType(); 85 } 86 87 /// Get an LValue path entry, which is known to not be an array index, as a 88 /// field or base class. 89 static 90 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) { 91 APValue::BaseOrMemberType Value; 92 Value.setFromOpaqueValue(E.BaseOrMember); 93 return Value; 94 } 95 96 /// Get an LValue path entry, which is known to not be an array index, as a 97 /// field declaration. 98 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 99 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer()); 100 } 101 /// Get an LValue path entry, which is known to not be an array index, as a 102 /// base class declaration. 103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer()); 105 } 106 /// Determine whether this LValue path entry for a base class names a virtual 107 /// base class. 108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 109 return getAsBaseOrMember(E).getInt(); 110 } 111 112 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 113 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 114 const FunctionDecl *Callee = CE->getDirectCallee(); 115 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 116 } 117 118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 119 /// This will look through a single cast. 120 /// 121 /// Returns null if we couldn't unwrap a function with alloc_size. 122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 123 if (!E->getType()->isPointerType()) 124 return nullptr; 125 126 E = E->IgnoreParens(); 127 // If we're doing a variable assignment from e.g. malloc(N), there will 128 // probably be a cast of some kind. Ignore it. 129 if (const auto *Cast = dyn_cast<CastExpr>(E)) 130 E = Cast->getSubExpr()->IgnoreParens(); 131 132 if (const auto *CE = dyn_cast<CallExpr>(E)) 133 return getAllocSizeAttr(CE) ? CE : nullptr; 134 return nullptr; 135 } 136 137 /// Determines whether or not the given Base contains a call to a function 138 /// with the alloc_size attribute. 139 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 140 const auto *E = Base.dyn_cast<const Expr *>(); 141 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 142 } 143 144 /// Determines if an LValue with the given LValueBase will have an unsized 145 /// array in its designator. 146 /// Find the path length and type of the most-derived subobject in the given 147 /// path, and find the size of the containing array, if any. 148 static unsigned 149 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 150 ArrayRef<APValue::LValuePathEntry> Path, 151 uint64_t &ArraySize, QualType &Type, bool &IsArray) { 152 // This only accepts LValueBases from APValues, and APValues don't support 153 // arrays that lack size info. 154 assert(!isBaseAnAllocSizeCall(Base) && 155 "Unsized arrays shouldn't appear here"); 156 unsigned MostDerivedLength = 0; 157 Type = getType(Base); 158 159 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 160 if (Type->isArrayType()) { 161 const ConstantArrayType *CAT = 162 cast<ConstantArrayType>(Ctx.getAsArrayType(Type)); 163 Type = CAT->getElementType(); 164 ArraySize = CAT->getSize().getZExtValue(); 165 MostDerivedLength = I + 1; 166 IsArray = true; 167 } else if (Type->isAnyComplexType()) { 168 const ComplexType *CT = Type->castAs<ComplexType>(); 169 Type = CT->getElementType(); 170 ArraySize = 2; 171 MostDerivedLength = I + 1; 172 IsArray = true; 173 } else if (const FieldDecl *FD = getAsField(Path[I])) { 174 Type = FD->getType(); 175 ArraySize = 0; 176 MostDerivedLength = I + 1; 177 IsArray = false; 178 } else { 179 // Path[I] describes a base class. 180 ArraySize = 0; 181 IsArray = false; 182 } 183 } 184 return MostDerivedLength; 185 } 186 187 // The order of this enum is important for diagnostics. 188 enum CheckSubobjectKind { 189 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex, 190 CSK_This, CSK_Real, CSK_Imag 191 }; 192 193 /// A path from a glvalue to a subobject of that glvalue. 194 struct SubobjectDesignator { 195 /// True if the subobject was named in a manner not supported by C++11. Such 196 /// lvalues can still be folded, but they are not core constant expressions 197 /// and we cannot perform lvalue-to-rvalue conversions on them. 198 unsigned Invalid : 1; 199 200 /// Is this a pointer one past the end of an object? 201 unsigned IsOnePastTheEnd : 1; 202 203 /// Indicator of whether the first entry is an unsized array. 204 unsigned FirstEntryIsAnUnsizedArray : 1; 205 206 /// Indicator of whether the most-derived object is an array element. 207 unsigned MostDerivedIsArrayElement : 1; 208 209 /// The length of the path to the most-derived object of which this is a 210 /// subobject. 211 unsigned MostDerivedPathLength : 28; 212 213 /// The size of the array of which the most-derived object is an element. 214 /// This will always be 0 if the most-derived object is not an array 215 /// element. 0 is not an indicator of whether or not the most-derived object 216 /// is an array, however, because 0-length arrays are allowed. 217 /// 218 /// If the current array is an unsized array, the value of this is 219 /// undefined. 220 uint64_t MostDerivedArraySize; 221 222 /// The type of the most derived object referred to by this address. 223 QualType MostDerivedType; 224 225 typedef APValue::LValuePathEntry PathEntry; 226 227 /// The entries on the path from the glvalue to the designated subobject. 228 SmallVector<PathEntry, 8> Entries; 229 230 SubobjectDesignator() : Invalid(true) {} 231 232 explicit SubobjectDesignator(QualType T) 233 : Invalid(false), IsOnePastTheEnd(false), 234 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 235 MostDerivedPathLength(0), MostDerivedArraySize(0), 236 MostDerivedType(T) {} 237 238 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 239 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 240 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 241 MostDerivedPathLength(0), MostDerivedArraySize(0) { 242 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 243 if (!Invalid) { 244 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 245 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 246 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 247 if (V.getLValueBase()) { 248 bool IsArray = false; 249 MostDerivedPathLength = findMostDerivedSubobject( 250 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 251 MostDerivedType, IsArray); 252 MostDerivedIsArrayElement = IsArray; 253 } 254 } 255 } 256 257 void setInvalid() { 258 Invalid = true; 259 Entries.clear(); 260 } 261 262 /// Determine whether the most derived subobject is an array without a 263 /// known bound. 264 bool isMostDerivedAnUnsizedArray() const { 265 assert(!Invalid && "Calling this makes no sense on invalid designators"); 266 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 267 } 268 269 /// Determine what the most derived array's size is. Results in an assertion 270 /// failure if the most derived array lacks a size. 271 uint64_t getMostDerivedArraySize() const { 272 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 273 return MostDerivedArraySize; 274 } 275 276 /// Determine whether this is a one-past-the-end pointer. 277 bool isOnePastTheEnd() const { 278 assert(!Invalid); 279 if (IsOnePastTheEnd) 280 return true; 281 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 282 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize) 283 return true; 284 return false; 285 } 286 287 /// Check that this refers to a valid subobject. 288 bool isValidSubobject() const { 289 if (Invalid) 290 return false; 291 return !isOnePastTheEnd(); 292 } 293 /// Check that this refers to a valid subobject, and if not, produce a 294 /// relevant diagnostic and set the designator as invalid. 295 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 296 297 /// Update this designator to refer to the first element within this array. 298 void addArrayUnchecked(const ConstantArrayType *CAT) { 299 PathEntry Entry; 300 Entry.ArrayIndex = 0; 301 Entries.push_back(Entry); 302 303 // This is a most-derived object. 304 MostDerivedType = CAT->getElementType(); 305 MostDerivedIsArrayElement = true; 306 MostDerivedArraySize = CAT->getSize().getZExtValue(); 307 MostDerivedPathLength = Entries.size(); 308 } 309 /// Update this designator to refer to the first element within the array of 310 /// elements of type T. This is an array of unknown size. 311 void addUnsizedArrayUnchecked(QualType ElemTy) { 312 PathEntry Entry; 313 Entry.ArrayIndex = 0; 314 Entries.push_back(Entry); 315 316 MostDerivedType = ElemTy; 317 MostDerivedIsArrayElement = true; 318 // The value in MostDerivedArraySize is undefined in this case. So, set it 319 // to an arbitrary value that's likely to loudly break things if it's 320 // used. 321 MostDerivedArraySize = std::numeric_limits<uint64_t>::max() / 2; 322 MostDerivedPathLength = Entries.size(); 323 } 324 /// Update this designator to refer to the given base or member of this 325 /// object. 326 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 327 PathEntry Entry; 328 APValue::BaseOrMemberType Value(D, Virtual); 329 Entry.BaseOrMember = Value.getOpaqueValue(); 330 Entries.push_back(Entry); 331 332 // If this isn't a base class, it's a new most-derived object. 333 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 334 MostDerivedType = FD->getType(); 335 MostDerivedIsArrayElement = false; 336 MostDerivedArraySize = 0; 337 MostDerivedPathLength = Entries.size(); 338 } 339 } 340 /// Update this designator to refer to the given complex component. 341 void addComplexUnchecked(QualType EltTy, bool Imag) { 342 PathEntry Entry; 343 Entry.ArrayIndex = Imag; 344 Entries.push_back(Entry); 345 346 // This is technically a most-derived object, though in practice this 347 // is unlikely to matter. 348 MostDerivedType = EltTy; 349 MostDerivedIsArrayElement = true; 350 MostDerivedArraySize = 2; 351 MostDerivedPathLength = Entries.size(); 352 } 353 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, APSInt N); 354 /// Add N to the address of this subobject. 355 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 356 if (Invalid || !N) return; 357 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 358 if (isMostDerivedAnUnsizedArray()) { 359 // Can't verify -- trust that the user is doing the right thing (or if 360 // not, trust that the caller will catch the bad behavior). 361 // FIXME: Should we reject if this overflows, at least? 362 Entries.back().ArrayIndex += TruncatedN; 363 return; 364 } 365 366 // [expr.add]p4: For the purposes of these operators, a pointer to a 367 // nonarray object behaves the same as a pointer to the first element of 368 // an array of length one with the type of the object as its element type. 369 bool IsArray = MostDerivedPathLength == Entries.size() && 370 MostDerivedIsArrayElement; 371 uint64_t ArrayIndex = 372 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd; 373 uint64_t ArraySize = 374 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 375 376 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 377 // Calculate the actual index in a wide enough type, so we can include 378 // it in the note. 379 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 380 (llvm::APInt&)N += ArrayIndex; 381 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 382 diagnosePointerArithmetic(Info, E, N); 383 setInvalid(); 384 return; 385 } 386 387 ArrayIndex += TruncatedN; 388 assert(ArrayIndex <= ArraySize && 389 "bounds check succeeded for out-of-bounds index"); 390 391 if (IsArray) 392 Entries.back().ArrayIndex = ArrayIndex; 393 else 394 IsOnePastTheEnd = (ArrayIndex != 0); 395 } 396 }; 397 398 /// A stack frame in the constexpr call stack. 399 struct CallStackFrame { 400 EvalInfo &Info; 401 402 /// Parent - The caller of this stack frame. 403 CallStackFrame *Caller; 404 405 /// Callee - The function which was called. 406 const FunctionDecl *Callee; 407 408 /// This - The binding for the this pointer in this call, if any. 409 const LValue *This; 410 411 /// Arguments - Parameter bindings for this function call, indexed by 412 /// parameters' function scope indices. 413 APValue *Arguments; 414 415 // Note that we intentionally use std::map here so that references to 416 // values are stable. 417 typedef std::map<const void*, APValue> MapTy; 418 typedef MapTy::const_iterator temp_iterator; 419 /// Temporaries - Temporary lvalues materialized within this stack frame. 420 MapTy Temporaries; 421 422 /// CallLoc - The location of the call expression for this call. 423 SourceLocation CallLoc; 424 425 /// Index - The call index of this call. 426 unsigned Index; 427 428 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 429 const FunctionDecl *Callee, const LValue *This, 430 APValue *Arguments); 431 ~CallStackFrame(); 432 433 APValue *getTemporary(const void *Key) { 434 MapTy::iterator I = Temporaries.find(Key); 435 return I == Temporaries.end() ? nullptr : &I->second; 436 } 437 APValue &createTemporary(const void *Key, bool IsLifetimeExtended); 438 }; 439 440 /// Temporarily override 'this'. 441 class ThisOverrideRAII { 442 public: 443 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 444 : Frame(Frame), OldThis(Frame.This) { 445 if (Enable) 446 Frame.This = NewThis; 447 } 448 ~ThisOverrideRAII() { 449 Frame.This = OldThis; 450 } 451 private: 452 CallStackFrame &Frame; 453 const LValue *OldThis; 454 }; 455 456 /// A partial diagnostic which we might know in advance that we are not going 457 /// to emit. 458 class OptionalDiagnostic { 459 PartialDiagnostic *Diag; 460 461 public: 462 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr) 463 : Diag(Diag) {} 464 465 template<typename T> 466 OptionalDiagnostic &operator<<(const T &v) { 467 if (Diag) 468 *Diag << v; 469 return *this; 470 } 471 472 OptionalDiagnostic &operator<<(const APSInt &I) { 473 if (Diag) { 474 SmallVector<char, 32> Buffer; 475 I.toString(Buffer); 476 *Diag << StringRef(Buffer.data(), Buffer.size()); 477 } 478 return *this; 479 } 480 481 OptionalDiagnostic &operator<<(const APFloat &F) { 482 if (Diag) { 483 // FIXME: Force the precision of the source value down so we don't 484 // print digits which are usually useless (we don't really care here if 485 // we truncate a digit by accident in edge cases). Ideally, 486 // APFloat::toString would automatically print the shortest 487 // representation which rounds to the correct value, but it's a bit 488 // tricky to implement. 489 unsigned precision = 490 llvm::APFloat::semanticsPrecision(F.getSemantics()); 491 precision = (precision * 59 + 195) / 196; 492 SmallVector<char, 32> Buffer; 493 F.toString(Buffer, precision); 494 *Diag << StringRef(Buffer.data(), Buffer.size()); 495 } 496 return *this; 497 } 498 }; 499 500 /// A cleanup, and a flag indicating whether it is lifetime-extended. 501 class Cleanup { 502 llvm::PointerIntPair<APValue*, 1, bool> Value; 503 504 public: 505 Cleanup(APValue *Val, bool IsLifetimeExtended) 506 : Value(Val, IsLifetimeExtended) {} 507 508 bool isLifetimeExtended() const { return Value.getInt(); } 509 void endLifetime() { 510 *Value.getPointer() = APValue(); 511 } 512 }; 513 514 /// EvalInfo - This is a private struct used by the evaluator to capture 515 /// information about a subexpression as it is folded. It retains information 516 /// about the AST context, but also maintains information about the folded 517 /// expression. 518 /// 519 /// If an expression could be evaluated, it is still possible it is not a C 520 /// "integer constant expression" or constant expression. If not, this struct 521 /// captures information about how and why not. 522 /// 523 /// One bit of information passed *into* the request for constant folding 524 /// indicates whether the subexpression is "evaluated" or not according to C 525 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 526 /// evaluate the expression regardless of what the RHS is, but C only allows 527 /// certain things in certain situations. 528 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo { 529 ASTContext &Ctx; 530 531 /// EvalStatus - Contains information about the evaluation. 532 Expr::EvalStatus &EvalStatus; 533 534 /// CurrentCall - The top of the constexpr call stack. 535 CallStackFrame *CurrentCall; 536 537 /// CallStackDepth - The number of calls in the call stack right now. 538 unsigned CallStackDepth; 539 540 /// NextCallIndex - The next call index to assign. 541 unsigned NextCallIndex; 542 543 /// StepsLeft - The remaining number of evaluation steps we're permitted 544 /// to perform. This is essentially a limit for the number of statements 545 /// we will evaluate. 546 unsigned StepsLeft; 547 548 /// BottomFrame - The frame in which evaluation started. This must be 549 /// initialized after CurrentCall and CallStackDepth. 550 CallStackFrame BottomFrame; 551 552 /// A stack of values whose lifetimes end at the end of some surrounding 553 /// evaluation frame. 554 llvm::SmallVector<Cleanup, 16> CleanupStack; 555 556 /// EvaluatingDecl - This is the declaration whose initializer is being 557 /// evaluated, if any. 558 APValue::LValueBase EvaluatingDecl; 559 560 /// EvaluatingDeclValue - This is the value being constructed for the 561 /// declaration whose initializer is being evaluated, if any. 562 APValue *EvaluatingDeclValue; 563 564 /// The current array initialization index, if we're performing array 565 /// initialization. 566 uint64_t ArrayInitIndex = -1; 567 568 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 569 /// notes attached to it will also be stored, otherwise they will not be. 570 bool HasActiveDiagnostic; 571 572 /// \brief Have we emitted a diagnostic explaining why we couldn't constant 573 /// fold (not just why it's not strictly a constant expression)? 574 bool HasFoldFailureDiagnostic; 575 576 /// \brief Whether or not we're currently speculatively evaluating. 577 bool IsSpeculativelyEvaluating; 578 579 enum EvaluationMode { 580 /// Evaluate as a constant expression. Stop if we find that the expression 581 /// is not a constant expression. 582 EM_ConstantExpression, 583 584 /// Evaluate as a potential constant expression. Keep going if we hit a 585 /// construct that we can't evaluate yet (because we don't yet know the 586 /// value of something) but stop if we hit something that could never be 587 /// a constant expression. 588 EM_PotentialConstantExpression, 589 590 /// Fold the expression to a constant. Stop if we hit a side-effect that 591 /// we can't model. 592 EM_ConstantFold, 593 594 /// Evaluate the expression looking for integer overflow and similar 595 /// issues. Don't worry about side-effects, and try to visit all 596 /// subexpressions. 597 EM_EvaluateForOverflow, 598 599 /// Evaluate in any way we know how. Don't worry about side-effects that 600 /// can't be modeled. 601 EM_IgnoreSideEffects, 602 603 /// Evaluate as a constant expression. Stop if we find that the expression 604 /// is not a constant expression. Some expressions can be retried in the 605 /// optimizer if we don't constant fold them here, but in an unevaluated 606 /// context we try to fold them immediately since the optimizer never 607 /// gets a chance to look at it. 608 EM_ConstantExpressionUnevaluated, 609 610 /// Evaluate as a potential constant expression. Keep going if we hit a 611 /// construct that we can't evaluate yet (because we don't yet know the 612 /// value of something) but stop if we hit something that could never be 613 /// a constant expression. Some expressions can be retried in the 614 /// optimizer if we don't constant fold them here, but in an unevaluated 615 /// context we try to fold them immediately since the optimizer never 616 /// gets a chance to look at it. 617 EM_PotentialConstantExpressionUnevaluated, 618 619 /// Evaluate as a constant expression. Continue evaluating if either: 620 /// - We find a MemberExpr with a base that can't be evaluated. 621 /// - We find a variable initialized with a call to a function that has 622 /// the alloc_size attribute on it. 623 /// In either case, the LValue returned shall have an invalid base; in the 624 /// former, the base will be the invalid MemberExpr, in the latter, the 625 /// base will be either the alloc_size CallExpr or a CastExpr wrapping 626 /// said CallExpr. 627 EM_OffsetFold, 628 } EvalMode; 629 630 /// Are we checking whether the expression is a potential constant 631 /// expression? 632 bool checkingPotentialConstantExpression() const { 633 return EvalMode == EM_PotentialConstantExpression || 634 EvalMode == EM_PotentialConstantExpressionUnevaluated; 635 } 636 637 /// Are we checking an expression for overflow? 638 // FIXME: We should check for any kind of undefined or suspicious behavior 639 // in such constructs, not just overflow. 640 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; } 641 642 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 643 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 644 CallStackDepth(0), NextCallIndex(1), 645 StepsLeft(getLangOpts().ConstexprStepLimit), 646 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 647 EvaluatingDecl((const ValueDecl *)nullptr), 648 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 649 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false), 650 EvalMode(Mode) {} 651 652 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) { 653 EvaluatingDecl = Base; 654 EvaluatingDeclValue = &Value; 655 } 656 657 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); } 658 659 bool CheckCallLimit(SourceLocation Loc) { 660 // Don't perform any constexpr calls (other than the call we're checking) 661 // when checking a potential constant expression. 662 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 663 return false; 664 if (NextCallIndex == 0) { 665 // NextCallIndex has wrapped around. 666 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 667 return false; 668 } 669 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 670 return true; 671 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 672 << getLangOpts().ConstexprCallDepth; 673 return false; 674 } 675 676 CallStackFrame *getCallFrame(unsigned CallIndex) { 677 assert(CallIndex && "no call index in getCallFrame"); 678 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 679 // be null in this loop. 680 CallStackFrame *Frame = CurrentCall; 681 while (Frame->Index > CallIndex) 682 Frame = Frame->Caller; 683 return (Frame->Index == CallIndex) ? Frame : nullptr; 684 } 685 686 bool nextStep(const Stmt *S) { 687 if (!StepsLeft) { 688 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded); 689 return false; 690 } 691 --StepsLeft; 692 return true; 693 } 694 695 private: 696 /// Add a diagnostic to the diagnostics list. 697 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) { 698 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator()); 699 EvalStatus.Diag->push_back(std::make_pair(Loc, PD)); 700 return EvalStatus.Diag->back().second; 701 } 702 703 /// Add notes containing a call stack to the current point of evaluation. 704 void addCallStack(unsigned Limit); 705 706 private: 707 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId, 708 unsigned ExtraNotes, bool IsCCEDiag) { 709 710 if (EvalStatus.Diag) { 711 // If we have a prior diagnostic, it will be noting that the expression 712 // isn't a constant expression. This diagnostic is more important, 713 // unless we require this evaluation to produce a constant expression. 714 // 715 // FIXME: We might want to show both diagnostics to the user in 716 // EM_ConstantFold mode. 717 if (!EvalStatus.Diag->empty()) { 718 switch (EvalMode) { 719 case EM_ConstantFold: 720 case EM_IgnoreSideEffects: 721 case EM_EvaluateForOverflow: 722 if (!HasFoldFailureDiagnostic) 723 break; 724 // We've already failed to fold something. Keep that diagnostic. 725 case EM_ConstantExpression: 726 case EM_PotentialConstantExpression: 727 case EM_ConstantExpressionUnevaluated: 728 case EM_PotentialConstantExpressionUnevaluated: 729 case EM_OffsetFold: 730 HasActiveDiagnostic = false; 731 return OptionalDiagnostic(); 732 } 733 } 734 735 unsigned CallStackNotes = CallStackDepth - 1; 736 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit(); 737 if (Limit) 738 CallStackNotes = std::min(CallStackNotes, Limit + 1); 739 if (checkingPotentialConstantExpression()) 740 CallStackNotes = 0; 741 742 HasActiveDiagnostic = true; 743 HasFoldFailureDiagnostic = !IsCCEDiag; 744 EvalStatus.Diag->clear(); 745 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes); 746 addDiag(Loc, DiagId); 747 if (!checkingPotentialConstantExpression()) 748 addCallStack(Limit); 749 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second); 750 } 751 HasActiveDiagnostic = false; 752 return OptionalDiagnostic(); 753 } 754 public: 755 // Diagnose that the evaluation could not be folded (FF => FoldFailure) 756 OptionalDiagnostic 757 FFDiag(SourceLocation Loc, 758 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr, 759 unsigned ExtraNotes = 0) { 760 return Diag(Loc, DiagId, ExtraNotes, false); 761 } 762 763 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId 764 = diag::note_invalid_subexpr_in_const_expr, 765 unsigned ExtraNotes = 0) { 766 if (EvalStatus.Diag) 767 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false); 768 HasActiveDiagnostic = false; 769 return OptionalDiagnostic(); 770 } 771 772 /// Diagnose that the evaluation does not produce a C++11 core constant 773 /// expression. 774 /// 775 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or 776 /// EM_PotentialConstantExpression mode and we produce one of these. 777 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId 778 = diag::note_invalid_subexpr_in_const_expr, 779 unsigned ExtraNotes = 0) { 780 // Don't override a previous diagnostic. Don't bother collecting 781 // diagnostics if we're evaluating for overflow. 782 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) { 783 HasActiveDiagnostic = false; 784 return OptionalDiagnostic(); 785 } 786 return Diag(Loc, DiagId, ExtraNotes, true); 787 } 788 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId 789 = diag::note_invalid_subexpr_in_const_expr, 790 unsigned ExtraNotes = 0) { 791 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes); 792 } 793 /// Add a note to a prior diagnostic. 794 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) { 795 if (!HasActiveDiagnostic) 796 return OptionalDiagnostic(); 797 return OptionalDiagnostic(&addDiag(Loc, DiagId)); 798 } 799 800 /// Add a stack of notes to a prior diagnostic. 801 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) { 802 if (HasActiveDiagnostic) { 803 EvalStatus.Diag->insert(EvalStatus.Diag->end(), 804 Diags.begin(), Diags.end()); 805 } 806 } 807 808 /// Should we continue evaluation after encountering a side-effect that we 809 /// couldn't model? 810 bool keepEvaluatingAfterSideEffect() { 811 switch (EvalMode) { 812 case EM_PotentialConstantExpression: 813 case EM_PotentialConstantExpressionUnevaluated: 814 case EM_EvaluateForOverflow: 815 case EM_IgnoreSideEffects: 816 return true; 817 818 case EM_ConstantExpression: 819 case EM_ConstantExpressionUnevaluated: 820 case EM_ConstantFold: 821 case EM_OffsetFold: 822 return false; 823 } 824 llvm_unreachable("Missed EvalMode case"); 825 } 826 827 /// Note that we have had a side-effect, and determine whether we should 828 /// keep evaluating. 829 bool noteSideEffect() { 830 EvalStatus.HasSideEffects = true; 831 return keepEvaluatingAfterSideEffect(); 832 } 833 834 /// Should we continue evaluation after encountering undefined behavior? 835 bool keepEvaluatingAfterUndefinedBehavior() { 836 switch (EvalMode) { 837 case EM_EvaluateForOverflow: 838 case EM_IgnoreSideEffects: 839 case EM_ConstantFold: 840 case EM_OffsetFold: 841 return true; 842 843 case EM_PotentialConstantExpression: 844 case EM_PotentialConstantExpressionUnevaluated: 845 case EM_ConstantExpression: 846 case EM_ConstantExpressionUnevaluated: 847 return false; 848 } 849 llvm_unreachable("Missed EvalMode case"); 850 } 851 852 /// Note that we hit something that was technically undefined behavior, but 853 /// that we can evaluate past it (such as signed overflow or floating-point 854 /// division by zero.) 855 bool noteUndefinedBehavior() { 856 EvalStatus.HasUndefinedBehavior = true; 857 return keepEvaluatingAfterUndefinedBehavior(); 858 } 859 860 /// Should we continue evaluation as much as possible after encountering a 861 /// construct which can't be reduced to a value? 862 bool keepEvaluatingAfterFailure() { 863 if (!StepsLeft) 864 return false; 865 866 switch (EvalMode) { 867 case EM_PotentialConstantExpression: 868 case EM_PotentialConstantExpressionUnevaluated: 869 case EM_EvaluateForOverflow: 870 return true; 871 872 case EM_ConstantExpression: 873 case EM_ConstantExpressionUnevaluated: 874 case EM_ConstantFold: 875 case EM_IgnoreSideEffects: 876 case EM_OffsetFold: 877 return false; 878 } 879 llvm_unreachable("Missed EvalMode case"); 880 } 881 882 /// Notes that we failed to evaluate an expression that other expressions 883 /// directly depend on, and determine if we should keep evaluating. This 884 /// should only be called if we actually intend to keep evaluating. 885 /// 886 /// Call noteSideEffect() instead if we may be able to ignore the value that 887 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 888 /// 889 /// (Foo(), 1) // use noteSideEffect 890 /// (Foo() || true) // use noteSideEffect 891 /// Foo() + 1 // use noteFailure 892 LLVM_NODISCARD bool noteFailure() { 893 // Failure when evaluating some expression often means there is some 894 // subexpression whose evaluation was skipped. Therefore, (because we 895 // don't track whether we skipped an expression when unwinding after an 896 // evaluation failure) every evaluation failure that bubbles up from a 897 // subexpression implies that a side-effect has potentially happened. We 898 // skip setting the HasSideEffects flag to true until we decide to 899 // continue evaluating after that point, which happens here. 900 bool KeepGoing = keepEvaluatingAfterFailure(); 901 EvalStatus.HasSideEffects |= KeepGoing; 902 return KeepGoing; 903 } 904 905 bool allowInvalidBaseExpr() const { 906 return EvalMode == EM_OffsetFold; 907 } 908 909 class ArrayInitLoopIndex { 910 EvalInfo &Info; 911 uint64_t OuterIndex; 912 913 public: 914 ArrayInitLoopIndex(EvalInfo &Info) 915 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 916 Info.ArrayInitIndex = 0; 917 } 918 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 919 920 operator uint64_t&() { return Info.ArrayInitIndex; } 921 }; 922 }; 923 924 /// Object used to treat all foldable expressions as constant expressions. 925 struct FoldConstant { 926 EvalInfo &Info; 927 bool Enabled; 928 bool HadNoPriorDiags; 929 EvalInfo::EvaluationMode OldMode; 930 931 explicit FoldConstant(EvalInfo &Info, bool Enabled) 932 : Info(Info), 933 Enabled(Enabled), 934 HadNoPriorDiags(Info.EvalStatus.Diag && 935 Info.EvalStatus.Diag->empty() && 936 !Info.EvalStatus.HasSideEffects), 937 OldMode(Info.EvalMode) { 938 if (Enabled && 939 (Info.EvalMode == EvalInfo::EM_ConstantExpression || 940 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated)) 941 Info.EvalMode = EvalInfo::EM_ConstantFold; 942 } 943 void keepDiagnostics() { Enabled = false; } 944 ~FoldConstant() { 945 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 946 !Info.EvalStatus.HasSideEffects) 947 Info.EvalStatus.Diag->clear(); 948 Info.EvalMode = OldMode; 949 } 950 }; 951 952 /// RAII object used to treat the current evaluation as the correct pointer 953 /// offset fold for the current EvalMode 954 struct FoldOffsetRAII { 955 EvalInfo &Info; 956 EvalInfo::EvaluationMode OldMode; 957 explicit FoldOffsetRAII(EvalInfo &Info) 958 : Info(Info), OldMode(Info.EvalMode) { 959 if (!Info.checkingPotentialConstantExpression()) 960 Info.EvalMode = EvalInfo::EM_OffsetFold; 961 } 962 963 ~FoldOffsetRAII() { Info.EvalMode = OldMode; } 964 }; 965 966 /// RAII object used to optionally suppress diagnostics and side-effects from 967 /// a speculative evaluation. 968 class SpeculativeEvaluationRAII { 969 /// Pair of EvalInfo, and a bit that stores whether or not we were 970 /// speculatively evaluating when we created this RAII. 971 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval; 972 Expr::EvalStatus Old; 973 974 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 975 InfoAndOldSpecEval = Other.InfoAndOldSpecEval; 976 Old = Other.Old; 977 Other.InfoAndOldSpecEval.setPointer(nullptr); 978 } 979 980 void maybeRestoreState() { 981 EvalInfo *Info = InfoAndOldSpecEval.getPointer(); 982 if (!Info) 983 return; 984 985 Info->EvalStatus = Old; 986 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt(); 987 } 988 989 public: 990 SpeculativeEvaluationRAII() = default; 991 992 SpeculativeEvaluationRAII( 993 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 994 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating), 995 Old(Info.EvalStatus) { 996 Info.EvalStatus.Diag = NewDiag; 997 Info.IsSpeculativelyEvaluating = true; 998 } 999 1000 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1001 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1002 moveFromAndCancel(std::move(Other)); 1003 } 1004 1005 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1006 maybeRestoreState(); 1007 moveFromAndCancel(std::move(Other)); 1008 return *this; 1009 } 1010 1011 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1012 }; 1013 1014 /// RAII object wrapping a full-expression or block scope, and handling 1015 /// the ending of the lifetime of temporaries created within it. 1016 template<bool IsFullExpression> 1017 class ScopeRAII { 1018 EvalInfo &Info; 1019 unsigned OldStackSize; 1020 public: 1021 ScopeRAII(EvalInfo &Info) 1022 : Info(Info), OldStackSize(Info.CleanupStack.size()) {} 1023 ~ScopeRAII() { 1024 // Body moved to a static method to encourage the compiler to inline away 1025 // instances of this class. 1026 cleanup(Info, OldStackSize); 1027 } 1028 private: 1029 static void cleanup(EvalInfo &Info, unsigned OldStackSize) { 1030 unsigned NewEnd = OldStackSize; 1031 for (unsigned I = OldStackSize, N = Info.CleanupStack.size(); 1032 I != N; ++I) { 1033 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) { 1034 // Full-expression cleanup of a lifetime-extended temporary: nothing 1035 // to do, just move this cleanup to the right place in the stack. 1036 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]); 1037 ++NewEnd; 1038 } else { 1039 // End the lifetime of the object. 1040 Info.CleanupStack[I].endLifetime(); 1041 } 1042 } 1043 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd, 1044 Info.CleanupStack.end()); 1045 } 1046 }; 1047 typedef ScopeRAII<false> BlockScopeRAII; 1048 typedef ScopeRAII<true> FullExpressionRAII; 1049 } 1050 1051 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1052 CheckSubobjectKind CSK) { 1053 if (Invalid) 1054 return false; 1055 if (isOnePastTheEnd()) { 1056 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1057 << CSK; 1058 setInvalid(); 1059 return false; 1060 } 1061 return true; 1062 } 1063 1064 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1065 const Expr *E, APSInt N) { 1066 // If we're complaining, we must be able to statically determine the size of 1067 // the most derived array. 1068 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1069 Info.CCEDiag(E, diag::note_constexpr_array_index) 1070 << N << /*array*/ 0 1071 << static_cast<unsigned>(getMostDerivedArraySize()); 1072 else 1073 Info.CCEDiag(E, diag::note_constexpr_array_index) 1074 << N << /*non-array*/ 1; 1075 setInvalid(); 1076 } 1077 1078 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1079 const FunctionDecl *Callee, const LValue *This, 1080 APValue *Arguments) 1081 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1082 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1083 Info.CurrentCall = this; 1084 ++Info.CallStackDepth; 1085 } 1086 1087 CallStackFrame::~CallStackFrame() { 1088 assert(Info.CurrentCall == this && "calls retired out of order"); 1089 --Info.CallStackDepth; 1090 Info.CurrentCall = Caller; 1091 } 1092 1093 APValue &CallStackFrame::createTemporary(const void *Key, 1094 bool IsLifetimeExtended) { 1095 APValue &Result = Temporaries[Key]; 1096 assert(Result.isUninit() && "temporary created multiple times"); 1097 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended)); 1098 return Result; 1099 } 1100 1101 static void describeCall(CallStackFrame *Frame, raw_ostream &Out); 1102 1103 void EvalInfo::addCallStack(unsigned Limit) { 1104 // Determine which calls to skip, if any. 1105 unsigned ActiveCalls = CallStackDepth - 1; 1106 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart; 1107 if (Limit && Limit < ActiveCalls) { 1108 SkipStart = Limit / 2 + Limit % 2; 1109 SkipEnd = ActiveCalls - Limit / 2; 1110 } 1111 1112 // Walk the call stack and add the diagnostics. 1113 unsigned CallIdx = 0; 1114 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame; 1115 Frame = Frame->Caller, ++CallIdx) { 1116 // Skip this call? 1117 if (CallIdx >= SkipStart && CallIdx < SkipEnd) { 1118 if (CallIdx == SkipStart) { 1119 // Note that we're skipping calls. 1120 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed) 1121 << unsigned(ActiveCalls - Limit); 1122 } 1123 continue; 1124 } 1125 1126 // Use a different note for an inheriting constructor, because from the 1127 // user's perspective it's not really a function at all. 1128 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) { 1129 if (CD->isInheritingConstructor()) { 1130 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here) 1131 << CD->getParent(); 1132 continue; 1133 } 1134 } 1135 1136 SmallVector<char, 128> Buffer; 1137 llvm::raw_svector_ostream Out(Buffer); 1138 describeCall(Frame, Out); 1139 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str(); 1140 } 1141 } 1142 1143 namespace { 1144 struct ComplexValue { 1145 private: 1146 bool IsInt; 1147 1148 public: 1149 APSInt IntReal, IntImag; 1150 APFloat FloatReal, FloatImag; 1151 1152 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1153 1154 void makeComplexFloat() { IsInt = false; } 1155 bool isComplexFloat() const { return !IsInt; } 1156 APFloat &getComplexFloatReal() { return FloatReal; } 1157 APFloat &getComplexFloatImag() { return FloatImag; } 1158 1159 void makeComplexInt() { IsInt = true; } 1160 bool isComplexInt() const { return IsInt; } 1161 APSInt &getComplexIntReal() { return IntReal; } 1162 APSInt &getComplexIntImag() { return IntImag; } 1163 1164 void moveInto(APValue &v) const { 1165 if (isComplexFloat()) 1166 v = APValue(FloatReal, FloatImag); 1167 else 1168 v = APValue(IntReal, IntImag); 1169 } 1170 void setFrom(const APValue &v) { 1171 assert(v.isComplexFloat() || v.isComplexInt()); 1172 if (v.isComplexFloat()) { 1173 makeComplexFloat(); 1174 FloatReal = v.getComplexFloatReal(); 1175 FloatImag = v.getComplexFloatImag(); 1176 } else { 1177 makeComplexInt(); 1178 IntReal = v.getComplexIntReal(); 1179 IntImag = v.getComplexIntImag(); 1180 } 1181 } 1182 }; 1183 1184 struct LValue { 1185 APValue::LValueBase Base; 1186 CharUnits Offset; 1187 unsigned InvalidBase : 1; 1188 unsigned CallIndex : 31; 1189 SubobjectDesignator Designator; 1190 bool IsNullPtr; 1191 1192 const APValue::LValueBase getLValueBase() const { return Base; } 1193 CharUnits &getLValueOffset() { return Offset; } 1194 const CharUnits &getLValueOffset() const { return Offset; } 1195 unsigned getLValueCallIndex() const { return CallIndex; } 1196 SubobjectDesignator &getLValueDesignator() { return Designator; } 1197 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1198 bool isNullPointer() const { return IsNullPtr;} 1199 1200 void moveInto(APValue &V) const { 1201 if (Designator.Invalid) 1202 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex, 1203 IsNullPtr); 1204 else { 1205 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1206 assert(!Designator.FirstEntryIsAnUnsizedArray && 1207 "Unsized array with a valid base?"); 1208 V = APValue(Base, Offset, Designator.Entries, 1209 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr); 1210 } 1211 } 1212 void setFrom(ASTContext &Ctx, const APValue &V) { 1213 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1214 Base = V.getLValueBase(); 1215 Offset = V.getLValueOffset(); 1216 InvalidBase = false; 1217 CallIndex = V.getLValueCallIndex(); 1218 Designator = SubobjectDesignator(Ctx, V); 1219 IsNullPtr = V.isNullPointer(); 1220 } 1221 1222 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false, 1223 bool IsNullPtr_ = false, uint64_t Offset_ = 0) { 1224 #ifndef NDEBUG 1225 // We only allow a few types of invalid bases. Enforce that here. 1226 if (BInvalid) { 1227 const auto *E = B.get<const Expr *>(); 1228 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1229 "Unexpected type of invalid base"); 1230 } 1231 #endif 1232 1233 Base = B; 1234 Offset = CharUnits::fromQuantity(Offset_); 1235 InvalidBase = BInvalid; 1236 CallIndex = I; 1237 Designator = SubobjectDesignator(getType(B)); 1238 IsNullPtr = IsNullPtr_; 1239 } 1240 1241 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1242 set(B, I, true); 1243 } 1244 1245 // Check that this LValue is not based on a null pointer. If it is, produce 1246 // a diagnostic and mark the designator as invalid. 1247 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1248 CheckSubobjectKind CSK) { 1249 if (Designator.Invalid) 1250 return false; 1251 if (IsNullPtr) { 1252 Info.CCEDiag(E, diag::note_constexpr_null_subobject) 1253 << CSK; 1254 Designator.setInvalid(); 1255 return false; 1256 } 1257 return true; 1258 } 1259 1260 // Check this LValue refers to an object. If not, set the designator to be 1261 // invalid and emit a diagnostic. 1262 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1263 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1264 Designator.checkSubobject(Info, E, CSK); 1265 } 1266 1267 void addDecl(EvalInfo &Info, const Expr *E, 1268 const Decl *D, bool Virtual = false) { 1269 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1270 Designator.addDeclUnchecked(D, Virtual); 1271 } 1272 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) { 1273 assert(Designator.Entries.empty() && getType(Base)->isPointerType()); 1274 assert(isBaseAnAllocSizeCall(Base) && 1275 "Only alloc_size bases can have unsized arrays"); 1276 Designator.FirstEntryIsAnUnsizedArray = true; 1277 Designator.addUnsizedArrayUnchecked(ElemTy); 1278 } 1279 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1280 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1281 Designator.addArrayUnchecked(CAT); 1282 } 1283 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1284 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1285 Designator.addComplexUnchecked(EltTy, Imag); 1286 } 1287 void clearIsNullPointer() { 1288 IsNullPtr = false; 1289 } 1290 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, APSInt Index, 1291 CharUnits ElementSize) { 1292 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1293 // but we're not required to diagnose it and it's valid in C++.) 1294 if (!Index) 1295 return; 1296 1297 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1298 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1299 // offsets. 1300 uint64_t Offset64 = Offset.getQuantity(); 1301 uint64_t ElemSize64 = ElementSize.getQuantity(); 1302 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1303 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1304 1305 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1306 Designator.adjustIndex(Info, E, Index); 1307 clearIsNullPointer(); 1308 } 1309 void adjustOffset(CharUnits N) { 1310 Offset += N; 1311 if (N.getQuantity()) 1312 clearIsNullPointer(); 1313 } 1314 }; 1315 1316 struct MemberPtr { 1317 MemberPtr() {} 1318 explicit MemberPtr(const ValueDecl *Decl) : 1319 DeclAndIsDerivedMember(Decl, false), Path() {} 1320 1321 /// The member or (direct or indirect) field referred to by this member 1322 /// pointer, or 0 if this is a null member pointer. 1323 const ValueDecl *getDecl() const { 1324 return DeclAndIsDerivedMember.getPointer(); 1325 } 1326 /// Is this actually a member of some type derived from the relevant class? 1327 bool isDerivedMember() const { 1328 return DeclAndIsDerivedMember.getInt(); 1329 } 1330 /// Get the class which the declaration actually lives in. 1331 const CXXRecordDecl *getContainingRecord() const { 1332 return cast<CXXRecordDecl>( 1333 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1334 } 1335 1336 void moveInto(APValue &V) const { 1337 V = APValue(getDecl(), isDerivedMember(), Path); 1338 } 1339 void setFrom(const APValue &V) { 1340 assert(V.isMemberPointer()); 1341 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1342 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1343 Path.clear(); 1344 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1345 Path.insert(Path.end(), P.begin(), P.end()); 1346 } 1347 1348 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1349 /// whether the member is a member of some class derived from the class type 1350 /// of the member pointer. 1351 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1352 /// Path - The path of base/derived classes from the member declaration's 1353 /// class (exclusive) to the class type of the member pointer (inclusive). 1354 SmallVector<const CXXRecordDecl*, 4> Path; 1355 1356 /// Perform a cast towards the class of the Decl (either up or down the 1357 /// hierarchy). 1358 bool castBack(const CXXRecordDecl *Class) { 1359 assert(!Path.empty()); 1360 const CXXRecordDecl *Expected; 1361 if (Path.size() >= 2) 1362 Expected = Path[Path.size() - 2]; 1363 else 1364 Expected = getContainingRecord(); 1365 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1366 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1367 // if B does not contain the original member and is not a base or 1368 // derived class of the class containing the original member, the result 1369 // of the cast is undefined. 1370 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1371 // (D::*). We consider that to be a language defect. 1372 return false; 1373 } 1374 Path.pop_back(); 1375 return true; 1376 } 1377 /// Perform a base-to-derived member pointer cast. 1378 bool castToDerived(const CXXRecordDecl *Derived) { 1379 if (!getDecl()) 1380 return true; 1381 if (!isDerivedMember()) { 1382 Path.push_back(Derived); 1383 return true; 1384 } 1385 if (!castBack(Derived)) 1386 return false; 1387 if (Path.empty()) 1388 DeclAndIsDerivedMember.setInt(false); 1389 return true; 1390 } 1391 /// Perform a derived-to-base member pointer cast. 1392 bool castToBase(const CXXRecordDecl *Base) { 1393 if (!getDecl()) 1394 return true; 1395 if (Path.empty()) 1396 DeclAndIsDerivedMember.setInt(true); 1397 if (isDerivedMember()) { 1398 Path.push_back(Base); 1399 return true; 1400 } 1401 return castBack(Base); 1402 } 1403 }; 1404 1405 /// Compare two member pointers, which are assumed to be of the same type. 1406 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1407 if (!LHS.getDecl() || !RHS.getDecl()) 1408 return !LHS.getDecl() && !RHS.getDecl(); 1409 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1410 return false; 1411 return LHS.Path == RHS.Path; 1412 } 1413 } 1414 1415 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1416 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1417 const LValue &This, const Expr *E, 1418 bool AllowNonLiteralTypes = false); 1419 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info); 1420 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info); 1421 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1422 EvalInfo &Info); 1423 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1424 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1425 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1426 EvalInfo &Info); 1427 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1428 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1429 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info); 1430 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1431 1432 //===----------------------------------------------------------------------===// 1433 // Misc utilities 1434 //===----------------------------------------------------------------------===// 1435 1436 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1437 /// preserving its value (by extending by up to one bit as needed). 1438 static void negateAsSigned(APSInt &Int) { 1439 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1440 Int = Int.extend(Int.getBitWidth() + 1); 1441 Int.setIsSigned(true); 1442 } 1443 Int = -Int; 1444 } 1445 1446 /// Produce a string describing the given constexpr call. 1447 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) { 1448 unsigned ArgIndex = 0; 1449 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) && 1450 !isa<CXXConstructorDecl>(Frame->Callee) && 1451 cast<CXXMethodDecl>(Frame->Callee)->isInstance(); 1452 1453 if (!IsMemberCall) 1454 Out << *Frame->Callee << '('; 1455 1456 if (Frame->This && IsMemberCall) { 1457 APValue Val; 1458 Frame->This->moveInto(Val); 1459 Val.printPretty(Out, Frame->Info.Ctx, 1460 Frame->This->Designator.MostDerivedType); 1461 // FIXME: Add parens around Val if needed. 1462 Out << "->" << *Frame->Callee << '('; 1463 IsMemberCall = false; 1464 } 1465 1466 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(), 1467 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) { 1468 if (ArgIndex > (unsigned)IsMemberCall) 1469 Out << ", "; 1470 1471 const ParmVarDecl *Param = *I; 1472 const APValue &Arg = Frame->Arguments[ArgIndex]; 1473 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType()); 1474 1475 if (ArgIndex == 0 && IsMemberCall) 1476 Out << "->" << *Frame->Callee << '('; 1477 } 1478 1479 Out << ')'; 1480 } 1481 1482 /// Evaluate an expression to see if it had side-effects, and discard its 1483 /// result. 1484 /// \return \c true if the caller should keep evaluating. 1485 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1486 APValue Scratch; 1487 if (!Evaluate(Scratch, Info, E)) 1488 // We don't need the value, but we might have skipped a side effect here. 1489 return Info.noteSideEffect(); 1490 return true; 1491 } 1492 1493 /// Should this call expression be treated as a string literal? 1494 static bool IsStringLiteralCall(const CallExpr *E) { 1495 unsigned Builtin = E->getBuiltinCallee(); 1496 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1497 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1498 } 1499 1500 static bool IsGlobalLValue(APValue::LValueBase B) { 1501 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1502 // constant expression of pointer type that evaluates to... 1503 1504 // ... a null pointer value, or a prvalue core constant expression of type 1505 // std::nullptr_t. 1506 if (!B) return true; 1507 1508 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1509 // ... the address of an object with static storage duration, 1510 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1511 return VD->hasGlobalStorage(); 1512 // ... the address of a function, 1513 return isa<FunctionDecl>(D); 1514 } 1515 1516 const Expr *E = B.get<const Expr*>(); 1517 switch (E->getStmtClass()) { 1518 default: 1519 return false; 1520 case Expr::CompoundLiteralExprClass: { 1521 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1522 return CLE->isFileScope() && CLE->isLValue(); 1523 } 1524 case Expr::MaterializeTemporaryExprClass: 1525 // A materialized temporary might have been lifetime-extended to static 1526 // storage duration. 1527 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1528 // A string literal has static storage duration. 1529 case Expr::StringLiteralClass: 1530 case Expr::PredefinedExprClass: 1531 case Expr::ObjCStringLiteralClass: 1532 case Expr::ObjCEncodeExprClass: 1533 case Expr::CXXTypeidExprClass: 1534 case Expr::CXXUuidofExprClass: 1535 return true; 1536 case Expr::CallExprClass: 1537 return IsStringLiteralCall(cast<CallExpr>(E)); 1538 // For GCC compatibility, &&label has static storage duration. 1539 case Expr::AddrLabelExprClass: 1540 return true; 1541 // A Block literal expression may be used as the initialization value for 1542 // Block variables at global or local static scope. 1543 case Expr::BlockExprClass: 1544 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1545 case Expr::ImplicitValueInitExprClass: 1546 // FIXME: 1547 // We can never form an lvalue with an implicit value initialization as its 1548 // base through expression evaluation, so these only appear in one case: the 1549 // implicit variable declaration we invent when checking whether a constexpr 1550 // constructor can produce a constant expression. We must assume that such 1551 // an expression might be a global lvalue. 1552 return true; 1553 } 1554 } 1555 1556 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1557 assert(Base && "no location for a null lvalue"); 1558 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1559 if (VD) 1560 Info.Note(VD->getLocation(), diag::note_declared_at); 1561 else 1562 Info.Note(Base.get<const Expr*>()->getExprLoc(), 1563 diag::note_constexpr_temporary_here); 1564 } 1565 1566 /// Check that this reference or pointer core constant expression is a valid 1567 /// value for an address or reference constant expression. Return true if we 1568 /// can fold this expression, whether or not it's a constant expression. 1569 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 1570 QualType Type, const LValue &LVal) { 1571 bool IsReferenceType = Type->isReferenceType(); 1572 1573 APValue::LValueBase Base = LVal.getLValueBase(); 1574 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 1575 1576 // Check that the object is a global. Note that the fake 'this' object we 1577 // manufacture when checking potential constant expressions is conservatively 1578 // assumed to be global here. 1579 if (!IsGlobalLValue(Base)) { 1580 if (Info.getLangOpts().CPlusPlus11) { 1581 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1582 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 1583 << IsReferenceType << !Designator.Entries.empty() 1584 << !!VD << VD; 1585 NoteLValueLocation(Info, Base); 1586 } else { 1587 Info.FFDiag(Loc); 1588 } 1589 // Don't allow references to temporaries to escape. 1590 return false; 1591 } 1592 assert((Info.checkingPotentialConstantExpression() || 1593 LVal.getLValueCallIndex() == 0) && 1594 "have call index for global lvalue"); 1595 1596 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 1597 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 1598 // Check if this is a thread-local variable. 1599 if (Var->getTLSKind()) 1600 return false; 1601 1602 // A dllimport variable never acts like a constant. 1603 if (Var->hasAttr<DLLImportAttr>()) 1604 return false; 1605 } 1606 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 1607 // __declspec(dllimport) must be handled very carefully: 1608 // We must never initialize an expression with the thunk in C++. 1609 // Doing otherwise would allow the same id-expression to yield 1610 // different addresses for the same function in different translation 1611 // units. However, this means that we must dynamically initialize the 1612 // expression with the contents of the import address table at runtime. 1613 // 1614 // The C language has no notion of ODR; furthermore, it has no notion of 1615 // dynamic initialization. This means that we are permitted to 1616 // perform initialization with the address of the thunk. 1617 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>()) 1618 return false; 1619 } 1620 } 1621 1622 // Allow address constant expressions to be past-the-end pointers. This is 1623 // an extension: the standard requires them to point to an object. 1624 if (!IsReferenceType) 1625 return true; 1626 1627 // A reference constant expression must refer to an object. 1628 if (!Base) { 1629 // FIXME: diagnostic 1630 Info.CCEDiag(Loc); 1631 return true; 1632 } 1633 1634 // Does this refer one past the end of some object? 1635 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 1636 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1637 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 1638 << !Designator.Entries.empty() << !!VD << VD; 1639 NoteLValueLocation(Info, Base); 1640 } 1641 1642 return true; 1643 } 1644 1645 /// Check that this core constant expression is of literal type, and if not, 1646 /// produce an appropriate diagnostic. 1647 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 1648 const LValue *This = nullptr) { 1649 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 1650 return true; 1651 1652 // C++1y: A constant initializer for an object o [...] may also invoke 1653 // constexpr constructors for o and its subobjects even if those objects 1654 // are of non-literal class types. 1655 // 1656 // C++11 missed this detail for aggregates, so classes like this: 1657 // struct foo_t { union { int i; volatile int j; } u; }; 1658 // are not (obviously) initializable like so: 1659 // __attribute__((__require_constant_initialization__)) 1660 // static const foo_t x = {{0}}; 1661 // because "i" is a subobject with non-literal initialization (due to the 1662 // volatile member of the union). See: 1663 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 1664 // Therefore, we use the C++1y behavior. 1665 if (This && Info.EvaluatingDecl == This->getLValueBase()) 1666 return true; 1667 1668 // Prvalue constant expressions must be of literal types. 1669 if (Info.getLangOpts().CPlusPlus11) 1670 Info.FFDiag(E, diag::note_constexpr_nonliteral) 1671 << E->getType(); 1672 else 1673 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 1674 return false; 1675 } 1676 1677 /// Check that this core constant expression value is a valid value for a 1678 /// constant expression. If not, report an appropriate diagnostic. Does not 1679 /// check that the expression is of literal type. 1680 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 1681 QualType Type, const APValue &Value) { 1682 if (Value.isUninit()) { 1683 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 1684 << true << Type; 1685 return false; 1686 } 1687 1688 // We allow _Atomic(T) to be initialized from anything that T can be 1689 // initialized from. 1690 if (const AtomicType *AT = Type->getAs<AtomicType>()) 1691 Type = AT->getValueType(); 1692 1693 // Core issue 1454: For a literal constant expression of array or class type, 1694 // each subobject of its value shall have been initialized by a constant 1695 // expression. 1696 if (Value.isArray()) { 1697 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 1698 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 1699 if (!CheckConstantExpression(Info, DiagLoc, EltTy, 1700 Value.getArrayInitializedElt(I))) 1701 return false; 1702 } 1703 if (!Value.hasArrayFiller()) 1704 return true; 1705 return CheckConstantExpression(Info, DiagLoc, EltTy, 1706 Value.getArrayFiller()); 1707 } 1708 if (Value.isUnion() && Value.getUnionField()) { 1709 return CheckConstantExpression(Info, DiagLoc, 1710 Value.getUnionField()->getType(), 1711 Value.getUnionValue()); 1712 } 1713 if (Value.isStruct()) { 1714 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 1715 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 1716 unsigned BaseIndex = 0; 1717 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 1718 End = CD->bases_end(); I != End; ++I, ++BaseIndex) { 1719 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 1720 Value.getStructBase(BaseIndex))) 1721 return false; 1722 } 1723 } 1724 for (const auto *I : RD->fields()) { 1725 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 1726 Value.getStructField(I->getFieldIndex()))) 1727 return false; 1728 } 1729 } 1730 1731 if (Value.isLValue()) { 1732 LValue LVal; 1733 LVal.setFrom(Info.Ctx, Value); 1734 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal); 1735 } 1736 1737 // Everything else is fine. 1738 return true; 1739 } 1740 1741 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1742 return LVal.Base.dyn_cast<const ValueDecl*>(); 1743 } 1744 1745 static bool IsLiteralLValue(const LValue &Value) { 1746 if (Value.CallIndex) 1747 return false; 1748 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1749 return E && !isa<MaterializeTemporaryExpr>(E); 1750 } 1751 1752 static bool IsWeakLValue(const LValue &Value) { 1753 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1754 return Decl && Decl->isWeak(); 1755 } 1756 1757 static bool isZeroSized(const LValue &Value) { 1758 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1759 if (Decl && isa<VarDecl>(Decl)) { 1760 QualType Ty = Decl->getType(); 1761 if (Ty->isArrayType()) 1762 return Ty->isIncompleteType() || 1763 Decl->getASTContext().getTypeSize(Ty) == 0; 1764 } 1765 return false; 1766 } 1767 1768 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 1769 // A null base expression indicates a null pointer. These are always 1770 // evaluatable, and they are false unless the offset is zero. 1771 if (!Value.getLValueBase()) { 1772 Result = !Value.getLValueOffset().isZero(); 1773 return true; 1774 } 1775 1776 // We have a non-null base. These are generally known to be true, but if it's 1777 // a weak declaration it can be null at runtime. 1778 Result = true; 1779 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 1780 return !Decl || !Decl->isWeak(); 1781 } 1782 1783 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 1784 switch (Val.getKind()) { 1785 case APValue::Uninitialized: 1786 return false; 1787 case APValue::Int: 1788 Result = Val.getInt().getBoolValue(); 1789 return true; 1790 case APValue::Float: 1791 Result = !Val.getFloat().isZero(); 1792 return true; 1793 case APValue::ComplexInt: 1794 Result = Val.getComplexIntReal().getBoolValue() || 1795 Val.getComplexIntImag().getBoolValue(); 1796 return true; 1797 case APValue::ComplexFloat: 1798 Result = !Val.getComplexFloatReal().isZero() || 1799 !Val.getComplexFloatImag().isZero(); 1800 return true; 1801 case APValue::LValue: 1802 return EvalPointerValueAsBool(Val, Result); 1803 case APValue::MemberPointer: 1804 Result = Val.getMemberPointerDecl(); 1805 return true; 1806 case APValue::Vector: 1807 case APValue::Array: 1808 case APValue::Struct: 1809 case APValue::Union: 1810 case APValue::AddrLabelDiff: 1811 return false; 1812 } 1813 1814 llvm_unreachable("unknown APValue kind"); 1815 } 1816 1817 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 1818 EvalInfo &Info) { 1819 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 1820 APValue Val; 1821 if (!Evaluate(Val, Info, E)) 1822 return false; 1823 return HandleConversionToBool(Val, Result); 1824 } 1825 1826 template<typename T> 1827 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 1828 const T &SrcValue, QualType DestType) { 1829 Info.CCEDiag(E, diag::note_constexpr_overflow) 1830 << SrcValue << DestType; 1831 return Info.noteUndefinedBehavior(); 1832 } 1833 1834 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 1835 QualType SrcType, const APFloat &Value, 1836 QualType DestType, APSInt &Result) { 1837 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 1838 // Determine whether we are converting to unsigned or signed. 1839 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 1840 1841 Result = APSInt(DestWidth, !DestSigned); 1842 bool ignored; 1843 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 1844 & APFloat::opInvalidOp) 1845 return HandleOverflow(Info, E, Value, DestType); 1846 return true; 1847 } 1848 1849 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 1850 QualType SrcType, QualType DestType, 1851 APFloat &Result) { 1852 APFloat Value = Result; 1853 bool ignored; 1854 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 1855 APFloat::rmNearestTiesToEven, &ignored) 1856 & APFloat::opOverflow) 1857 return HandleOverflow(Info, E, Value, DestType); 1858 return true; 1859 } 1860 1861 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 1862 QualType DestType, QualType SrcType, 1863 const APSInt &Value) { 1864 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 1865 APSInt Result = Value; 1866 // Figure out if this is a truncate, extend or noop cast. 1867 // If the input is signed, do a sign extend, noop, or truncate. 1868 Result = Result.extOrTrunc(DestWidth); 1869 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 1870 return Result; 1871 } 1872 1873 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 1874 QualType SrcType, const APSInt &Value, 1875 QualType DestType, APFloat &Result) { 1876 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 1877 if (Result.convertFromAPInt(Value, Value.isSigned(), 1878 APFloat::rmNearestTiesToEven) 1879 & APFloat::opOverflow) 1880 return HandleOverflow(Info, E, Value, DestType); 1881 return true; 1882 } 1883 1884 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 1885 APValue &Value, const FieldDecl *FD) { 1886 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 1887 1888 if (!Value.isInt()) { 1889 // Trying to store a pointer-cast-to-integer into a bitfield. 1890 // FIXME: In this case, we should provide the diagnostic for casting 1891 // a pointer to an integer. 1892 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 1893 Info.FFDiag(E); 1894 return false; 1895 } 1896 1897 APSInt &Int = Value.getInt(); 1898 unsigned OldBitWidth = Int.getBitWidth(); 1899 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 1900 if (NewBitWidth < OldBitWidth) 1901 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 1902 return true; 1903 } 1904 1905 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 1906 llvm::APInt &Res) { 1907 APValue SVal; 1908 if (!Evaluate(SVal, Info, E)) 1909 return false; 1910 if (SVal.isInt()) { 1911 Res = SVal.getInt(); 1912 return true; 1913 } 1914 if (SVal.isFloat()) { 1915 Res = SVal.getFloat().bitcastToAPInt(); 1916 return true; 1917 } 1918 if (SVal.isVector()) { 1919 QualType VecTy = E->getType(); 1920 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 1921 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 1922 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 1923 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 1924 Res = llvm::APInt::getNullValue(VecSize); 1925 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 1926 APValue &Elt = SVal.getVectorElt(i); 1927 llvm::APInt EltAsInt; 1928 if (Elt.isInt()) { 1929 EltAsInt = Elt.getInt(); 1930 } else if (Elt.isFloat()) { 1931 EltAsInt = Elt.getFloat().bitcastToAPInt(); 1932 } else { 1933 // Don't try to handle vectors of anything other than int or float 1934 // (not sure if it's possible to hit this case). 1935 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 1936 return false; 1937 } 1938 unsigned BaseEltSize = EltAsInt.getBitWidth(); 1939 if (BigEndian) 1940 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 1941 else 1942 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 1943 } 1944 return true; 1945 } 1946 // Give up if the input isn't an int, float, or vector. For example, we 1947 // reject "(v4i16)(intptr_t)&a". 1948 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 1949 return false; 1950 } 1951 1952 /// Perform the given integer operation, which is known to need at most BitWidth 1953 /// bits, and check for overflow in the original type (if that type was not an 1954 /// unsigned type). 1955 template<typename Operation> 1956 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 1957 const APSInt &LHS, const APSInt &RHS, 1958 unsigned BitWidth, Operation Op, 1959 APSInt &Result) { 1960 if (LHS.isUnsigned()) { 1961 Result = Op(LHS, RHS); 1962 return true; 1963 } 1964 1965 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 1966 Result = Value.trunc(LHS.getBitWidth()); 1967 if (Result.extend(BitWidth) != Value) { 1968 if (Info.checkingForOverflow()) 1969 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 1970 diag::warn_integer_constant_overflow) 1971 << Result.toString(10) << E->getType(); 1972 else 1973 return HandleOverflow(Info, E, Value, E->getType()); 1974 } 1975 return true; 1976 } 1977 1978 /// Perform the given binary integer operation. 1979 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 1980 BinaryOperatorKind Opcode, APSInt RHS, 1981 APSInt &Result) { 1982 switch (Opcode) { 1983 default: 1984 Info.FFDiag(E); 1985 return false; 1986 case BO_Mul: 1987 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 1988 std::multiplies<APSInt>(), Result); 1989 case BO_Add: 1990 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 1991 std::plus<APSInt>(), Result); 1992 case BO_Sub: 1993 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 1994 std::minus<APSInt>(), Result); 1995 case BO_And: Result = LHS & RHS; return true; 1996 case BO_Xor: Result = LHS ^ RHS; return true; 1997 case BO_Or: Result = LHS | RHS; return true; 1998 case BO_Div: 1999 case BO_Rem: 2000 if (RHS == 0) { 2001 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2002 return false; 2003 } 2004 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2005 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2006 // this operation and gives the two's complement result. 2007 if (RHS.isNegative() && RHS.isAllOnesValue() && 2008 LHS.isSigned() && LHS.isMinSignedValue()) 2009 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2010 E->getType()); 2011 return true; 2012 case BO_Shl: { 2013 if (Info.getLangOpts().OpenCL) 2014 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2015 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2016 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2017 RHS.isUnsigned()); 2018 else if (RHS.isSigned() && RHS.isNegative()) { 2019 // During constant-folding, a negative shift is an opposite shift. Such 2020 // a shift is not a constant expression. 2021 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2022 RHS = -RHS; 2023 goto shift_right; 2024 } 2025 shift_left: 2026 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2027 // the shifted type. 2028 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2029 if (SA != RHS) { 2030 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2031 << RHS << E->getType() << LHS.getBitWidth(); 2032 } else if (LHS.isSigned()) { 2033 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2034 // operand, and must not overflow the corresponding unsigned type. 2035 if (LHS.isNegative()) 2036 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2037 else if (LHS.countLeadingZeros() < SA) 2038 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2039 } 2040 Result = LHS << SA; 2041 return true; 2042 } 2043 case BO_Shr: { 2044 if (Info.getLangOpts().OpenCL) 2045 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2046 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2047 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2048 RHS.isUnsigned()); 2049 else if (RHS.isSigned() && RHS.isNegative()) { 2050 // During constant-folding, a negative shift is an opposite shift. Such a 2051 // shift is not a constant expression. 2052 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2053 RHS = -RHS; 2054 goto shift_left; 2055 } 2056 shift_right: 2057 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2058 // shifted type. 2059 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2060 if (SA != RHS) 2061 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2062 << RHS << E->getType() << LHS.getBitWidth(); 2063 Result = LHS >> SA; 2064 return true; 2065 } 2066 2067 case BO_LT: Result = LHS < RHS; return true; 2068 case BO_GT: Result = LHS > RHS; return true; 2069 case BO_LE: Result = LHS <= RHS; return true; 2070 case BO_GE: Result = LHS >= RHS; return true; 2071 case BO_EQ: Result = LHS == RHS; return true; 2072 case BO_NE: Result = LHS != RHS; return true; 2073 } 2074 } 2075 2076 /// Perform the given binary floating-point operation, in-place, on LHS. 2077 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2078 APFloat &LHS, BinaryOperatorKind Opcode, 2079 const APFloat &RHS) { 2080 switch (Opcode) { 2081 default: 2082 Info.FFDiag(E); 2083 return false; 2084 case BO_Mul: 2085 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2086 break; 2087 case BO_Add: 2088 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2089 break; 2090 case BO_Sub: 2091 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2092 break; 2093 case BO_Div: 2094 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2095 break; 2096 } 2097 2098 if (LHS.isInfinity() || LHS.isNaN()) { 2099 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2100 return Info.noteUndefinedBehavior(); 2101 } 2102 return true; 2103 } 2104 2105 /// Cast an lvalue referring to a base subobject to a derived class, by 2106 /// truncating the lvalue's path to the given length. 2107 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2108 const RecordDecl *TruncatedType, 2109 unsigned TruncatedElements) { 2110 SubobjectDesignator &D = Result.Designator; 2111 2112 // Check we actually point to a derived class object. 2113 if (TruncatedElements == D.Entries.size()) 2114 return true; 2115 assert(TruncatedElements >= D.MostDerivedPathLength && 2116 "not casting to a derived class"); 2117 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2118 return false; 2119 2120 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2121 const RecordDecl *RD = TruncatedType; 2122 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2123 if (RD->isInvalidDecl()) return false; 2124 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2125 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2126 if (isVirtualBaseClass(D.Entries[I])) 2127 Result.Offset -= Layout.getVBaseClassOffset(Base); 2128 else 2129 Result.Offset -= Layout.getBaseClassOffset(Base); 2130 RD = Base; 2131 } 2132 D.Entries.resize(TruncatedElements); 2133 return true; 2134 } 2135 2136 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2137 const CXXRecordDecl *Derived, 2138 const CXXRecordDecl *Base, 2139 const ASTRecordLayout *RL = nullptr) { 2140 if (!RL) { 2141 if (Derived->isInvalidDecl()) return false; 2142 RL = &Info.Ctx.getASTRecordLayout(Derived); 2143 } 2144 2145 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2146 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2147 return true; 2148 } 2149 2150 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2151 const CXXRecordDecl *DerivedDecl, 2152 const CXXBaseSpecifier *Base) { 2153 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2154 2155 if (!Base->isVirtual()) 2156 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2157 2158 SubobjectDesignator &D = Obj.Designator; 2159 if (D.Invalid) 2160 return false; 2161 2162 // Extract most-derived object and corresponding type. 2163 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2164 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2165 return false; 2166 2167 // Find the virtual base class. 2168 if (DerivedDecl->isInvalidDecl()) return false; 2169 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2170 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2171 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2172 return true; 2173 } 2174 2175 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2176 QualType Type, LValue &Result) { 2177 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2178 PathE = E->path_end(); 2179 PathI != PathE; ++PathI) { 2180 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2181 *PathI)) 2182 return false; 2183 Type = (*PathI)->getType(); 2184 } 2185 return true; 2186 } 2187 2188 /// Update LVal to refer to the given field, which must be a member of the type 2189 /// currently described by LVal. 2190 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2191 const FieldDecl *FD, 2192 const ASTRecordLayout *RL = nullptr) { 2193 if (!RL) { 2194 if (FD->getParent()->isInvalidDecl()) return false; 2195 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2196 } 2197 2198 unsigned I = FD->getFieldIndex(); 2199 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2200 LVal.addDecl(Info, E, FD); 2201 return true; 2202 } 2203 2204 /// Update LVal to refer to the given indirect field. 2205 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2206 LValue &LVal, 2207 const IndirectFieldDecl *IFD) { 2208 for (const auto *C : IFD->chain()) 2209 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2210 return false; 2211 return true; 2212 } 2213 2214 /// Get the size of the given type in char units. 2215 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2216 QualType Type, CharUnits &Size) { 2217 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2218 // extension. 2219 if (Type->isVoidType() || Type->isFunctionType()) { 2220 Size = CharUnits::One(); 2221 return true; 2222 } 2223 2224 if (Type->isDependentType()) { 2225 Info.FFDiag(Loc); 2226 return false; 2227 } 2228 2229 if (!Type->isConstantSizeType()) { 2230 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2231 // FIXME: Better diagnostic. 2232 Info.FFDiag(Loc); 2233 return false; 2234 } 2235 2236 Size = Info.Ctx.getTypeSizeInChars(Type); 2237 return true; 2238 } 2239 2240 /// Update a pointer value to model pointer arithmetic. 2241 /// \param Info - Information about the ongoing evaluation. 2242 /// \param E - The expression being evaluated, for diagnostic purposes. 2243 /// \param LVal - The pointer value to be updated. 2244 /// \param EltTy - The pointee type represented by LVal. 2245 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2246 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2247 LValue &LVal, QualType EltTy, 2248 APSInt Adjustment) { 2249 CharUnits SizeOfPointee; 2250 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2251 return false; 2252 2253 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2254 return true; 2255 } 2256 2257 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2258 LValue &LVal, QualType EltTy, 2259 int64_t Adjustment) { 2260 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 2261 APSInt::get(Adjustment)); 2262 } 2263 2264 /// Update an lvalue to refer to a component of a complex number. 2265 /// \param Info - Information about the ongoing evaluation. 2266 /// \param LVal - The lvalue to be updated. 2267 /// \param EltTy - The complex number's component type. 2268 /// \param Imag - False for the real component, true for the imaginary. 2269 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 2270 LValue &LVal, QualType EltTy, 2271 bool Imag) { 2272 if (Imag) { 2273 CharUnits SizeOfComponent; 2274 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 2275 return false; 2276 LVal.Offset += SizeOfComponent; 2277 } 2278 LVal.addComplex(Info, E, EltTy, Imag); 2279 return true; 2280 } 2281 2282 /// Try to evaluate the initializer for a variable declaration. 2283 /// 2284 /// \param Info Information about the ongoing evaluation. 2285 /// \param E An expression to be used when printing diagnostics. 2286 /// \param VD The variable whose initializer should be obtained. 2287 /// \param Frame The frame in which the variable was created. Must be null 2288 /// if this variable is not local to the evaluation. 2289 /// \param Result Filled in with a pointer to the value of the variable. 2290 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 2291 const VarDecl *VD, CallStackFrame *Frame, 2292 APValue *&Result) { 2293 // If this is a parameter to an active constexpr function call, perform 2294 // argument substitution. 2295 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 2296 // Assume arguments of a potential constant expression are unknown 2297 // constant expressions. 2298 if (Info.checkingPotentialConstantExpression()) 2299 return false; 2300 if (!Frame || !Frame->Arguments) { 2301 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2302 return false; 2303 } 2304 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 2305 return true; 2306 } 2307 2308 // If this is a local variable, dig out its value. 2309 if (Frame) { 2310 Result = Frame->getTemporary(VD); 2311 if (!Result) { 2312 // Assume variables referenced within a lambda's call operator that were 2313 // not declared within the call operator are captures and during checking 2314 // of a potential constant expression, assume they are unknown constant 2315 // expressions. 2316 assert(isLambdaCallOperator(Frame->Callee) && 2317 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 2318 "missing value for local variable"); 2319 if (Info.checkingPotentialConstantExpression()) 2320 return false; 2321 // FIXME: implement capture evaluation during constant expr evaluation. 2322 Info.FFDiag(E->getLocStart(), 2323 diag::note_unimplemented_constexpr_lambda_feature_ast) 2324 << "captures not currently allowed"; 2325 return false; 2326 } 2327 return true; 2328 } 2329 2330 // Dig out the initializer, and use the declaration which it's attached to. 2331 const Expr *Init = VD->getAnyInitializer(VD); 2332 if (!Init || Init->isValueDependent()) { 2333 // If we're checking a potential constant expression, the variable could be 2334 // initialized later. 2335 if (!Info.checkingPotentialConstantExpression()) 2336 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2337 return false; 2338 } 2339 2340 // If we're currently evaluating the initializer of this declaration, use that 2341 // in-flight value. 2342 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 2343 Result = Info.EvaluatingDeclValue; 2344 return true; 2345 } 2346 2347 // Never evaluate the initializer of a weak variable. We can't be sure that 2348 // this is the definition which will be used. 2349 if (VD->isWeak()) { 2350 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2351 return false; 2352 } 2353 2354 // Check that we can fold the initializer. In C++, we will have already done 2355 // this in the cases where it matters for conformance. 2356 SmallVector<PartialDiagnosticAt, 8> Notes; 2357 if (!VD->evaluateValue(Notes)) { 2358 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 2359 Notes.size() + 1) << VD; 2360 Info.Note(VD->getLocation(), diag::note_declared_at); 2361 Info.addNotes(Notes); 2362 return false; 2363 } else if (!VD->checkInitIsICE()) { 2364 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 2365 Notes.size() + 1) << VD; 2366 Info.Note(VD->getLocation(), diag::note_declared_at); 2367 Info.addNotes(Notes); 2368 } 2369 2370 Result = VD->getEvaluatedValue(); 2371 return true; 2372 } 2373 2374 static bool IsConstNonVolatile(QualType T) { 2375 Qualifiers Quals = T.getQualifiers(); 2376 return Quals.hasConst() && !Quals.hasVolatile(); 2377 } 2378 2379 /// Get the base index of the given base class within an APValue representing 2380 /// the given derived class. 2381 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 2382 const CXXRecordDecl *Base) { 2383 Base = Base->getCanonicalDecl(); 2384 unsigned Index = 0; 2385 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 2386 E = Derived->bases_end(); I != E; ++I, ++Index) { 2387 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 2388 return Index; 2389 } 2390 2391 llvm_unreachable("base class missing from derived class's bases list"); 2392 } 2393 2394 /// Extract the value of a character from a string literal. 2395 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 2396 uint64_t Index) { 2397 // FIXME: Support MakeStringConstant 2398 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 2399 std::string Str; 2400 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 2401 assert(Index <= Str.size() && "Index too large"); 2402 return APSInt::getUnsigned(Str.c_str()[Index]); 2403 } 2404 2405 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 2406 Lit = PE->getFunctionName(); 2407 const StringLiteral *S = cast<StringLiteral>(Lit); 2408 const ConstantArrayType *CAT = 2409 Info.Ctx.getAsConstantArrayType(S->getType()); 2410 assert(CAT && "string literal isn't an array"); 2411 QualType CharType = CAT->getElementType(); 2412 assert(CharType->isIntegerType() && "unexpected character type"); 2413 2414 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2415 CharType->isUnsignedIntegerType()); 2416 if (Index < S->getLength()) 2417 Value = S->getCodeUnit(Index); 2418 return Value; 2419 } 2420 2421 // Expand a string literal into an array of characters. 2422 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit, 2423 APValue &Result) { 2424 const StringLiteral *S = cast<StringLiteral>(Lit); 2425 const ConstantArrayType *CAT = 2426 Info.Ctx.getAsConstantArrayType(S->getType()); 2427 assert(CAT && "string literal isn't an array"); 2428 QualType CharType = CAT->getElementType(); 2429 assert(CharType->isIntegerType() && "unexpected character type"); 2430 2431 unsigned Elts = CAT->getSize().getZExtValue(); 2432 Result = APValue(APValue::UninitArray(), 2433 std::min(S->getLength(), Elts), Elts); 2434 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2435 CharType->isUnsignedIntegerType()); 2436 if (Result.hasArrayFiller()) 2437 Result.getArrayFiller() = APValue(Value); 2438 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 2439 Value = S->getCodeUnit(I); 2440 Result.getArrayInitializedElt(I) = APValue(Value); 2441 } 2442 } 2443 2444 // Expand an array so that it has more than Index filled elements. 2445 static void expandArray(APValue &Array, unsigned Index) { 2446 unsigned Size = Array.getArraySize(); 2447 assert(Index < Size); 2448 2449 // Always at least double the number of elements for which we store a value. 2450 unsigned OldElts = Array.getArrayInitializedElts(); 2451 unsigned NewElts = std::max(Index+1, OldElts * 2); 2452 NewElts = std::min(Size, std::max(NewElts, 8u)); 2453 2454 // Copy the data across. 2455 APValue NewValue(APValue::UninitArray(), NewElts, Size); 2456 for (unsigned I = 0; I != OldElts; ++I) 2457 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 2458 for (unsigned I = OldElts; I != NewElts; ++I) 2459 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 2460 if (NewValue.hasArrayFiller()) 2461 NewValue.getArrayFiller() = Array.getArrayFiller(); 2462 Array.swap(NewValue); 2463 } 2464 2465 /// Determine whether a type would actually be read by an lvalue-to-rvalue 2466 /// conversion. If it's of class type, we may assume that the copy operation 2467 /// is trivial. Note that this is never true for a union type with fields 2468 /// (because the copy always "reads" the active member) and always true for 2469 /// a non-class type. 2470 static bool isReadByLvalueToRvalueConversion(QualType T) { 2471 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2472 if (!RD || (RD->isUnion() && !RD->field_empty())) 2473 return true; 2474 if (RD->isEmpty()) 2475 return false; 2476 2477 for (auto *Field : RD->fields()) 2478 if (isReadByLvalueToRvalueConversion(Field->getType())) 2479 return true; 2480 2481 for (auto &BaseSpec : RD->bases()) 2482 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 2483 return true; 2484 2485 return false; 2486 } 2487 2488 /// Diagnose an attempt to read from any unreadable field within the specified 2489 /// type, which might be a class type. 2490 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E, 2491 QualType T) { 2492 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2493 if (!RD) 2494 return false; 2495 2496 if (!RD->hasMutableFields()) 2497 return false; 2498 2499 for (auto *Field : RD->fields()) { 2500 // If we're actually going to read this field in some way, then it can't 2501 // be mutable. If we're in a union, then assigning to a mutable field 2502 // (even an empty one) can change the active member, so that's not OK. 2503 // FIXME: Add core issue number for the union case. 2504 if (Field->isMutable() && 2505 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 2506 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field; 2507 Info.Note(Field->getLocation(), diag::note_declared_at); 2508 return true; 2509 } 2510 2511 if (diagnoseUnreadableFields(Info, E, Field->getType())) 2512 return true; 2513 } 2514 2515 for (auto &BaseSpec : RD->bases()) 2516 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType())) 2517 return true; 2518 2519 // All mutable fields were empty, and thus not actually read. 2520 return false; 2521 } 2522 2523 /// Kinds of access we can perform on an object, for diagnostics. 2524 enum AccessKinds { 2525 AK_Read, 2526 AK_Assign, 2527 AK_Increment, 2528 AK_Decrement 2529 }; 2530 2531 namespace { 2532 /// A handle to a complete object (an object that is not a subobject of 2533 /// another object). 2534 struct CompleteObject { 2535 /// The value of the complete object. 2536 APValue *Value; 2537 /// The type of the complete object. 2538 QualType Type; 2539 2540 CompleteObject() : Value(nullptr) {} 2541 CompleteObject(APValue *Value, QualType Type) 2542 : Value(Value), Type(Type) { 2543 assert(Value && "missing value for complete object"); 2544 } 2545 2546 explicit operator bool() const { return Value; } 2547 }; 2548 } // end anonymous namespace 2549 2550 /// Find the designated sub-object of an rvalue. 2551 template<typename SubobjectHandler> 2552 typename SubobjectHandler::result_type 2553 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 2554 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 2555 if (Sub.Invalid) 2556 // A diagnostic will have already been produced. 2557 return handler.failed(); 2558 if (Sub.isOnePastTheEnd()) { 2559 if (Info.getLangOpts().CPlusPlus11) 2560 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2561 << handler.AccessKind; 2562 else 2563 Info.FFDiag(E); 2564 return handler.failed(); 2565 } 2566 2567 APValue *O = Obj.Value; 2568 QualType ObjType = Obj.Type; 2569 const FieldDecl *LastField = nullptr; 2570 2571 // Walk the designator's path to find the subobject. 2572 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 2573 if (O->isUninit()) { 2574 if (!Info.checkingPotentialConstantExpression()) 2575 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind; 2576 return handler.failed(); 2577 } 2578 2579 if (I == N) { 2580 // If we are reading an object of class type, there may still be more 2581 // things we need to check: if there are any mutable subobjects, we 2582 // cannot perform this read. (This only happens when performing a trivial 2583 // copy or assignment.) 2584 if (ObjType->isRecordType() && handler.AccessKind == AK_Read && 2585 diagnoseUnreadableFields(Info, E, ObjType)) 2586 return handler.failed(); 2587 2588 if (!handler.found(*O, ObjType)) 2589 return false; 2590 2591 // If we modified a bit-field, truncate it to the right width. 2592 if (handler.AccessKind != AK_Read && 2593 LastField && LastField->isBitField() && 2594 !truncateBitfieldValue(Info, E, *O, LastField)) 2595 return false; 2596 2597 return true; 2598 } 2599 2600 LastField = nullptr; 2601 if (ObjType->isArrayType()) { 2602 // Next subobject is an array element. 2603 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 2604 assert(CAT && "vla in literal type?"); 2605 uint64_t Index = Sub.Entries[I].ArrayIndex; 2606 if (CAT->getSize().ule(Index)) { 2607 // Note, it should not be possible to form a pointer with a valid 2608 // designator which points more than one past the end of the array. 2609 if (Info.getLangOpts().CPlusPlus11) 2610 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2611 << handler.AccessKind; 2612 else 2613 Info.FFDiag(E); 2614 return handler.failed(); 2615 } 2616 2617 ObjType = CAT->getElementType(); 2618 2619 // An array object is represented as either an Array APValue or as an 2620 // LValue which refers to a string literal. 2621 if (O->isLValue()) { 2622 assert(I == N - 1 && "extracting subobject of character?"); 2623 assert(!O->hasLValuePath() || O->getLValuePath().empty()); 2624 if (handler.AccessKind != AK_Read) 2625 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(), 2626 *O); 2627 else 2628 return handler.foundString(*O, ObjType, Index); 2629 } 2630 2631 if (O->getArrayInitializedElts() > Index) 2632 O = &O->getArrayInitializedElt(Index); 2633 else if (handler.AccessKind != AK_Read) { 2634 expandArray(*O, Index); 2635 O = &O->getArrayInitializedElt(Index); 2636 } else 2637 O = &O->getArrayFiller(); 2638 } else if (ObjType->isAnyComplexType()) { 2639 // Next subobject is a complex number. 2640 uint64_t Index = Sub.Entries[I].ArrayIndex; 2641 if (Index > 1) { 2642 if (Info.getLangOpts().CPlusPlus11) 2643 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2644 << handler.AccessKind; 2645 else 2646 Info.FFDiag(E); 2647 return handler.failed(); 2648 } 2649 2650 bool WasConstQualified = ObjType.isConstQualified(); 2651 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 2652 if (WasConstQualified) 2653 ObjType.addConst(); 2654 2655 assert(I == N - 1 && "extracting subobject of scalar?"); 2656 if (O->isComplexInt()) { 2657 return handler.found(Index ? O->getComplexIntImag() 2658 : O->getComplexIntReal(), ObjType); 2659 } else { 2660 assert(O->isComplexFloat()); 2661 return handler.found(Index ? O->getComplexFloatImag() 2662 : O->getComplexFloatReal(), ObjType); 2663 } 2664 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 2665 if (Field->isMutable() && handler.AccessKind == AK_Read) { 2666 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) 2667 << Field; 2668 Info.Note(Field->getLocation(), diag::note_declared_at); 2669 return handler.failed(); 2670 } 2671 2672 // Next subobject is a class, struct or union field. 2673 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 2674 if (RD->isUnion()) { 2675 const FieldDecl *UnionField = O->getUnionField(); 2676 if (!UnionField || 2677 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 2678 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 2679 << handler.AccessKind << Field << !UnionField << UnionField; 2680 return handler.failed(); 2681 } 2682 O = &O->getUnionValue(); 2683 } else 2684 O = &O->getStructField(Field->getFieldIndex()); 2685 2686 bool WasConstQualified = ObjType.isConstQualified(); 2687 ObjType = Field->getType(); 2688 if (WasConstQualified && !Field->isMutable()) 2689 ObjType.addConst(); 2690 2691 if (ObjType.isVolatileQualified()) { 2692 if (Info.getLangOpts().CPlusPlus) { 2693 // FIXME: Include a description of the path to the volatile subobject. 2694 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 2695 << handler.AccessKind << 2 << Field; 2696 Info.Note(Field->getLocation(), diag::note_declared_at); 2697 } else { 2698 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2699 } 2700 return handler.failed(); 2701 } 2702 2703 LastField = Field; 2704 } else { 2705 // Next subobject is a base class. 2706 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 2707 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 2708 O = &O->getStructBase(getBaseIndex(Derived, Base)); 2709 2710 bool WasConstQualified = ObjType.isConstQualified(); 2711 ObjType = Info.Ctx.getRecordType(Base); 2712 if (WasConstQualified) 2713 ObjType.addConst(); 2714 } 2715 } 2716 } 2717 2718 namespace { 2719 struct ExtractSubobjectHandler { 2720 EvalInfo &Info; 2721 APValue &Result; 2722 2723 static const AccessKinds AccessKind = AK_Read; 2724 2725 typedef bool result_type; 2726 bool failed() { return false; } 2727 bool found(APValue &Subobj, QualType SubobjType) { 2728 Result = Subobj; 2729 return true; 2730 } 2731 bool found(APSInt &Value, QualType SubobjType) { 2732 Result = APValue(Value); 2733 return true; 2734 } 2735 bool found(APFloat &Value, QualType SubobjType) { 2736 Result = APValue(Value); 2737 return true; 2738 } 2739 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 2740 Result = APValue(extractStringLiteralCharacter( 2741 Info, Subobj.getLValueBase().get<const Expr *>(), Character)); 2742 return true; 2743 } 2744 }; 2745 } // end anonymous namespace 2746 2747 const AccessKinds ExtractSubobjectHandler::AccessKind; 2748 2749 /// Extract the designated sub-object of an rvalue. 2750 static bool extractSubobject(EvalInfo &Info, const Expr *E, 2751 const CompleteObject &Obj, 2752 const SubobjectDesignator &Sub, 2753 APValue &Result) { 2754 ExtractSubobjectHandler Handler = { Info, Result }; 2755 return findSubobject(Info, E, Obj, Sub, Handler); 2756 } 2757 2758 namespace { 2759 struct ModifySubobjectHandler { 2760 EvalInfo &Info; 2761 APValue &NewVal; 2762 const Expr *E; 2763 2764 typedef bool result_type; 2765 static const AccessKinds AccessKind = AK_Assign; 2766 2767 bool checkConst(QualType QT) { 2768 // Assigning to a const object has undefined behavior. 2769 if (QT.isConstQualified()) { 2770 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 2771 return false; 2772 } 2773 return true; 2774 } 2775 2776 bool failed() { return false; } 2777 bool found(APValue &Subobj, QualType SubobjType) { 2778 if (!checkConst(SubobjType)) 2779 return false; 2780 // We've been given ownership of NewVal, so just swap it in. 2781 Subobj.swap(NewVal); 2782 return true; 2783 } 2784 bool found(APSInt &Value, QualType SubobjType) { 2785 if (!checkConst(SubobjType)) 2786 return false; 2787 if (!NewVal.isInt()) { 2788 // Maybe trying to write a cast pointer value into a complex? 2789 Info.FFDiag(E); 2790 return false; 2791 } 2792 Value = NewVal.getInt(); 2793 return true; 2794 } 2795 bool found(APFloat &Value, QualType SubobjType) { 2796 if (!checkConst(SubobjType)) 2797 return false; 2798 Value = NewVal.getFloat(); 2799 return true; 2800 } 2801 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 2802 llvm_unreachable("shouldn't encounter string elements with ExpandArrays"); 2803 } 2804 }; 2805 } // end anonymous namespace 2806 2807 const AccessKinds ModifySubobjectHandler::AccessKind; 2808 2809 /// Update the designated sub-object of an rvalue to the given value. 2810 static bool modifySubobject(EvalInfo &Info, const Expr *E, 2811 const CompleteObject &Obj, 2812 const SubobjectDesignator &Sub, 2813 APValue &NewVal) { 2814 ModifySubobjectHandler Handler = { Info, NewVal, E }; 2815 return findSubobject(Info, E, Obj, Sub, Handler); 2816 } 2817 2818 /// Find the position where two subobject designators diverge, or equivalently 2819 /// the length of the common initial subsequence. 2820 static unsigned FindDesignatorMismatch(QualType ObjType, 2821 const SubobjectDesignator &A, 2822 const SubobjectDesignator &B, 2823 bool &WasArrayIndex) { 2824 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 2825 for (/**/; I != N; ++I) { 2826 if (!ObjType.isNull() && 2827 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 2828 // Next subobject is an array element. 2829 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) { 2830 WasArrayIndex = true; 2831 return I; 2832 } 2833 if (ObjType->isAnyComplexType()) 2834 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 2835 else 2836 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 2837 } else { 2838 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) { 2839 WasArrayIndex = false; 2840 return I; 2841 } 2842 if (const FieldDecl *FD = getAsField(A.Entries[I])) 2843 // Next subobject is a field. 2844 ObjType = FD->getType(); 2845 else 2846 // Next subobject is a base class. 2847 ObjType = QualType(); 2848 } 2849 } 2850 WasArrayIndex = false; 2851 return I; 2852 } 2853 2854 /// Determine whether the given subobject designators refer to elements of the 2855 /// same array object. 2856 static bool AreElementsOfSameArray(QualType ObjType, 2857 const SubobjectDesignator &A, 2858 const SubobjectDesignator &B) { 2859 if (A.Entries.size() != B.Entries.size()) 2860 return false; 2861 2862 bool IsArray = A.MostDerivedIsArrayElement; 2863 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 2864 // A is a subobject of the array element. 2865 return false; 2866 2867 // If A (and B) designates an array element, the last entry will be the array 2868 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 2869 // of length 1' case, and the entire path must match. 2870 bool WasArrayIndex; 2871 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 2872 return CommonLength >= A.Entries.size() - IsArray; 2873 } 2874 2875 /// Find the complete object to which an LValue refers. 2876 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 2877 AccessKinds AK, const LValue &LVal, 2878 QualType LValType) { 2879 if (!LVal.Base) { 2880 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 2881 return CompleteObject(); 2882 } 2883 2884 CallStackFrame *Frame = nullptr; 2885 if (LVal.CallIndex) { 2886 Frame = Info.getCallFrame(LVal.CallIndex); 2887 if (!Frame) { 2888 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 2889 << AK << LVal.Base.is<const ValueDecl*>(); 2890 NoteLValueLocation(Info, LVal.Base); 2891 return CompleteObject(); 2892 } 2893 } 2894 2895 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 2896 // is not a constant expression (even if the object is non-volatile). We also 2897 // apply this rule to C++98, in order to conform to the expected 'volatile' 2898 // semantics. 2899 if (LValType.isVolatileQualified()) { 2900 if (Info.getLangOpts().CPlusPlus) 2901 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 2902 << AK << LValType; 2903 else 2904 Info.FFDiag(E); 2905 return CompleteObject(); 2906 } 2907 2908 // Compute value storage location and type of base object. 2909 APValue *BaseVal = nullptr; 2910 QualType BaseType = getType(LVal.Base); 2911 2912 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 2913 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 2914 // In C++11, constexpr, non-volatile variables initialized with constant 2915 // expressions are constant expressions too. Inside constexpr functions, 2916 // parameters are constant expressions even if they're non-const. 2917 // In C++1y, objects local to a constant expression (those with a Frame) are 2918 // both readable and writable inside constant expressions. 2919 // In C, such things can also be folded, although they are not ICEs. 2920 const VarDecl *VD = dyn_cast<VarDecl>(D); 2921 if (VD) { 2922 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 2923 VD = VDef; 2924 } 2925 if (!VD || VD->isInvalidDecl()) { 2926 Info.FFDiag(E); 2927 return CompleteObject(); 2928 } 2929 2930 // Accesses of volatile-qualified objects are not allowed. 2931 if (BaseType.isVolatileQualified()) { 2932 if (Info.getLangOpts().CPlusPlus) { 2933 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 2934 << AK << 1 << VD; 2935 Info.Note(VD->getLocation(), diag::note_declared_at); 2936 } else { 2937 Info.FFDiag(E); 2938 } 2939 return CompleteObject(); 2940 } 2941 2942 // Unless we're looking at a local variable or argument in a constexpr call, 2943 // the variable we're reading must be const. 2944 if (!Frame) { 2945 if (Info.getLangOpts().CPlusPlus14 && 2946 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) { 2947 // OK, we can read and modify an object if we're in the process of 2948 // evaluating its initializer, because its lifetime began in this 2949 // evaluation. 2950 } else if (AK != AK_Read) { 2951 // All the remaining cases only permit reading. 2952 Info.FFDiag(E, diag::note_constexpr_modify_global); 2953 return CompleteObject(); 2954 } else if (VD->isConstexpr()) { 2955 // OK, we can read this variable. 2956 } else if (BaseType->isIntegralOrEnumerationType()) { 2957 // In OpenCL if a variable is in constant address space it is a const value. 2958 if (!(BaseType.isConstQualified() || 2959 (Info.getLangOpts().OpenCL && 2960 BaseType.getAddressSpace() == LangAS::opencl_constant))) { 2961 if (Info.getLangOpts().CPlusPlus) { 2962 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 2963 Info.Note(VD->getLocation(), diag::note_declared_at); 2964 } else { 2965 Info.FFDiag(E); 2966 } 2967 return CompleteObject(); 2968 } 2969 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { 2970 // We support folding of const floating-point types, in order to make 2971 // static const data members of such types (supported as an extension) 2972 // more useful. 2973 if (Info.getLangOpts().CPlusPlus11) { 2974 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 2975 Info.Note(VD->getLocation(), diag::note_declared_at); 2976 } else { 2977 Info.CCEDiag(E); 2978 } 2979 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { 2980 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; 2981 // Keep evaluating to see what we can do. 2982 } else { 2983 // FIXME: Allow folding of values of any literal type in all languages. 2984 if (Info.checkingPotentialConstantExpression() && 2985 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { 2986 // The definition of this variable could be constexpr. We can't 2987 // access it right now, but may be able to in future. 2988 } else if (Info.getLangOpts().CPlusPlus11) { 2989 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 2990 Info.Note(VD->getLocation(), diag::note_declared_at); 2991 } else { 2992 Info.FFDiag(E); 2993 } 2994 return CompleteObject(); 2995 } 2996 } 2997 2998 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal)) 2999 return CompleteObject(); 3000 } else { 3001 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3002 3003 if (!Frame) { 3004 if (const MaterializeTemporaryExpr *MTE = 3005 dyn_cast<MaterializeTemporaryExpr>(Base)) { 3006 assert(MTE->getStorageDuration() == SD_Static && 3007 "should have a frame for a non-global materialized temporary"); 3008 3009 // Per C++1y [expr.const]p2: 3010 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3011 // - a [...] glvalue of integral or enumeration type that refers to 3012 // a non-volatile const object [...] 3013 // [...] 3014 // - a [...] glvalue of literal type that refers to a non-volatile 3015 // object whose lifetime began within the evaluation of e. 3016 // 3017 // C++11 misses the 'began within the evaluation of e' check and 3018 // instead allows all temporaries, including things like: 3019 // int &&r = 1; 3020 // int x = ++r; 3021 // constexpr int k = r; 3022 // Therefore we use the C++1y rules in C++11 too. 3023 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3024 const ValueDecl *ED = MTE->getExtendingDecl(); 3025 if (!(BaseType.isConstQualified() && 3026 BaseType->isIntegralOrEnumerationType()) && 3027 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) { 3028 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3029 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3030 return CompleteObject(); 3031 } 3032 3033 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false); 3034 assert(BaseVal && "got reference to unevaluated temporary"); 3035 } else { 3036 Info.FFDiag(E); 3037 return CompleteObject(); 3038 } 3039 } else { 3040 BaseVal = Frame->getTemporary(Base); 3041 assert(BaseVal && "missing value for temporary"); 3042 } 3043 3044 // Volatile temporary objects cannot be accessed in constant expressions. 3045 if (BaseType.isVolatileQualified()) { 3046 if (Info.getLangOpts().CPlusPlus) { 3047 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3048 << AK << 0; 3049 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here); 3050 } else { 3051 Info.FFDiag(E); 3052 } 3053 return CompleteObject(); 3054 } 3055 } 3056 3057 // During the construction of an object, it is not yet 'const'. 3058 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries, 3059 // and this doesn't do quite the right thing for const subobjects of the 3060 // object under construction. 3061 if (LVal.getLValueBase() == Info.EvaluatingDecl) { 3062 BaseType = Info.Ctx.getCanonicalType(BaseType); 3063 BaseType.removeLocalConst(); 3064 } 3065 3066 // In C++1y, we can't safely access any mutable state when we might be 3067 // evaluating after an unmodeled side effect. 3068 // 3069 // FIXME: Not all local state is mutable. Allow local constant subobjects 3070 // to be read here (but take care with 'mutable' fields). 3071 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3072 Info.EvalStatus.HasSideEffects) || 3073 (AK != AK_Read && Info.IsSpeculativelyEvaluating)) 3074 return CompleteObject(); 3075 3076 return CompleteObject(BaseVal, BaseType); 3077 } 3078 3079 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This 3080 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3081 /// glvalue referred to by an entity of reference type. 3082 /// 3083 /// \param Info - Information about the ongoing evaluation. 3084 /// \param Conv - The expression for which we are performing the conversion. 3085 /// Used for diagnostics. 3086 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 3087 /// case of a non-class type). 3088 /// \param LVal - The glvalue on which we are attempting to perform this action. 3089 /// \param RVal - The produced value will be placed here. 3090 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 3091 QualType Type, 3092 const LValue &LVal, APValue &RVal) { 3093 if (LVal.Designator.Invalid) 3094 return false; 3095 3096 // Check for special cases where there is no existing APValue to look at. 3097 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3098 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) { 3099 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 3100 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 3101 // initializer until now for such expressions. Such an expression can't be 3102 // an ICE in C, so this only matters for fold. 3103 if (Type.isVolatileQualified()) { 3104 Info.FFDiag(Conv); 3105 return false; 3106 } 3107 APValue Lit; 3108 if (!Evaluate(Lit, Info, CLE->getInitializer())) 3109 return false; 3110 CompleteObject LitObj(&Lit, Base->getType()); 3111 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal); 3112 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 3113 // We represent a string literal array as an lvalue pointing at the 3114 // corresponding expression, rather than building an array of chars. 3115 // FIXME: Support ObjCEncodeExpr, MakeStringConstant 3116 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0); 3117 CompleteObject StrObj(&Str, Base->getType()); 3118 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal); 3119 } 3120 } 3121 3122 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type); 3123 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal); 3124 } 3125 3126 /// Perform an assignment of Val to LVal. Takes ownership of Val. 3127 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 3128 QualType LValType, APValue &Val) { 3129 if (LVal.Designator.Invalid) 3130 return false; 3131 3132 if (!Info.getLangOpts().CPlusPlus14) { 3133 Info.FFDiag(E); 3134 return false; 3135 } 3136 3137 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3138 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 3139 } 3140 3141 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 3142 return T->isSignedIntegerType() && 3143 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 3144 } 3145 3146 namespace { 3147 struct CompoundAssignSubobjectHandler { 3148 EvalInfo &Info; 3149 const Expr *E; 3150 QualType PromotedLHSType; 3151 BinaryOperatorKind Opcode; 3152 const APValue &RHS; 3153 3154 static const AccessKinds AccessKind = AK_Assign; 3155 3156 typedef bool result_type; 3157 3158 bool checkConst(QualType QT) { 3159 // Assigning to a const object has undefined behavior. 3160 if (QT.isConstQualified()) { 3161 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3162 return false; 3163 } 3164 return true; 3165 } 3166 3167 bool failed() { return false; } 3168 bool found(APValue &Subobj, QualType SubobjType) { 3169 switch (Subobj.getKind()) { 3170 case APValue::Int: 3171 return found(Subobj.getInt(), SubobjType); 3172 case APValue::Float: 3173 return found(Subobj.getFloat(), SubobjType); 3174 case APValue::ComplexInt: 3175 case APValue::ComplexFloat: 3176 // FIXME: Implement complex compound assignment. 3177 Info.FFDiag(E); 3178 return false; 3179 case APValue::LValue: 3180 return foundPointer(Subobj, SubobjType); 3181 default: 3182 // FIXME: can this happen? 3183 Info.FFDiag(E); 3184 return false; 3185 } 3186 } 3187 bool found(APSInt &Value, QualType SubobjType) { 3188 if (!checkConst(SubobjType)) 3189 return false; 3190 3191 if (!SubobjType->isIntegerType() || !RHS.isInt()) { 3192 // We don't support compound assignment on integer-cast-to-pointer 3193 // values. 3194 Info.FFDiag(E); 3195 return false; 3196 } 3197 3198 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType, 3199 SubobjType, Value); 3200 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 3201 return false; 3202 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 3203 return true; 3204 } 3205 bool found(APFloat &Value, QualType SubobjType) { 3206 return checkConst(SubobjType) && 3207 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 3208 Value) && 3209 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 3210 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 3211 } 3212 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3213 if (!checkConst(SubobjType)) 3214 return false; 3215 3216 QualType PointeeType; 3217 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3218 PointeeType = PT->getPointeeType(); 3219 3220 if (PointeeType.isNull() || !RHS.isInt() || 3221 (Opcode != BO_Add && Opcode != BO_Sub)) { 3222 Info.FFDiag(E); 3223 return false; 3224 } 3225 3226 APSInt Offset = RHS.getInt(); 3227 if (Opcode == BO_Sub) 3228 negateAsSigned(Offset); 3229 3230 LValue LVal; 3231 LVal.setFrom(Info.Ctx, Subobj); 3232 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 3233 return false; 3234 LVal.moveInto(Subobj); 3235 return true; 3236 } 3237 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3238 llvm_unreachable("shouldn't encounter string elements here"); 3239 } 3240 }; 3241 } // end anonymous namespace 3242 3243 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 3244 3245 /// Perform a compound assignment of LVal <op>= RVal. 3246 static bool handleCompoundAssignment( 3247 EvalInfo &Info, const Expr *E, 3248 const LValue &LVal, QualType LValType, QualType PromotedLValType, 3249 BinaryOperatorKind Opcode, const APValue &RVal) { 3250 if (LVal.Designator.Invalid) 3251 return false; 3252 3253 if (!Info.getLangOpts().CPlusPlus14) { 3254 Info.FFDiag(E); 3255 return false; 3256 } 3257 3258 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3259 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 3260 RVal }; 3261 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3262 } 3263 3264 namespace { 3265 struct IncDecSubobjectHandler { 3266 EvalInfo &Info; 3267 const Expr *E; 3268 AccessKinds AccessKind; 3269 APValue *Old; 3270 3271 typedef bool result_type; 3272 3273 bool checkConst(QualType QT) { 3274 // Assigning to a const object has undefined behavior. 3275 if (QT.isConstQualified()) { 3276 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3277 return false; 3278 } 3279 return true; 3280 } 3281 3282 bool failed() { return false; } 3283 bool found(APValue &Subobj, QualType SubobjType) { 3284 // Stash the old value. Also clear Old, so we don't clobber it later 3285 // if we're post-incrementing a complex. 3286 if (Old) { 3287 *Old = Subobj; 3288 Old = nullptr; 3289 } 3290 3291 switch (Subobj.getKind()) { 3292 case APValue::Int: 3293 return found(Subobj.getInt(), SubobjType); 3294 case APValue::Float: 3295 return found(Subobj.getFloat(), SubobjType); 3296 case APValue::ComplexInt: 3297 return found(Subobj.getComplexIntReal(), 3298 SubobjType->castAs<ComplexType>()->getElementType() 3299 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3300 case APValue::ComplexFloat: 3301 return found(Subobj.getComplexFloatReal(), 3302 SubobjType->castAs<ComplexType>()->getElementType() 3303 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3304 case APValue::LValue: 3305 return foundPointer(Subobj, SubobjType); 3306 default: 3307 // FIXME: can this happen? 3308 Info.FFDiag(E); 3309 return false; 3310 } 3311 } 3312 bool found(APSInt &Value, QualType SubobjType) { 3313 if (!checkConst(SubobjType)) 3314 return false; 3315 3316 if (!SubobjType->isIntegerType()) { 3317 // We don't support increment / decrement on integer-cast-to-pointer 3318 // values. 3319 Info.FFDiag(E); 3320 return false; 3321 } 3322 3323 if (Old) *Old = APValue(Value); 3324 3325 // bool arithmetic promotes to int, and the conversion back to bool 3326 // doesn't reduce mod 2^n, so special-case it. 3327 if (SubobjType->isBooleanType()) { 3328 if (AccessKind == AK_Increment) 3329 Value = 1; 3330 else 3331 Value = !Value; 3332 return true; 3333 } 3334 3335 bool WasNegative = Value.isNegative(); 3336 if (AccessKind == AK_Increment) { 3337 ++Value; 3338 3339 if (!WasNegative && Value.isNegative() && 3340 isOverflowingIntegerType(Info.Ctx, SubobjType)) { 3341 APSInt ActualValue(Value, /*IsUnsigned*/true); 3342 return HandleOverflow(Info, E, ActualValue, SubobjType); 3343 } 3344 } else { 3345 --Value; 3346 3347 if (WasNegative && !Value.isNegative() && 3348 isOverflowingIntegerType(Info.Ctx, SubobjType)) { 3349 unsigned BitWidth = Value.getBitWidth(); 3350 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 3351 ActualValue.setBit(BitWidth); 3352 return HandleOverflow(Info, E, ActualValue, SubobjType); 3353 } 3354 } 3355 return true; 3356 } 3357 bool found(APFloat &Value, QualType SubobjType) { 3358 if (!checkConst(SubobjType)) 3359 return false; 3360 3361 if (Old) *Old = APValue(Value); 3362 3363 APFloat One(Value.getSemantics(), 1); 3364 if (AccessKind == AK_Increment) 3365 Value.add(One, APFloat::rmNearestTiesToEven); 3366 else 3367 Value.subtract(One, APFloat::rmNearestTiesToEven); 3368 return true; 3369 } 3370 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3371 if (!checkConst(SubobjType)) 3372 return false; 3373 3374 QualType PointeeType; 3375 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3376 PointeeType = PT->getPointeeType(); 3377 else { 3378 Info.FFDiag(E); 3379 return false; 3380 } 3381 3382 LValue LVal; 3383 LVal.setFrom(Info.Ctx, Subobj); 3384 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 3385 AccessKind == AK_Increment ? 1 : -1)) 3386 return false; 3387 LVal.moveInto(Subobj); 3388 return true; 3389 } 3390 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3391 llvm_unreachable("shouldn't encounter string elements here"); 3392 } 3393 }; 3394 } // end anonymous namespace 3395 3396 /// Perform an increment or decrement on LVal. 3397 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 3398 QualType LValType, bool IsIncrement, APValue *Old) { 3399 if (LVal.Designator.Invalid) 3400 return false; 3401 3402 if (!Info.getLangOpts().CPlusPlus14) { 3403 Info.FFDiag(E); 3404 return false; 3405 } 3406 3407 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 3408 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 3409 IncDecSubobjectHandler Handler = { Info, E, AK, Old }; 3410 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3411 } 3412 3413 /// Build an lvalue for the object argument of a member function call. 3414 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 3415 LValue &This) { 3416 if (Object->getType()->isPointerType()) 3417 return EvaluatePointer(Object, This, Info); 3418 3419 if (Object->isGLValue()) 3420 return EvaluateLValue(Object, This, Info); 3421 3422 if (Object->getType()->isLiteralType(Info.Ctx)) 3423 return EvaluateTemporary(Object, This, Info); 3424 3425 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 3426 return false; 3427 } 3428 3429 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 3430 /// lvalue referring to the result. 3431 /// 3432 /// \param Info - Information about the ongoing evaluation. 3433 /// \param LV - An lvalue referring to the base of the member pointer. 3434 /// \param RHS - The member pointer expression. 3435 /// \param IncludeMember - Specifies whether the member itself is included in 3436 /// the resulting LValue subobject designator. This is not possible when 3437 /// creating a bound member function. 3438 /// \return The field or method declaration to which the member pointer refers, 3439 /// or 0 if evaluation fails. 3440 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3441 QualType LVType, 3442 LValue &LV, 3443 const Expr *RHS, 3444 bool IncludeMember = true) { 3445 MemberPtr MemPtr; 3446 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 3447 return nullptr; 3448 3449 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 3450 // member value, the behavior is undefined. 3451 if (!MemPtr.getDecl()) { 3452 // FIXME: Specific diagnostic. 3453 Info.FFDiag(RHS); 3454 return nullptr; 3455 } 3456 3457 if (MemPtr.isDerivedMember()) { 3458 // This is a member of some derived class. Truncate LV appropriately. 3459 // The end of the derived-to-base path for the base object must match the 3460 // derived-to-base path for the member pointer. 3461 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 3462 LV.Designator.Entries.size()) { 3463 Info.FFDiag(RHS); 3464 return nullptr; 3465 } 3466 unsigned PathLengthToMember = 3467 LV.Designator.Entries.size() - MemPtr.Path.size(); 3468 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 3469 const CXXRecordDecl *LVDecl = getAsBaseClass( 3470 LV.Designator.Entries[PathLengthToMember + I]); 3471 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 3472 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 3473 Info.FFDiag(RHS); 3474 return nullptr; 3475 } 3476 } 3477 3478 // Truncate the lvalue to the appropriate derived class. 3479 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 3480 PathLengthToMember)) 3481 return nullptr; 3482 } else if (!MemPtr.Path.empty()) { 3483 // Extend the LValue path with the member pointer's path. 3484 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 3485 MemPtr.Path.size() + IncludeMember); 3486 3487 // Walk down to the appropriate base class. 3488 if (const PointerType *PT = LVType->getAs<PointerType>()) 3489 LVType = PT->getPointeeType(); 3490 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 3491 assert(RD && "member pointer access on non-class-type expression"); 3492 // The first class in the path is that of the lvalue. 3493 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 3494 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 3495 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 3496 return nullptr; 3497 RD = Base; 3498 } 3499 // Finally cast to the class containing the member. 3500 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 3501 MemPtr.getContainingRecord())) 3502 return nullptr; 3503 } 3504 3505 // Add the member. Note that we cannot build bound member functions here. 3506 if (IncludeMember) { 3507 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 3508 if (!HandleLValueMember(Info, RHS, LV, FD)) 3509 return nullptr; 3510 } else if (const IndirectFieldDecl *IFD = 3511 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 3512 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 3513 return nullptr; 3514 } else { 3515 llvm_unreachable("can't construct reference to bound member function"); 3516 } 3517 } 3518 3519 return MemPtr.getDecl(); 3520 } 3521 3522 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3523 const BinaryOperator *BO, 3524 LValue &LV, 3525 bool IncludeMember = true) { 3526 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 3527 3528 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 3529 if (Info.noteFailure()) { 3530 MemberPtr MemPtr; 3531 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 3532 } 3533 return nullptr; 3534 } 3535 3536 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 3537 BO->getRHS(), IncludeMember); 3538 } 3539 3540 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 3541 /// the provided lvalue, which currently refers to the base object. 3542 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 3543 LValue &Result) { 3544 SubobjectDesignator &D = Result.Designator; 3545 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 3546 return false; 3547 3548 QualType TargetQT = E->getType(); 3549 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 3550 TargetQT = PT->getPointeeType(); 3551 3552 // Check this cast lands within the final derived-to-base subobject path. 3553 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 3554 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3555 << D.MostDerivedType << TargetQT; 3556 return false; 3557 } 3558 3559 // Check the type of the final cast. We don't need to check the path, 3560 // since a cast can only be formed if the path is unique. 3561 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 3562 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 3563 const CXXRecordDecl *FinalType; 3564 if (NewEntriesSize == D.MostDerivedPathLength) 3565 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 3566 else 3567 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 3568 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 3569 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3570 << D.MostDerivedType << TargetQT; 3571 return false; 3572 } 3573 3574 // Truncate the lvalue to the appropriate derived class. 3575 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 3576 } 3577 3578 namespace { 3579 enum EvalStmtResult { 3580 /// Evaluation failed. 3581 ESR_Failed, 3582 /// Hit a 'return' statement. 3583 ESR_Returned, 3584 /// Evaluation succeeded. 3585 ESR_Succeeded, 3586 /// Hit a 'continue' statement. 3587 ESR_Continue, 3588 /// Hit a 'break' statement. 3589 ESR_Break, 3590 /// Still scanning for 'case' or 'default' statement. 3591 ESR_CaseNotFound 3592 }; 3593 } 3594 3595 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 3596 // We don't need to evaluate the initializer for a static local. 3597 if (!VD->hasLocalStorage()) 3598 return true; 3599 3600 LValue Result; 3601 Result.set(VD, Info.CurrentCall->Index); 3602 APValue &Val = Info.CurrentCall->createTemporary(VD, true); 3603 3604 const Expr *InitE = VD->getInit(); 3605 if (!InitE) { 3606 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized) 3607 << false << VD->getType(); 3608 Val = APValue(); 3609 return false; 3610 } 3611 3612 if (InitE->isValueDependent()) 3613 return false; 3614 3615 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 3616 // Wipe out any partially-computed value, to allow tracking that this 3617 // evaluation failed. 3618 Val = APValue(); 3619 return false; 3620 } 3621 3622 return true; 3623 } 3624 3625 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 3626 bool OK = true; 3627 3628 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 3629 OK &= EvaluateVarDecl(Info, VD); 3630 3631 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 3632 for (auto *BD : DD->bindings()) 3633 if (auto *VD = BD->getHoldingVar()) 3634 OK &= EvaluateDecl(Info, VD); 3635 3636 return OK; 3637 } 3638 3639 3640 /// Evaluate a condition (either a variable declaration or an expression). 3641 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 3642 const Expr *Cond, bool &Result) { 3643 FullExpressionRAII Scope(Info); 3644 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 3645 return false; 3646 return EvaluateAsBooleanCondition(Cond, Result, Info); 3647 } 3648 3649 namespace { 3650 /// \brief A location where the result (returned value) of evaluating a 3651 /// statement should be stored. 3652 struct StmtResult { 3653 /// The APValue that should be filled in with the returned value. 3654 APValue &Value; 3655 /// The location containing the result, if any (used to support RVO). 3656 const LValue *Slot; 3657 }; 3658 } 3659 3660 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 3661 const Stmt *S, 3662 const SwitchCase *SC = nullptr); 3663 3664 /// Evaluate the body of a loop, and translate the result as appropriate. 3665 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 3666 const Stmt *Body, 3667 const SwitchCase *Case = nullptr) { 3668 BlockScopeRAII Scope(Info); 3669 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) { 3670 case ESR_Break: 3671 return ESR_Succeeded; 3672 case ESR_Succeeded: 3673 case ESR_Continue: 3674 return ESR_Continue; 3675 case ESR_Failed: 3676 case ESR_Returned: 3677 case ESR_CaseNotFound: 3678 return ESR; 3679 } 3680 llvm_unreachable("Invalid EvalStmtResult!"); 3681 } 3682 3683 /// Evaluate a switch statement. 3684 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 3685 const SwitchStmt *SS) { 3686 BlockScopeRAII Scope(Info); 3687 3688 // Evaluate the switch condition. 3689 APSInt Value; 3690 { 3691 FullExpressionRAII Scope(Info); 3692 if (const Stmt *Init = SS->getInit()) { 3693 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 3694 if (ESR != ESR_Succeeded) 3695 return ESR; 3696 } 3697 if (SS->getConditionVariable() && 3698 !EvaluateDecl(Info, SS->getConditionVariable())) 3699 return ESR_Failed; 3700 if (!EvaluateInteger(SS->getCond(), Value, Info)) 3701 return ESR_Failed; 3702 } 3703 3704 // Find the switch case corresponding to the value of the condition. 3705 // FIXME: Cache this lookup. 3706 const SwitchCase *Found = nullptr; 3707 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 3708 SC = SC->getNextSwitchCase()) { 3709 if (isa<DefaultStmt>(SC)) { 3710 Found = SC; 3711 continue; 3712 } 3713 3714 const CaseStmt *CS = cast<CaseStmt>(SC); 3715 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 3716 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 3717 : LHS; 3718 if (LHS <= Value && Value <= RHS) { 3719 Found = SC; 3720 break; 3721 } 3722 } 3723 3724 if (!Found) 3725 return ESR_Succeeded; 3726 3727 // Search the switch body for the switch case and evaluate it from there. 3728 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) { 3729 case ESR_Break: 3730 return ESR_Succeeded; 3731 case ESR_Succeeded: 3732 case ESR_Continue: 3733 case ESR_Failed: 3734 case ESR_Returned: 3735 return ESR; 3736 case ESR_CaseNotFound: 3737 // This can only happen if the switch case is nested within a statement 3738 // expression. We have no intention of supporting that. 3739 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported); 3740 return ESR_Failed; 3741 } 3742 llvm_unreachable("Invalid EvalStmtResult!"); 3743 } 3744 3745 // Evaluate a statement. 3746 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 3747 const Stmt *S, const SwitchCase *Case) { 3748 if (!Info.nextStep(S)) 3749 return ESR_Failed; 3750 3751 // If we're hunting down a 'case' or 'default' label, recurse through 3752 // substatements until we hit the label. 3753 if (Case) { 3754 // FIXME: We don't start the lifetime of objects whose initialization we 3755 // jump over. However, such objects must be of class type with a trivial 3756 // default constructor that initialize all subobjects, so must be empty, 3757 // so this almost never matters. 3758 switch (S->getStmtClass()) { 3759 case Stmt::CompoundStmtClass: 3760 // FIXME: Precompute which substatement of a compound statement we 3761 // would jump to, and go straight there rather than performing a 3762 // linear scan each time. 3763 case Stmt::LabelStmtClass: 3764 case Stmt::AttributedStmtClass: 3765 case Stmt::DoStmtClass: 3766 break; 3767 3768 case Stmt::CaseStmtClass: 3769 case Stmt::DefaultStmtClass: 3770 if (Case == S) 3771 Case = nullptr; 3772 break; 3773 3774 case Stmt::IfStmtClass: { 3775 // FIXME: Precompute which side of an 'if' we would jump to, and go 3776 // straight there rather than scanning both sides. 3777 const IfStmt *IS = cast<IfStmt>(S); 3778 3779 // Wrap the evaluation in a block scope, in case it's a DeclStmt 3780 // preceded by our switch label. 3781 BlockScopeRAII Scope(Info); 3782 3783 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 3784 if (ESR != ESR_CaseNotFound || !IS->getElse()) 3785 return ESR; 3786 return EvaluateStmt(Result, Info, IS->getElse(), Case); 3787 } 3788 3789 case Stmt::WhileStmtClass: { 3790 EvalStmtResult ESR = 3791 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 3792 if (ESR != ESR_Continue) 3793 return ESR; 3794 break; 3795 } 3796 3797 case Stmt::ForStmtClass: { 3798 const ForStmt *FS = cast<ForStmt>(S); 3799 EvalStmtResult ESR = 3800 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 3801 if (ESR != ESR_Continue) 3802 return ESR; 3803 if (FS->getInc()) { 3804 FullExpressionRAII IncScope(Info); 3805 if (!EvaluateIgnoredValue(Info, FS->getInc())) 3806 return ESR_Failed; 3807 } 3808 break; 3809 } 3810 3811 case Stmt::DeclStmtClass: 3812 // FIXME: If the variable has initialization that can't be jumped over, 3813 // bail out of any immediately-surrounding compound-statement too. 3814 default: 3815 return ESR_CaseNotFound; 3816 } 3817 } 3818 3819 switch (S->getStmtClass()) { 3820 default: 3821 if (const Expr *E = dyn_cast<Expr>(S)) { 3822 // Don't bother evaluating beyond an expression-statement which couldn't 3823 // be evaluated. 3824 FullExpressionRAII Scope(Info); 3825 if (!EvaluateIgnoredValue(Info, E)) 3826 return ESR_Failed; 3827 return ESR_Succeeded; 3828 } 3829 3830 Info.FFDiag(S->getLocStart()); 3831 return ESR_Failed; 3832 3833 case Stmt::NullStmtClass: 3834 return ESR_Succeeded; 3835 3836 case Stmt::DeclStmtClass: { 3837 const DeclStmt *DS = cast<DeclStmt>(S); 3838 for (const auto *DclIt : DS->decls()) { 3839 // Each declaration initialization is its own full-expression. 3840 // FIXME: This isn't quite right; if we're performing aggregate 3841 // initialization, each braced subexpression is its own full-expression. 3842 FullExpressionRAII Scope(Info); 3843 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure()) 3844 return ESR_Failed; 3845 } 3846 return ESR_Succeeded; 3847 } 3848 3849 case Stmt::ReturnStmtClass: { 3850 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 3851 FullExpressionRAII Scope(Info); 3852 if (RetExpr && 3853 !(Result.Slot 3854 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 3855 : Evaluate(Result.Value, Info, RetExpr))) 3856 return ESR_Failed; 3857 return ESR_Returned; 3858 } 3859 3860 case Stmt::CompoundStmtClass: { 3861 BlockScopeRAII Scope(Info); 3862 3863 const CompoundStmt *CS = cast<CompoundStmt>(S); 3864 for (const auto *BI : CS->body()) { 3865 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 3866 if (ESR == ESR_Succeeded) 3867 Case = nullptr; 3868 else if (ESR != ESR_CaseNotFound) 3869 return ESR; 3870 } 3871 return Case ? ESR_CaseNotFound : ESR_Succeeded; 3872 } 3873 3874 case Stmt::IfStmtClass: { 3875 const IfStmt *IS = cast<IfStmt>(S); 3876 3877 // Evaluate the condition, as either a var decl or as an expression. 3878 BlockScopeRAII Scope(Info); 3879 if (const Stmt *Init = IS->getInit()) { 3880 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 3881 if (ESR != ESR_Succeeded) 3882 return ESR; 3883 } 3884 bool Cond; 3885 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 3886 return ESR_Failed; 3887 3888 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 3889 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 3890 if (ESR != ESR_Succeeded) 3891 return ESR; 3892 } 3893 return ESR_Succeeded; 3894 } 3895 3896 case Stmt::WhileStmtClass: { 3897 const WhileStmt *WS = cast<WhileStmt>(S); 3898 while (true) { 3899 BlockScopeRAII Scope(Info); 3900 bool Continue; 3901 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 3902 Continue)) 3903 return ESR_Failed; 3904 if (!Continue) 3905 break; 3906 3907 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 3908 if (ESR != ESR_Continue) 3909 return ESR; 3910 } 3911 return ESR_Succeeded; 3912 } 3913 3914 case Stmt::DoStmtClass: { 3915 const DoStmt *DS = cast<DoStmt>(S); 3916 bool Continue; 3917 do { 3918 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 3919 if (ESR != ESR_Continue) 3920 return ESR; 3921 Case = nullptr; 3922 3923 FullExpressionRAII CondScope(Info); 3924 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info)) 3925 return ESR_Failed; 3926 } while (Continue); 3927 return ESR_Succeeded; 3928 } 3929 3930 case Stmt::ForStmtClass: { 3931 const ForStmt *FS = cast<ForStmt>(S); 3932 BlockScopeRAII Scope(Info); 3933 if (FS->getInit()) { 3934 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 3935 if (ESR != ESR_Succeeded) 3936 return ESR; 3937 } 3938 while (true) { 3939 BlockScopeRAII Scope(Info); 3940 bool Continue = true; 3941 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 3942 FS->getCond(), Continue)) 3943 return ESR_Failed; 3944 if (!Continue) 3945 break; 3946 3947 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 3948 if (ESR != ESR_Continue) 3949 return ESR; 3950 3951 if (FS->getInc()) { 3952 FullExpressionRAII IncScope(Info); 3953 if (!EvaluateIgnoredValue(Info, FS->getInc())) 3954 return ESR_Failed; 3955 } 3956 } 3957 return ESR_Succeeded; 3958 } 3959 3960 case Stmt::CXXForRangeStmtClass: { 3961 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 3962 BlockScopeRAII Scope(Info); 3963 3964 // Initialize the __range variable. 3965 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 3966 if (ESR != ESR_Succeeded) 3967 return ESR; 3968 3969 // Create the __begin and __end iterators. 3970 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 3971 if (ESR != ESR_Succeeded) 3972 return ESR; 3973 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 3974 if (ESR != ESR_Succeeded) 3975 return ESR; 3976 3977 while (true) { 3978 // Condition: __begin != __end. 3979 { 3980 bool Continue = true; 3981 FullExpressionRAII CondExpr(Info); 3982 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 3983 return ESR_Failed; 3984 if (!Continue) 3985 break; 3986 } 3987 3988 // User's variable declaration, initialized by *__begin. 3989 BlockScopeRAII InnerScope(Info); 3990 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 3991 if (ESR != ESR_Succeeded) 3992 return ESR; 3993 3994 // Loop body. 3995 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 3996 if (ESR != ESR_Continue) 3997 return ESR; 3998 3999 // Increment: ++__begin 4000 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4001 return ESR_Failed; 4002 } 4003 4004 return ESR_Succeeded; 4005 } 4006 4007 case Stmt::SwitchStmtClass: 4008 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 4009 4010 case Stmt::ContinueStmtClass: 4011 return ESR_Continue; 4012 4013 case Stmt::BreakStmtClass: 4014 return ESR_Break; 4015 4016 case Stmt::LabelStmtClass: 4017 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 4018 4019 case Stmt::AttributedStmtClass: 4020 // As a general principle, C++11 attributes can be ignored without 4021 // any semantic impact. 4022 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 4023 Case); 4024 4025 case Stmt::CaseStmtClass: 4026 case Stmt::DefaultStmtClass: 4027 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 4028 } 4029 } 4030 4031 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 4032 /// default constructor. If so, we'll fold it whether or not it's marked as 4033 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 4034 /// so we need special handling. 4035 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 4036 const CXXConstructorDecl *CD, 4037 bool IsValueInitialization) { 4038 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 4039 return false; 4040 4041 // Value-initialization does not call a trivial default constructor, so such a 4042 // call is a core constant expression whether or not the constructor is 4043 // constexpr. 4044 if (!CD->isConstexpr() && !IsValueInitialization) { 4045 if (Info.getLangOpts().CPlusPlus11) { 4046 // FIXME: If DiagDecl is an implicitly-declared special member function, 4047 // we should be much more explicit about why it's not constexpr. 4048 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 4049 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 4050 Info.Note(CD->getLocation(), diag::note_declared_at); 4051 } else { 4052 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 4053 } 4054 } 4055 return true; 4056 } 4057 4058 /// CheckConstexprFunction - Check that a function can be called in a constant 4059 /// expression. 4060 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 4061 const FunctionDecl *Declaration, 4062 const FunctionDecl *Definition, 4063 const Stmt *Body) { 4064 // Potential constant expressions can contain calls to declared, but not yet 4065 // defined, constexpr functions. 4066 if (Info.checkingPotentialConstantExpression() && !Definition && 4067 Declaration->isConstexpr()) 4068 return false; 4069 4070 // Bail out with no diagnostic if the function declaration itself is invalid. 4071 // We will have produced a relevant diagnostic while parsing it. 4072 if (Declaration->isInvalidDecl()) 4073 return false; 4074 4075 // Can we evaluate this function call? 4076 if (Definition && Definition->isConstexpr() && 4077 !Definition->isInvalidDecl() && Body) 4078 return true; 4079 4080 if (Info.getLangOpts().CPlusPlus11) { 4081 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 4082 4083 // If this function is not constexpr because it is an inherited 4084 // non-constexpr constructor, diagnose that directly. 4085 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 4086 if (CD && CD->isInheritingConstructor()) { 4087 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 4088 if (!Inherited->isConstexpr()) 4089 DiagDecl = CD = Inherited; 4090 } 4091 4092 // FIXME: If DiagDecl is an implicitly-declared special member function 4093 // or an inheriting constructor, we should be much more explicit about why 4094 // it's not constexpr. 4095 if (CD && CD->isInheritingConstructor()) 4096 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 4097 << CD->getInheritedConstructor().getConstructor()->getParent(); 4098 else 4099 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 4100 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 4101 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 4102 } else { 4103 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4104 } 4105 return false; 4106 } 4107 4108 /// Determine if a class has any fields that might need to be copied by a 4109 /// trivial copy or move operation. 4110 static bool hasFields(const CXXRecordDecl *RD) { 4111 if (!RD || RD->isEmpty()) 4112 return false; 4113 for (auto *FD : RD->fields()) { 4114 if (FD->isUnnamedBitfield()) 4115 continue; 4116 return true; 4117 } 4118 for (auto &Base : RD->bases()) 4119 if (hasFields(Base.getType()->getAsCXXRecordDecl())) 4120 return true; 4121 return false; 4122 } 4123 4124 namespace { 4125 typedef SmallVector<APValue, 8> ArgVector; 4126 } 4127 4128 /// EvaluateArgs - Evaluate the arguments to a function call. 4129 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues, 4130 EvalInfo &Info) { 4131 bool Success = true; 4132 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 4133 I != E; ++I) { 4134 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) { 4135 // If we're checking for a potential constant expression, evaluate all 4136 // initializers even if some of them fail. 4137 if (!Info.noteFailure()) 4138 return false; 4139 Success = false; 4140 } 4141 } 4142 return Success; 4143 } 4144 4145 /// Evaluate a function call. 4146 static bool HandleFunctionCall(SourceLocation CallLoc, 4147 const FunctionDecl *Callee, const LValue *This, 4148 ArrayRef<const Expr*> Args, const Stmt *Body, 4149 EvalInfo &Info, APValue &Result, 4150 const LValue *ResultSlot) { 4151 ArgVector ArgValues(Args.size()); 4152 if (!EvaluateArgs(Args, ArgValues, Info)) 4153 return false; 4154 4155 if (!Info.CheckCallLimit(CallLoc)) 4156 return false; 4157 4158 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 4159 4160 // For a trivial copy or move assignment, perform an APValue copy. This is 4161 // essential for unions, where the operations performed by the assignment 4162 // operator cannot be represented as statements. 4163 // 4164 // Skip this for non-union classes with no fields; in that case, the defaulted 4165 // copy/move does not actually read the object. 4166 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 4167 if (MD && MD->isDefaulted() && 4168 (MD->getParent()->isUnion() || 4169 (MD->isTrivial() && hasFields(MD->getParent())))) { 4170 assert(This && 4171 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 4172 LValue RHS; 4173 RHS.setFrom(Info.Ctx, ArgValues[0]); 4174 APValue RHSValue; 4175 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), 4176 RHS, RHSValue)) 4177 return false; 4178 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx), 4179 RHSValue)) 4180 return false; 4181 This->moveInto(Result); 4182 return true; 4183 } 4184 4185 StmtResult Ret = {Result, ResultSlot}; 4186 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 4187 if (ESR == ESR_Succeeded) { 4188 if (Callee->getReturnType()->isVoidType()) 4189 return true; 4190 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return); 4191 } 4192 return ESR == ESR_Returned; 4193 } 4194 4195 /// Evaluate a constructor call. 4196 static bool HandleConstructorCall(const Expr *E, const LValue &This, 4197 APValue *ArgValues, 4198 const CXXConstructorDecl *Definition, 4199 EvalInfo &Info, APValue &Result) { 4200 SourceLocation CallLoc = E->getExprLoc(); 4201 if (!Info.CheckCallLimit(CallLoc)) 4202 return false; 4203 4204 const CXXRecordDecl *RD = Definition->getParent(); 4205 if (RD->getNumVBases()) { 4206 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 4207 return false; 4208 } 4209 4210 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 4211 4212 // FIXME: Creating an APValue just to hold a nonexistent return value is 4213 // wasteful. 4214 APValue RetVal; 4215 StmtResult Ret = {RetVal, nullptr}; 4216 4217 // If it's a delegating constructor, delegate. 4218 if (Definition->isDelegatingConstructor()) { 4219 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 4220 { 4221 FullExpressionRAII InitScope(Info); 4222 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit())) 4223 return false; 4224 } 4225 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 4226 } 4227 4228 // For a trivial copy or move constructor, perform an APValue copy. This is 4229 // essential for unions (or classes with anonymous union members), where the 4230 // operations performed by the constructor cannot be represented by 4231 // ctor-initializers. 4232 // 4233 // Skip this for empty non-union classes; we should not perform an 4234 // lvalue-to-rvalue conversion on them because their copy constructor does not 4235 // actually read them. 4236 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 4237 (Definition->getParent()->isUnion() || 4238 (Definition->isTrivial() && hasFields(Definition->getParent())))) { 4239 LValue RHS; 4240 RHS.setFrom(Info.Ctx, ArgValues[0]); 4241 return handleLValueToRValueConversion( 4242 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 4243 RHS, Result); 4244 } 4245 4246 // Reserve space for the struct members. 4247 if (!RD->isUnion() && Result.isUninit()) 4248 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4249 std::distance(RD->field_begin(), RD->field_end())); 4250 4251 if (RD->isInvalidDecl()) return false; 4252 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 4253 4254 // A scope for temporaries lifetime-extended by reference members. 4255 BlockScopeRAII LifetimeExtendedScope(Info); 4256 4257 bool Success = true; 4258 unsigned BasesSeen = 0; 4259 #ifndef NDEBUG 4260 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 4261 #endif 4262 for (const auto *I : Definition->inits()) { 4263 LValue Subobject = This; 4264 APValue *Value = &Result; 4265 4266 // Determine the subobject to initialize. 4267 FieldDecl *FD = nullptr; 4268 if (I->isBaseInitializer()) { 4269 QualType BaseType(I->getBaseClass(), 0); 4270 #ifndef NDEBUG 4271 // Non-virtual base classes are initialized in the order in the class 4272 // definition. We have already checked for virtual base classes. 4273 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 4274 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 4275 "base class initializers not in expected order"); 4276 ++BaseIt; 4277 #endif 4278 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 4279 BaseType->getAsCXXRecordDecl(), &Layout)) 4280 return false; 4281 Value = &Result.getStructBase(BasesSeen++); 4282 } else if ((FD = I->getMember())) { 4283 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 4284 return false; 4285 if (RD->isUnion()) { 4286 Result = APValue(FD); 4287 Value = &Result.getUnionValue(); 4288 } else { 4289 Value = &Result.getStructField(FD->getFieldIndex()); 4290 } 4291 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 4292 // Walk the indirect field decl's chain to find the object to initialize, 4293 // and make sure we've initialized every step along it. 4294 for (auto *C : IFD->chain()) { 4295 FD = cast<FieldDecl>(C); 4296 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 4297 // Switch the union field if it differs. This happens if we had 4298 // preceding zero-initialization, and we're now initializing a union 4299 // subobject other than the first. 4300 // FIXME: In this case, the values of the other subobjects are 4301 // specified, since zero-initialization sets all padding bits to zero. 4302 if (Value->isUninit() || 4303 (Value->isUnion() && Value->getUnionField() != FD)) { 4304 if (CD->isUnion()) 4305 *Value = APValue(FD); 4306 else 4307 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(), 4308 std::distance(CD->field_begin(), CD->field_end())); 4309 } 4310 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 4311 return false; 4312 if (CD->isUnion()) 4313 Value = &Value->getUnionValue(); 4314 else 4315 Value = &Value->getStructField(FD->getFieldIndex()); 4316 } 4317 } else { 4318 llvm_unreachable("unknown base initializer kind"); 4319 } 4320 4321 FullExpressionRAII InitScope(Info); 4322 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) || 4323 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(), 4324 *Value, FD))) { 4325 // If we're checking for a potential constant expression, evaluate all 4326 // initializers even if some of them fail. 4327 if (!Info.noteFailure()) 4328 return false; 4329 Success = false; 4330 } 4331 } 4332 4333 return Success && 4334 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 4335 } 4336 4337 static bool HandleConstructorCall(const Expr *E, const LValue &This, 4338 ArrayRef<const Expr*> Args, 4339 const CXXConstructorDecl *Definition, 4340 EvalInfo &Info, APValue &Result) { 4341 ArgVector ArgValues(Args.size()); 4342 if (!EvaluateArgs(Args, ArgValues, Info)) 4343 return false; 4344 4345 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 4346 Info, Result); 4347 } 4348 4349 //===----------------------------------------------------------------------===// 4350 // Generic Evaluation 4351 //===----------------------------------------------------------------------===// 4352 namespace { 4353 4354 template <class Derived> 4355 class ExprEvaluatorBase 4356 : public ConstStmtVisitor<Derived, bool> { 4357 private: 4358 Derived &getDerived() { return static_cast<Derived&>(*this); } 4359 bool DerivedSuccess(const APValue &V, const Expr *E) { 4360 return getDerived().Success(V, E); 4361 } 4362 bool DerivedZeroInitialization(const Expr *E) { 4363 return getDerived().ZeroInitialization(E); 4364 } 4365 4366 // Check whether a conditional operator with a non-constant condition is a 4367 // potential constant expression. If neither arm is a potential constant 4368 // expression, then the conditional operator is not either. 4369 template<typename ConditionalOperator> 4370 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 4371 assert(Info.checkingPotentialConstantExpression()); 4372 4373 // Speculatively evaluate both arms. 4374 SmallVector<PartialDiagnosticAt, 8> Diag; 4375 { 4376 SpeculativeEvaluationRAII Speculate(Info, &Diag); 4377 StmtVisitorTy::Visit(E->getFalseExpr()); 4378 if (Diag.empty()) 4379 return; 4380 } 4381 4382 { 4383 SpeculativeEvaluationRAII Speculate(Info, &Diag); 4384 Diag.clear(); 4385 StmtVisitorTy::Visit(E->getTrueExpr()); 4386 if (Diag.empty()) 4387 return; 4388 } 4389 4390 Error(E, diag::note_constexpr_conditional_never_const); 4391 } 4392 4393 4394 template<typename ConditionalOperator> 4395 bool HandleConditionalOperator(const ConditionalOperator *E) { 4396 bool BoolResult; 4397 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 4398 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) 4399 CheckPotentialConstantConditional(E); 4400 return false; 4401 } 4402 4403 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 4404 return StmtVisitorTy::Visit(EvalExpr); 4405 } 4406 4407 protected: 4408 EvalInfo &Info; 4409 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 4410 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 4411 4412 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 4413 return Info.CCEDiag(E, D); 4414 } 4415 4416 bool ZeroInitialization(const Expr *E) { return Error(E); } 4417 4418 public: 4419 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 4420 4421 EvalInfo &getEvalInfo() { return Info; } 4422 4423 /// Report an evaluation error. This should only be called when an error is 4424 /// first discovered. When propagating an error, just return false. 4425 bool Error(const Expr *E, diag::kind D) { 4426 Info.FFDiag(E, D); 4427 return false; 4428 } 4429 bool Error(const Expr *E) { 4430 return Error(E, diag::note_invalid_subexpr_in_const_expr); 4431 } 4432 4433 bool VisitStmt(const Stmt *) { 4434 llvm_unreachable("Expression evaluator should not be called on stmts"); 4435 } 4436 bool VisitExpr(const Expr *E) { 4437 return Error(E); 4438 } 4439 4440 bool VisitParenExpr(const ParenExpr *E) 4441 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4442 bool VisitUnaryExtension(const UnaryOperator *E) 4443 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4444 bool VisitUnaryPlus(const UnaryOperator *E) 4445 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4446 bool VisitChooseExpr(const ChooseExpr *E) 4447 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 4448 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 4449 { return StmtVisitorTy::Visit(E->getResultExpr()); } 4450 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 4451 { return StmtVisitorTy::Visit(E->getReplacement()); } 4452 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) 4453 { return StmtVisitorTy::Visit(E->getExpr()); } 4454 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 4455 // The initializer may not have been parsed yet, or might be erroneous. 4456 if (!E->getExpr()) 4457 return Error(E); 4458 return StmtVisitorTy::Visit(E->getExpr()); 4459 } 4460 // We cannot create any objects for which cleanups are required, so there is 4461 // nothing to do here; all cleanups must come from unevaluated subexpressions. 4462 bool VisitExprWithCleanups(const ExprWithCleanups *E) 4463 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4464 4465 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 4466 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 4467 return static_cast<Derived*>(this)->VisitCastExpr(E); 4468 } 4469 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 4470 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 4471 return static_cast<Derived*>(this)->VisitCastExpr(E); 4472 } 4473 4474 bool VisitBinaryOperator(const BinaryOperator *E) { 4475 switch (E->getOpcode()) { 4476 default: 4477 return Error(E); 4478 4479 case BO_Comma: 4480 VisitIgnoredValue(E->getLHS()); 4481 return StmtVisitorTy::Visit(E->getRHS()); 4482 4483 case BO_PtrMemD: 4484 case BO_PtrMemI: { 4485 LValue Obj; 4486 if (!HandleMemberPointerAccess(Info, E, Obj)) 4487 return false; 4488 APValue Result; 4489 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 4490 return false; 4491 return DerivedSuccess(Result, E); 4492 } 4493 } 4494 } 4495 4496 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 4497 // Evaluate and cache the common expression. We treat it as a temporary, 4498 // even though it's not quite the same thing. 4499 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false), 4500 Info, E->getCommon())) 4501 return false; 4502 4503 return HandleConditionalOperator(E); 4504 } 4505 4506 bool VisitConditionalOperator(const ConditionalOperator *E) { 4507 bool IsBcpCall = false; 4508 // If the condition (ignoring parens) is a __builtin_constant_p call, 4509 // the result is a constant expression if it can be folded without 4510 // side-effects. This is an important GNU extension. See GCC PR38377 4511 // for discussion. 4512 if (const CallExpr *CallCE = 4513 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 4514 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 4515 IsBcpCall = true; 4516 4517 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 4518 // constant expression; we can't check whether it's potentially foldable. 4519 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 4520 return false; 4521 4522 FoldConstant Fold(Info, IsBcpCall); 4523 if (!HandleConditionalOperator(E)) { 4524 Fold.keepDiagnostics(); 4525 return false; 4526 } 4527 4528 return true; 4529 } 4530 4531 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 4532 if (APValue *Value = Info.CurrentCall->getTemporary(E)) 4533 return DerivedSuccess(*Value, E); 4534 4535 const Expr *Source = E->getSourceExpr(); 4536 if (!Source) 4537 return Error(E); 4538 if (Source == E) { // sanity checking. 4539 assert(0 && "OpaqueValueExpr recursively refers to itself"); 4540 return Error(E); 4541 } 4542 return StmtVisitorTy::Visit(Source); 4543 } 4544 4545 bool VisitCallExpr(const CallExpr *E) { 4546 APValue Result; 4547 if (!handleCallExpr(E, Result, nullptr)) 4548 return false; 4549 return DerivedSuccess(Result, E); 4550 } 4551 4552 bool handleCallExpr(const CallExpr *E, APValue &Result, 4553 const LValue *ResultSlot) { 4554 const Expr *Callee = E->getCallee()->IgnoreParens(); 4555 QualType CalleeType = Callee->getType(); 4556 4557 const FunctionDecl *FD = nullptr; 4558 LValue *This = nullptr, ThisVal; 4559 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 4560 bool HasQualifier = false; 4561 4562 // Extract function decl and 'this' pointer from the callee. 4563 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 4564 const ValueDecl *Member = nullptr; 4565 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 4566 // Explicit bound member calls, such as x.f() or p->g(); 4567 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 4568 return false; 4569 Member = ME->getMemberDecl(); 4570 This = &ThisVal; 4571 HasQualifier = ME->hasQualifier(); 4572 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 4573 // Indirect bound member calls ('.*' or '->*'). 4574 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false); 4575 if (!Member) return false; 4576 This = &ThisVal; 4577 } else 4578 return Error(Callee); 4579 4580 FD = dyn_cast<FunctionDecl>(Member); 4581 if (!FD) 4582 return Error(Callee); 4583 } else if (CalleeType->isFunctionPointerType()) { 4584 LValue Call; 4585 if (!EvaluatePointer(Callee, Call, Info)) 4586 return false; 4587 4588 if (!Call.getLValueOffset().isZero()) 4589 return Error(Callee); 4590 FD = dyn_cast_or_null<FunctionDecl>( 4591 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 4592 if (!FD) 4593 return Error(Callee); 4594 // Don't call function pointers which have been cast to some other type. 4595 // Per DR (no number yet), the caller and callee can differ in noexcept. 4596 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 4597 CalleeType->getPointeeType(), FD->getType())) { 4598 return Error(E); 4599 } 4600 4601 // Overloaded operator calls to member functions are represented as normal 4602 // calls with '*this' as the first argument. 4603 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 4604 if (MD && !MD->isStatic()) { 4605 // FIXME: When selecting an implicit conversion for an overloaded 4606 // operator delete, we sometimes try to evaluate calls to conversion 4607 // operators without a 'this' parameter! 4608 if (Args.empty()) 4609 return Error(E); 4610 4611 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 4612 return false; 4613 This = &ThisVal; 4614 Args = Args.slice(1); 4615 } else if (MD && MD->isLambdaStaticInvoker()) { 4616 // Map the static invoker for the lambda back to the call operator. 4617 // Conveniently, we don't have to slice out the 'this' argument (as is 4618 // being done for the non-static case), since a static member function 4619 // doesn't have an implicit argument passed in. 4620 const CXXRecordDecl *ClosureClass = MD->getParent(); 4621 assert( 4622 ClosureClass->captures_begin() == ClosureClass->captures_end() && 4623 "Number of captures must be zero for conversion to function-ptr"); 4624 4625 const CXXMethodDecl *LambdaCallOp = 4626 ClosureClass->getLambdaCallOperator(); 4627 4628 // Set 'FD', the function that will be called below, to the call 4629 // operator. If the closure object represents a generic lambda, find 4630 // the corresponding specialization of the call operator. 4631 4632 if (ClosureClass->isGenericLambda()) { 4633 assert(MD->isFunctionTemplateSpecialization() && 4634 "A generic lambda's static-invoker function must be a " 4635 "template specialization"); 4636 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 4637 FunctionTemplateDecl *CallOpTemplate = 4638 LambdaCallOp->getDescribedFunctionTemplate(); 4639 void *InsertPos = nullptr; 4640 FunctionDecl *CorrespondingCallOpSpecialization = 4641 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 4642 assert(CorrespondingCallOpSpecialization && 4643 "We must always have a function call operator specialization " 4644 "that corresponds to our static invoker specialization"); 4645 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 4646 } else 4647 FD = LambdaCallOp; 4648 } 4649 4650 4651 } else 4652 return Error(E); 4653 4654 if (This && !This->checkSubobject(Info, E, CSK_This)) 4655 return false; 4656 4657 // DR1358 allows virtual constexpr functions in some cases. Don't allow 4658 // calls to such functions in constant expressions. 4659 if (This && !HasQualifier && 4660 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual()) 4661 return Error(E, diag::note_constexpr_virtual_call); 4662 4663 const FunctionDecl *Definition = nullptr; 4664 Stmt *Body = FD->getBody(Definition); 4665 4666 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 4667 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 4668 Result, ResultSlot)) 4669 return false; 4670 4671 return true; 4672 } 4673 4674 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 4675 return StmtVisitorTy::Visit(E->getInitializer()); 4676 } 4677 bool VisitInitListExpr(const InitListExpr *E) { 4678 if (E->getNumInits() == 0) 4679 return DerivedZeroInitialization(E); 4680 if (E->getNumInits() == 1) 4681 return StmtVisitorTy::Visit(E->getInit(0)); 4682 return Error(E); 4683 } 4684 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 4685 return DerivedZeroInitialization(E); 4686 } 4687 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 4688 return DerivedZeroInitialization(E); 4689 } 4690 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 4691 return DerivedZeroInitialization(E); 4692 } 4693 4694 /// A member expression where the object is a prvalue is itself a prvalue. 4695 bool VisitMemberExpr(const MemberExpr *E) { 4696 assert(!E->isArrow() && "missing call to bound member function?"); 4697 4698 APValue Val; 4699 if (!Evaluate(Val, Info, E->getBase())) 4700 return false; 4701 4702 QualType BaseTy = E->getBase()->getType(); 4703 4704 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 4705 if (!FD) return Error(E); 4706 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 4707 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 4708 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 4709 4710 CompleteObject Obj(&Val, BaseTy); 4711 SubobjectDesignator Designator(BaseTy); 4712 Designator.addDeclUnchecked(FD); 4713 4714 APValue Result; 4715 return extractSubobject(Info, E, Obj, Designator, Result) && 4716 DerivedSuccess(Result, E); 4717 } 4718 4719 bool VisitCastExpr(const CastExpr *E) { 4720 switch (E->getCastKind()) { 4721 default: 4722 break; 4723 4724 case CK_AtomicToNonAtomic: { 4725 APValue AtomicVal; 4726 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info)) 4727 return false; 4728 return DerivedSuccess(AtomicVal, E); 4729 } 4730 4731 case CK_NoOp: 4732 case CK_UserDefinedConversion: 4733 return StmtVisitorTy::Visit(E->getSubExpr()); 4734 4735 case CK_LValueToRValue: { 4736 LValue LVal; 4737 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 4738 return false; 4739 APValue RVal; 4740 // Note, we use the subexpression's type in order to retain cv-qualifiers. 4741 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 4742 LVal, RVal)) 4743 return false; 4744 return DerivedSuccess(RVal, E); 4745 } 4746 } 4747 4748 return Error(E); 4749 } 4750 4751 bool VisitUnaryPostInc(const UnaryOperator *UO) { 4752 return VisitUnaryPostIncDec(UO); 4753 } 4754 bool VisitUnaryPostDec(const UnaryOperator *UO) { 4755 return VisitUnaryPostIncDec(UO); 4756 } 4757 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 4758 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 4759 return Error(UO); 4760 4761 LValue LVal; 4762 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 4763 return false; 4764 APValue RVal; 4765 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 4766 UO->isIncrementOp(), &RVal)) 4767 return false; 4768 return DerivedSuccess(RVal, UO); 4769 } 4770 4771 bool VisitStmtExpr(const StmtExpr *E) { 4772 // We will have checked the full-expressions inside the statement expression 4773 // when they were completed, and don't need to check them again now. 4774 if (Info.checkingForOverflow()) 4775 return Error(E); 4776 4777 BlockScopeRAII Scope(Info); 4778 const CompoundStmt *CS = E->getSubStmt(); 4779 if (CS->body_empty()) 4780 return true; 4781 4782 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 4783 BE = CS->body_end(); 4784 /**/; ++BI) { 4785 if (BI + 1 == BE) { 4786 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 4787 if (!FinalExpr) { 4788 Info.FFDiag((*BI)->getLocStart(), 4789 diag::note_constexpr_stmt_expr_unsupported); 4790 return false; 4791 } 4792 return this->Visit(FinalExpr); 4793 } 4794 4795 APValue ReturnValue; 4796 StmtResult Result = { ReturnValue, nullptr }; 4797 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 4798 if (ESR != ESR_Succeeded) { 4799 // FIXME: If the statement-expression terminated due to 'return', 4800 // 'break', or 'continue', it would be nice to propagate that to 4801 // the outer statement evaluation rather than bailing out. 4802 if (ESR != ESR_Failed) 4803 Info.FFDiag((*BI)->getLocStart(), 4804 diag::note_constexpr_stmt_expr_unsupported); 4805 return false; 4806 } 4807 } 4808 4809 llvm_unreachable("Return from function from the loop above."); 4810 } 4811 4812 /// Visit a value which is evaluated, but whose value is ignored. 4813 void VisitIgnoredValue(const Expr *E) { 4814 EvaluateIgnoredValue(Info, E); 4815 } 4816 4817 /// Potentially visit a MemberExpr's base expression. 4818 void VisitIgnoredBaseExpression(const Expr *E) { 4819 // While MSVC doesn't evaluate the base expression, it does diagnose the 4820 // presence of side-effecting behavior. 4821 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 4822 return; 4823 VisitIgnoredValue(E); 4824 } 4825 }; 4826 4827 } 4828 4829 //===----------------------------------------------------------------------===// 4830 // Common base class for lvalue and temporary evaluation. 4831 //===----------------------------------------------------------------------===// 4832 namespace { 4833 template<class Derived> 4834 class LValueExprEvaluatorBase 4835 : public ExprEvaluatorBase<Derived> { 4836 protected: 4837 LValue &Result; 4838 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 4839 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 4840 4841 bool Success(APValue::LValueBase B) { 4842 Result.set(B); 4843 return true; 4844 } 4845 4846 public: 4847 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) : 4848 ExprEvaluatorBaseTy(Info), Result(Result) {} 4849 4850 bool Success(const APValue &V, const Expr *E) { 4851 Result.setFrom(this->Info.Ctx, V); 4852 return true; 4853 } 4854 4855 bool VisitMemberExpr(const MemberExpr *E) { 4856 // Handle non-static data members. 4857 QualType BaseTy; 4858 bool EvalOK; 4859 if (E->isArrow()) { 4860 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info); 4861 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 4862 } else if (E->getBase()->isRValue()) { 4863 assert(E->getBase()->getType()->isRecordType()); 4864 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 4865 BaseTy = E->getBase()->getType(); 4866 } else { 4867 EvalOK = this->Visit(E->getBase()); 4868 BaseTy = E->getBase()->getType(); 4869 } 4870 if (!EvalOK) { 4871 if (!this->Info.allowInvalidBaseExpr()) 4872 return false; 4873 Result.setInvalid(E); 4874 return true; 4875 } 4876 4877 const ValueDecl *MD = E->getMemberDecl(); 4878 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 4879 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 4880 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 4881 (void)BaseTy; 4882 if (!HandleLValueMember(this->Info, E, Result, FD)) 4883 return false; 4884 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 4885 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 4886 return false; 4887 } else 4888 return this->Error(E); 4889 4890 if (MD->getType()->isReferenceType()) { 4891 APValue RefValue; 4892 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 4893 RefValue)) 4894 return false; 4895 return Success(RefValue, E); 4896 } 4897 return true; 4898 } 4899 4900 bool VisitBinaryOperator(const BinaryOperator *E) { 4901 switch (E->getOpcode()) { 4902 default: 4903 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 4904 4905 case BO_PtrMemD: 4906 case BO_PtrMemI: 4907 return HandleMemberPointerAccess(this->Info, E, Result); 4908 } 4909 } 4910 4911 bool VisitCastExpr(const CastExpr *E) { 4912 switch (E->getCastKind()) { 4913 default: 4914 return ExprEvaluatorBaseTy::VisitCastExpr(E); 4915 4916 case CK_DerivedToBase: 4917 case CK_UncheckedDerivedToBase: 4918 if (!this->Visit(E->getSubExpr())) 4919 return false; 4920 4921 // Now figure out the necessary offset to add to the base LV to get from 4922 // the derived class to the base class. 4923 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 4924 Result); 4925 } 4926 } 4927 }; 4928 } 4929 4930 //===----------------------------------------------------------------------===// 4931 // LValue Evaluation 4932 // 4933 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 4934 // function designators (in C), decl references to void objects (in C), and 4935 // temporaries (if building with -Wno-address-of-temporary). 4936 // 4937 // LValue evaluation produces values comprising a base expression of one of the 4938 // following types: 4939 // - Declarations 4940 // * VarDecl 4941 // * FunctionDecl 4942 // - Literals 4943 // * CompoundLiteralExpr in C (and in global scope in C++) 4944 // * StringLiteral 4945 // * CXXTypeidExpr 4946 // * PredefinedExpr 4947 // * ObjCStringLiteralExpr 4948 // * ObjCEncodeExpr 4949 // * AddrLabelExpr 4950 // * BlockExpr 4951 // * CallExpr for a MakeStringConstant builtin 4952 // - Locals and temporaries 4953 // * MaterializeTemporaryExpr 4954 // * Any Expr, with a CallIndex indicating the function in which the temporary 4955 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 4956 // from the AST (FIXME). 4957 // * A MaterializeTemporaryExpr that has static storage duration, with no 4958 // CallIndex, for a lifetime-extended temporary. 4959 // plus an offset in bytes. 4960 //===----------------------------------------------------------------------===// 4961 namespace { 4962 class LValueExprEvaluator 4963 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 4964 public: 4965 LValueExprEvaluator(EvalInfo &Info, LValue &Result) : 4966 LValueExprEvaluatorBaseTy(Info, Result) {} 4967 4968 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 4969 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 4970 4971 bool VisitDeclRefExpr(const DeclRefExpr *E); 4972 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 4973 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 4974 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 4975 bool VisitMemberExpr(const MemberExpr *E); 4976 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 4977 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 4978 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 4979 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 4980 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 4981 bool VisitUnaryDeref(const UnaryOperator *E); 4982 bool VisitUnaryReal(const UnaryOperator *E); 4983 bool VisitUnaryImag(const UnaryOperator *E); 4984 bool VisitUnaryPreInc(const UnaryOperator *UO) { 4985 return VisitUnaryPreIncDec(UO); 4986 } 4987 bool VisitUnaryPreDec(const UnaryOperator *UO) { 4988 return VisitUnaryPreIncDec(UO); 4989 } 4990 bool VisitBinAssign(const BinaryOperator *BO); 4991 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 4992 4993 bool VisitCastExpr(const CastExpr *E) { 4994 switch (E->getCastKind()) { 4995 default: 4996 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 4997 4998 case CK_LValueBitCast: 4999 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5000 if (!Visit(E->getSubExpr())) 5001 return false; 5002 Result.Designator.setInvalid(); 5003 return true; 5004 5005 case CK_BaseToDerived: 5006 if (!Visit(E->getSubExpr())) 5007 return false; 5008 return HandleBaseToDerivedCast(Info, E, Result); 5009 } 5010 } 5011 }; 5012 } // end anonymous namespace 5013 5014 /// Evaluate an expression as an lvalue. This can be legitimately called on 5015 /// expressions which are not glvalues, in three cases: 5016 /// * function designators in C, and 5017 /// * "extern void" objects 5018 /// * @selector() expressions in Objective-C 5019 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) { 5020 assert(E->isGLValue() || E->getType()->isFunctionType() || 5021 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 5022 return LValueExprEvaluator(Info, Result).Visit(E); 5023 } 5024 5025 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 5026 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 5027 return Success(FD); 5028 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 5029 return VisitVarDecl(E, VD); 5030 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 5031 return Visit(BD->getBinding()); 5032 return Error(E); 5033 } 5034 5035 5036 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 5037 CallStackFrame *Frame = nullptr; 5038 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 5039 // Only if a local variable was declared in the function currently being 5040 // evaluated, do we expect to be able to find its value in the current 5041 // frame. (Otherwise it was likely declared in an enclosing context and 5042 // could either have a valid evaluatable value (for e.g. a constexpr 5043 // variable) or be ill-formed (and trigger an appropriate evaluation 5044 // diagnostic)). 5045 if (Info.CurrentCall->Callee && 5046 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 5047 Frame = Info.CurrentCall; 5048 } 5049 } 5050 5051 if (!VD->getType()->isReferenceType()) { 5052 if (Frame) { 5053 Result.set(VD, Frame->Index); 5054 return true; 5055 } 5056 return Success(VD); 5057 } 5058 5059 APValue *V; 5060 if (!evaluateVarDeclInit(Info, E, VD, Frame, V)) 5061 return false; 5062 if (V->isUninit()) { 5063 if (!Info.checkingPotentialConstantExpression()) 5064 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 5065 return false; 5066 } 5067 return Success(*V, E); 5068 } 5069 5070 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 5071 const MaterializeTemporaryExpr *E) { 5072 // Walk through the expression to find the materialized temporary itself. 5073 SmallVector<const Expr *, 2> CommaLHSs; 5074 SmallVector<SubobjectAdjustment, 2> Adjustments; 5075 const Expr *Inner = E->GetTemporaryExpr()-> 5076 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 5077 5078 // If we passed any comma operators, evaluate their LHSs. 5079 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 5080 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 5081 return false; 5082 5083 // A materialized temporary with static storage duration can appear within the 5084 // result of a constant expression evaluation, so we need to preserve its 5085 // value for use outside this evaluation. 5086 APValue *Value; 5087 if (E->getStorageDuration() == SD_Static) { 5088 Value = Info.Ctx.getMaterializedTemporaryValue(E, true); 5089 *Value = APValue(); 5090 Result.set(E); 5091 } else { 5092 Value = &Info.CurrentCall-> 5093 createTemporary(E, E->getStorageDuration() == SD_Automatic); 5094 Result.set(E, Info.CurrentCall->Index); 5095 } 5096 5097 QualType Type = Inner->getType(); 5098 5099 // Materialize the temporary itself. 5100 if (!EvaluateInPlace(*Value, Info, Result, Inner) || 5101 (E->getStorageDuration() == SD_Static && 5102 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) { 5103 *Value = APValue(); 5104 return false; 5105 } 5106 5107 // Adjust our lvalue to refer to the desired subobject. 5108 for (unsigned I = Adjustments.size(); I != 0; /**/) { 5109 --I; 5110 switch (Adjustments[I].Kind) { 5111 case SubobjectAdjustment::DerivedToBaseAdjustment: 5112 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 5113 Type, Result)) 5114 return false; 5115 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 5116 break; 5117 5118 case SubobjectAdjustment::FieldAdjustment: 5119 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 5120 return false; 5121 Type = Adjustments[I].Field->getType(); 5122 break; 5123 5124 case SubobjectAdjustment::MemberPointerAdjustment: 5125 if (!HandleMemberPointerAccess(this->Info, Type, Result, 5126 Adjustments[I].Ptr.RHS)) 5127 return false; 5128 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 5129 break; 5130 } 5131 } 5132 5133 return true; 5134 } 5135 5136 bool 5137 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 5138 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 5139 "lvalue compound literal in c++?"); 5140 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 5141 // only see this when folding in C, so there's no standard to follow here. 5142 return Success(E); 5143 } 5144 5145 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 5146 if (!E->isPotentiallyEvaluated()) 5147 return Success(E); 5148 5149 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic) 5150 << E->getExprOperand()->getType() 5151 << E->getExprOperand()->getSourceRange(); 5152 return false; 5153 } 5154 5155 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 5156 return Success(E); 5157 } 5158 5159 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 5160 // Handle static data members. 5161 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 5162 VisitIgnoredBaseExpression(E->getBase()); 5163 return VisitVarDecl(E, VD); 5164 } 5165 5166 // Handle static member functions. 5167 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 5168 if (MD->isStatic()) { 5169 VisitIgnoredBaseExpression(E->getBase()); 5170 return Success(MD); 5171 } 5172 } 5173 5174 // Handle non-static data members. 5175 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 5176 } 5177 5178 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 5179 // FIXME: Deal with vectors as array subscript bases. 5180 if (E->getBase()->getType()->isVectorType()) 5181 return Error(E); 5182 5183 if (!EvaluatePointer(E->getBase(), Result, Info)) 5184 return false; 5185 5186 APSInt Index; 5187 if (!EvaluateInteger(E->getIdx(), Index, Info)) 5188 return false; 5189 5190 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 5191 } 5192 5193 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 5194 return EvaluatePointer(E->getSubExpr(), Result, Info); 5195 } 5196 5197 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 5198 if (!Visit(E->getSubExpr())) 5199 return false; 5200 // __real is a no-op on scalar lvalues. 5201 if (E->getSubExpr()->getType()->isAnyComplexType()) 5202 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 5203 return true; 5204 } 5205 5206 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 5207 assert(E->getSubExpr()->getType()->isAnyComplexType() && 5208 "lvalue __imag__ on scalar?"); 5209 if (!Visit(E->getSubExpr())) 5210 return false; 5211 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 5212 return true; 5213 } 5214 5215 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 5216 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5217 return Error(UO); 5218 5219 if (!this->Visit(UO->getSubExpr())) 5220 return false; 5221 5222 return handleIncDec( 5223 this->Info, UO, Result, UO->getSubExpr()->getType(), 5224 UO->isIncrementOp(), nullptr); 5225 } 5226 5227 bool LValueExprEvaluator::VisitCompoundAssignOperator( 5228 const CompoundAssignOperator *CAO) { 5229 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5230 return Error(CAO); 5231 5232 APValue RHS; 5233 5234 // The overall lvalue result is the result of evaluating the LHS. 5235 if (!this->Visit(CAO->getLHS())) { 5236 if (Info.noteFailure()) 5237 Evaluate(RHS, this->Info, CAO->getRHS()); 5238 return false; 5239 } 5240 5241 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 5242 return false; 5243 5244 return handleCompoundAssignment( 5245 this->Info, CAO, 5246 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 5247 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 5248 } 5249 5250 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 5251 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5252 return Error(E); 5253 5254 APValue NewVal; 5255 5256 if (!this->Visit(E->getLHS())) { 5257 if (Info.noteFailure()) 5258 Evaluate(NewVal, this->Info, E->getRHS()); 5259 return false; 5260 } 5261 5262 if (!Evaluate(NewVal, this->Info, E->getRHS())) 5263 return false; 5264 5265 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 5266 NewVal); 5267 } 5268 5269 //===----------------------------------------------------------------------===// 5270 // Pointer Evaluation 5271 //===----------------------------------------------------------------------===// 5272 5273 /// \brief Attempts to compute the number of bytes available at the pointer 5274 /// returned by a function with the alloc_size attribute. Returns true if we 5275 /// were successful. Places an unsigned number into `Result`. 5276 /// 5277 /// This expects the given CallExpr to be a call to a function with an 5278 /// alloc_size attribute. 5279 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 5280 const CallExpr *Call, 5281 llvm::APInt &Result) { 5282 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 5283 5284 // alloc_size args are 1-indexed, 0 means not present. 5285 assert(AllocSize && AllocSize->getElemSizeParam() != 0); 5286 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1; 5287 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 5288 if (Call->getNumArgs() <= SizeArgNo) 5289 return false; 5290 5291 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 5292 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects)) 5293 return false; 5294 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 5295 return false; 5296 Into = Into.zextOrSelf(BitsInSizeT); 5297 return true; 5298 }; 5299 5300 APSInt SizeOfElem; 5301 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 5302 return false; 5303 5304 if (!AllocSize->getNumElemsParam()) { 5305 Result = std::move(SizeOfElem); 5306 return true; 5307 } 5308 5309 APSInt NumberOfElems; 5310 // Argument numbers start at 1 5311 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1; 5312 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 5313 return false; 5314 5315 bool Overflow; 5316 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 5317 if (Overflow) 5318 return false; 5319 5320 Result = std::move(BytesAvailable); 5321 return true; 5322 } 5323 5324 /// \brief Convenience function. LVal's base must be a call to an alloc_size 5325 /// function. 5326 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 5327 const LValue &LVal, 5328 llvm::APInt &Result) { 5329 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 5330 "Can't get the size of a non alloc_size function"); 5331 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 5332 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 5333 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 5334 } 5335 5336 /// \brief Attempts to evaluate the given LValueBase as the result of a call to 5337 /// a function with the alloc_size attribute. If it was possible to do so, this 5338 /// function will return true, make Result's Base point to said function call, 5339 /// and mark Result's Base as invalid. 5340 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 5341 LValue &Result) { 5342 if (!Info.allowInvalidBaseExpr() || Base.isNull()) 5343 return false; 5344 5345 // Because we do no form of static analysis, we only support const variables. 5346 // 5347 // Additionally, we can't support parameters, nor can we support static 5348 // variables (in the latter case, use-before-assign isn't UB; in the former, 5349 // we have no clue what they'll be assigned to). 5350 const auto *VD = 5351 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 5352 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 5353 return false; 5354 5355 const Expr *Init = VD->getAnyInitializer(); 5356 if (!Init) 5357 return false; 5358 5359 const Expr *E = Init->IgnoreParens(); 5360 if (!tryUnwrapAllocSizeCall(E)) 5361 return false; 5362 5363 // Store E instead of E unwrapped so that the type of the LValue's base is 5364 // what the user wanted. 5365 Result.setInvalid(E); 5366 5367 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 5368 Result.addUnsizedArray(Info, Pointee); 5369 return true; 5370 } 5371 5372 namespace { 5373 class PointerExprEvaluator 5374 : public ExprEvaluatorBase<PointerExprEvaluator> { 5375 LValue &Result; 5376 5377 bool Success(const Expr *E) { 5378 Result.set(E); 5379 return true; 5380 } 5381 5382 bool visitNonBuiltinCallExpr(const CallExpr *E); 5383 public: 5384 5385 PointerExprEvaluator(EvalInfo &info, LValue &Result) 5386 : ExprEvaluatorBaseTy(info), Result(Result) {} 5387 5388 bool Success(const APValue &V, const Expr *E) { 5389 Result.setFrom(Info.Ctx, V); 5390 return true; 5391 } 5392 bool ZeroInitialization(const Expr *E) { 5393 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType()); 5394 Result.set((Expr*)nullptr, 0, false, true, Offset); 5395 return true; 5396 } 5397 5398 bool VisitBinaryOperator(const BinaryOperator *E); 5399 bool VisitCastExpr(const CastExpr* E); 5400 bool VisitUnaryAddrOf(const UnaryOperator *E); 5401 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 5402 { return Success(E); } 5403 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) 5404 { return Success(E); } 5405 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 5406 { return Success(E); } 5407 bool VisitCallExpr(const CallExpr *E); 5408 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 5409 bool VisitBlockExpr(const BlockExpr *E) { 5410 if (!E->getBlockDecl()->hasCaptures()) 5411 return Success(E); 5412 return Error(E); 5413 } 5414 bool VisitCXXThisExpr(const CXXThisExpr *E) { 5415 // Can't look at 'this' when checking a potential constant expression. 5416 if (Info.checkingPotentialConstantExpression()) 5417 return false; 5418 if (!Info.CurrentCall->This) { 5419 if (Info.getLangOpts().CPlusPlus11) 5420 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 5421 else 5422 Info.FFDiag(E); 5423 return false; 5424 } 5425 Result = *Info.CurrentCall->This; 5426 return true; 5427 } 5428 5429 // FIXME: Missing: @protocol, @selector 5430 }; 5431 } // end anonymous namespace 5432 5433 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) { 5434 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 5435 return PointerExprEvaluator(Info, Result).Visit(E); 5436 } 5437 5438 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 5439 if (E->getOpcode() != BO_Add && 5440 E->getOpcode() != BO_Sub) 5441 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5442 5443 const Expr *PExp = E->getLHS(); 5444 const Expr *IExp = E->getRHS(); 5445 if (IExp->getType()->isPointerType()) 5446 std::swap(PExp, IExp); 5447 5448 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info); 5449 if (!EvalPtrOK && !Info.noteFailure()) 5450 return false; 5451 5452 llvm::APSInt Offset; 5453 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 5454 return false; 5455 5456 if (E->getOpcode() == BO_Sub) 5457 negateAsSigned(Offset); 5458 5459 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 5460 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 5461 } 5462 5463 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 5464 return EvaluateLValue(E->getSubExpr(), Result, Info); 5465 } 5466 5467 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) { 5468 const Expr* SubExpr = E->getSubExpr(); 5469 5470 switch (E->getCastKind()) { 5471 default: 5472 break; 5473 5474 case CK_BitCast: 5475 case CK_CPointerToObjCPointerCast: 5476 case CK_BlockPointerToObjCPointerCast: 5477 case CK_AnyPointerToBlockPointerCast: 5478 case CK_AddressSpaceConversion: 5479 if (!Visit(SubExpr)) 5480 return false; 5481 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 5482 // permitted in constant expressions in C++11. Bitcasts from cv void* are 5483 // also static_casts, but we disallow them as a resolution to DR1312. 5484 if (!E->getType()->isVoidPointerType()) { 5485 Result.Designator.setInvalid(); 5486 if (SubExpr->getType()->isVoidPointerType()) 5487 CCEDiag(E, diag::note_constexpr_invalid_cast) 5488 << 3 << SubExpr->getType(); 5489 else 5490 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5491 } 5492 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 5493 ZeroInitialization(E); 5494 return true; 5495 5496 case CK_DerivedToBase: 5497 case CK_UncheckedDerivedToBase: 5498 if (!EvaluatePointer(E->getSubExpr(), Result, Info)) 5499 return false; 5500 if (!Result.Base && Result.Offset.isZero()) 5501 return true; 5502 5503 // Now figure out the necessary offset to add to the base LV to get from 5504 // the derived class to the base class. 5505 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 5506 castAs<PointerType>()->getPointeeType(), 5507 Result); 5508 5509 case CK_BaseToDerived: 5510 if (!Visit(E->getSubExpr())) 5511 return false; 5512 if (!Result.Base && Result.Offset.isZero()) 5513 return true; 5514 return HandleBaseToDerivedCast(Info, E, Result); 5515 5516 case CK_NullToPointer: 5517 VisitIgnoredValue(E->getSubExpr()); 5518 return ZeroInitialization(E); 5519 5520 case CK_IntegralToPointer: { 5521 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5522 5523 APValue Value; 5524 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 5525 break; 5526 5527 if (Value.isInt()) { 5528 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 5529 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 5530 Result.Base = (Expr*)nullptr; 5531 Result.InvalidBase = false; 5532 Result.Offset = CharUnits::fromQuantity(N); 5533 Result.CallIndex = 0; 5534 Result.Designator.setInvalid(); 5535 Result.IsNullPtr = false; 5536 return true; 5537 } else { 5538 // Cast is of an lvalue, no need to change value. 5539 Result.setFrom(Info.Ctx, Value); 5540 return true; 5541 } 5542 } 5543 case CK_ArrayToPointerDecay: 5544 if (SubExpr->isGLValue()) { 5545 if (!EvaluateLValue(SubExpr, Result, Info)) 5546 return false; 5547 } else { 5548 Result.set(SubExpr, Info.CurrentCall->Index); 5549 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false), 5550 Info, Result, SubExpr)) 5551 return false; 5552 } 5553 // The result is a pointer to the first element of the array. 5554 if (const ConstantArrayType *CAT 5555 = Info.Ctx.getAsConstantArrayType(SubExpr->getType())) 5556 Result.addArray(Info, E, CAT); 5557 else 5558 Result.Designator.setInvalid(); 5559 return true; 5560 5561 case CK_FunctionToPointerDecay: 5562 return EvaluateLValue(SubExpr, Result, Info); 5563 5564 case CK_LValueToRValue: { 5565 LValue LVal; 5566 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 5567 return false; 5568 5569 APValue RVal; 5570 // Note, we use the subexpression's type in order to retain cv-qualifiers. 5571 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 5572 LVal, RVal)) 5573 return evaluateLValueAsAllocSize(Info, LVal.Base, Result); 5574 return Success(RVal, E); 5575 } 5576 } 5577 5578 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5579 } 5580 5581 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) { 5582 // C++ [expr.alignof]p3: 5583 // When alignof is applied to a reference type, the result is the 5584 // alignment of the referenced type. 5585 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 5586 T = Ref->getPointeeType(); 5587 5588 // __alignof is defined to return the preferred alignment. 5589 return Info.Ctx.toCharUnitsFromBits( 5590 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 5591 } 5592 5593 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) { 5594 E = E->IgnoreParens(); 5595 5596 // The kinds of expressions that we have special-case logic here for 5597 // should be kept up to date with the special checks for those 5598 // expressions in Sema. 5599 5600 // alignof decl is always accepted, even if it doesn't make sense: we default 5601 // to 1 in those cases. 5602 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 5603 return Info.Ctx.getDeclAlign(DRE->getDecl(), 5604 /*RefAsPointee*/true); 5605 5606 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 5607 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 5608 /*RefAsPointee*/true); 5609 5610 return GetAlignOfType(Info, E->getType()); 5611 } 5612 5613 // To be clear: this happily visits unsupported builtins. Better name welcomed. 5614 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 5615 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 5616 return true; 5617 5618 if (!(Info.allowInvalidBaseExpr() && getAllocSizeAttr(E))) 5619 return false; 5620 5621 Result.setInvalid(E); 5622 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 5623 Result.addUnsizedArray(Info, PointeeTy); 5624 return true; 5625 } 5626 5627 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 5628 if (IsStringLiteralCall(E)) 5629 return Success(E); 5630 5631 if (unsigned BuiltinOp = E->getBuiltinCallee()) 5632 return VisitBuiltinCallExpr(E, BuiltinOp); 5633 5634 return visitNonBuiltinCallExpr(E); 5635 } 5636 5637 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 5638 unsigned BuiltinOp) { 5639 switch (BuiltinOp) { 5640 case Builtin::BI__builtin_addressof: 5641 return EvaluateLValue(E->getArg(0), Result, Info); 5642 case Builtin::BI__builtin_assume_aligned: { 5643 // We need to be very careful here because: if the pointer does not have the 5644 // asserted alignment, then the behavior is undefined, and undefined 5645 // behavior is non-constant. 5646 if (!EvaluatePointer(E->getArg(0), Result, Info)) 5647 return false; 5648 5649 LValue OffsetResult(Result); 5650 APSInt Alignment; 5651 if (!EvaluateInteger(E->getArg(1), Alignment, Info)) 5652 return false; 5653 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 5654 5655 if (E->getNumArgs() > 2) { 5656 APSInt Offset; 5657 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 5658 return false; 5659 5660 int64_t AdditionalOffset = -Offset.getZExtValue(); 5661 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 5662 } 5663 5664 // If there is a base object, then it must have the correct alignment. 5665 if (OffsetResult.Base) { 5666 CharUnits BaseAlignment; 5667 if (const ValueDecl *VD = 5668 OffsetResult.Base.dyn_cast<const ValueDecl*>()) { 5669 BaseAlignment = Info.Ctx.getDeclAlign(VD); 5670 } else { 5671 BaseAlignment = 5672 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>()); 5673 } 5674 5675 if (BaseAlignment < Align) { 5676 Result.Designator.setInvalid(); 5677 // FIXME: Add support to Diagnostic for long / long long. 5678 CCEDiag(E->getArg(0), 5679 diag::note_constexpr_baa_insufficient_alignment) << 0 5680 << (unsigned)BaseAlignment.getQuantity() 5681 << (unsigned)Align.getQuantity(); 5682 return false; 5683 } 5684 } 5685 5686 // The offset must also have the correct alignment. 5687 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 5688 Result.Designator.setInvalid(); 5689 5690 (OffsetResult.Base 5691 ? CCEDiag(E->getArg(0), 5692 diag::note_constexpr_baa_insufficient_alignment) << 1 5693 : CCEDiag(E->getArg(0), 5694 diag::note_constexpr_baa_value_insufficient_alignment)) 5695 << (int)OffsetResult.Offset.getQuantity() 5696 << (unsigned)Align.getQuantity(); 5697 return false; 5698 } 5699 5700 return true; 5701 } 5702 5703 case Builtin::BIstrchr: 5704 case Builtin::BIwcschr: 5705 case Builtin::BImemchr: 5706 case Builtin::BIwmemchr: 5707 if (Info.getLangOpts().CPlusPlus11) 5708 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 5709 << /*isConstexpr*/0 << /*isConstructor*/0 5710 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 5711 else 5712 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 5713 // Fall through. 5714 case Builtin::BI__builtin_strchr: 5715 case Builtin::BI__builtin_wcschr: 5716 case Builtin::BI__builtin_memchr: 5717 case Builtin::BI__builtin_char_memchr: 5718 case Builtin::BI__builtin_wmemchr: { 5719 if (!Visit(E->getArg(0))) 5720 return false; 5721 APSInt Desired; 5722 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 5723 return false; 5724 uint64_t MaxLength = uint64_t(-1); 5725 if (BuiltinOp != Builtin::BIstrchr && 5726 BuiltinOp != Builtin::BIwcschr && 5727 BuiltinOp != Builtin::BI__builtin_strchr && 5728 BuiltinOp != Builtin::BI__builtin_wcschr) { 5729 APSInt N; 5730 if (!EvaluateInteger(E->getArg(2), N, Info)) 5731 return false; 5732 MaxLength = N.getExtValue(); 5733 } 5734 5735 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 5736 5737 // Figure out what value we're actually looking for (after converting to 5738 // the corresponding unsigned type if necessary). 5739 uint64_t DesiredVal; 5740 bool StopAtNull = false; 5741 switch (BuiltinOp) { 5742 case Builtin::BIstrchr: 5743 case Builtin::BI__builtin_strchr: 5744 // strchr compares directly to the passed integer, and therefore 5745 // always fails if given an int that is not a char. 5746 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 5747 E->getArg(1)->getType(), 5748 Desired), 5749 Desired)) 5750 return ZeroInitialization(E); 5751 StopAtNull = true; 5752 // Fall through. 5753 case Builtin::BImemchr: 5754 case Builtin::BI__builtin_memchr: 5755 case Builtin::BI__builtin_char_memchr: 5756 // memchr compares by converting both sides to unsigned char. That's also 5757 // correct for strchr if we get this far (to cope with plain char being 5758 // unsigned in the strchr case). 5759 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 5760 break; 5761 5762 case Builtin::BIwcschr: 5763 case Builtin::BI__builtin_wcschr: 5764 StopAtNull = true; 5765 // Fall through. 5766 case Builtin::BIwmemchr: 5767 case Builtin::BI__builtin_wmemchr: 5768 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 5769 DesiredVal = Desired.getZExtValue(); 5770 break; 5771 } 5772 5773 for (; MaxLength; --MaxLength) { 5774 APValue Char; 5775 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 5776 !Char.isInt()) 5777 return false; 5778 if (Char.getInt().getZExtValue() == DesiredVal) 5779 return true; 5780 if (StopAtNull && !Char.getInt()) 5781 break; 5782 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 5783 return false; 5784 } 5785 // Not found: return nullptr. 5786 return ZeroInitialization(E); 5787 } 5788 5789 default: 5790 return visitNonBuiltinCallExpr(E); 5791 } 5792 } 5793 5794 //===----------------------------------------------------------------------===// 5795 // Member Pointer Evaluation 5796 //===----------------------------------------------------------------------===// 5797 5798 namespace { 5799 class MemberPointerExprEvaluator 5800 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 5801 MemberPtr &Result; 5802 5803 bool Success(const ValueDecl *D) { 5804 Result = MemberPtr(D); 5805 return true; 5806 } 5807 public: 5808 5809 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 5810 : ExprEvaluatorBaseTy(Info), Result(Result) {} 5811 5812 bool Success(const APValue &V, const Expr *E) { 5813 Result.setFrom(V); 5814 return true; 5815 } 5816 bool ZeroInitialization(const Expr *E) { 5817 return Success((const ValueDecl*)nullptr); 5818 } 5819 5820 bool VisitCastExpr(const CastExpr *E); 5821 bool VisitUnaryAddrOf(const UnaryOperator *E); 5822 }; 5823 } // end anonymous namespace 5824 5825 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 5826 EvalInfo &Info) { 5827 assert(E->isRValue() && E->getType()->isMemberPointerType()); 5828 return MemberPointerExprEvaluator(Info, Result).Visit(E); 5829 } 5830 5831 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 5832 switch (E->getCastKind()) { 5833 default: 5834 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5835 5836 case CK_NullToMemberPointer: 5837 VisitIgnoredValue(E->getSubExpr()); 5838 return ZeroInitialization(E); 5839 5840 case CK_BaseToDerivedMemberPointer: { 5841 if (!Visit(E->getSubExpr())) 5842 return false; 5843 if (E->path_empty()) 5844 return true; 5845 // Base-to-derived member pointer casts store the path in derived-to-base 5846 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 5847 // the wrong end of the derived->base arc, so stagger the path by one class. 5848 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 5849 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 5850 PathI != PathE; ++PathI) { 5851 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 5852 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 5853 if (!Result.castToDerived(Derived)) 5854 return Error(E); 5855 } 5856 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 5857 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 5858 return Error(E); 5859 return true; 5860 } 5861 5862 case CK_DerivedToBaseMemberPointer: 5863 if (!Visit(E->getSubExpr())) 5864 return false; 5865 for (CastExpr::path_const_iterator PathI = E->path_begin(), 5866 PathE = E->path_end(); PathI != PathE; ++PathI) { 5867 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 5868 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 5869 if (!Result.castToBase(Base)) 5870 return Error(E); 5871 } 5872 return true; 5873 } 5874 } 5875 5876 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 5877 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 5878 // member can be formed. 5879 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 5880 } 5881 5882 //===----------------------------------------------------------------------===// 5883 // Record Evaluation 5884 //===----------------------------------------------------------------------===// 5885 5886 namespace { 5887 class RecordExprEvaluator 5888 : public ExprEvaluatorBase<RecordExprEvaluator> { 5889 const LValue &This; 5890 APValue &Result; 5891 public: 5892 5893 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 5894 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 5895 5896 bool Success(const APValue &V, const Expr *E) { 5897 Result = V; 5898 return true; 5899 } 5900 bool ZeroInitialization(const Expr *E) { 5901 return ZeroInitialization(E, E->getType()); 5902 } 5903 bool ZeroInitialization(const Expr *E, QualType T); 5904 5905 bool VisitCallExpr(const CallExpr *E) { 5906 return handleCallExpr(E, Result, &This); 5907 } 5908 bool VisitCastExpr(const CastExpr *E); 5909 bool VisitInitListExpr(const InitListExpr *E); 5910 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 5911 return VisitCXXConstructExpr(E, E->getType()); 5912 } 5913 bool VisitLambdaExpr(const LambdaExpr *E); 5914 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 5915 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 5916 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 5917 }; 5918 } 5919 5920 /// Perform zero-initialization on an object of non-union class type. 5921 /// C++11 [dcl.init]p5: 5922 /// To zero-initialize an object or reference of type T means: 5923 /// [...] 5924 /// -- if T is a (possibly cv-qualified) non-union class type, 5925 /// each non-static data member and each base-class subobject is 5926 /// zero-initialized 5927 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 5928 const RecordDecl *RD, 5929 const LValue &This, APValue &Result) { 5930 assert(!RD->isUnion() && "Expected non-union class type"); 5931 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 5932 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 5933 std::distance(RD->field_begin(), RD->field_end())); 5934 5935 if (RD->isInvalidDecl()) return false; 5936 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5937 5938 if (CD) { 5939 unsigned Index = 0; 5940 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 5941 End = CD->bases_end(); I != End; ++I, ++Index) { 5942 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 5943 LValue Subobject = This; 5944 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 5945 return false; 5946 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 5947 Result.getStructBase(Index))) 5948 return false; 5949 } 5950 } 5951 5952 for (const auto *I : RD->fields()) { 5953 // -- if T is a reference type, no initialization is performed. 5954 if (I->getType()->isReferenceType()) 5955 continue; 5956 5957 LValue Subobject = This; 5958 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 5959 return false; 5960 5961 ImplicitValueInitExpr VIE(I->getType()); 5962 if (!EvaluateInPlace( 5963 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 5964 return false; 5965 } 5966 5967 return true; 5968 } 5969 5970 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 5971 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 5972 if (RD->isInvalidDecl()) return false; 5973 if (RD->isUnion()) { 5974 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 5975 // object's first non-static named data member is zero-initialized 5976 RecordDecl::field_iterator I = RD->field_begin(); 5977 if (I == RD->field_end()) { 5978 Result = APValue((const FieldDecl*)nullptr); 5979 return true; 5980 } 5981 5982 LValue Subobject = This; 5983 if (!HandleLValueMember(Info, E, Subobject, *I)) 5984 return false; 5985 Result = APValue(*I); 5986 ImplicitValueInitExpr VIE(I->getType()); 5987 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 5988 } 5989 5990 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 5991 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 5992 return false; 5993 } 5994 5995 return HandleClassZeroInitialization(Info, E, RD, This, Result); 5996 } 5997 5998 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 5999 switch (E->getCastKind()) { 6000 default: 6001 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6002 6003 case CK_ConstructorConversion: 6004 return Visit(E->getSubExpr()); 6005 6006 case CK_DerivedToBase: 6007 case CK_UncheckedDerivedToBase: { 6008 APValue DerivedObject; 6009 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 6010 return false; 6011 if (!DerivedObject.isStruct()) 6012 return Error(E->getSubExpr()); 6013 6014 // Derived-to-base rvalue conversion: just slice off the derived part. 6015 APValue *Value = &DerivedObject; 6016 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 6017 for (CastExpr::path_const_iterator PathI = E->path_begin(), 6018 PathE = E->path_end(); PathI != PathE; ++PathI) { 6019 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 6020 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 6021 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 6022 RD = Base; 6023 } 6024 Result = *Value; 6025 return true; 6026 } 6027 } 6028 } 6029 6030 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6031 if (E->isTransparent()) 6032 return Visit(E->getInit(0)); 6033 6034 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 6035 if (RD->isInvalidDecl()) return false; 6036 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6037 6038 if (RD->isUnion()) { 6039 const FieldDecl *Field = E->getInitializedFieldInUnion(); 6040 Result = APValue(Field); 6041 if (!Field) 6042 return true; 6043 6044 // If the initializer list for a union does not contain any elements, the 6045 // first element of the union is value-initialized. 6046 // FIXME: The element should be initialized from an initializer list. 6047 // Is this difference ever observable for initializer lists which 6048 // we don't build? 6049 ImplicitValueInitExpr VIE(Field->getType()); 6050 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 6051 6052 LValue Subobject = This; 6053 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 6054 return false; 6055 6056 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 6057 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 6058 isa<CXXDefaultInitExpr>(InitExpr)); 6059 6060 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 6061 } 6062 6063 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 6064 if (Result.isUninit()) 6065 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 6066 std::distance(RD->field_begin(), RD->field_end())); 6067 unsigned ElementNo = 0; 6068 bool Success = true; 6069 6070 // Initialize base classes. 6071 if (CXXRD) { 6072 for (const auto &Base : CXXRD->bases()) { 6073 assert(ElementNo < E->getNumInits() && "missing init for base class"); 6074 const Expr *Init = E->getInit(ElementNo); 6075 6076 LValue Subobject = This; 6077 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 6078 return false; 6079 6080 APValue &FieldVal = Result.getStructBase(ElementNo); 6081 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 6082 if (!Info.noteFailure()) 6083 return false; 6084 Success = false; 6085 } 6086 ++ElementNo; 6087 } 6088 } 6089 6090 // Initialize members. 6091 for (const auto *Field : RD->fields()) { 6092 // Anonymous bit-fields are not considered members of the class for 6093 // purposes of aggregate initialization. 6094 if (Field->isUnnamedBitfield()) 6095 continue; 6096 6097 LValue Subobject = This; 6098 6099 bool HaveInit = ElementNo < E->getNumInits(); 6100 6101 // FIXME: Diagnostics here should point to the end of the initializer 6102 // list, not the start. 6103 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 6104 Subobject, Field, &Layout)) 6105 return false; 6106 6107 // Perform an implicit value-initialization for members beyond the end of 6108 // the initializer list. 6109 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 6110 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 6111 6112 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 6113 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 6114 isa<CXXDefaultInitExpr>(Init)); 6115 6116 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 6117 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 6118 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 6119 FieldVal, Field))) { 6120 if (!Info.noteFailure()) 6121 return false; 6122 Success = false; 6123 } 6124 } 6125 6126 return Success; 6127 } 6128 6129 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 6130 QualType T) { 6131 // Note that E's type is not necessarily the type of our class here; we might 6132 // be initializing an array element instead. 6133 const CXXConstructorDecl *FD = E->getConstructor(); 6134 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 6135 6136 bool ZeroInit = E->requiresZeroInitialization(); 6137 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 6138 // If we've already performed zero-initialization, we're already done. 6139 if (!Result.isUninit()) 6140 return true; 6141 6142 // We can get here in two different ways: 6143 // 1) We're performing value-initialization, and should zero-initialize 6144 // the object, or 6145 // 2) We're performing default-initialization of an object with a trivial 6146 // constexpr default constructor, in which case we should start the 6147 // lifetimes of all the base subobjects (there can be no data member 6148 // subobjects in this case) per [basic.life]p1. 6149 // Either way, ZeroInitialization is appropriate. 6150 return ZeroInitialization(E, T); 6151 } 6152 6153 const FunctionDecl *Definition = nullptr; 6154 auto Body = FD->getBody(Definition); 6155 6156 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 6157 return false; 6158 6159 // Avoid materializing a temporary for an elidable copy/move constructor. 6160 if (E->isElidable() && !ZeroInit) 6161 if (const MaterializeTemporaryExpr *ME 6162 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 6163 return Visit(ME->GetTemporaryExpr()); 6164 6165 if (ZeroInit && !ZeroInitialization(E, T)) 6166 return false; 6167 6168 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 6169 return HandleConstructorCall(E, This, Args, 6170 cast<CXXConstructorDecl>(Definition), Info, 6171 Result); 6172 } 6173 6174 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 6175 const CXXInheritedCtorInitExpr *E) { 6176 if (!Info.CurrentCall) { 6177 assert(Info.checkingPotentialConstantExpression()); 6178 return false; 6179 } 6180 6181 const CXXConstructorDecl *FD = E->getConstructor(); 6182 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 6183 return false; 6184 6185 const FunctionDecl *Definition = nullptr; 6186 auto Body = FD->getBody(Definition); 6187 6188 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 6189 return false; 6190 6191 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 6192 cast<CXXConstructorDecl>(Definition), Info, 6193 Result); 6194 } 6195 6196 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 6197 const CXXStdInitializerListExpr *E) { 6198 const ConstantArrayType *ArrayType = 6199 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 6200 6201 LValue Array; 6202 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 6203 return false; 6204 6205 // Get a pointer to the first element of the array. 6206 Array.addArray(Info, E, ArrayType); 6207 6208 // FIXME: Perform the checks on the field types in SemaInit. 6209 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 6210 RecordDecl::field_iterator Field = Record->field_begin(); 6211 if (Field == Record->field_end()) 6212 return Error(E); 6213 6214 // Start pointer. 6215 if (!Field->getType()->isPointerType() || 6216 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 6217 ArrayType->getElementType())) 6218 return Error(E); 6219 6220 // FIXME: What if the initializer_list type has base classes, etc? 6221 Result = APValue(APValue::UninitStruct(), 0, 2); 6222 Array.moveInto(Result.getStructField(0)); 6223 6224 if (++Field == Record->field_end()) 6225 return Error(E); 6226 6227 if (Field->getType()->isPointerType() && 6228 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 6229 ArrayType->getElementType())) { 6230 // End pointer. 6231 if (!HandleLValueArrayAdjustment(Info, E, Array, 6232 ArrayType->getElementType(), 6233 ArrayType->getSize().getZExtValue())) 6234 return false; 6235 Array.moveInto(Result.getStructField(1)); 6236 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 6237 // Length. 6238 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 6239 else 6240 return Error(E); 6241 6242 if (++Field != Record->field_end()) 6243 return Error(E); 6244 6245 return true; 6246 } 6247 6248 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 6249 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 6250 if (ClosureClass->isInvalidDecl()) return false; 6251 6252 if (Info.checkingPotentialConstantExpression()) return true; 6253 if (E->capture_size()) { 6254 Info.FFDiag(E, diag::note_unimplemented_constexpr_lambda_feature_ast) 6255 << "can not evaluate lambda expressions with captures"; 6256 return false; 6257 } 6258 // FIXME: Implement captures. 6259 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, /*NumFields*/0); 6260 return true; 6261 } 6262 6263 static bool EvaluateRecord(const Expr *E, const LValue &This, 6264 APValue &Result, EvalInfo &Info) { 6265 assert(E->isRValue() && E->getType()->isRecordType() && 6266 "can't evaluate expression as a record rvalue"); 6267 return RecordExprEvaluator(Info, This, Result).Visit(E); 6268 } 6269 6270 //===----------------------------------------------------------------------===// 6271 // Temporary Evaluation 6272 // 6273 // Temporaries are represented in the AST as rvalues, but generally behave like 6274 // lvalues. The full-object of which the temporary is a subobject is implicitly 6275 // materialized so that a reference can bind to it. 6276 //===----------------------------------------------------------------------===// 6277 namespace { 6278 class TemporaryExprEvaluator 6279 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 6280 public: 6281 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 6282 LValueExprEvaluatorBaseTy(Info, Result) {} 6283 6284 /// Visit an expression which constructs the value of this temporary. 6285 bool VisitConstructExpr(const Expr *E) { 6286 Result.set(E, Info.CurrentCall->Index); 6287 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false), 6288 Info, Result, E); 6289 } 6290 6291 bool VisitCastExpr(const CastExpr *E) { 6292 switch (E->getCastKind()) { 6293 default: 6294 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 6295 6296 case CK_ConstructorConversion: 6297 return VisitConstructExpr(E->getSubExpr()); 6298 } 6299 } 6300 bool VisitInitListExpr(const InitListExpr *E) { 6301 return VisitConstructExpr(E); 6302 } 6303 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 6304 return VisitConstructExpr(E); 6305 } 6306 bool VisitCallExpr(const CallExpr *E) { 6307 return VisitConstructExpr(E); 6308 } 6309 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 6310 return VisitConstructExpr(E); 6311 } 6312 bool VisitLambdaExpr(const LambdaExpr *E) { 6313 return VisitConstructExpr(E); 6314 } 6315 }; 6316 } // end anonymous namespace 6317 6318 /// Evaluate an expression of record type as a temporary. 6319 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 6320 assert(E->isRValue() && E->getType()->isRecordType()); 6321 return TemporaryExprEvaluator(Info, Result).Visit(E); 6322 } 6323 6324 //===----------------------------------------------------------------------===// 6325 // Vector Evaluation 6326 //===----------------------------------------------------------------------===// 6327 6328 namespace { 6329 class VectorExprEvaluator 6330 : public ExprEvaluatorBase<VectorExprEvaluator> { 6331 APValue &Result; 6332 public: 6333 6334 VectorExprEvaluator(EvalInfo &info, APValue &Result) 6335 : ExprEvaluatorBaseTy(info), Result(Result) {} 6336 6337 bool Success(ArrayRef<APValue> V, const Expr *E) { 6338 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 6339 // FIXME: remove this APValue copy. 6340 Result = APValue(V.data(), V.size()); 6341 return true; 6342 } 6343 bool Success(const APValue &V, const Expr *E) { 6344 assert(V.isVector()); 6345 Result = V; 6346 return true; 6347 } 6348 bool ZeroInitialization(const Expr *E); 6349 6350 bool VisitUnaryReal(const UnaryOperator *E) 6351 { return Visit(E->getSubExpr()); } 6352 bool VisitCastExpr(const CastExpr* E); 6353 bool VisitInitListExpr(const InitListExpr *E); 6354 bool VisitUnaryImag(const UnaryOperator *E); 6355 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 6356 // binary comparisons, binary and/or/xor, 6357 // shufflevector, ExtVectorElementExpr 6358 }; 6359 } // end anonymous namespace 6360 6361 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 6362 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 6363 return VectorExprEvaluator(Info, Result).Visit(E); 6364 } 6365 6366 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 6367 const VectorType *VTy = E->getType()->castAs<VectorType>(); 6368 unsigned NElts = VTy->getNumElements(); 6369 6370 const Expr *SE = E->getSubExpr(); 6371 QualType SETy = SE->getType(); 6372 6373 switch (E->getCastKind()) { 6374 case CK_VectorSplat: { 6375 APValue Val = APValue(); 6376 if (SETy->isIntegerType()) { 6377 APSInt IntResult; 6378 if (!EvaluateInteger(SE, IntResult, Info)) 6379 return false; 6380 Val = APValue(std::move(IntResult)); 6381 } else if (SETy->isRealFloatingType()) { 6382 APFloat FloatResult(0.0); 6383 if (!EvaluateFloat(SE, FloatResult, Info)) 6384 return false; 6385 Val = APValue(std::move(FloatResult)); 6386 } else { 6387 return Error(E); 6388 } 6389 6390 // Splat and create vector APValue. 6391 SmallVector<APValue, 4> Elts(NElts, Val); 6392 return Success(Elts, E); 6393 } 6394 case CK_BitCast: { 6395 // Evaluate the operand into an APInt we can extract from. 6396 llvm::APInt SValInt; 6397 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 6398 return false; 6399 // Extract the elements 6400 QualType EltTy = VTy->getElementType(); 6401 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 6402 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 6403 SmallVector<APValue, 4> Elts; 6404 if (EltTy->isRealFloatingType()) { 6405 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 6406 unsigned FloatEltSize = EltSize; 6407 if (&Sem == &APFloat::x87DoubleExtended()) 6408 FloatEltSize = 80; 6409 for (unsigned i = 0; i < NElts; i++) { 6410 llvm::APInt Elt; 6411 if (BigEndian) 6412 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 6413 else 6414 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 6415 Elts.push_back(APValue(APFloat(Sem, Elt))); 6416 } 6417 } else if (EltTy->isIntegerType()) { 6418 for (unsigned i = 0; i < NElts; i++) { 6419 llvm::APInt Elt; 6420 if (BigEndian) 6421 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 6422 else 6423 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 6424 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 6425 } 6426 } else { 6427 return Error(E); 6428 } 6429 return Success(Elts, E); 6430 } 6431 default: 6432 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6433 } 6434 } 6435 6436 bool 6437 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6438 const VectorType *VT = E->getType()->castAs<VectorType>(); 6439 unsigned NumInits = E->getNumInits(); 6440 unsigned NumElements = VT->getNumElements(); 6441 6442 QualType EltTy = VT->getElementType(); 6443 SmallVector<APValue, 4> Elements; 6444 6445 // The number of initializers can be less than the number of 6446 // vector elements. For OpenCL, this can be due to nested vector 6447 // initialization. For GCC compatibility, missing trailing elements 6448 // should be initialized with zeroes. 6449 unsigned CountInits = 0, CountElts = 0; 6450 while (CountElts < NumElements) { 6451 // Handle nested vector initialization. 6452 if (CountInits < NumInits 6453 && E->getInit(CountInits)->getType()->isVectorType()) { 6454 APValue v; 6455 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 6456 return Error(E); 6457 unsigned vlen = v.getVectorLength(); 6458 for (unsigned j = 0; j < vlen; j++) 6459 Elements.push_back(v.getVectorElt(j)); 6460 CountElts += vlen; 6461 } else if (EltTy->isIntegerType()) { 6462 llvm::APSInt sInt(32); 6463 if (CountInits < NumInits) { 6464 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 6465 return false; 6466 } else // trailing integer zero. 6467 sInt = Info.Ctx.MakeIntValue(0, EltTy); 6468 Elements.push_back(APValue(sInt)); 6469 CountElts++; 6470 } else { 6471 llvm::APFloat f(0.0); 6472 if (CountInits < NumInits) { 6473 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 6474 return false; 6475 } else // trailing float zero. 6476 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 6477 Elements.push_back(APValue(f)); 6478 CountElts++; 6479 } 6480 CountInits++; 6481 } 6482 return Success(Elements, E); 6483 } 6484 6485 bool 6486 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 6487 const VectorType *VT = E->getType()->getAs<VectorType>(); 6488 QualType EltTy = VT->getElementType(); 6489 APValue ZeroElement; 6490 if (EltTy->isIntegerType()) 6491 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 6492 else 6493 ZeroElement = 6494 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 6495 6496 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 6497 return Success(Elements, E); 6498 } 6499 6500 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 6501 VisitIgnoredValue(E->getSubExpr()); 6502 return ZeroInitialization(E); 6503 } 6504 6505 //===----------------------------------------------------------------------===// 6506 // Array Evaluation 6507 //===----------------------------------------------------------------------===// 6508 6509 namespace { 6510 class ArrayExprEvaluator 6511 : public ExprEvaluatorBase<ArrayExprEvaluator> { 6512 const LValue &This; 6513 APValue &Result; 6514 public: 6515 6516 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 6517 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 6518 6519 bool Success(const APValue &V, const Expr *E) { 6520 assert((V.isArray() || V.isLValue()) && 6521 "expected array or string literal"); 6522 Result = V; 6523 return true; 6524 } 6525 6526 bool ZeroInitialization(const Expr *E) { 6527 const ConstantArrayType *CAT = 6528 Info.Ctx.getAsConstantArrayType(E->getType()); 6529 if (!CAT) 6530 return Error(E); 6531 6532 Result = APValue(APValue::UninitArray(), 0, 6533 CAT->getSize().getZExtValue()); 6534 if (!Result.hasArrayFiller()) return true; 6535 6536 // Zero-initialize all elements. 6537 LValue Subobject = This; 6538 Subobject.addArray(Info, E, CAT); 6539 ImplicitValueInitExpr VIE(CAT->getElementType()); 6540 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 6541 } 6542 6543 bool VisitCallExpr(const CallExpr *E) { 6544 return handleCallExpr(E, Result, &This); 6545 } 6546 bool VisitInitListExpr(const InitListExpr *E); 6547 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 6548 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 6549 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 6550 const LValue &Subobject, 6551 APValue *Value, QualType Type); 6552 }; 6553 } // end anonymous namespace 6554 6555 static bool EvaluateArray(const Expr *E, const LValue &This, 6556 APValue &Result, EvalInfo &Info) { 6557 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 6558 return ArrayExprEvaluator(Info, This, Result).Visit(E); 6559 } 6560 6561 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6562 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 6563 if (!CAT) 6564 return Error(E); 6565 6566 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 6567 // an appropriately-typed string literal enclosed in braces. 6568 if (E->isStringLiteralInit()) { 6569 LValue LV; 6570 if (!EvaluateLValue(E->getInit(0), LV, Info)) 6571 return false; 6572 APValue Val; 6573 LV.moveInto(Val); 6574 return Success(Val, E); 6575 } 6576 6577 bool Success = true; 6578 6579 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 6580 "zero-initialized array shouldn't have any initialized elts"); 6581 APValue Filler; 6582 if (Result.isArray() && Result.hasArrayFiller()) 6583 Filler = Result.getArrayFiller(); 6584 6585 unsigned NumEltsToInit = E->getNumInits(); 6586 unsigned NumElts = CAT->getSize().getZExtValue(); 6587 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 6588 6589 // If the initializer might depend on the array index, run it for each 6590 // array element. For now, just whitelist non-class value-initialization. 6591 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr)) 6592 NumEltsToInit = NumElts; 6593 6594 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 6595 6596 // If the array was previously zero-initialized, preserve the 6597 // zero-initialized values. 6598 if (!Filler.isUninit()) { 6599 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 6600 Result.getArrayInitializedElt(I) = Filler; 6601 if (Result.hasArrayFiller()) 6602 Result.getArrayFiller() = Filler; 6603 } 6604 6605 LValue Subobject = This; 6606 Subobject.addArray(Info, E, CAT); 6607 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 6608 const Expr *Init = 6609 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 6610 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 6611 Info, Subobject, Init) || 6612 !HandleLValueArrayAdjustment(Info, Init, Subobject, 6613 CAT->getElementType(), 1)) { 6614 if (!Info.noteFailure()) 6615 return false; 6616 Success = false; 6617 } 6618 } 6619 6620 if (!Result.hasArrayFiller()) 6621 return Success; 6622 6623 // If we get here, we have a trivial filler, which we can just evaluate 6624 // once and splat over the rest of the array elements. 6625 assert(FillerExpr && "no array filler for incomplete init list"); 6626 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 6627 FillerExpr) && Success; 6628 } 6629 6630 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 6631 if (E->getCommonExpr() && 6632 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false), 6633 Info, E->getCommonExpr()->getSourceExpr())) 6634 return false; 6635 6636 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 6637 6638 uint64_t Elements = CAT->getSize().getZExtValue(); 6639 Result = APValue(APValue::UninitArray(), Elements, Elements); 6640 6641 LValue Subobject = This; 6642 Subobject.addArray(Info, E, CAT); 6643 6644 bool Success = true; 6645 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 6646 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 6647 Info, Subobject, E->getSubExpr()) || 6648 !HandleLValueArrayAdjustment(Info, E, Subobject, 6649 CAT->getElementType(), 1)) { 6650 if (!Info.noteFailure()) 6651 return false; 6652 Success = false; 6653 } 6654 } 6655 6656 return Success; 6657 } 6658 6659 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 6660 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 6661 } 6662 6663 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 6664 const LValue &Subobject, 6665 APValue *Value, 6666 QualType Type) { 6667 bool HadZeroInit = !Value->isUninit(); 6668 6669 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 6670 unsigned N = CAT->getSize().getZExtValue(); 6671 6672 // Preserve the array filler if we had prior zero-initialization. 6673 APValue Filler = 6674 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 6675 : APValue(); 6676 6677 *Value = APValue(APValue::UninitArray(), N, N); 6678 6679 if (HadZeroInit) 6680 for (unsigned I = 0; I != N; ++I) 6681 Value->getArrayInitializedElt(I) = Filler; 6682 6683 // Initialize the elements. 6684 LValue ArrayElt = Subobject; 6685 ArrayElt.addArray(Info, E, CAT); 6686 for (unsigned I = 0; I != N; ++I) 6687 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 6688 CAT->getElementType()) || 6689 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 6690 CAT->getElementType(), 1)) 6691 return false; 6692 6693 return true; 6694 } 6695 6696 if (!Type->isRecordType()) 6697 return Error(E); 6698 6699 return RecordExprEvaluator(Info, Subobject, *Value) 6700 .VisitCXXConstructExpr(E, Type); 6701 } 6702 6703 //===----------------------------------------------------------------------===// 6704 // Integer Evaluation 6705 // 6706 // As a GNU extension, we support casting pointers to sufficiently-wide integer 6707 // types and back in constant folding. Integer values are thus represented 6708 // either as an integer-valued APValue, or as an lvalue-valued APValue. 6709 //===----------------------------------------------------------------------===// 6710 6711 namespace { 6712 class IntExprEvaluator 6713 : public ExprEvaluatorBase<IntExprEvaluator> { 6714 APValue &Result; 6715 public: 6716 IntExprEvaluator(EvalInfo &info, APValue &result) 6717 : ExprEvaluatorBaseTy(info), Result(result) {} 6718 6719 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 6720 assert(E->getType()->isIntegralOrEnumerationType() && 6721 "Invalid evaluation result."); 6722 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 6723 "Invalid evaluation result."); 6724 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 6725 "Invalid evaluation result."); 6726 Result = APValue(SI); 6727 return true; 6728 } 6729 bool Success(const llvm::APSInt &SI, const Expr *E) { 6730 return Success(SI, E, Result); 6731 } 6732 6733 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 6734 assert(E->getType()->isIntegralOrEnumerationType() && 6735 "Invalid evaluation result."); 6736 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 6737 "Invalid evaluation result."); 6738 Result = APValue(APSInt(I)); 6739 Result.getInt().setIsUnsigned( 6740 E->getType()->isUnsignedIntegerOrEnumerationType()); 6741 return true; 6742 } 6743 bool Success(const llvm::APInt &I, const Expr *E) { 6744 return Success(I, E, Result); 6745 } 6746 6747 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 6748 assert(E->getType()->isIntegralOrEnumerationType() && 6749 "Invalid evaluation result."); 6750 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 6751 return true; 6752 } 6753 bool Success(uint64_t Value, const Expr *E) { 6754 return Success(Value, E, Result); 6755 } 6756 6757 bool Success(CharUnits Size, const Expr *E) { 6758 return Success(Size.getQuantity(), E); 6759 } 6760 6761 bool Success(const APValue &V, const Expr *E) { 6762 if (V.isLValue() || V.isAddrLabelDiff()) { 6763 Result = V; 6764 return true; 6765 } 6766 return Success(V.getInt(), E); 6767 } 6768 6769 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 6770 6771 //===--------------------------------------------------------------------===// 6772 // Visitor Methods 6773 //===--------------------------------------------------------------------===// 6774 6775 bool VisitIntegerLiteral(const IntegerLiteral *E) { 6776 return Success(E->getValue(), E); 6777 } 6778 bool VisitCharacterLiteral(const CharacterLiteral *E) { 6779 return Success(E->getValue(), E); 6780 } 6781 6782 bool CheckReferencedDecl(const Expr *E, const Decl *D); 6783 bool VisitDeclRefExpr(const DeclRefExpr *E) { 6784 if (CheckReferencedDecl(E, E->getDecl())) 6785 return true; 6786 6787 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 6788 } 6789 bool VisitMemberExpr(const MemberExpr *E) { 6790 if (CheckReferencedDecl(E, E->getMemberDecl())) { 6791 VisitIgnoredBaseExpression(E->getBase()); 6792 return true; 6793 } 6794 6795 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 6796 } 6797 6798 bool VisitCallExpr(const CallExpr *E); 6799 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 6800 bool VisitBinaryOperator(const BinaryOperator *E); 6801 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 6802 bool VisitUnaryOperator(const UnaryOperator *E); 6803 6804 bool VisitCastExpr(const CastExpr* E); 6805 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 6806 6807 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 6808 return Success(E->getValue(), E); 6809 } 6810 6811 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 6812 return Success(E->getValue(), E); 6813 } 6814 6815 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 6816 if (Info.ArrayInitIndex == uint64_t(-1)) { 6817 // We were asked to evaluate this subexpression independent of the 6818 // enclosing ArrayInitLoopExpr. We can't do that. 6819 Info.FFDiag(E); 6820 return false; 6821 } 6822 return Success(Info.ArrayInitIndex, E); 6823 } 6824 6825 // Note, GNU defines __null as an integer, not a pointer. 6826 bool VisitGNUNullExpr(const GNUNullExpr *E) { 6827 return ZeroInitialization(E); 6828 } 6829 6830 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 6831 return Success(E->getValue(), E); 6832 } 6833 6834 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 6835 return Success(E->getValue(), E); 6836 } 6837 6838 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 6839 return Success(E->getValue(), E); 6840 } 6841 6842 bool VisitUnaryReal(const UnaryOperator *E); 6843 bool VisitUnaryImag(const UnaryOperator *E); 6844 6845 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 6846 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 6847 6848 // FIXME: Missing: array subscript of vector, member of vector 6849 }; 6850 } // end anonymous namespace 6851 6852 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 6853 /// produce either the integer value or a pointer. 6854 /// 6855 /// GCC has a heinous extension which folds casts between pointer types and 6856 /// pointer-sized integral types. We support this by allowing the evaluation of 6857 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 6858 /// Some simple arithmetic on such values is supported (they are treated much 6859 /// like char*). 6860 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 6861 EvalInfo &Info) { 6862 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 6863 return IntExprEvaluator(Info, Result).Visit(E); 6864 } 6865 6866 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 6867 APValue Val; 6868 if (!EvaluateIntegerOrLValue(E, Val, Info)) 6869 return false; 6870 if (!Val.isInt()) { 6871 // FIXME: It would be better to produce the diagnostic for casting 6872 // a pointer to an integer. 6873 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 6874 return false; 6875 } 6876 Result = Val.getInt(); 6877 return true; 6878 } 6879 6880 /// Check whether the given declaration can be directly converted to an integral 6881 /// rvalue. If not, no diagnostic is produced; there are other things we can 6882 /// try. 6883 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 6884 // Enums are integer constant exprs. 6885 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 6886 // Check for signedness/width mismatches between E type and ECD value. 6887 bool SameSign = (ECD->getInitVal().isSigned() 6888 == E->getType()->isSignedIntegerOrEnumerationType()); 6889 bool SameWidth = (ECD->getInitVal().getBitWidth() 6890 == Info.Ctx.getIntWidth(E->getType())); 6891 if (SameSign && SameWidth) 6892 return Success(ECD->getInitVal(), E); 6893 else { 6894 // Get rid of mismatch (otherwise Success assertions will fail) 6895 // by computing a new value matching the type of E. 6896 llvm::APSInt Val = ECD->getInitVal(); 6897 if (!SameSign) 6898 Val.setIsSigned(!ECD->getInitVal().isSigned()); 6899 if (!SameWidth) 6900 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 6901 return Success(Val, E); 6902 } 6903 } 6904 return false; 6905 } 6906 6907 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 6908 /// as GCC. 6909 static int EvaluateBuiltinClassifyType(const CallExpr *E, 6910 const LangOptions &LangOpts) { 6911 // The following enum mimics the values returned by GCC. 6912 // FIXME: Does GCC differ between lvalue and rvalue references here? 6913 enum gcc_type_class { 6914 no_type_class = -1, 6915 void_type_class, integer_type_class, char_type_class, 6916 enumeral_type_class, boolean_type_class, 6917 pointer_type_class, reference_type_class, offset_type_class, 6918 real_type_class, complex_type_class, 6919 function_type_class, method_type_class, 6920 record_type_class, union_type_class, 6921 array_type_class, string_type_class, 6922 lang_type_class 6923 }; 6924 6925 // If no argument was supplied, default to "no_type_class". This isn't 6926 // ideal, however it is what gcc does. 6927 if (E->getNumArgs() == 0) 6928 return no_type_class; 6929 6930 QualType CanTy = E->getArg(0)->getType().getCanonicalType(); 6931 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 6932 6933 switch (CanTy->getTypeClass()) { 6934 #define TYPE(ID, BASE) 6935 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 6936 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 6937 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 6938 #include "clang/AST/TypeNodes.def" 6939 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 6940 6941 case Type::Builtin: 6942 switch (BT->getKind()) { 6943 #define BUILTIN_TYPE(ID, SINGLETON_ID) 6944 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class; 6945 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class; 6946 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break; 6947 #include "clang/AST/BuiltinTypes.def" 6948 case BuiltinType::Void: 6949 return void_type_class; 6950 6951 case BuiltinType::Bool: 6952 return boolean_type_class; 6953 6954 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class 6955 case BuiltinType::UChar: 6956 case BuiltinType::UShort: 6957 case BuiltinType::UInt: 6958 case BuiltinType::ULong: 6959 case BuiltinType::ULongLong: 6960 case BuiltinType::UInt128: 6961 return integer_type_class; 6962 6963 case BuiltinType::NullPtr: 6964 return pointer_type_class; 6965 6966 case BuiltinType::WChar_U: 6967 case BuiltinType::Char16: 6968 case BuiltinType::Char32: 6969 case BuiltinType::ObjCId: 6970 case BuiltinType::ObjCClass: 6971 case BuiltinType::ObjCSel: 6972 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6973 case BuiltinType::Id: 6974 #include "clang/Basic/OpenCLImageTypes.def" 6975 case BuiltinType::OCLSampler: 6976 case BuiltinType::OCLEvent: 6977 case BuiltinType::OCLClkEvent: 6978 case BuiltinType::OCLQueue: 6979 case BuiltinType::OCLNDRange: 6980 case BuiltinType::OCLReserveID: 6981 case BuiltinType::Dependent: 6982 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 6983 }; 6984 6985 case Type::Enum: 6986 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class; 6987 break; 6988 6989 case Type::Pointer: 6990 return pointer_type_class; 6991 break; 6992 6993 case Type::MemberPointer: 6994 if (CanTy->isMemberDataPointerType()) 6995 return offset_type_class; 6996 else { 6997 // We expect member pointers to be either data or function pointers, 6998 // nothing else. 6999 assert(CanTy->isMemberFunctionPointerType()); 7000 return method_type_class; 7001 } 7002 7003 case Type::Complex: 7004 return complex_type_class; 7005 7006 case Type::FunctionNoProto: 7007 case Type::FunctionProto: 7008 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class; 7009 7010 case Type::Record: 7011 if (const RecordType *RT = CanTy->getAs<RecordType>()) { 7012 switch (RT->getDecl()->getTagKind()) { 7013 case TagTypeKind::TTK_Struct: 7014 case TagTypeKind::TTK_Class: 7015 case TagTypeKind::TTK_Interface: 7016 return record_type_class; 7017 7018 case TagTypeKind::TTK_Enum: 7019 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class; 7020 7021 case TagTypeKind::TTK_Union: 7022 return union_type_class; 7023 } 7024 } 7025 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 7026 7027 case Type::ConstantArray: 7028 case Type::VariableArray: 7029 case Type::IncompleteArray: 7030 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class; 7031 7032 case Type::BlockPointer: 7033 case Type::LValueReference: 7034 case Type::RValueReference: 7035 case Type::Vector: 7036 case Type::ExtVector: 7037 case Type::Auto: 7038 case Type::DeducedTemplateSpecialization: 7039 case Type::ObjCObject: 7040 case Type::ObjCInterface: 7041 case Type::ObjCObjectPointer: 7042 case Type::Pipe: 7043 case Type::Atomic: 7044 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 7045 } 7046 7047 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 7048 } 7049 7050 /// EvaluateBuiltinConstantPForLValue - Determine the result of 7051 /// __builtin_constant_p when applied to the given lvalue. 7052 /// 7053 /// An lvalue is only "constant" if it is a pointer or reference to the first 7054 /// character of a string literal. 7055 template<typename LValue> 7056 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) { 7057 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>(); 7058 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero(); 7059 } 7060 7061 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 7062 /// GCC as we can manage. 7063 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) { 7064 QualType ArgType = Arg->getType(); 7065 7066 // __builtin_constant_p always has one operand. The rules which gcc follows 7067 // are not precisely documented, but are as follows: 7068 // 7069 // - If the operand is of integral, floating, complex or enumeration type, 7070 // and can be folded to a known value of that type, it returns 1. 7071 // - If the operand and can be folded to a pointer to the first character 7072 // of a string literal (or such a pointer cast to an integral type), it 7073 // returns 1. 7074 // 7075 // Otherwise, it returns 0. 7076 // 7077 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 7078 // its support for this does not currently work. 7079 if (ArgType->isIntegralOrEnumerationType()) { 7080 Expr::EvalResult Result; 7081 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects) 7082 return false; 7083 7084 APValue &V = Result.Val; 7085 if (V.getKind() == APValue::Int) 7086 return true; 7087 if (V.getKind() == APValue::LValue) 7088 return EvaluateBuiltinConstantPForLValue(V); 7089 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) { 7090 return Arg->isEvaluatable(Ctx); 7091 } else if (ArgType->isPointerType() || Arg->isGLValue()) { 7092 LValue LV; 7093 Expr::EvalStatus Status; 7094 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 7095 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info) 7096 : EvaluatePointer(Arg, LV, Info)) && 7097 !Status.HasSideEffects) 7098 return EvaluateBuiltinConstantPForLValue(LV); 7099 } 7100 7101 // Anything else isn't considered to be sufficiently constant. 7102 return false; 7103 } 7104 7105 /// Retrieves the "underlying object type" of the given expression, 7106 /// as used by __builtin_object_size. 7107 static QualType getObjectType(APValue::LValueBase B) { 7108 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 7109 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 7110 return VD->getType(); 7111 } else if (const Expr *E = B.get<const Expr*>()) { 7112 if (isa<CompoundLiteralExpr>(E)) 7113 return E->getType(); 7114 } 7115 7116 return QualType(); 7117 } 7118 7119 /// A more selective version of E->IgnoreParenCasts for 7120 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 7121 /// to change the type of E. 7122 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 7123 /// 7124 /// Always returns an RValue with a pointer representation. 7125 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 7126 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 7127 7128 auto *NoParens = E->IgnoreParens(); 7129 auto *Cast = dyn_cast<CastExpr>(NoParens); 7130 if (Cast == nullptr) 7131 return NoParens; 7132 7133 // We only conservatively allow a few kinds of casts, because this code is 7134 // inherently a simple solution that seeks to support the common case. 7135 auto CastKind = Cast->getCastKind(); 7136 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 7137 CastKind != CK_AddressSpaceConversion) 7138 return NoParens; 7139 7140 auto *SubExpr = Cast->getSubExpr(); 7141 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 7142 return NoParens; 7143 return ignorePointerCastsAndParens(SubExpr); 7144 } 7145 7146 /// Checks to see if the given LValue's Designator is at the end of the LValue's 7147 /// record layout. e.g. 7148 /// struct { struct { int a, b; } fst, snd; } obj; 7149 /// obj.fst // no 7150 /// obj.snd // yes 7151 /// obj.fst.a // no 7152 /// obj.fst.b // no 7153 /// obj.snd.a // no 7154 /// obj.snd.b // yes 7155 /// 7156 /// Please note: this function is specialized for how __builtin_object_size 7157 /// views "objects". 7158 /// 7159 /// If this encounters an invalid RecordDecl, it will always return true. 7160 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 7161 assert(!LVal.Designator.Invalid); 7162 7163 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 7164 const RecordDecl *Parent = FD->getParent(); 7165 Invalid = Parent->isInvalidDecl(); 7166 if (Invalid || Parent->isUnion()) 7167 return true; 7168 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 7169 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 7170 }; 7171 7172 auto &Base = LVal.getLValueBase(); 7173 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 7174 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 7175 bool Invalid; 7176 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 7177 return Invalid; 7178 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 7179 for (auto *FD : IFD->chain()) { 7180 bool Invalid; 7181 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 7182 return Invalid; 7183 } 7184 } 7185 } 7186 7187 unsigned I = 0; 7188 QualType BaseType = getType(Base); 7189 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 7190 assert(isBaseAnAllocSizeCall(Base) && 7191 "Unsized array in non-alloc_size call?"); 7192 // If this is an alloc_size base, we should ignore the initial array index 7193 ++I; 7194 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 7195 } 7196 7197 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 7198 const auto &Entry = LVal.Designator.Entries[I]; 7199 if (BaseType->isArrayType()) { 7200 // Because __builtin_object_size treats arrays as objects, we can ignore 7201 // the index iff this is the last array in the Designator. 7202 if (I + 1 == E) 7203 return true; 7204 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 7205 uint64_t Index = Entry.ArrayIndex; 7206 if (Index + 1 != CAT->getSize()) 7207 return false; 7208 BaseType = CAT->getElementType(); 7209 } else if (BaseType->isAnyComplexType()) { 7210 const auto *CT = BaseType->castAs<ComplexType>(); 7211 uint64_t Index = Entry.ArrayIndex; 7212 if (Index != 1) 7213 return false; 7214 BaseType = CT->getElementType(); 7215 } else if (auto *FD = getAsField(Entry)) { 7216 bool Invalid; 7217 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 7218 return Invalid; 7219 BaseType = FD->getType(); 7220 } else { 7221 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 7222 return false; 7223 } 7224 } 7225 return true; 7226 } 7227 7228 /// Tests to see if the LValue has a user-specified designator (that isn't 7229 /// necessarily valid). Note that this always returns 'true' if the LValue has 7230 /// an unsized array as its first designator entry, because there's currently no 7231 /// way to tell if the user typed *foo or foo[0]. 7232 static bool refersToCompleteObject(const LValue &LVal) { 7233 if (LVal.Designator.Invalid) 7234 return false; 7235 7236 if (!LVal.Designator.Entries.empty()) 7237 return LVal.Designator.isMostDerivedAnUnsizedArray(); 7238 7239 if (!LVal.InvalidBase) 7240 return true; 7241 7242 // If `E` is a MemberExpr, then the first part of the designator is hiding in 7243 // the LValueBase. 7244 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 7245 return !E || !isa<MemberExpr>(E); 7246 } 7247 7248 /// Attempts to detect a user writing into a piece of memory that's impossible 7249 /// to figure out the size of by just using types. 7250 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 7251 const SubobjectDesignator &Designator = LVal.Designator; 7252 // Notes: 7253 // - Users can only write off of the end when we have an invalid base. Invalid 7254 // bases imply we don't know where the memory came from. 7255 // - We used to be a bit more aggressive here; we'd only be conservative if 7256 // the array at the end was flexible, or if it had 0 or 1 elements. This 7257 // broke some common standard library extensions (PR30346), but was 7258 // otherwise seemingly fine. It may be useful to reintroduce this behavior 7259 // with some sort of whitelist. OTOH, it seems that GCC is always 7260 // conservative with the last element in structs (if it's an array), so our 7261 // current behavior is more compatible than a whitelisting approach would 7262 // be. 7263 return LVal.InvalidBase && 7264 Designator.Entries.size() == Designator.MostDerivedPathLength && 7265 Designator.MostDerivedIsArrayElement && 7266 isDesignatorAtObjectEnd(Ctx, LVal); 7267 } 7268 7269 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 7270 /// Fails if the conversion would cause loss of precision. 7271 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 7272 CharUnits &Result) { 7273 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 7274 if (Int.ugt(CharUnitsMax)) 7275 return false; 7276 Result = CharUnits::fromQuantity(Int.getZExtValue()); 7277 return true; 7278 } 7279 7280 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 7281 /// determine how many bytes exist from the beginning of the object to either 7282 /// the end of the current subobject, or the end of the object itself, depending 7283 /// on what the LValue looks like + the value of Type. 7284 /// 7285 /// If this returns false, the value of Result is undefined. 7286 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 7287 unsigned Type, const LValue &LVal, 7288 CharUnits &EndOffset) { 7289 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 7290 7291 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 7292 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 7293 return false; 7294 return HandleSizeof(Info, ExprLoc, Ty, Result); 7295 }; 7296 7297 // We want to evaluate the size of the entire object. This is a valid fallback 7298 // for when Type=1 and the designator is invalid, because we're asked for an 7299 // upper-bound. 7300 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 7301 // Type=3 wants a lower bound, so we can't fall back to this. 7302 if (Type == 3 && !DetermineForCompleteObject) 7303 return false; 7304 7305 llvm::APInt APEndOffset; 7306 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 7307 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 7308 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 7309 7310 if (LVal.InvalidBase) 7311 return false; 7312 7313 QualType BaseTy = getObjectType(LVal.getLValueBase()); 7314 return CheckedHandleSizeof(BaseTy, EndOffset); 7315 } 7316 7317 // We want to evaluate the size of a subobject. 7318 const SubobjectDesignator &Designator = LVal.Designator; 7319 7320 // The following is a moderately common idiom in C: 7321 // 7322 // struct Foo { int a; char c[1]; }; 7323 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 7324 // strcpy(&F->c[0], Bar); 7325 // 7326 // In order to not break too much legacy code, we need to support it. 7327 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 7328 // If we can resolve this to an alloc_size call, we can hand that back, 7329 // because we know for certain how many bytes there are to write to. 7330 llvm::APInt APEndOffset; 7331 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 7332 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 7333 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 7334 7335 // If we cannot determine the size of the initial allocation, then we can't 7336 // given an accurate upper-bound. However, we are still able to give 7337 // conservative lower-bounds for Type=3. 7338 if (Type == 1) 7339 return false; 7340 } 7341 7342 CharUnits BytesPerElem; 7343 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 7344 return false; 7345 7346 // According to the GCC documentation, we want the size of the subobject 7347 // denoted by the pointer. But that's not quite right -- what we actually 7348 // want is the size of the immediately-enclosing array, if there is one. 7349 int64_t ElemsRemaining; 7350 if (Designator.MostDerivedIsArrayElement && 7351 Designator.Entries.size() == Designator.MostDerivedPathLength) { 7352 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 7353 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex; 7354 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 7355 } else { 7356 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 7357 } 7358 7359 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 7360 return true; 7361 } 7362 7363 /// \brief Tries to evaluate the __builtin_object_size for @p E. If successful, 7364 /// returns true and stores the result in @p Size. 7365 /// 7366 /// If @p WasError is non-null, this will report whether the failure to evaluate 7367 /// is to be treated as an Error in IntExprEvaluator. 7368 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 7369 EvalInfo &Info, uint64_t &Size) { 7370 // Determine the denoted object. 7371 LValue LVal; 7372 { 7373 // The operand of __builtin_object_size is never evaluated for side-effects. 7374 // If there are any, but we can determine the pointed-to object anyway, then 7375 // ignore the side-effects. 7376 SpeculativeEvaluationRAII SpeculativeEval(Info); 7377 FoldOffsetRAII Fold(Info); 7378 7379 if (E->isGLValue()) { 7380 // It's possible for us to be given GLValues if we're called via 7381 // Expr::tryEvaluateObjectSize. 7382 APValue RVal; 7383 if (!EvaluateAsRValue(Info, E, RVal)) 7384 return false; 7385 LVal.setFrom(Info.Ctx, RVal); 7386 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info)) 7387 return false; 7388 } 7389 7390 // If we point to before the start of the object, there are no accessible 7391 // bytes. 7392 if (LVal.getLValueOffset().isNegative()) { 7393 Size = 0; 7394 return true; 7395 } 7396 7397 CharUnits EndOffset; 7398 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 7399 return false; 7400 7401 // If we've fallen outside of the end offset, just pretend there's nothing to 7402 // write to/read from. 7403 if (EndOffset <= LVal.getLValueOffset()) 7404 Size = 0; 7405 else 7406 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 7407 return true; 7408 } 7409 7410 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 7411 if (unsigned BuiltinOp = E->getBuiltinCallee()) 7412 return VisitBuiltinCallExpr(E, BuiltinOp); 7413 7414 return ExprEvaluatorBaseTy::VisitCallExpr(E); 7415 } 7416 7417 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 7418 unsigned BuiltinOp) { 7419 switch (unsigned BuiltinOp = E->getBuiltinCallee()) { 7420 default: 7421 return ExprEvaluatorBaseTy::VisitCallExpr(E); 7422 7423 case Builtin::BI__builtin_object_size: { 7424 // The type was checked when we built the expression. 7425 unsigned Type = 7426 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 7427 assert(Type <= 3 && "unexpected type"); 7428 7429 uint64_t Size; 7430 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 7431 return Success(Size, E); 7432 7433 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 7434 return Success((Type & 2) ? 0 : -1, E); 7435 7436 // Expression had no side effects, but we couldn't statically determine the 7437 // size of the referenced object. 7438 switch (Info.EvalMode) { 7439 case EvalInfo::EM_ConstantExpression: 7440 case EvalInfo::EM_PotentialConstantExpression: 7441 case EvalInfo::EM_ConstantFold: 7442 case EvalInfo::EM_EvaluateForOverflow: 7443 case EvalInfo::EM_IgnoreSideEffects: 7444 case EvalInfo::EM_OffsetFold: 7445 // Leave it to IR generation. 7446 return Error(E); 7447 case EvalInfo::EM_ConstantExpressionUnevaluated: 7448 case EvalInfo::EM_PotentialConstantExpressionUnevaluated: 7449 // Reduce it to a constant now. 7450 return Success((Type & 2) ? 0 : -1, E); 7451 } 7452 7453 llvm_unreachable("unexpected EvalMode"); 7454 } 7455 7456 case Builtin::BI__builtin_bswap16: 7457 case Builtin::BI__builtin_bswap32: 7458 case Builtin::BI__builtin_bswap64: { 7459 APSInt Val; 7460 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7461 return false; 7462 7463 return Success(Val.byteSwap(), E); 7464 } 7465 7466 case Builtin::BI__builtin_classify_type: 7467 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 7468 7469 // FIXME: BI__builtin_clrsb 7470 // FIXME: BI__builtin_clrsbl 7471 // FIXME: BI__builtin_clrsbll 7472 7473 case Builtin::BI__builtin_clz: 7474 case Builtin::BI__builtin_clzl: 7475 case Builtin::BI__builtin_clzll: 7476 case Builtin::BI__builtin_clzs: { 7477 APSInt Val; 7478 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7479 return false; 7480 if (!Val) 7481 return Error(E); 7482 7483 return Success(Val.countLeadingZeros(), E); 7484 } 7485 7486 case Builtin::BI__builtin_constant_p: 7487 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E); 7488 7489 case Builtin::BI__builtin_ctz: 7490 case Builtin::BI__builtin_ctzl: 7491 case Builtin::BI__builtin_ctzll: 7492 case Builtin::BI__builtin_ctzs: { 7493 APSInt Val; 7494 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7495 return false; 7496 if (!Val) 7497 return Error(E); 7498 7499 return Success(Val.countTrailingZeros(), E); 7500 } 7501 7502 case Builtin::BI__builtin_eh_return_data_regno: { 7503 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 7504 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 7505 return Success(Operand, E); 7506 } 7507 7508 case Builtin::BI__builtin_expect: 7509 return Visit(E->getArg(0)); 7510 7511 case Builtin::BI__builtin_ffs: 7512 case Builtin::BI__builtin_ffsl: 7513 case Builtin::BI__builtin_ffsll: { 7514 APSInt Val; 7515 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7516 return false; 7517 7518 unsigned N = Val.countTrailingZeros(); 7519 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 7520 } 7521 7522 case Builtin::BI__builtin_fpclassify: { 7523 APFloat Val(0.0); 7524 if (!EvaluateFloat(E->getArg(5), Val, Info)) 7525 return false; 7526 unsigned Arg; 7527 switch (Val.getCategory()) { 7528 case APFloat::fcNaN: Arg = 0; break; 7529 case APFloat::fcInfinity: Arg = 1; break; 7530 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 7531 case APFloat::fcZero: Arg = 4; break; 7532 } 7533 return Visit(E->getArg(Arg)); 7534 } 7535 7536 case Builtin::BI__builtin_isinf_sign: { 7537 APFloat Val(0.0); 7538 return EvaluateFloat(E->getArg(0), Val, Info) && 7539 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 7540 } 7541 7542 case Builtin::BI__builtin_isinf: { 7543 APFloat Val(0.0); 7544 return EvaluateFloat(E->getArg(0), Val, Info) && 7545 Success(Val.isInfinity() ? 1 : 0, E); 7546 } 7547 7548 case Builtin::BI__builtin_isfinite: { 7549 APFloat Val(0.0); 7550 return EvaluateFloat(E->getArg(0), Val, Info) && 7551 Success(Val.isFinite() ? 1 : 0, E); 7552 } 7553 7554 case Builtin::BI__builtin_isnan: { 7555 APFloat Val(0.0); 7556 return EvaluateFloat(E->getArg(0), Val, Info) && 7557 Success(Val.isNaN() ? 1 : 0, E); 7558 } 7559 7560 case Builtin::BI__builtin_isnormal: { 7561 APFloat Val(0.0); 7562 return EvaluateFloat(E->getArg(0), Val, Info) && 7563 Success(Val.isNormal() ? 1 : 0, E); 7564 } 7565 7566 case Builtin::BI__builtin_parity: 7567 case Builtin::BI__builtin_parityl: 7568 case Builtin::BI__builtin_parityll: { 7569 APSInt Val; 7570 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7571 return false; 7572 7573 return Success(Val.countPopulation() % 2, E); 7574 } 7575 7576 case Builtin::BI__builtin_popcount: 7577 case Builtin::BI__builtin_popcountl: 7578 case Builtin::BI__builtin_popcountll: { 7579 APSInt Val; 7580 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7581 return false; 7582 7583 return Success(Val.countPopulation(), E); 7584 } 7585 7586 case Builtin::BIstrlen: 7587 case Builtin::BIwcslen: 7588 // A call to strlen is not a constant expression. 7589 if (Info.getLangOpts().CPlusPlus11) 7590 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 7591 << /*isConstexpr*/0 << /*isConstructor*/0 7592 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 7593 else 7594 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 7595 // Fall through. 7596 case Builtin::BI__builtin_strlen: 7597 case Builtin::BI__builtin_wcslen: { 7598 // As an extension, we support __builtin_strlen() as a constant expression, 7599 // and support folding strlen() to a constant. 7600 LValue String; 7601 if (!EvaluatePointer(E->getArg(0), String, Info)) 7602 return false; 7603 7604 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 7605 7606 // Fast path: if it's a string literal, search the string value. 7607 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 7608 String.getLValueBase().dyn_cast<const Expr *>())) { 7609 // The string literal may have embedded null characters. Find the first 7610 // one and truncate there. 7611 StringRef Str = S->getBytes(); 7612 int64_t Off = String.Offset.getQuantity(); 7613 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 7614 S->getCharByteWidth() == 1 && 7615 // FIXME: Add fast-path for wchar_t too. 7616 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 7617 Str = Str.substr(Off); 7618 7619 StringRef::size_type Pos = Str.find(0); 7620 if (Pos != StringRef::npos) 7621 Str = Str.substr(0, Pos); 7622 7623 return Success(Str.size(), E); 7624 } 7625 7626 // Fall through to slow path to issue appropriate diagnostic. 7627 } 7628 7629 // Slow path: scan the bytes of the string looking for the terminating 0. 7630 for (uint64_t Strlen = 0; /**/; ++Strlen) { 7631 APValue Char; 7632 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 7633 !Char.isInt()) 7634 return false; 7635 if (!Char.getInt()) 7636 return Success(Strlen, E); 7637 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 7638 return false; 7639 } 7640 } 7641 7642 case Builtin::BIstrcmp: 7643 case Builtin::BIwcscmp: 7644 case Builtin::BIstrncmp: 7645 case Builtin::BIwcsncmp: 7646 case Builtin::BImemcmp: 7647 case Builtin::BIwmemcmp: 7648 // A call to strlen is not a constant expression. 7649 if (Info.getLangOpts().CPlusPlus11) 7650 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 7651 << /*isConstexpr*/0 << /*isConstructor*/0 7652 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 7653 else 7654 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 7655 // Fall through. 7656 case Builtin::BI__builtin_strcmp: 7657 case Builtin::BI__builtin_wcscmp: 7658 case Builtin::BI__builtin_strncmp: 7659 case Builtin::BI__builtin_wcsncmp: 7660 case Builtin::BI__builtin_memcmp: 7661 case Builtin::BI__builtin_wmemcmp: { 7662 LValue String1, String2; 7663 if (!EvaluatePointer(E->getArg(0), String1, Info) || 7664 !EvaluatePointer(E->getArg(1), String2, Info)) 7665 return false; 7666 7667 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 7668 7669 uint64_t MaxLength = uint64_t(-1); 7670 if (BuiltinOp != Builtin::BIstrcmp && 7671 BuiltinOp != Builtin::BIwcscmp && 7672 BuiltinOp != Builtin::BI__builtin_strcmp && 7673 BuiltinOp != Builtin::BI__builtin_wcscmp) { 7674 APSInt N; 7675 if (!EvaluateInteger(E->getArg(2), N, Info)) 7676 return false; 7677 MaxLength = N.getExtValue(); 7678 } 7679 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp && 7680 BuiltinOp != Builtin::BIwmemcmp && 7681 BuiltinOp != Builtin::BI__builtin_memcmp && 7682 BuiltinOp != Builtin::BI__builtin_wmemcmp); 7683 for (; MaxLength; --MaxLength) { 7684 APValue Char1, Char2; 7685 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) || 7686 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) || 7687 !Char1.isInt() || !Char2.isInt()) 7688 return false; 7689 if (Char1.getInt() != Char2.getInt()) 7690 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 7691 if (StopAtNull && !Char1.getInt()) 7692 return Success(0, E); 7693 assert(!(StopAtNull && !Char2.getInt())); 7694 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) || 7695 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1)) 7696 return false; 7697 } 7698 // We hit the strncmp / memcmp limit. 7699 return Success(0, E); 7700 } 7701 7702 case Builtin::BI__atomic_always_lock_free: 7703 case Builtin::BI__atomic_is_lock_free: 7704 case Builtin::BI__c11_atomic_is_lock_free: { 7705 APSInt SizeVal; 7706 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 7707 return false; 7708 7709 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 7710 // of two less than the maximum inline atomic width, we know it is 7711 // lock-free. If the size isn't a power of two, or greater than the 7712 // maximum alignment where we promote atomics, we know it is not lock-free 7713 // (at least not in the sense of atomic_is_lock_free). Otherwise, 7714 // the answer can only be determined at runtime; for example, 16-byte 7715 // atomics have lock-free implementations on some, but not all, 7716 // x86-64 processors. 7717 7718 // Check power-of-two. 7719 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 7720 if (Size.isPowerOfTwo()) { 7721 // Check against inlining width. 7722 unsigned InlineWidthBits = 7723 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 7724 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 7725 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 7726 Size == CharUnits::One() || 7727 E->getArg(1)->isNullPointerConstant(Info.Ctx, 7728 Expr::NPC_NeverValueDependent)) 7729 // OK, we will inline appropriately-aligned operations of this size, 7730 // and _Atomic(T) is appropriately-aligned. 7731 return Success(1, E); 7732 7733 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 7734 castAs<PointerType>()->getPointeeType(); 7735 if (!PointeeType->isIncompleteType() && 7736 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 7737 // OK, we will inline operations on this object. 7738 return Success(1, E); 7739 } 7740 } 7741 } 7742 7743 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 7744 Success(0, E) : Error(E); 7745 } 7746 } 7747 } 7748 7749 static bool HasSameBase(const LValue &A, const LValue &B) { 7750 if (!A.getLValueBase()) 7751 return !B.getLValueBase(); 7752 if (!B.getLValueBase()) 7753 return false; 7754 7755 if (A.getLValueBase().getOpaqueValue() != 7756 B.getLValueBase().getOpaqueValue()) { 7757 const Decl *ADecl = GetLValueBaseDecl(A); 7758 if (!ADecl) 7759 return false; 7760 const Decl *BDecl = GetLValueBaseDecl(B); 7761 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 7762 return false; 7763 } 7764 7765 return IsGlobalLValue(A.getLValueBase()) || 7766 A.getLValueCallIndex() == B.getLValueCallIndex(); 7767 } 7768 7769 /// \brief Determine whether this is a pointer past the end of the complete 7770 /// object referred to by the lvalue. 7771 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 7772 const LValue &LV) { 7773 // A null pointer can be viewed as being "past the end" but we don't 7774 // choose to look at it that way here. 7775 if (!LV.getLValueBase()) 7776 return false; 7777 7778 // If the designator is valid and refers to a subobject, we're not pointing 7779 // past the end. 7780 if (!LV.getLValueDesignator().Invalid && 7781 !LV.getLValueDesignator().isOnePastTheEnd()) 7782 return false; 7783 7784 // A pointer to an incomplete type might be past-the-end if the type's size is 7785 // zero. We cannot tell because the type is incomplete. 7786 QualType Ty = getType(LV.getLValueBase()); 7787 if (Ty->isIncompleteType()) 7788 return true; 7789 7790 // We're a past-the-end pointer if we point to the byte after the object, 7791 // no matter what our type or path is. 7792 auto Size = Ctx.getTypeSizeInChars(Ty); 7793 return LV.getLValueOffset() == Size; 7794 } 7795 7796 namespace { 7797 7798 /// \brief Data recursive integer evaluator of certain binary operators. 7799 /// 7800 /// We use a data recursive algorithm for binary operators so that we are able 7801 /// to handle extreme cases of chained binary operators without causing stack 7802 /// overflow. 7803 class DataRecursiveIntBinOpEvaluator { 7804 struct EvalResult { 7805 APValue Val; 7806 bool Failed; 7807 7808 EvalResult() : Failed(false) { } 7809 7810 void swap(EvalResult &RHS) { 7811 Val.swap(RHS.Val); 7812 Failed = RHS.Failed; 7813 RHS.Failed = false; 7814 } 7815 }; 7816 7817 struct Job { 7818 const Expr *E; 7819 EvalResult LHSResult; // meaningful only for binary operator expression. 7820 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 7821 7822 Job() = default; 7823 Job(Job &&) = default; 7824 7825 void startSpeculativeEval(EvalInfo &Info) { 7826 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 7827 } 7828 7829 private: 7830 SpeculativeEvaluationRAII SpecEvalRAII; 7831 }; 7832 7833 SmallVector<Job, 16> Queue; 7834 7835 IntExprEvaluator &IntEval; 7836 EvalInfo &Info; 7837 APValue &FinalResult; 7838 7839 public: 7840 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 7841 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 7842 7843 /// \brief True if \param E is a binary operator that we are going to handle 7844 /// data recursively. 7845 /// We handle binary operators that are comma, logical, or that have operands 7846 /// with integral or enumeration type. 7847 static bool shouldEnqueue(const BinaryOperator *E) { 7848 return E->getOpcode() == BO_Comma || 7849 E->isLogicalOp() || 7850 (E->isRValue() && 7851 E->getType()->isIntegralOrEnumerationType() && 7852 E->getLHS()->getType()->isIntegralOrEnumerationType() && 7853 E->getRHS()->getType()->isIntegralOrEnumerationType()); 7854 } 7855 7856 bool Traverse(const BinaryOperator *E) { 7857 enqueue(E); 7858 EvalResult PrevResult; 7859 while (!Queue.empty()) 7860 process(PrevResult); 7861 7862 if (PrevResult.Failed) return false; 7863 7864 FinalResult.swap(PrevResult.Val); 7865 return true; 7866 } 7867 7868 private: 7869 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 7870 return IntEval.Success(Value, E, Result); 7871 } 7872 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 7873 return IntEval.Success(Value, E, Result); 7874 } 7875 bool Error(const Expr *E) { 7876 return IntEval.Error(E); 7877 } 7878 bool Error(const Expr *E, diag::kind D) { 7879 return IntEval.Error(E, D); 7880 } 7881 7882 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7883 return Info.CCEDiag(E, D); 7884 } 7885 7886 // \brief Returns true if visiting the RHS is necessary, false otherwise. 7887 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 7888 bool &SuppressRHSDiags); 7889 7890 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 7891 const BinaryOperator *E, APValue &Result); 7892 7893 void EvaluateExpr(const Expr *E, EvalResult &Result) { 7894 Result.Failed = !Evaluate(Result.Val, Info, E); 7895 if (Result.Failed) 7896 Result.Val = APValue(); 7897 } 7898 7899 void process(EvalResult &Result); 7900 7901 void enqueue(const Expr *E) { 7902 E = E->IgnoreParens(); 7903 Queue.resize(Queue.size()+1); 7904 Queue.back().E = E; 7905 Queue.back().Kind = Job::AnyExprKind; 7906 } 7907 }; 7908 7909 } 7910 7911 bool DataRecursiveIntBinOpEvaluator:: 7912 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 7913 bool &SuppressRHSDiags) { 7914 if (E->getOpcode() == BO_Comma) { 7915 // Ignore LHS but note if we could not evaluate it. 7916 if (LHSResult.Failed) 7917 return Info.noteSideEffect(); 7918 return true; 7919 } 7920 7921 if (E->isLogicalOp()) { 7922 bool LHSAsBool; 7923 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 7924 // We were able to evaluate the LHS, see if we can get away with not 7925 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 7926 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 7927 Success(LHSAsBool, E, LHSResult.Val); 7928 return false; // Ignore RHS 7929 } 7930 } else { 7931 LHSResult.Failed = true; 7932 7933 // Since we weren't able to evaluate the left hand side, it 7934 // might have had side effects. 7935 if (!Info.noteSideEffect()) 7936 return false; 7937 7938 // We can't evaluate the LHS; however, sometimes the result 7939 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 7940 // Don't ignore RHS and suppress diagnostics from this arm. 7941 SuppressRHSDiags = true; 7942 } 7943 7944 return true; 7945 } 7946 7947 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 7948 E->getRHS()->getType()->isIntegralOrEnumerationType()); 7949 7950 if (LHSResult.Failed && !Info.noteFailure()) 7951 return false; // Ignore RHS; 7952 7953 return true; 7954 } 7955 7956 static void addOrSubLValueAsInteger(APValue &LVal, APSInt Index, bool IsSub) { 7957 // Compute the new offset in the appropriate width, wrapping at 64 bits. 7958 // FIXME: When compiling for a 32-bit target, we should use 32-bit 7959 // offsets. 7960 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 7961 CharUnits &Offset = LVal.getLValueOffset(); 7962 uint64_t Offset64 = Offset.getQuantity(); 7963 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 7964 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 7965 : Offset64 + Index64); 7966 } 7967 7968 bool DataRecursiveIntBinOpEvaluator:: 7969 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 7970 const BinaryOperator *E, APValue &Result) { 7971 if (E->getOpcode() == BO_Comma) { 7972 if (RHSResult.Failed) 7973 return false; 7974 Result = RHSResult.Val; 7975 return true; 7976 } 7977 7978 if (E->isLogicalOp()) { 7979 bool lhsResult, rhsResult; 7980 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 7981 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 7982 7983 if (LHSIsOK) { 7984 if (RHSIsOK) { 7985 if (E->getOpcode() == BO_LOr) 7986 return Success(lhsResult || rhsResult, E, Result); 7987 else 7988 return Success(lhsResult && rhsResult, E, Result); 7989 } 7990 } else { 7991 if (RHSIsOK) { 7992 // We can't evaluate the LHS; however, sometimes the result 7993 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 7994 if (rhsResult == (E->getOpcode() == BO_LOr)) 7995 return Success(rhsResult, E, Result); 7996 } 7997 } 7998 7999 return false; 8000 } 8001 8002 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 8003 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8004 8005 if (LHSResult.Failed || RHSResult.Failed) 8006 return false; 8007 8008 const APValue &LHSVal = LHSResult.Val; 8009 const APValue &RHSVal = RHSResult.Val; 8010 8011 // Handle cases like (unsigned long)&a + 4. 8012 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 8013 Result = LHSVal; 8014 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 8015 return true; 8016 } 8017 8018 // Handle cases like 4 + (unsigned long)&a 8019 if (E->getOpcode() == BO_Add && 8020 RHSVal.isLValue() && LHSVal.isInt()) { 8021 Result = RHSVal; 8022 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 8023 return true; 8024 } 8025 8026 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 8027 // Handle (intptr_t)&&A - (intptr_t)&&B. 8028 if (!LHSVal.getLValueOffset().isZero() || 8029 !RHSVal.getLValueOffset().isZero()) 8030 return false; 8031 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 8032 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 8033 if (!LHSExpr || !RHSExpr) 8034 return false; 8035 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 8036 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 8037 if (!LHSAddrExpr || !RHSAddrExpr) 8038 return false; 8039 // Make sure both labels come from the same function. 8040 if (LHSAddrExpr->getLabel()->getDeclContext() != 8041 RHSAddrExpr->getLabel()->getDeclContext()) 8042 return false; 8043 Result = APValue(LHSAddrExpr, RHSAddrExpr); 8044 return true; 8045 } 8046 8047 // All the remaining cases expect both operands to be an integer 8048 if (!LHSVal.isInt() || !RHSVal.isInt()) 8049 return Error(E); 8050 8051 // Set up the width and signedness manually, in case it can't be deduced 8052 // from the operation we're performing. 8053 // FIXME: Don't do this in the cases where we can deduce it. 8054 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 8055 E->getType()->isUnsignedIntegerOrEnumerationType()); 8056 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 8057 RHSVal.getInt(), Value)) 8058 return false; 8059 return Success(Value, E, Result); 8060 } 8061 8062 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 8063 Job &job = Queue.back(); 8064 8065 switch (job.Kind) { 8066 case Job::AnyExprKind: { 8067 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 8068 if (shouldEnqueue(Bop)) { 8069 job.Kind = Job::BinOpKind; 8070 enqueue(Bop->getLHS()); 8071 return; 8072 } 8073 } 8074 8075 EvaluateExpr(job.E, Result); 8076 Queue.pop_back(); 8077 return; 8078 } 8079 8080 case Job::BinOpKind: { 8081 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 8082 bool SuppressRHSDiags = false; 8083 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 8084 Queue.pop_back(); 8085 return; 8086 } 8087 if (SuppressRHSDiags) 8088 job.startSpeculativeEval(Info); 8089 job.LHSResult.swap(Result); 8090 job.Kind = Job::BinOpVisitedLHSKind; 8091 enqueue(Bop->getRHS()); 8092 return; 8093 } 8094 8095 case Job::BinOpVisitedLHSKind: { 8096 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 8097 EvalResult RHS; 8098 RHS.swap(Result); 8099 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 8100 Queue.pop_back(); 8101 return; 8102 } 8103 } 8104 8105 llvm_unreachable("Invalid Job::Kind!"); 8106 } 8107 8108 namespace { 8109 /// Used when we determine that we should fail, but can keep evaluating prior to 8110 /// noting that we had a failure. 8111 class DelayedNoteFailureRAII { 8112 EvalInfo &Info; 8113 bool NoteFailure; 8114 8115 public: 8116 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 8117 : Info(Info), NoteFailure(NoteFailure) {} 8118 ~DelayedNoteFailureRAII() { 8119 if (NoteFailure) { 8120 bool ContinueAfterFailure = Info.noteFailure(); 8121 (void)ContinueAfterFailure; 8122 assert(ContinueAfterFailure && 8123 "Shouldn't have kept evaluating on failure."); 8124 } 8125 } 8126 }; 8127 } 8128 8129 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8130 // We don't call noteFailure immediately because the assignment happens after 8131 // we evaluate LHS and RHS. 8132 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 8133 return Error(E); 8134 8135 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 8136 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 8137 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 8138 8139 QualType LHSTy = E->getLHS()->getType(); 8140 QualType RHSTy = E->getRHS()->getType(); 8141 8142 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 8143 ComplexValue LHS, RHS; 8144 bool LHSOK; 8145 if (E->isAssignmentOp()) { 8146 LValue LV; 8147 EvaluateLValue(E->getLHS(), LV, Info); 8148 LHSOK = false; 8149 } else if (LHSTy->isRealFloatingType()) { 8150 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 8151 if (LHSOK) { 8152 LHS.makeComplexFloat(); 8153 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 8154 } 8155 } else { 8156 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 8157 } 8158 if (!LHSOK && !Info.noteFailure()) 8159 return false; 8160 8161 if (E->getRHS()->getType()->isRealFloatingType()) { 8162 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 8163 return false; 8164 RHS.makeComplexFloat(); 8165 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 8166 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 8167 return false; 8168 8169 if (LHS.isComplexFloat()) { 8170 APFloat::cmpResult CR_r = 8171 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 8172 APFloat::cmpResult CR_i = 8173 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 8174 8175 if (E->getOpcode() == BO_EQ) 8176 return Success((CR_r == APFloat::cmpEqual && 8177 CR_i == APFloat::cmpEqual), E); 8178 else { 8179 assert(E->getOpcode() == BO_NE && 8180 "Invalid complex comparison."); 8181 return Success(((CR_r == APFloat::cmpGreaterThan || 8182 CR_r == APFloat::cmpLessThan || 8183 CR_r == APFloat::cmpUnordered) || 8184 (CR_i == APFloat::cmpGreaterThan || 8185 CR_i == APFloat::cmpLessThan || 8186 CR_i == APFloat::cmpUnordered)), E); 8187 } 8188 } else { 8189 if (E->getOpcode() == BO_EQ) 8190 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() && 8191 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E); 8192 else { 8193 assert(E->getOpcode() == BO_NE && 8194 "Invalid compex comparison."); 8195 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() || 8196 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E); 8197 } 8198 } 8199 } 8200 8201 if (LHSTy->isRealFloatingType() && 8202 RHSTy->isRealFloatingType()) { 8203 APFloat RHS(0.0), LHS(0.0); 8204 8205 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 8206 if (!LHSOK && !Info.noteFailure()) 8207 return false; 8208 8209 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 8210 return false; 8211 8212 APFloat::cmpResult CR = LHS.compare(RHS); 8213 8214 switch (E->getOpcode()) { 8215 default: 8216 llvm_unreachable("Invalid binary operator!"); 8217 case BO_LT: 8218 return Success(CR == APFloat::cmpLessThan, E); 8219 case BO_GT: 8220 return Success(CR == APFloat::cmpGreaterThan, E); 8221 case BO_LE: 8222 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E); 8223 case BO_GE: 8224 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual, 8225 E); 8226 case BO_EQ: 8227 return Success(CR == APFloat::cmpEqual, E); 8228 case BO_NE: 8229 return Success(CR == APFloat::cmpGreaterThan 8230 || CR == APFloat::cmpLessThan 8231 || CR == APFloat::cmpUnordered, E); 8232 } 8233 } 8234 8235 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 8236 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) { 8237 LValue LHSValue, RHSValue; 8238 8239 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 8240 if (!LHSOK && !Info.noteFailure()) 8241 return false; 8242 8243 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 8244 return false; 8245 8246 // Reject differing bases from the normal codepath; we special-case 8247 // comparisons to null. 8248 if (!HasSameBase(LHSValue, RHSValue)) { 8249 if (E->getOpcode() == BO_Sub) { 8250 // Handle &&A - &&B. 8251 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 8252 return Error(E); 8253 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>(); 8254 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>(); 8255 if (!LHSExpr || !RHSExpr) 8256 return Error(E); 8257 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 8258 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 8259 if (!LHSAddrExpr || !RHSAddrExpr) 8260 return Error(E); 8261 // Make sure both labels come from the same function. 8262 if (LHSAddrExpr->getLabel()->getDeclContext() != 8263 RHSAddrExpr->getLabel()->getDeclContext()) 8264 return Error(E); 8265 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 8266 } 8267 // Inequalities and subtractions between unrelated pointers have 8268 // unspecified or undefined behavior. 8269 if (!E->isEqualityOp()) 8270 return Error(E); 8271 // A constant address may compare equal to the address of a symbol. 8272 // The one exception is that address of an object cannot compare equal 8273 // to a null pointer constant. 8274 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 8275 (!RHSValue.Base && !RHSValue.Offset.isZero())) 8276 return Error(E); 8277 // It's implementation-defined whether distinct literals will have 8278 // distinct addresses. In clang, the result of such a comparison is 8279 // unspecified, so it is not a constant expression. However, we do know 8280 // that the address of a literal will be non-null. 8281 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 8282 LHSValue.Base && RHSValue.Base) 8283 return Error(E); 8284 // We can't tell whether weak symbols will end up pointing to the same 8285 // object. 8286 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 8287 return Error(E); 8288 // We can't compare the address of the start of one object with the 8289 // past-the-end address of another object, per C++ DR1652. 8290 if ((LHSValue.Base && LHSValue.Offset.isZero() && 8291 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 8292 (RHSValue.Base && RHSValue.Offset.isZero() && 8293 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 8294 return Error(E); 8295 // We can't tell whether an object is at the same address as another 8296 // zero sized object. 8297 if ((RHSValue.Base && isZeroSized(LHSValue)) || 8298 (LHSValue.Base && isZeroSized(RHSValue))) 8299 return Error(E); 8300 // Pointers with different bases cannot represent the same object. 8301 // (Note that clang defaults to -fmerge-all-constants, which can 8302 // lead to inconsistent results for comparisons involving the address 8303 // of a constant; this generally doesn't matter in practice.) 8304 return Success(E->getOpcode() == BO_NE, E); 8305 } 8306 8307 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 8308 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 8309 8310 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 8311 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 8312 8313 if (E->getOpcode() == BO_Sub) { 8314 // C++11 [expr.add]p6: 8315 // Unless both pointers point to elements of the same array object, or 8316 // one past the last element of the array object, the behavior is 8317 // undefined. 8318 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 8319 !AreElementsOfSameArray(getType(LHSValue.Base), 8320 LHSDesignator, RHSDesignator)) 8321 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 8322 8323 QualType Type = E->getLHS()->getType(); 8324 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 8325 8326 CharUnits ElementSize; 8327 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 8328 return false; 8329 8330 // As an extension, a type may have zero size (empty struct or union in 8331 // C, array of zero length). Pointer subtraction in such cases has 8332 // undefined behavior, so is not constant. 8333 if (ElementSize.isZero()) { 8334 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 8335 << ElementType; 8336 return false; 8337 } 8338 8339 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 8340 // and produce incorrect results when it overflows. Such behavior 8341 // appears to be non-conforming, but is common, so perhaps we should 8342 // assume the standard intended for such cases to be undefined behavior 8343 // and check for them. 8344 8345 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 8346 // overflow in the final conversion to ptrdiff_t. 8347 APSInt LHS( 8348 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 8349 APSInt RHS( 8350 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 8351 APSInt ElemSize( 8352 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false); 8353 APSInt TrueResult = (LHS - RHS) / ElemSize; 8354 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 8355 8356 if (Result.extend(65) != TrueResult && 8357 !HandleOverflow(Info, E, TrueResult, E->getType())) 8358 return false; 8359 return Success(Result, E); 8360 } 8361 8362 // C++11 [expr.rel]p3: 8363 // Pointers to void (after pointer conversions) can be compared, with a 8364 // result defined as follows: If both pointers represent the same 8365 // address or are both the null pointer value, the result is true if the 8366 // operator is <= or >= and false otherwise; otherwise the result is 8367 // unspecified. 8368 // We interpret this as applying to pointers to *cv* void. 8369 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && 8370 E->isRelationalOp()) 8371 CCEDiag(E, diag::note_constexpr_void_comparison); 8372 8373 // C++11 [expr.rel]p2: 8374 // - If two pointers point to non-static data members of the same object, 8375 // or to subobjects or array elements fo such members, recursively, the 8376 // pointer to the later declared member compares greater provided the 8377 // two members have the same access control and provided their class is 8378 // not a union. 8379 // [...] 8380 // - Otherwise pointer comparisons are unspecified. 8381 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 8382 E->isRelationalOp()) { 8383 bool WasArrayIndex; 8384 unsigned Mismatch = 8385 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator, 8386 RHSDesignator, WasArrayIndex); 8387 // At the point where the designators diverge, the comparison has a 8388 // specified value if: 8389 // - we are comparing array indices 8390 // - we are comparing fields of a union, or fields with the same access 8391 // Otherwise, the result is unspecified and thus the comparison is not a 8392 // constant expression. 8393 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 8394 Mismatch < RHSDesignator.Entries.size()) { 8395 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 8396 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 8397 if (!LF && !RF) 8398 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 8399 else if (!LF) 8400 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 8401 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 8402 << RF->getParent() << RF; 8403 else if (!RF) 8404 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 8405 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 8406 << LF->getParent() << LF; 8407 else if (!LF->getParent()->isUnion() && 8408 LF->getAccess() != RF->getAccess()) 8409 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access) 8410 << LF << LF->getAccess() << RF << RF->getAccess() 8411 << LF->getParent(); 8412 } 8413 } 8414 8415 // The comparison here must be unsigned, and performed with the same 8416 // width as the pointer. 8417 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 8418 uint64_t CompareLHS = LHSOffset.getQuantity(); 8419 uint64_t CompareRHS = RHSOffset.getQuantity(); 8420 assert(PtrSize <= 64 && "Unexpected pointer width"); 8421 uint64_t Mask = ~0ULL >> (64 - PtrSize); 8422 CompareLHS &= Mask; 8423 CompareRHS &= Mask; 8424 8425 // If there is a base and this is a relational operator, we can only 8426 // compare pointers within the object in question; otherwise, the result 8427 // depends on where the object is located in memory. 8428 if (!LHSValue.Base.isNull() && E->isRelationalOp()) { 8429 QualType BaseTy = getType(LHSValue.Base); 8430 if (BaseTy->isIncompleteType()) 8431 return Error(E); 8432 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 8433 uint64_t OffsetLimit = Size.getQuantity(); 8434 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 8435 return Error(E); 8436 } 8437 8438 switch (E->getOpcode()) { 8439 default: llvm_unreachable("missing comparison operator"); 8440 case BO_LT: return Success(CompareLHS < CompareRHS, E); 8441 case BO_GT: return Success(CompareLHS > CompareRHS, E); 8442 case BO_LE: return Success(CompareLHS <= CompareRHS, E); 8443 case BO_GE: return Success(CompareLHS >= CompareRHS, E); 8444 case BO_EQ: return Success(CompareLHS == CompareRHS, E); 8445 case BO_NE: return Success(CompareLHS != CompareRHS, E); 8446 } 8447 } 8448 } 8449 8450 if (LHSTy->isMemberPointerType()) { 8451 assert(E->isEqualityOp() && "unexpected member pointer operation"); 8452 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 8453 8454 MemberPtr LHSValue, RHSValue; 8455 8456 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 8457 if (!LHSOK && !Info.noteFailure()) 8458 return false; 8459 8460 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 8461 return false; 8462 8463 // C++11 [expr.eq]p2: 8464 // If both operands are null, they compare equal. Otherwise if only one is 8465 // null, they compare unequal. 8466 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 8467 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 8468 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E); 8469 } 8470 8471 // Otherwise if either is a pointer to a virtual member function, the 8472 // result is unspecified. 8473 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 8474 if (MD->isVirtual()) 8475 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 8476 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 8477 if (MD->isVirtual()) 8478 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 8479 8480 // Otherwise they compare equal if and only if they would refer to the 8481 // same member of the same most derived object or the same subobject if 8482 // they were dereferenced with a hypothetical object of the associated 8483 // class type. 8484 bool Equal = LHSValue == RHSValue; 8485 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E); 8486 } 8487 8488 if (LHSTy->isNullPtrType()) { 8489 assert(E->isComparisonOp() && "unexpected nullptr operation"); 8490 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 8491 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 8492 // are compared, the result is true of the operator is <=, >= or ==, and 8493 // false otherwise. 8494 BinaryOperator::Opcode Opcode = E->getOpcode(); 8495 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E); 8496 } 8497 8498 assert((!LHSTy->isIntegralOrEnumerationType() || 8499 !RHSTy->isIntegralOrEnumerationType()) && 8500 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 8501 // We can't continue from here for non-integral types. 8502 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8503 } 8504 8505 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 8506 /// a result as the expression's type. 8507 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 8508 const UnaryExprOrTypeTraitExpr *E) { 8509 switch(E->getKind()) { 8510 case UETT_AlignOf: { 8511 if (E->isArgumentType()) 8512 return Success(GetAlignOfType(Info, E->getArgumentType()), E); 8513 else 8514 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E); 8515 } 8516 8517 case UETT_VecStep: { 8518 QualType Ty = E->getTypeOfArgument(); 8519 8520 if (Ty->isVectorType()) { 8521 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 8522 8523 // The vec_step built-in functions that take a 3-component 8524 // vector return 4. (OpenCL 1.1 spec 6.11.12) 8525 if (n == 3) 8526 n = 4; 8527 8528 return Success(n, E); 8529 } else 8530 return Success(1, E); 8531 } 8532 8533 case UETT_SizeOf: { 8534 QualType SrcTy = E->getTypeOfArgument(); 8535 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 8536 // the result is the size of the referenced type." 8537 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 8538 SrcTy = Ref->getPointeeType(); 8539 8540 CharUnits Sizeof; 8541 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 8542 return false; 8543 return Success(Sizeof, E); 8544 } 8545 case UETT_OpenMPRequiredSimdAlign: 8546 assert(E->isArgumentType()); 8547 return Success( 8548 Info.Ctx.toCharUnitsFromBits( 8549 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 8550 .getQuantity(), 8551 E); 8552 } 8553 8554 llvm_unreachable("unknown expr/type trait"); 8555 } 8556 8557 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 8558 CharUnits Result; 8559 unsigned n = OOE->getNumComponents(); 8560 if (n == 0) 8561 return Error(OOE); 8562 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 8563 for (unsigned i = 0; i != n; ++i) { 8564 OffsetOfNode ON = OOE->getComponent(i); 8565 switch (ON.getKind()) { 8566 case OffsetOfNode::Array: { 8567 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 8568 APSInt IdxResult; 8569 if (!EvaluateInteger(Idx, IdxResult, Info)) 8570 return false; 8571 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 8572 if (!AT) 8573 return Error(OOE); 8574 CurrentType = AT->getElementType(); 8575 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 8576 Result += IdxResult.getSExtValue() * ElementSize; 8577 break; 8578 } 8579 8580 case OffsetOfNode::Field: { 8581 FieldDecl *MemberDecl = ON.getField(); 8582 const RecordType *RT = CurrentType->getAs<RecordType>(); 8583 if (!RT) 8584 return Error(OOE); 8585 RecordDecl *RD = RT->getDecl(); 8586 if (RD->isInvalidDecl()) return false; 8587 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 8588 unsigned i = MemberDecl->getFieldIndex(); 8589 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 8590 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 8591 CurrentType = MemberDecl->getType().getNonReferenceType(); 8592 break; 8593 } 8594 8595 case OffsetOfNode::Identifier: 8596 llvm_unreachable("dependent __builtin_offsetof"); 8597 8598 case OffsetOfNode::Base: { 8599 CXXBaseSpecifier *BaseSpec = ON.getBase(); 8600 if (BaseSpec->isVirtual()) 8601 return Error(OOE); 8602 8603 // Find the layout of the class whose base we are looking into. 8604 const RecordType *RT = CurrentType->getAs<RecordType>(); 8605 if (!RT) 8606 return Error(OOE); 8607 RecordDecl *RD = RT->getDecl(); 8608 if (RD->isInvalidDecl()) return false; 8609 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 8610 8611 // Find the base class itself. 8612 CurrentType = BaseSpec->getType(); 8613 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 8614 if (!BaseRT) 8615 return Error(OOE); 8616 8617 // Add the offset to the base. 8618 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 8619 break; 8620 } 8621 } 8622 } 8623 return Success(Result, OOE); 8624 } 8625 8626 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 8627 switch (E->getOpcode()) { 8628 default: 8629 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 8630 // See C99 6.6p3. 8631 return Error(E); 8632 case UO_Extension: 8633 // FIXME: Should extension allow i-c-e extension expressions in its scope? 8634 // If so, we could clear the diagnostic ID. 8635 return Visit(E->getSubExpr()); 8636 case UO_Plus: 8637 // The result is just the value. 8638 return Visit(E->getSubExpr()); 8639 case UO_Minus: { 8640 if (!Visit(E->getSubExpr())) 8641 return false; 8642 if (!Result.isInt()) return Error(E); 8643 const APSInt &Value = Result.getInt(); 8644 if (Value.isSigned() && Value.isMinSignedValue() && 8645 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 8646 E->getType())) 8647 return false; 8648 return Success(-Value, E); 8649 } 8650 case UO_Not: { 8651 if (!Visit(E->getSubExpr())) 8652 return false; 8653 if (!Result.isInt()) return Error(E); 8654 return Success(~Result.getInt(), E); 8655 } 8656 case UO_LNot: { 8657 bool bres; 8658 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 8659 return false; 8660 return Success(!bres, E); 8661 } 8662 } 8663 } 8664 8665 /// HandleCast - This is used to evaluate implicit or explicit casts where the 8666 /// result type is integer. 8667 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 8668 const Expr *SubExpr = E->getSubExpr(); 8669 QualType DestType = E->getType(); 8670 QualType SrcType = SubExpr->getType(); 8671 8672 switch (E->getCastKind()) { 8673 case CK_BaseToDerived: 8674 case CK_DerivedToBase: 8675 case CK_UncheckedDerivedToBase: 8676 case CK_Dynamic: 8677 case CK_ToUnion: 8678 case CK_ArrayToPointerDecay: 8679 case CK_FunctionToPointerDecay: 8680 case CK_NullToPointer: 8681 case CK_NullToMemberPointer: 8682 case CK_BaseToDerivedMemberPointer: 8683 case CK_DerivedToBaseMemberPointer: 8684 case CK_ReinterpretMemberPointer: 8685 case CK_ConstructorConversion: 8686 case CK_IntegralToPointer: 8687 case CK_ToVoid: 8688 case CK_VectorSplat: 8689 case CK_IntegralToFloating: 8690 case CK_FloatingCast: 8691 case CK_CPointerToObjCPointerCast: 8692 case CK_BlockPointerToObjCPointerCast: 8693 case CK_AnyPointerToBlockPointerCast: 8694 case CK_ObjCObjectLValueCast: 8695 case CK_FloatingRealToComplex: 8696 case CK_FloatingComplexToReal: 8697 case CK_FloatingComplexCast: 8698 case CK_FloatingComplexToIntegralComplex: 8699 case CK_IntegralRealToComplex: 8700 case CK_IntegralComplexCast: 8701 case CK_IntegralComplexToFloatingComplex: 8702 case CK_BuiltinFnToFnPtr: 8703 case CK_ZeroToOCLEvent: 8704 case CK_ZeroToOCLQueue: 8705 case CK_NonAtomicToAtomic: 8706 case CK_AddressSpaceConversion: 8707 case CK_IntToOCLSampler: 8708 llvm_unreachable("invalid cast kind for integral value"); 8709 8710 case CK_BitCast: 8711 case CK_Dependent: 8712 case CK_LValueBitCast: 8713 case CK_ARCProduceObject: 8714 case CK_ARCConsumeObject: 8715 case CK_ARCReclaimReturnedObject: 8716 case CK_ARCExtendBlockObject: 8717 case CK_CopyAndAutoreleaseBlockObject: 8718 return Error(E); 8719 8720 case CK_UserDefinedConversion: 8721 case CK_LValueToRValue: 8722 case CK_AtomicToNonAtomic: 8723 case CK_NoOp: 8724 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8725 8726 case CK_MemberPointerToBoolean: 8727 case CK_PointerToBoolean: 8728 case CK_IntegralToBoolean: 8729 case CK_FloatingToBoolean: 8730 case CK_BooleanToSignedIntegral: 8731 case CK_FloatingComplexToBoolean: 8732 case CK_IntegralComplexToBoolean: { 8733 bool BoolResult; 8734 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 8735 return false; 8736 uint64_t IntResult = BoolResult; 8737 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 8738 IntResult = (uint64_t)-1; 8739 return Success(IntResult, E); 8740 } 8741 8742 case CK_IntegralCast: { 8743 if (!Visit(SubExpr)) 8744 return false; 8745 8746 if (!Result.isInt()) { 8747 // Allow casts of address-of-label differences if they are no-ops 8748 // or narrowing. (The narrowing case isn't actually guaranteed to 8749 // be constant-evaluatable except in some narrow cases which are hard 8750 // to detect here. We let it through on the assumption the user knows 8751 // what they are doing.) 8752 if (Result.isAddrLabelDiff()) 8753 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 8754 // Only allow casts of lvalues if they are lossless. 8755 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 8756 } 8757 8758 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 8759 Result.getInt()), E); 8760 } 8761 8762 case CK_PointerToIntegral: { 8763 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8764 8765 LValue LV; 8766 if (!EvaluatePointer(SubExpr, LV, Info)) 8767 return false; 8768 8769 if (LV.getLValueBase()) { 8770 // Only allow based lvalue casts if they are lossless. 8771 // FIXME: Allow a larger integer size than the pointer size, and allow 8772 // narrowing back down to pointer width in subsequent integral casts. 8773 // FIXME: Check integer type's active bits, not its type size. 8774 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 8775 return Error(E); 8776 8777 LV.Designator.setInvalid(); 8778 LV.moveInto(Result); 8779 return true; 8780 } 8781 8782 uint64_t V; 8783 if (LV.isNullPointer()) 8784 V = Info.Ctx.getTargetNullPointerValue(SrcType); 8785 else 8786 V = LV.getLValueOffset().getQuantity(); 8787 8788 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType); 8789 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 8790 } 8791 8792 case CK_IntegralComplexToReal: { 8793 ComplexValue C; 8794 if (!EvaluateComplex(SubExpr, C, Info)) 8795 return false; 8796 return Success(C.getComplexIntReal(), E); 8797 } 8798 8799 case CK_FloatingToIntegral: { 8800 APFloat F(0.0); 8801 if (!EvaluateFloat(SubExpr, F, Info)) 8802 return false; 8803 8804 APSInt Value; 8805 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 8806 return false; 8807 return Success(Value, E); 8808 } 8809 } 8810 8811 llvm_unreachable("unknown cast resulting in integral value"); 8812 } 8813 8814 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8815 if (E->getSubExpr()->getType()->isAnyComplexType()) { 8816 ComplexValue LV; 8817 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 8818 return false; 8819 if (!LV.isComplexInt()) 8820 return Error(E); 8821 return Success(LV.getComplexIntReal(), E); 8822 } 8823 8824 return Visit(E->getSubExpr()); 8825 } 8826 8827 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8828 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 8829 ComplexValue LV; 8830 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 8831 return false; 8832 if (!LV.isComplexInt()) 8833 return Error(E); 8834 return Success(LV.getComplexIntImag(), E); 8835 } 8836 8837 VisitIgnoredValue(E->getSubExpr()); 8838 return Success(0, E); 8839 } 8840 8841 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 8842 return Success(E->getPackLength(), E); 8843 } 8844 8845 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 8846 return Success(E->getValue(), E); 8847 } 8848 8849 //===----------------------------------------------------------------------===// 8850 // Float Evaluation 8851 //===----------------------------------------------------------------------===// 8852 8853 namespace { 8854 class FloatExprEvaluator 8855 : public ExprEvaluatorBase<FloatExprEvaluator> { 8856 APFloat &Result; 8857 public: 8858 FloatExprEvaluator(EvalInfo &info, APFloat &result) 8859 : ExprEvaluatorBaseTy(info), Result(result) {} 8860 8861 bool Success(const APValue &V, const Expr *e) { 8862 Result = V.getFloat(); 8863 return true; 8864 } 8865 8866 bool ZeroInitialization(const Expr *E) { 8867 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 8868 return true; 8869 } 8870 8871 bool VisitCallExpr(const CallExpr *E); 8872 8873 bool VisitUnaryOperator(const UnaryOperator *E); 8874 bool VisitBinaryOperator(const BinaryOperator *E); 8875 bool VisitFloatingLiteral(const FloatingLiteral *E); 8876 bool VisitCastExpr(const CastExpr *E); 8877 8878 bool VisitUnaryReal(const UnaryOperator *E); 8879 bool VisitUnaryImag(const UnaryOperator *E); 8880 8881 // FIXME: Missing: array subscript of vector, member of vector 8882 }; 8883 } // end anonymous namespace 8884 8885 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 8886 assert(E->isRValue() && E->getType()->isRealFloatingType()); 8887 return FloatExprEvaluator(Info, Result).Visit(E); 8888 } 8889 8890 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 8891 QualType ResultTy, 8892 const Expr *Arg, 8893 bool SNaN, 8894 llvm::APFloat &Result) { 8895 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 8896 if (!S) return false; 8897 8898 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 8899 8900 llvm::APInt fill; 8901 8902 // Treat empty strings as if they were zero. 8903 if (S->getString().empty()) 8904 fill = llvm::APInt(32, 0); 8905 else if (S->getString().getAsInteger(0, fill)) 8906 return false; 8907 8908 if (Context.getTargetInfo().isNan2008()) { 8909 if (SNaN) 8910 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 8911 else 8912 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 8913 } else { 8914 // Prior to IEEE 754-2008, architectures were allowed to choose whether 8915 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 8916 // a different encoding to what became a standard in 2008, and for pre- 8917 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 8918 // sNaN. This is now known as "legacy NaN" encoding. 8919 if (SNaN) 8920 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 8921 else 8922 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 8923 } 8924 8925 return true; 8926 } 8927 8928 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 8929 switch (E->getBuiltinCallee()) { 8930 default: 8931 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8932 8933 case Builtin::BI__builtin_huge_val: 8934 case Builtin::BI__builtin_huge_valf: 8935 case Builtin::BI__builtin_huge_vall: 8936 case Builtin::BI__builtin_inf: 8937 case Builtin::BI__builtin_inff: 8938 case Builtin::BI__builtin_infl: { 8939 const llvm::fltSemantics &Sem = 8940 Info.Ctx.getFloatTypeSemantics(E->getType()); 8941 Result = llvm::APFloat::getInf(Sem); 8942 return true; 8943 } 8944 8945 case Builtin::BI__builtin_nans: 8946 case Builtin::BI__builtin_nansf: 8947 case Builtin::BI__builtin_nansl: 8948 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 8949 true, Result)) 8950 return Error(E); 8951 return true; 8952 8953 case Builtin::BI__builtin_nan: 8954 case Builtin::BI__builtin_nanf: 8955 case Builtin::BI__builtin_nanl: 8956 // If this is __builtin_nan() turn this into a nan, otherwise we 8957 // can't constant fold it. 8958 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 8959 false, Result)) 8960 return Error(E); 8961 return true; 8962 8963 case Builtin::BI__builtin_fabs: 8964 case Builtin::BI__builtin_fabsf: 8965 case Builtin::BI__builtin_fabsl: 8966 if (!EvaluateFloat(E->getArg(0), Result, Info)) 8967 return false; 8968 8969 if (Result.isNegative()) 8970 Result.changeSign(); 8971 return true; 8972 8973 // FIXME: Builtin::BI__builtin_powi 8974 // FIXME: Builtin::BI__builtin_powif 8975 // FIXME: Builtin::BI__builtin_powil 8976 8977 case Builtin::BI__builtin_copysign: 8978 case Builtin::BI__builtin_copysignf: 8979 case Builtin::BI__builtin_copysignl: { 8980 APFloat RHS(0.); 8981 if (!EvaluateFloat(E->getArg(0), Result, Info) || 8982 !EvaluateFloat(E->getArg(1), RHS, Info)) 8983 return false; 8984 Result.copySign(RHS); 8985 return true; 8986 } 8987 } 8988 } 8989 8990 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8991 if (E->getSubExpr()->getType()->isAnyComplexType()) { 8992 ComplexValue CV; 8993 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 8994 return false; 8995 Result = CV.FloatReal; 8996 return true; 8997 } 8998 8999 return Visit(E->getSubExpr()); 9000 } 9001 9002 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9003 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9004 ComplexValue CV; 9005 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 9006 return false; 9007 Result = CV.FloatImag; 9008 return true; 9009 } 9010 9011 VisitIgnoredValue(E->getSubExpr()); 9012 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 9013 Result = llvm::APFloat::getZero(Sem); 9014 return true; 9015 } 9016 9017 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9018 switch (E->getOpcode()) { 9019 default: return Error(E); 9020 case UO_Plus: 9021 return EvaluateFloat(E->getSubExpr(), Result, Info); 9022 case UO_Minus: 9023 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 9024 return false; 9025 Result.changeSign(); 9026 return true; 9027 } 9028 } 9029 9030 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9031 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 9032 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9033 9034 APFloat RHS(0.0); 9035 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 9036 if (!LHSOK && !Info.noteFailure()) 9037 return false; 9038 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 9039 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 9040 } 9041 9042 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 9043 Result = E->getValue(); 9044 return true; 9045 } 9046 9047 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 9048 const Expr* SubExpr = E->getSubExpr(); 9049 9050 switch (E->getCastKind()) { 9051 default: 9052 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9053 9054 case CK_IntegralToFloating: { 9055 APSInt IntResult; 9056 return EvaluateInteger(SubExpr, IntResult, Info) && 9057 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 9058 E->getType(), Result); 9059 } 9060 9061 case CK_FloatingCast: { 9062 if (!Visit(SubExpr)) 9063 return false; 9064 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 9065 Result); 9066 } 9067 9068 case CK_FloatingComplexToReal: { 9069 ComplexValue V; 9070 if (!EvaluateComplex(SubExpr, V, Info)) 9071 return false; 9072 Result = V.getComplexFloatReal(); 9073 return true; 9074 } 9075 } 9076 } 9077 9078 //===----------------------------------------------------------------------===// 9079 // Complex Evaluation (for float and integer) 9080 //===----------------------------------------------------------------------===// 9081 9082 namespace { 9083 class ComplexExprEvaluator 9084 : public ExprEvaluatorBase<ComplexExprEvaluator> { 9085 ComplexValue &Result; 9086 9087 public: 9088 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 9089 : ExprEvaluatorBaseTy(info), Result(Result) {} 9090 9091 bool Success(const APValue &V, const Expr *e) { 9092 Result.setFrom(V); 9093 return true; 9094 } 9095 9096 bool ZeroInitialization(const Expr *E); 9097 9098 //===--------------------------------------------------------------------===// 9099 // Visitor Methods 9100 //===--------------------------------------------------------------------===// 9101 9102 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 9103 bool VisitCastExpr(const CastExpr *E); 9104 bool VisitBinaryOperator(const BinaryOperator *E); 9105 bool VisitUnaryOperator(const UnaryOperator *E); 9106 bool VisitInitListExpr(const InitListExpr *E); 9107 }; 9108 } // end anonymous namespace 9109 9110 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 9111 EvalInfo &Info) { 9112 assert(E->isRValue() && E->getType()->isAnyComplexType()); 9113 return ComplexExprEvaluator(Info, Result).Visit(E); 9114 } 9115 9116 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 9117 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 9118 if (ElemTy->isRealFloatingType()) { 9119 Result.makeComplexFloat(); 9120 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 9121 Result.FloatReal = Zero; 9122 Result.FloatImag = Zero; 9123 } else { 9124 Result.makeComplexInt(); 9125 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 9126 Result.IntReal = Zero; 9127 Result.IntImag = Zero; 9128 } 9129 return true; 9130 } 9131 9132 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 9133 const Expr* SubExpr = E->getSubExpr(); 9134 9135 if (SubExpr->getType()->isRealFloatingType()) { 9136 Result.makeComplexFloat(); 9137 APFloat &Imag = Result.FloatImag; 9138 if (!EvaluateFloat(SubExpr, Imag, Info)) 9139 return false; 9140 9141 Result.FloatReal = APFloat(Imag.getSemantics()); 9142 return true; 9143 } else { 9144 assert(SubExpr->getType()->isIntegerType() && 9145 "Unexpected imaginary literal."); 9146 9147 Result.makeComplexInt(); 9148 APSInt &Imag = Result.IntImag; 9149 if (!EvaluateInteger(SubExpr, Imag, Info)) 9150 return false; 9151 9152 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 9153 return true; 9154 } 9155 } 9156 9157 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 9158 9159 switch (E->getCastKind()) { 9160 case CK_BitCast: 9161 case CK_BaseToDerived: 9162 case CK_DerivedToBase: 9163 case CK_UncheckedDerivedToBase: 9164 case CK_Dynamic: 9165 case CK_ToUnion: 9166 case CK_ArrayToPointerDecay: 9167 case CK_FunctionToPointerDecay: 9168 case CK_NullToPointer: 9169 case CK_NullToMemberPointer: 9170 case CK_BaseToDerivedMemberPointer: 9171 case CK_DerivedToBaseMemberPointer: 9172 case CK_MemberPointerToBoolean: 9173 case CK_ReinterpretMemberPointer: 9174 case CK_ConstructorConversion: 9175 case CK_IntegralToPointer: 9176 case CK_PointerToIntegral: 9177 case CK_PointerToBoolean: 9178 case CK_ToVoid: 9179 case CK_VectorSplat: 9180 case CK_IntegralCast: 9181 case CK_BooleanToSignedIntegral: 9182 case CK_IntegralToBoolean: 9183 case CK_IntegralToFloating: 9184 case CK_FloatingToIntegral: 9185 case CK_FloatingToBoolean: 9186 case CK_FloatingCast: 9187 case CK_CPointerToObjCPointerCast: 9188 case CK_BlockPointerToObjCPointerCast: 9189 case CK_AnyPointerToBlockPointerCast: 9190 case CK_ObjCObjectLValueCast: 9191 case CK_FloatingComplexToReal: 9192 case CK_FloatingComplexToBoolean: 9193 case CK_IntegralComplexToReal: 9194 case CK_IntegralComplexToBoolean: 9195 case CK_ARCProduceObject: 9196 case CK_ARCConsumeObject: 9197 case CK_ARCReclaimReturnedObject: 9198 case CK_ARCExtendBlockObject: 9199 case CK_CopyAndAutoreleaseBlockObject: 9200 case CK_BuiltinFnToFnPtr: 9201 case CK_ZeroToOCLEvent: 9202 case CK_ZeroToOCLQueue: 9203 case CK_NonAtomicToAtomic: 9204 case CK_AddressSpaceConversion: 9205 case CK_IntToOCLSampler: 9206 llvm_unreachable("invalid cast kind for complex value"); 9207 9208 case CK_LValueToRValue: 9209 case CK_AtomicToNonAtomic: 9210 case CK_NoOp: 9211 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9212 9213 case CK_Dependent: 9214 case CK_LValueBitCast: 9215 case CK_UserDefinedConversion: 9216 return Error(E); 9217 9218 case CK_FloatingRealToComplex: { 9219 APFloat &Real = Result.FloatReal; 9220 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 9221 return false; 9222 9223 Result.makeComplexFloat(); 9224 Result.FloatImag = APFloat(Real.getSemantics()); 9225 return true; 9226 } 9227 9228 case CK_FloatingComplexCast: { 9229 if (!Visit(E->getSubExpr())) 9230 return false; 9231 9232 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 9233 QualType From 9234 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 9235 9236 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 9237 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 9238 } 9239 9240 case CK_FloatingComplexToIntegralComplex: { 9241 if (!Visit(E->getSubExpr())) 9242 return false; 9243 9244 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 9245 QualType From 9246 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 9247 Result.makeComplexInt(); 9248 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 9249 To, Result.IntReal) && 9250 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 9251 To, Result.IntImag); 9252 } 9253 9254 case CK_IntegralRealToComplex: { 9255 APSInt &Real = Result.IntReal; 9256 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 9257 return false; 9258 9259 Result.makeComplexInt(); 9260 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 9261 return true; 9262 } 9263 9264 case CK_IntegralComplexCast: { 9265 if (!Visit(E->getSubExpr())) 9266 return false; 9267 9268 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 9269 QualType From 9270 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 9271 9272 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 9273 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 9274 return true; 9275 } 9276 9277 case CK_IntegralComplexToFloatingComplex: { 9278 if (!Visit(E->getSubExpr())) 9279 return false; 9280 9281 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 9282 QualType From 9283 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 9284 Result.makeComplexFloat(); 9285 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 9286 To, Result.FloatReal) && 9287 HandleIntToFloatCast(Info, E, From, Result.IntImag, 9288 To, Result.FloatImag); 9289 } 9290 } 9291 9292 llvm_unreachable("unknown cast resulting in complex value"); 9293 } 9294 9295 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9296 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 9297 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9298 9299 // Track whether the LHS or RHS is real at the type system level. When this is 9300 // the case we can simplify our evaluation strategy. 9301 bool LHSReal = false, RHSReal = false; 9302 9303 bool LHSOK; 9304 if (E->getLHS()->getType()->isRealFloatingType()) { 9305 LHSReal = true; 9306 APFloat &Real = Result.FloatReal; 9307 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 9308 if (LHSOK) { 9309 Result.makeComplexFloat(); 9310 Result.FloatImag = APFloat(Real.getSemantics()); 9311 } 9312 } else { 9313 LHSOK = Visit(E->getLHS()); 9314 } 9315 if (!LHSOK && !Info.noteFailure()) 9316 return false; 9317 9318 ComplexValue RHS; 9319 if (E->getRHS()->getType()->isRealFloatingType()) { 9320 RHSReal = true; 9321 APFloat &Real = RHS.FloatReal; 9322 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 9323 return false; 9324 RHS.makeComplexFloat(); 9325 RHS.FloatImag = APFloat(Real.getSemantics()); 9326 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 9327 return false; 9328 9329 assert(!(LHSReal && RHSReal) && 9330 "Cannot have both operands of a complex operation be real."); 9331 switch (E->getOpcode()) { 9332 default: return Error(E); 9333 case BO_Add: 9334 if (Result.isComplexFloat()) { 9335 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 9336 APFloat::rmNearestTiesToEven); 9337 if (LHSReal) 9338 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 9339 else if (!RHSReal) 9340 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 9341 APFloat::rmNearestTiesToEven); 9342 } else { 9343 Result.getComplexIntReal() += RHS.getComplexIntReal(); 9344 Result.getComplexIntImag() += RHS.getComplexIntImag(); 9345 } 9346 break; 9347 case BO_Sub: 9348 if (Result.isComplexFloat()) { 9349 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 9350 APFloat::rmNearestTiesToEven); 9351 if (LHSReal) { 9352 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 9353 Result.getComplexFloatImag().changeSign(); 9354 } else if (!RHSReal) { 9355 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 9356 APFloat::rmNearestTiesToEven); 9357 } 9358 } else { 9359 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 9360 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 9361 } 9362 break; 9363 case BO_Mul: 9364 if (Result.isComplexFloat()) { 9365 // This is an implementation of complex multiplication according to the 9366 // constraints laid out in C11 Annex G. The implemantion uses the 9367 // following naming scheme: 9368 // (a + ib) * (c + id) 9369 ComplexValue LHS = Result; 9370 APFloat &A = LHS.getComplexFloatReal(); 9371 APFloat &B = LHS.getComplexFloatImag(); 9372 APFloat &C = RHS.getComplexFloatReal(); 9373 APFloat &D = RHS.getComplexFloatImag(); 9374 APFloat &ResR = Result.getComplexFloatReal(); 9375 APFloat &ResI = Result.getComplexFloatImag(); 9376 if (LHSReal) { 9377 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 9378 ResR = A * C; 9379 ResI = A * D; 9380 } else if (RHSReal) { 9381 ResR = C * A; 9382 ResI = C * B; 9383 } else { 9384 // In the fully general case, we need to handle NaNs and infinities 9385 // robustly. 9386 APFloat AC = A * C; 9387 APFloat BD = B * D; 9388 APFloat AD = A * D; 9389 APFloat BC = B * C; 9390 ResR = AC - BD; 9391 ResI = AD + BC; 9392 if (ResR.isNaN() && ResI.isNaN()) { 9393 bool Recalc = false; 9394 if (A.isInfinity() || B.isInfinity()) { 9395 A = APFloat::copySign( 9396 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 9397 B = APFloat::copySign( 9398 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 9399 if (C.isNaN()) 9400 C = APFloat::copySign(APFloat(C.getSemantics()), C); 9401 if (D.isNaN()) 9402 D = APFloat::copySign(APFloat(D.getSemantics()), D); 9403 Recalc = true; 9404 } 9405 if (C.isInfinity() || D.isInfinity()) { 9406 C = APFloat::copySign( 9407 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 9408 D = APFloat::copySign( 9409 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 9410 if (A.isNaN()) 9411 A = APFloat::copySign(APFloat(A.getSemantics()), A); 9412 if (B.isNaN()) 9413 B = APFloat::copySign(APFloat(B.getSemantics()), B); 9414 Recalc = true; 9415 } 9416 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 9417 AD.isInfinity() || BC.isInfinity())) { 9418 if (A.isNaN()) 9419 A = APFloat::copySign(APFloat(A.getSemantics()), A); 9420 if (B.isNaN()) 9421 B = APFloat::copySign(APFloat(B.getSemantics()), B); 9422 if (C.isNaN()) 9423 C = APFloat::copySign(APFloat(C.getSemantics()), C); 9424 if (D.isNaN()) 9425 D = APFloat::copySign(APFloat(D.getSemantics()), D); 9426 Recalc = true; 9427 } 9428 if (Recalc) { 9429 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 9430 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 9431 } 9432 } 9433 } 9434 } else { 9435 ComplexValue LHS = Result; 9436 Result.getComplexIntReal() = 9437 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 9438 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 9439 Result.getComplexIntImag() = 9440 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 9441 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 9442 } 9443 break; 9444 case BO_Div: 9445 if (Result.isComplexFloat()) { 9446 // This is an implementation of complex division according to the 9447 // constraints laid out in C11 Annex G. The implemantion uses the 9448 // following naming scheme: 9449 // (a + ib) / (c + id) 9450 ComplexValue LHS = Result; 9451 APFloat &A = LHS.getComplexFloatReal(); 9452 APFloat &B = LHS.getComplexFloatImag(); 9453 APFloat &C = RHS.getComplexFloatReal(); 9454 APFloat &D = RHS.getComplexFloatImag(); 9455 APFloat &ResR = Result.getComplexFloatReal(); 9456 APFloat &ResI = Result.getComplexFloatImag(); 9457 if (RHSReal) { 9458 ResR = A / C; 9459 ResI = B / C; 9460 } else { 9461 if (LHSReal) { 9462 // No real optimizations we can do here, stub out with zero. 9463 B = APFloat::getZero(A.getSemantics()); 9464 } 9465 int DenomLogB = 0; 9466 APFloat MaxCD = maxnum(abs(C), abs(D)); 9467 if (MaxCD.isFinite()) { 9468 DenomLogB = ilogb(MaxCD); 9469 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 9470 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 9471 } 9472 APFloat Denom = C * C + D * D; 9473 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 9474 APFloat::rmNearestTiesToEven); 9475 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 9476 APFloat::rmNearestTiesToEven); 9477 if (ResR.isNaN() && ResI.isNaN()) { 9478 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 9479 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 9480 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 9481 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 9482 D.isFinite()) { 9483 A = APFloat::copySign( 9484 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 9485 B = APFloat::copySign( 9486 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 9487 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 9488 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 9489 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 9490 C = APFloat::copySign( 9491 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 9492 D = APFloat::copySign( 9493 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 9494 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 9495 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 9496 } 9497 } 9498 } 9499 } else { 9500 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 9501 return Error(E, diag::note_expr_divide_by_zero); 9502 9503 ComplexValue LHS = Result; 9504 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 9505 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 9506 Result.getComplexIntReal() = 9507 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 9508 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 9509 Result.getComplexIntImag() = 9510 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 9511 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 9512 } 9513 break; 9514 } 9515 9516 return true; 9517 } 9518 9519 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9520 // Get the operand value into 'Result'. 9521 if (!Visit(E->getSubExpr())) 9522 return false; 9523 9524 switch (E->getOpcode()) { 9525 default: 9526 return Error(E); 9527 case UO_Extension: 9528 return true; 9529 case UO_Plus: 9530 // The result is always just the subexpr. 9531 return true; 9532 case UO_Minus: 9533 if (Result.isComplexFloat()) { 9534 Result.getComplexFloatReal().changeSign(); 9535 Result.getComplexFloatImag().changeSign(); 9536 } 9537 else { 9538 Result.getComplexIntReal() = -Result.getComplexIntReal(); 9539 Result.getComplexIntImag() = -Result.getComplexIntImag(); 9540 } 9541 return true; 9542 case UO_Not: 9543 if (Result.isComplexFloat()) 9544 Result.getComplexFloatImag().changeSign(); 9545 else 9546 Result.getComplexIntImag() = -Result.getComplexIntImag(); 9547 return true; 9548 } 9549 } 9550 9551 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9552 if (E->getNumInits() == 2) { 9553 if (E->getType()->isComplexType()) { 9554 Result.makeComplexFloat(); 9555 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 9556 return false; 9557 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 9558 return false; 9559 } else { 9560 Result.makeComplexInt(); 9561 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 9562 return false; 9563 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 9564 return false; 9565 } 9566 return true; 9567 } 9568 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 9569 } 9570 9571 //===----------------------------------------------------------------------===// 9572 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 9573 // implicit conversion. 9574 //===----------------------------------------------------------------------===// 9575 9576 namespace { 9577 class AtomicExprEvaluator : 9578 public ExprEvaluatorBase<AtomicExprEvaluator> { 9579 APValue &Result; 9580 public: 9581 AtomicExprEvaluator(EvalInfo &Info, APValue &Result) 9582 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9583 9584 bool Success(const APValue &V, const Expr *E) { 9585 Result = V; 9586 return true; 9587 } 9588 9589 bool ZeroInitialization(const Expr *E) { 9590 ImplicitValueInitExpr VIE( 9591 E->getType()->castAs<AtomicType>()->getValueType()); 9592 return Evaluate(Result, Info, &VIE); 9593 } 9594 9595 bool VisitCastExpr(const CastExpr *E) { 9596 switch (E->getCastKind()) { 9597 default: 9598 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9599 case CK_NonAtomicToAtomic: 9600 return Evaluate(Result, Info, E->getSubExpr()); 9601 } 9602 } 9603 }; 9604 } // end anonymous namespace 9605 9606 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) { 9607 assert(E->isRValue() && E->getType()->isAtomicType()); 9608 return AtomicExprEvaluator(Info, Result).Visit(E); 9609 } 9610 9611 //===----------------------------------------------------------------------===// 9612 // Void expression evaluation, primarily for a cast to void on the LHS of a 9613 // comma operator 9614 //===----------------------------------------------------------------------===// 9615 9616 namespace { 9617 class VoidExprEvaluator 9618 : public ExprEvaluatorBase<VoidExprEvaluator> { 9619 public: 9620 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 9621 9622 bool Success(const APValue &V, const Expr *e) { return true; } 9623 9624 bool VisitCastExpr(const CastExpr *E) { 9625 switch (E->getCastKind()) { 9626 default: 9627 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9628 case CK_ToVoid: 9629 VisitIgnoredValue(E->getSubExpr()); 9630 return true; 9631 } 9632 } 9633 9634 bool VisitCallExpr(const CallExpr *E) { 9635 switch (E->getBuiltinCallee()) { 9636 default: 9637 return ExprEvaluatorBaseTy::VisitCallExpr(E); 9638 case Builtin::BI__assume: 9639 case Builtin::BI__builtin_assume: 9640 // The argument is not evaluated! 9641 return true; 9642 } 9643 } 9644 }; 9645 } // end anonymous namespace 9646 9647 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 9648 assert(E->isRValue() && E->getType()->isVoidType()); 9649 return VoidExprEvaluator(Info).Visit(E); 9650 } 9651 9652 //===----------------------------------------------------------------------===// 9653 // Top level Expr::EvaluateAsRValue method. 9654 //===----------------------------------------------------------------------===// 9655 9656 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 9657 // In C, function designators are not lvalues, but we evaluate them as if they 9658 // are. 9659 QualType T = E->getType(); 9660 if (E->isGLValue() || T->isFunctionType()) { 9661 LValue LV; 9662 if (!EvaluateLValue(E, LV, Info)) 9663 return false; 9664 LV.moveInto(Result); 9665 } else if (T->isVectorType()) { 9666 if (!EvaluateVector(E, Result, Info)) 9667 return false; 9668 } else if (T->isIntegralOrEnumerationType()) { 9669 if (!IntExprEvaluator(Info, Result).Visit(E)) 9670 return false; 9671 } else if (T->hasPointerRepresentation()) { 9672 LValue LV; 9673 if (!EvaluatePointer(E, LV, Info)) 9674 return false; 9675 LV.moveInto(Result); 9676 } else if (T->isRealFloatingType()) { 9677 llvm::APFloat F(0.0); 9678 if (!EvaluateFloat(E, F, Info)) 9679 return false; 9680 Result = APValue(F); 9681 } else if (T->isAnyComplexType()) { 9682 ComplexValue C; 9683 if (!EvaluateComplex(E, C, Info)) 9684 return false; 9685 C.moveInto(Result); 9686 } else if (T->isMemberPointerType()) { 9687 MemberPtr P; 9688 if (!EvaluateMemberPointer(E, P, Info)) 9689 return false; 9690 P.moveInto(Result); 9691 return true; 9692 } else if (T->isArrayType()) { 9693 LValue LV; 9694 LV.set(E, Info.CurrentCall->Index); 9695 APValue &Value = Info.CurrentCall->createTemporary(E, false); 9696 if (!EvaluateArray(E, LV, Value, Info)) 9697 return false; 9698 Result = Value; 9699 } else if (T->isRecordType()) { 9700 LValue LV; 9701 LV.set(E, Info.CurrentCall->Index); 9702 APValue &Value = Info.CurrentCall->createTemporary(E, false); 9703 if (!EvaluateRecord(E, LV, Value, Info)) 9704 return false; 9705 Result = Value; 9706 } else if (T->isVoidType()) { 9707 if (!Info.getLangOpts().CPlusPlus11) 9708 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 9709 << E->getType(); 9710 if (!EvaluateVoid(E, Info)) 9711 return false; 9712 } else if (T->isAtomicType()) { 9713 if (!EvaluateAtomic(E, Result, Info)) 9714 return false; 9715 } else if (Info.getLangOpts().CPlusPlus11) { 9716 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 9717 return false; 9718 } else { 9719 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 9720 return false; 9721 } 9722 9723 return true; 9724 } 9725 9726 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 9727 /// cases, the in-place evaluation is essential, since later initializers for 9728 /// an object can indirectly refer to subobjects which were initialized earlier. 9729 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 9730 const Expr *E, bool AllowNonLiteralTypes) { 9731 assert(!E->isValueDependent()); 9732 9733 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 9734 return false; 9735 9736 if (E->isRValue()) { 9737 // Evaluate arrays and record types in-place, so that later initializers can 9738 // refer to earlier-initialized members of the object. 9739 if (E->getType()->isArrayType()) 9740 return EvaluateArray(E, This, Result, Info); 9741 else if (E->getType()->isRecordType()) 9742 return EvaluateRecord(E, This, Result, Info); 9743 } 9744 9745 // For any other type, in-place evaluation is unimportant. 9746 return Evaluate(Result, Info, E); 9747 } 9748 9749 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 9750 /// lvalue-to-rvalue cast if it is an lvalue. 9751 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 9752 if (E->getType().isNull()) 9753 return false; 9754 9755 if (!CheckLiteralType(Info, E)) 9756 return false; 9757 9758 if (!::Evaluate(Result, Info, E)) 9759 return false; 9760 9761 if (E->isGLValue()) { 9762 LValue LV; 9763 LV.setFrom(Info.Ctx, Result); 9764 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 9765 return false; 9766 } 9767 9768 // Check this core constant expression is a constant expression. 9769 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 9770 } 9771 9772 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 9773 const ASTContext &Ctx, bool &IsConst) { 9774 // Fast-path evaluations of integer literals, since we sometimes see files 9775 // containing vast quantities of these. 9776 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 9777 Result.Val = APValue(APSInt(L->getValue(), 9778 L->getType()->isUnsignedIntegerType())); 9779 IsConst = true; 9780 return true; 9781 } 9782 9783 // This case should be rare, but we need to check it before we check on 9784 // the type below. 9785 if (Exp->getType().isNull()) { 9786 IsConst = false; 9787 return true; 9788 } 9789 9790 // FIXME: Evaluating values of large array and record types can cause 9791 // performance problems. Only do so in C++11 for now. 9792 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 9793 Exp->getType()->isRecordType()) && 9794 !Ctx.getLangOpts().CPlusPlus11) { 9795 IsConst = false; 9796 return true; 9797 } 9798 return false; 9799 } 9800 9801 9802 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 9803 /// any crazy technique (that has nothing to do with language standards) that 9804 /// we want to. If this function returns true, it returns the folded constant 9805 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 9806 /// will be applied to the result. 9807 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const { 9808 bool IsConst; 9809 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst)) 9810 return IsConst; 9811 9812 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 9813 return ::EvaluateAsRValue(Info, this, Result.Val); 9814 } 9815 9816 bool Expr::EvaluateAsBooleanCondition(bool &Result, 9817 const ASTContext &Ctx) const { 9818 EvalResult Scratch; 9819 return EvaluateAsRValue(Scratch, Ctx) && 9820 HandleConversionToBool(Scratch.Val, Result); 9821 } 9822 9823 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 9824 Expr::SideEffectsKind SEK) { 9825 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 9826 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 9827 } 9828 9829 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx, 9830 SideEffectsKind AllowSideEffects) const { 9831 if (!getType()->isIntegralOrEnumerationType()) 9832 return false; 9833 9834 EvalResult ExprResult; 9835 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() || 9836 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 9837 return false; 9838 9839 Result = ExprResult.Val.getInt(); 9840 return true; 9841 } 9842 9843 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 9844 SideEffectsKind AllowSideEffects) const { 9845 if (!getType()->isRealFloatingType()) 9846 return false; 9847 9848 EvalResult ExprResult; 9849 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() || 9850 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 9851 return false; 9852 9853 Result = ExprResult.Val.getFloat(); 9854 return true; 9855 } 9856 9857 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const { 9858 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 9859 9860 LValue LV; 9861 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects || 9862 !CheckLValueConstantExpression(Info, getExprLoc(), 9863 Ctx.getLValueReferenceType(getType()), LV)) 9864 return false; 9865 9866 LV.moveInto(Result.Val); 9867 return true; 9868 } 9869 9870 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 9871 const VarDecl *VD, 9872 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 9873 // FIXME: Evaluating initializers for large array and record types can cause 9874 // performance problems. Only do so in C++11 for now. 9875 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 9876 !Ctx.getLangOpts().CPlusPlus11) 9877 return false; 9878 9879 Expr::EvalStatus EStatus; 9880 EStatus.Diag = &Notes; 9881 9882 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr() 9883 ? EvalInfo::EM_ConstantExpression 9884 : EvalInfo::EM_ConstantFold); 9885 InitInfo.setEvaluatingDecl(VD, Value); 9886 9887 LValue LVal; 9888 LVal.set(VD); 9889 9890 // C++11 [basic.start.init]p2: 9891 // Variables with static storage duration or thread storage duration shall be 9892 // zero-initialized before any other initialization takes place. 9893 // This behavior is not present in C. 9894 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && 9895 !VD->getType()->isReferenceType()) { 9896 ImplicitValueInitExpr VIE(VD->getType()); 9897 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, 9898 /*AllowNonLiteralTypes=*/true)) 9899 return false; 9900 } 9901 9902 if (!EvaluateInPlace(Value, InitInfo, LVal, this, 9903 /*AllowNonLiteralTypes=*/true) || 9904 EStatus.HasSideEffects) 9905 return false; 9906 9907 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(), 9908 Value); 9909 } 9910 9911 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 9912 /// constant folded, but discard the result. 9913 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 9914 EvalResult Result; 9915 return EvaluateAsRValue(Result, Ctx) && 9916 !hasUnacceptableSideEffect(Result, SEK); 9917 } 9918 9919 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 9920 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 9921 EvalResult EvalResult; 9922 EvalResult.Diag = Diag; 9923 bool Result = EvaluateAsRValue(EvalResult, Ctx); 9924 (void)Result; 9925 assert(Result && "Could not evaluate expression"); 9926 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer"); 9927 9928 return EvalResult.Val.getInt(); 9929 } 9930 9931 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 9932 bool IsConst; 9933 EvalResult EvalResult; 9934 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) { 9935 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow); 9936 (void)::EvaluateAsRValue(Info, this, EvalResult.Val); 9937 } 9938 } 9939 9940 bool Expr::EvalResult::isGlobalLValue() const { 9941 assert(Val.isLValue()); 9942 return IsGlobalLValue(Val.getLValueBase()); 9943 } 9944 9945 9946 /// isIntegerConstantExpr - this recursive routine will test if an expression is 9947 /// an integer constant expression. 9948 9949 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 9950 /// comma, etc 9951 9952 // CheckICE - This function does the fundamental ICE checking: the returned 9953 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 9954 // and a (possibly null) SourceLocation indicating the location of the problem. 9955 // 9956 // Note that to reduce code duplication, this helper does no evaluation 9957 // itself; the caller checks whether the expression is evaluatable, and 9958 // in the rare cases where CheckICE actually cares about the evaluated 9959 // value, it calls into Evaluate. 9960 9961 namespace { 9962 9963 enum ICEKind { 9964 /// This expression is an ICE. 9965 IK_ICE, 9966 /// This expression is not an ICE, but if it isn't evaluated, it's 9967 /// a legal subexpression for an ICE. This return value is used to handle 9968 /// the comma operator in C99 mode, and non-constant subexpressions. 9969 IK_ICEIfUnevaluated, 9970 /// This expression is not an ICE, and is not a legal subexpression for one. 9971 IK_NotICE 9972 }; 9973 9974 struct ICEDiag { 9975 ICEKind Kind; 9976 SourceLocation Loc; 9977 9978 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 9979 }; 9980 9981 } 9982 9983 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 9984 9985 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 9986 9987 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 9988 Expr::EvalResult EVResult; 9989 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects || 9990 !EVResult.Val.isInt()) 9991 return ICEDiag(IK_NotICE, E->getLocStart()); 9992 9993 return NoDiag(); 9994 } 9995 9996 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 9997 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 9998 if (!E->getType()->isIntegralOrEnumerationType()) 9999 return ICEDiag(IK_NotICE, E->getLocStart()); 10000 10001 switch (E->getStmtClass()) { 10002 #define ABSTRACT_STMT(Node) 10003 #define STMT(Node, Base) case Expr::Node##Class: 10004 #define EXPR(Node, Base) 10005 #include "clang/AST/StmtNodes.inc" 10006 case Expr::PredefinedExprClass: 10007 case Expr::FloatingLiteralClass: 10008 case Expr::ImaginaryLiteralClass: 10009 case Expr::StringLiteralClass: 10010 case Expr::ArraySubscriptExprClass: 10011 case Expr::OMPArraySectionExprClass: 10012 case Expr::MemberExprClass: 10013 case Expr::CompoundAssignOperatorClass: 10014 case Expr::CompoundLiteralExprClass: 10015 case Expr::ExtVectorElementExprClass: 10016 case Expr::DesignatedInitExprClass: 10017 case Expr::ArrayInitLoopExprClass: 10018 case Expr::ArrayInitIndexExprClass: 10019 case Expr::NoInitExprClass: 10020 case Expr::DesignatedInitUpdateExprClass: 10021 case Expr::ImplicitValueInitExprClass: 10022 case Expr::ParenListExprClass: 10023 case Expr::VAArgExprClass: 10024 case Expr::AddrLabelExprClass: 10025 case Expr::StmtExprClass: 10026 case Expr::CXXMemberCallExprClass: 10027 case Expr::CUDAKernelCallExprClass: 10028 case Expr::CXXDynamicCastExprClass: 10029 case Expr::CXXTypeidExprClass: 10030 case Expr::CXXUuidofExprClass: 10031 case Expr::MSPropertyRefExprClass: 10032 case Expr::MSPropertySubscriptExprClass: 10033 case Expr::CXXNullPtrLiteralExprClass: 10034 case Expr::UserDefinedLiteralClass: 10035 case Expr::CXXThisExprClass: 10036 case Expr::CXXThrowExprClass: 10037 case Expr::CXXNewExprClass: 10038 case Expr::CXXDeleteExprClass: 10039 case Expr::CXXPseudoDestructorExprClass: 10040 case Expr::UnresolvedLookupExprClass: 10041 case Expr::TypoExprClass: 10042 case Expr::DependentScopeDeclRefExprClass: 10043 case Expr::CXXConstructExprClass: 10044 case Expr::CXXInheritedCtorInitExprClass: 10045 case Expr::CXXStdInitializerListExprClass: 10046 case Expr::CXXBindTemporaryExprClass: 10047 case Expr::ExprWithCleanupsClass: 10048 case Expr::CXXTemporaryObjectExprClass: 10049 case Expr::CXXUnresolvedConstructExprClass: 10050 case Expr::CXXDependentScopeMemberExprClass: 10051 case Expr::UnresolvedMemberExprClass: 10052 case Expr::ObjCStringLiteralClass: 10053 case Expr::ObjCBoxedExprClass: 10054 case Expr::ObjCArrayLiteralClass: 10055 case Expr::ObjCDictionaryLiteralClass: 10056 case Expr::ObjCEncodeExprClass: 10057 case Expr::ObjCMessageExprClass: 10058 case Expr::ObjCSelectorExprClass: 10059 case Expr::ObjCProtocolExprClass: 10060 case Expr::ObjCIvarRefExprClass: 10061 case Expr::ObjCPropertyRefExprClass: 10062 case Expr::ObjCSubscriptRefExprClass: 10063 case Expr::ObjCIsaExprClass: 10064 case Expr::ObjCAvailabilityCheckExprClass: 10065 case Expr::ShuffleVectorExprClass: 10066 case Expr::ConvertVectorExprClass: 10067 case Expr::BlockExprClass: 10068 case Expr::NoStmtClass: 10069 case Expr::OpaqueValueExprClass: 10070 case Expr::PackExpansionExprClass: 10071 case Expr::SubstNonTypeTemplateParmPackExprClass: 10072 case Expr::FunctionParmPackExprClass: 10073 case Expr::AsTypeExprClass: 10074 case Expr::ObjCIndirectCopyRestoreExprClass: 10075 case Expr::MaterializeTemporaryExprClass: 10076 case Expr::PseudoObjectExprClass: 10077 case Expr::AtomicExprClass: 10078 case Expr::LambdaExprClass: 10079 case Expr::CXXFoldExprClass: 10080 case Expr::CoawaitExprClass: 10081 case Expr::CoyieldExprClass: 10082 return ICEDiag(IK_NotICE, E->getLocStart()); 10083 10084 case Expr::InitListExprClass: { 10085 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 10086 // form "T x = { a };" is equivalent to "T x = a;". 10087 // Unless we're initializing a reference, T is a scalar as it is known to be 10088 // of integral or enumeration type. 10089 if (E->isRValue()) 10090 if (cast<InitListExpr>(E)->getNumInits() == 1) 10091 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 10092 return ICEDiag(IK_NotICE, E->getLocStart()); 10093 } 10094 10095 case Expr::SizeOfPackExprClass: 10096 case Expr::GNUNullExprClass: 10097 // GCC considers the GNU __null value to be an integral constant expression. 10098 return NoDiag(); 10099 10100 case Expr::SubstNonTypeTemplateParmExprClass: 10101 return 10102 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 10103 10104 case Expr::ParenExprClass: 10105 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 10106 case Expr::GenericSelectionExprClass: 10107 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 10108 case Expr::IntegerLiteralClass: 10109 case Expr::CharacterLiteralClass: 10110 case Expr::ObjCBoolLiteralExprClass: 10111 case Expr::CXXBoolLiteralExprClass: 10112 case Expr::CXXScalarValueInitExprClass: 10113 case Expr::TypeTraitExprClass: 10114 case Expr::ArrayTypeTraitExprClass: 10115 case Expr::ExpressionTraitExprClass: 10116 case Expr::CXXNoexceptExprClass: 10117 return NoDiag(); 10118 case Expr::CallExprClass: 10119 case Expr::CXXOperatorCallExprClass: { 10120 // C99 6.6/3 allows function calls within unevaluated subexpressions of 10121 // constant expressions, but they can never be ICEs because an ICE cannot 10122 // contain an operand of (pointer to) function type. 10123 const CallExpr *CE = cast<CallExpr>(E); 10124 if (CE->getBuiltinCallee()) 10125 return CheckEvalInICE(E, Ctx); 10126 return ICEDiag(IK_NotICE, E->getLocStart()); 10127 } 10128 case Expr::DeclRefExprClass: { 10129 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 10130 return NoDiag(); 10131 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl()); 10132 if (Ctx.getLangOpts().CPlusPlus && 10133 D && IsConstNonVolatile(D->getType())) { 10134 // Parameter variables are never constants. Without this check, 10135 // getAnyInitializer() can find a default argument, which leads 10136 // to chaos. 10137 if (isa<ParmVarDecl>(D)) 10138 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 10139 10140 // C++ 7.1.5.1p2 10141 // A variable of non-volatile const-qualified integral or enumeration 10142 // type initialized by an ICE can be used in ICEs. 10143 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 10144 if (!Dcl->getType()->isIntegralOrEnumerationType()) 10145 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 10146 10147 const VarDecl *VD; 10148 // Look for a declaration of this variable that has an initializer, and 10149 // check whether it is an ICE. 10150 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 10151 return NoDiag(); 10152 else 10153 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 10154 } 10155 } 10156 return ICEDiag(IK_NotICE, E->getLocStart()); 10157 } 10158 case Expr::UnaryOperatorClass: { 10159 const UnaryOperator *Exp = cast<UnaryOperator>(E); 10160 switch (Exp->getOpcode()) { 10161 case UO_PostInc: 10162 case UO_PostDec: 10163 case UO_PreInc: 10164 case UO_PreDec: 10165 case UO_AddrOf: 10166 case UO_Deref: 10167 case UO_Coawait: 10168 // C99 6.6/3 allows increment and decrement within unevaluated 10169 // subexpressions of constant expressions, but they can never be ICEs 10170 // because an ICE cannot contain an lvalue operand. 10171 return ICEDiag(IK_NotICE, E->getLocStart()); 10172 case UO_Extension: 10173 case UO_LNot: 10174 case UO_Plus: 10175 case UO_Minus: 10176 case UO_Not: 10177 case UO_Real: 10178 case UO_Imag: 10179 return CheckICE(Exp->getSubExpr(), Ctx); 10180 } 10181 10182 // OffsetOf falls through here. 10183 } 10184 case Expr::OffsetOfExprClass: { 10185 // Note that per C99, offsetof must be an ICE. And AFAIK, using 10186 // EvaluateAsRValue matches the proposed gcc behavior for cases like 10187 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 10188 // compliance: we should warn earlier for offsetof expressions with 10189 // array subscripts that aren't ICEs, and if the array subscripts 10190 // are ICEs, the value of the offsetof must be an integer constant. 10191 return CheckEvalInICE(E, Ctx); 10192 } 10193 case Expr::UnaryExprOrTypeTraitExprClass: { 10194 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 10195 if ((Exp->getKind() == UETT_SizeOf) && 10196 Exp->getTypeOfArgument()->isVariableArrayType()) 10197 return ICEDiag(IK_NotICE, E->getLocStart()); 10198 return NoDiag(); 10199 } 10200 case Expr::BinaryOperatorClass: { 10201 const BinaryOperator *Exp = cast<BinaryOperator>(E); 10202 switch (Exp->getOpcode()) { 10203 case BO_PtrMemD: 10204 case BO_PtrMemI: 10205 case BO_Assign: 10206 case BO_MulAssign: 10207 case BO_DivAssign: 10208 case BO_RemAssign: 10209 case BO_AddAssign: 10210 case BO_SubAssign: 10211 case BO_ShlAssign: 10212 case BO_ShrAssign: 10213 case BO_AndAssign: 10214 case BO_XorAssign: 10215 case BO_OrAssign: 10216 // C99 6.6/3 allows assignments within unevaluated subexpressions of 10217 // constant expressions, but they can never be ICEs because an ICE cannot 10218 // contain an lvalue operand. 10219 return ICEDiag(IK_NotICE, E->getLocStart()); 10220 10221 case BO_Mul: 10222 case BO_Div: 10223 case BO_Rem: 10224 case BO_Add: 10225 case BO_Sub: 10226 case BO_Shl: 10227 case BO_Shr: 10228 case BO_LT: 10229 case BO_GT: 10230 case BO_LE: 10231 case BO_GE: 10232 case BO_EQ: 10233 case BO_NE: 10234 case BO_And: 10235 case BO_Xor: 10236 case BO_Or: 10237 case BO_Comma: { 10238 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 10239 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 10240 if (Exp->getOpcode() == BO_Div || 10241 Exp->getOpcode() == BO_Rem) { 10242 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 10243 // we don't evaluate one. 10244 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 10245 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 10246 if (REval == 0) 10247 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart()); 10248 if (REval.isSigned() && REval.isAllOnesValue()) { 10249 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 10250 if (LEval.isMinSignedValue()) 10251 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart()); 10252 } 10253 } 10254 } 10255 if (Exp->getOpcode() == BO_Comma) { 10256 if (Ctx.getLangOpts().C99) { 10257 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 10258 // if it isn't evaluated. 10259 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 10260 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart()); 10261 } else { 10262 // In both C89 and C++, commas in ICEs are illegal. 10263 return ICEDiag(IK_NotICE, E->getLocStart()); 10264 } 10265 } 10266 return Worst(LHSResult, RHSResult); 10267 } 10268 case BO_LAnd: 10269 case BO_LOr: { 10270 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 10271 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 10272 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 10273 // Rare case where the RHS has a comma "side-effect"; we need 10274 // to actually check the condition to see whether the side 10275 // with the comma is evaluated. 10276 if ((Exp->getOpcode() == BO_LAnd) != 10277 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 10278 return RHSResult; 10279 return NoDiag(); 10280 } 10281 10282 return Worst(LHSResult, RHSResult); 10283 } 10284 } 10285 } 10286 case Expr::ImplicitCastExprClass: 10287 case Expr::CStyleCastExprClass: 10288 case Expr::CXXFunctionalCastExprClass: 10289 case Expr::CXXStaticCastExprClass: 10290 case Expr::CXXReinterpretCastExprClass: 10291 case Expr::CXXConstCastExprClass: 10292 case Expr::ObjCBridgedCastExprClass: { 10293 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 10294 if (isa<ExplicitCastExpr>(E)) { 10295 if (const FloatingLiteral *FL 10296 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 10297 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 10298 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 10299 APSInt IgnoredVal(DestWidth, !DestSigned); 10300 bool Ignored; 10301 // If the value does not fit in the destination type, the behavior is 10302 // undefined, so we are not required to treat it as a constant 10303 // expression. 10304 if (FL->getValue().convertToInteger(IgnoredVal, 10305 llvm::APFloat::rmTowardZero, 10306 &Ignored) & APFloat::opInvalidOp) 10307 return ICEDiag(IK_NotICE, E->getLocStart()); 10308 return NoDiag(); 10309 } 10310 } 10311 switch (cast<CastExpr>(E)->getCastKind()) { 10312 case CK_LValueToRValue: 10313 case CK_AtomicToNonAtomic: 10314 case CK_NonAtomicToAtomic: 10315 case CK_NoOp: 10316 case CK_IntegralToBoolean: 10317 case CK_IntegralCast: 10318 return CheckICE(SubExpr, Ctx); 10319 default: 10320 return ICEDiag(IK_NotICE, E->getLocStart()); 10321 } 10322 } 10323 case Expr::BinaryConditionalOperatorClass: { 10324 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 10325 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 10326 if (CommonResult.Kind == IK_NotICE) return CommonResult; 10327 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 10328 if (FalseResult.Kind == IK_NotICE) return FalseResult; 10329 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 10330 if (FalseResult.Kind == IK_ICEIfUnevaluated && 10331 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 10332 return FalseResult; 10333 } 10334 case Expr::ConditionalOperatorClass: { 10335 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 10336 // If the condition (ignoring parens) is a __builtin_constant_p call, 10337 // then only the true side is actually considered in an integer constant 10338 // expression, and it is fully evaluated. This is an important GNU 10339 // extension. See GCC PR38377 for discussion. 10340 if (const CallExpr *CallCE 10341 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 10342 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 10343 return CheckEvalInICE(E, Ctx); 10344 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 10345 if (CondResult.Kind == IK_NotICE) 10346 return CondResult; 10347 10348 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 10349 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 10350 10351 if (TrueResult.Kind == IK_NotICE) 10352 return TrueResult; 10353 if (FalseResult.Kind == IK_NotICE) 10354 return FalseResult; 10355 if (CondResult.Kind == IK_ICEIfUnevaluated) 10356 return CondResult; 10357 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 10358 return NoDiag(); 10359 // Rare case where the diagnostics depend on which side is evaluated 10360 // Note that if we get here, CondResult is 0, and at least one of 10361 // TrueResult and FalseResult is non-zero. 10362 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 10363 return FalseResult; 10364 return TrueResult; 10365 } 10366 case Expr::CXXDefaultArgExprClass: 10367 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 10368 case Expr::CXXDefaultInitExprClass: 10369 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 10370 case Expr::ChooseExprClass: { 10371 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 10372 } 10373 } 10374 10375 llvm_unreachable("Invalid StmtClass!"); 10376 } 10377 10378 /// Evaluate an expression as a C++11 integral constant expression. 10379 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 10380 const Expr *E, 10381 llvm::APSInt *Value, 10382 SourceLocation *Loc) { 10383 if (!E->getType()->isIntegralOrEnumerationType()) { 10384 if (Loc) *Loc = E->getExprLoc(); 10385 return false; 10386 } 10387 10388 APValue Result; 10389 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 10390 return false; 10391 10392 if (!Result.isInt()) { 10393 if (Loc) *Loc = E->getExprLoc(); 10394 return false; 10395 } 10396 10397 if (Value) *Value = Result.getInt(); 10398 return true; 10399 } 10400 10401 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 10402 SourceLocation *Loc) const { 10403 if (Ctx.getLangOpts().CPlusPlus11) 10404 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 10405 10406 ICEDiag D = CheckICE(this, Ctx); 10407 if (D.Kind != IK_ICE) { 10408 if (Loc) *Loc = D.Loc; 10409 return false; 10410 } 10411 return true; 10412 } 10413 10414 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, 10415 SourceLocation *Loc, bool isEvaluated) const { 10416 if (Ctx.getLangOpts().CPlusPlus11) 10417 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 10418 10419 if (!isIntegerConstantExpr(Ctx, Loc)) 10420 return false; 10421 // The only possible side-effects here are due to UB discovered in the 10422 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 10423 // required to treat the expression as an ICE, so we produce the folded 10424 // value. 10425 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects)) 10426 llvm_unreachable("ICE cannot be evaluated!"); 10427 return true; 10428 } 10429 10430 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 10431 return CheckICE(this, Ctx).Kind == IK_ICE; 10432 } 10433 10434 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 10435 SourceLocation *Loc) const { 10436 // We support this checking in C++98 mode in order to diagnose compatibility 10437 // issues. 10438 assert(Ctx.getLangOpts().CPlusPlus); 10439 10440 // Build evaluation settings. 10441 Expr::EvalStatus Status; 10442 SmallVector<PartialDiagnosticAt, 8> Diags; 10443 Status.Diag = &Diags; 10444 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 10445 10446 APValue Scratch; 10447 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch); 10448 10449 if (!Diags.empty()) { 10450 IsConstExpr = false; 10451 if (Loc) *Loc = Diags[0].first; 10452 } else if (!IsConstExpr) { 10453 // FIXME: This shouldn't happen. 10454 if (Loc) *Loc = getExprLoc(); 10455 } 10456 10457 return IsConstExpr; 10458 } 10459 10460 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 10461 const FunctionDecl *Callee, 10462 ArrayRef<const Expr*> Args, 10463 const Expr *This) const { 10464 Expr::EvalStatus Status; 10465 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 10466 10467 LValue ThisVal; 10468 const LValue *ThisPtr = nullptr; 10469 if (This) { 10470 #ifndef NDEBUG 10471 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 10472 assert(MD && "Don't provide `this` for non-methods."); 10473 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 10474 #endif 10475 if (EvaluateObjectArgument(Info, This, ThisVal)) 10476 ThisPtr = &ThisVal; 10477 if (Info.EvalStatus.HasSideEffects) 10478 return false; 10479 } 10480 10481 ArgVector ArgValues(Args.size()); 10482 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 10483 I != E; ++I) { 10484 if ((*I)->isValueDependent() || 10485 !Evaluate(ArgValues[I - Args.begin()], Info, *I)) 10486 // If evaluation fails, throw away the argument entirely. 10487 ArgValues[I - Args.begin()] = APValue(); 10488 if (Info.EvalStatus.HasSideEffects) 10489 return false; 10490 } 10491 10492 // Build fake call to Callee. 10493 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 10494 ArgValues.data()); 10495 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects; 10496 } 10497 10498 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 10499 SmallVectorImpl< 10500 PartialDiagnosticAt> &Diags) { 10501 // FIXME: It would be useful to check constexpr function templates, but at the 10502 // moment the constant expression evaluator cannot cope with the non-rigorous 10503 // ASTs which we build for dependent expressions. 10504 if (FD->isDependentContext()) 10505 return true; 10506 10507 Expr::EvalStatus Status; 10508 Status.Diag = &Diags; 10509 10510 EvalInfo Info(FD->getASTContext(), Status, 10511 EvalInfo::EM_PotentialConstantExpression); 10512 10513 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 10514 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 10515 10516 // Fabricate an arbitrary expression on the stack and pretend that it 10517 // is a temporary being used as the 'this' pointer. 10518 LValue This; 10519 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 10520 This.set(&VIE, Info.CurrentCall->Index); 10521 10522 ArrayRef<const Expr*> Args; 10523 10524 APValue Scratch; 10525 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 10526 // Evaluate the call as a constant initializer, to allow the construction 10527 // of objects of non-literal types. 10528 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 10529 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 10530 } else { 10531 SourceLocation Loc = FD->getLocation(); 10532 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 10533 Args, FD->getBody(), Info, Scratch, nullptr); 10534 } 10535 10536 return Diags.empty(); 10537 } 10538 10539 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 10540 const FunctionDecl *FD, 10541 SmallVectorImpl< 10542 PartialDiagnosticAt> &Diags) { 10543 Expr::EvalStatus Status; 10544 Status.Diag = &Diags; 10545 10546 EvalInfo Info(FD->getASTContext(), Status, 10547 EvalInfo::EM_PotentialConstantExpressionUnevaluated); 10548 10549 // Fabricate a call stack frame to give the arguments a plausible cover story. 10550 ArrayRef<const Expr*> Args; 10551 ArgVector ArgValues(0); 10552 bool Success = EvaluateArgs(Args, ArgValues, Info); 10553 (void)Success; 10554 assert(Success && 10555 "Failed to set up arguments for potential constant evaluation"); 10556 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 10557 10558 APValue ResultScratch; 10559 Evaluate(ResultScratch, Info, E); 10560 return Diags.empty(); 10561 } 10562 10563 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 10564 unsigned Type) const { 10565 if (!getType()->isPointerType()) 10566 return false; 10567 10568 Expr::EvalStatus Status; 10569 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 10570 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 10571 } 10572