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