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