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