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