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