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