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