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