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