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