1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Expr constant evaluator. 10 // 11 // Constant expression evaluation produces four main results: 12 // 13 // * A success/failure flag indicating whether constant folding was successful. 14 // This is the 'bool' return value used by most of the code in this file. A 15 // 'false' return value indicates that constant folding has failed, and any 16 // appropriate diagnostic has already been produced. 17 // 18 // * An evaluated result, valid only if constant folding has not failed. 19 // 20 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 21 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 22 // where it is possible to determine the evaluated result regardless. 23 // 24 // * A set of notes indicating why the evaluation was not a constant expression 25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 26 // too, why the expression could not be folded. 27 // 28 // If we are checking for a potential constant expression, failure to constant 29 // fold a potential constant sub-expression will be indicated by a 'false' 30 // return value (the expression could not be folded) and no diagnostic (the 31 // expression is not necessarily non-constant). 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include <cstring> 36 #include <functional> 37 #include "Interp/Context.h" 38 #include "Interp/Frame.h" 39 #include "Interp/State.h" 40 #include "clang/AST/APValue.h" 41 #include "clang/AST/ASTContext.h" 42 #include "clang/AST/ASTDiagnostic.h" 43 #include "clang/AST/ASTLambda.h" 44 #include "clang/AST/CXXInheritance.h" 45 #include "clang/AST/CharUnits.h" 46 #include "clang/AST/CurrentSourceLocExprScope.h" 47 #include "clang/AST/Expr.h" 48 #include "clang/AST/OSLog.h" 49 #include "clang/AST/OptionalDiagnostic.h" 50 #include "clang/AST/RecordLayout.h" 51 #include "clang/AST/StmtVisitor.h" 52 #include "clang/AST/TypeLoc.h" 53 #include "clang/Basic/Builtins.h" 54 #include "clang/Basic/FixedPoint.h" 55 #include "clang/Basic/TargetInfo.h" 56 #include "llvm/ADT/Optional.h" 57 #include "llvm/ADT/SmallBitVector.h" 58 #include "llvm/Support/SaveAndRestore.h" 59 #include "llvm/Support/raw_ostream.h" 60 61 #define DEBUG_TYPE "exprconstant" 62 63 using namespace clang; 64 using llvm::APInt; 65 using llvm::APSInt; 66 using llvm::APFloat; 67 using llvm::Optional; 68 69 static bool IsGlobalLValue(APValue::LValueBase B); 70 71 namespace { 72 struct LValue; 73 class CallStackFrame; 74 class EvalInfo; 75 76 using SourceLocExprScopeGuard = 77 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 78 79 static QualType getType(APValue::LValueBase B) { 80 if (!B) return QualType(); 81 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 82 // FIXME: It's unclear where we're supposed to take the type from, and 83 // this actually matters for arrays of unknown bound. Eg: 84 // 85 // extern int arr[]; void f() { extern int arr[3]; }; 86 // constexpr int *p = &arr[1]; // valid? 87 // 88 // For now, we take the array bound from the most recent declaration. 89 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 90 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 91 QualType T = Redecl->getType(); 92 if (!T->isIncompleteArrayType()) 93 return T; 94 } 95 return D->getType(); 96 } 97 98 if (B.is<TypeInfoLValue>()) 99 return B.getTypeInfoType(); 100 101 const Expr *Base = B.get<const Expr*>(); 102 103 // For a materialized temporary, the type of the temporary we materialized 104 // may not be the type of the expression. 105 if (const MaterializeTemporaryExpr *MTE = 106 dyn_cast<MaterializeTemporaryExpr>(Base)) { 107 SmallVector<const Expr *, 2> CommaLHSs; 108 SmallVector<SubobjectAdjustment, 2> Adjustments; 109 const Expr *Temp = MTE->GetTemporaryExpr(); 110 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 111 Adjustments); 112 // Keep any cv-qualifiers from the reference if we generated a temporary 113 // for it directly. Otherwise use the type after adjustment. 114 if (!Adjustments.empty()) 115 return Inner->getType(); 116 } 117 118 return Base->getType(); 119 } 120 121 /// Get an LValue path entry, which is known to not be an array index, as a 122 /// field declaration. 123 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 124 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 125 } 126 /// Get an LValue path entry, which is known to not be an array index, as a 127 /// base class declaration. 128 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 129 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 130 } 131 /// Determine whether this LValue path entry for a base class names a virtual 132 /// base class. 133 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 134 return E.getAsBaseOrMember().getInt(); 135 } 136 137 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 138 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 139 const FunctionDecl *Callee = CE->getDirectCallee(); 140 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 141 } 142 143 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 144 /// This will look through a single cast. 145 /// 146 /// Returns null if we couldn't unwrap a function with alloc_size. 147 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 148 if (!E->getType()->isPointerType()) 149 return nullptr; 150 151 E = E->IgnoreParens(); 152 // If we're doing a variable assignment from e.g. malloc(N), there will 153 // probably be a cast of some kind. In exotic cases, we might also see a 154 // top-level ExprWithCleanups. Ignore them either way. 155 if (const auto *FE = dyn_cast<FullExpr>(E)) 156 E = FE->getSubExpr()->IgnoreParens(); 157 158 if (const auto *Cast = dyn_cast<CastExpr>(E)) 159 E = Cast->getSubExpr()->IgnoreParens(); 160 161 if (const auto *CE = dyn_cast<CallExpr>(E)) 162 return getAllocSizeAttr(CE) ? CE : nullptr; 163 return nullptr; 164 } 165 166 /// Determines whether or not the given Base contains a call to a function 167 /// with the alloc_size attribute. 168 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 169 const auto *E = Base.dyn_cast<const Expr *>(); 170 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 171 } 172 173 /// The bound to claim that an array of unknown bound has. 174 /// The value in MostDerivedArraySize is undefined in this case. So, set it 175 /// to an arbitrary value that's likely to loudly break things if it's used. 176 static const uint64_t AssumedSizeForUnsizedArray = 177 std::numeric_limits<uint64_t>::max() / 2; 178 179 /// Determines if an LValue with the given LValueBase will have an unsized 180 /// array in its designator. 181 /// Find the path length and type of the most-derived subobject in the given 182 /// path, and find the size of the containing array, if any. 183 static unsigned 184 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 185 ArrayRef<APValue::LValuePathEntry> Path, 186 uint64_t &ArraySize, QualType &Type, bool &IsArray, 187 bool &FirstEntryIsUnsizedArray) { 188 // This only accepts LValueBases from APValues, and APValues don't support 189 // arrays that lack size info. 190 assert(!isBaseAnAllocSizeCall(Base) && 191 "Unsized arrays shouldn't appear here"); 192 unsigned MostDerivedLength = 0; 193 Type = getType(Base); 194 195 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 196 if (Type->isArrayType()) { 197 const ArrayType *AT = Ctx.getAsArrayType(Type); 198 Type = AT->getElementType(); 199 MostDerivedLength = I + 1; 200 IsArray = true; 201 202 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 203 ArraySize = CAT->getSize().getZExtValue(); 204 } else { 205 assert(I == 0 && "unexpected unsized array designator"); 206 FirstEntryIsUnsizedArray = true; 207 ArraySize = AssumedSizeForUnsizedArray; 208 } 209 } else if (Type->isAnyComplexType()) { 210 const ComplexType *CT = Type->castAs<ComplexType>(); 211 Type = CT->getElementType(); 212 ArraySize = 2; 213 MostDerivedLength = I + 1; 214 IsArray = true; 215 } else if (const FieldDecl *FD = getAsField(Path[I])) { 216 Type = FD->getType(); 217 ArraySize = 0; 218 MostDerivedLength = I + 1; 219 IsArray = false; 220 } else { 221 // Path[I] describes a base class. 222 ArraySize = 0; 223 IsArray = false; 224 } 225 } 226 return MostDerivedLength; 227 } 228 229 /// A path from a glvalue to a subobject of that glvalue. 230 struct SubobjectDesignator { 231 /// True if the subobject was named in a manner not supported by C++11. Such 232 /// lvalues can still be folded, but they are not core constant expressions 233 /// and we cannot perform lvalue-to-rvalue conversions on them. 234 unsigned Invalid : 1; 235 236 /// Is this a pointer one past the end of an object? 237 unsigned IsOnePastTheEnd : 1; 238 239 /// Indicator of whether the first entry is an unsized array. 240 unsigned FirstEntryIsAnUnsizedArray : 1; 241 242 /// Indicator of whether the most-derived object is an array element. 243 unsigned MostDerivedIsArrayElement : 1; 244 245 /// The length of the path to the most-derived object of which this is a 246 /// subobject. 247 unsigned MostDerivedPathLength : 28; 248 249 /// The size of the array of which the most-derived object is an element. 250 /// This will always be 0 if the most-derived object is not an array 251 /// element. 0 is not an indicator of whether or not the most-derived object 252 /// is an array, however, because 0-length arrays are allowed. 253 /// 254 /// If the current array is an unsized array, the value of this is 255 /// undefined. 256 uint64_t MostDerivedArraySize; 257 258 /// The type of the most derived object referred to by this address. 259 QualType MostDerivedType; 260 261 typedef APValue::LValuePathEntry PathEntry; 262 263 /// The entries on the path from the glvalue to the designated subobject. 264 SmallVector<PathEntry, 8> Entries; 265 266 SubobjectDesignator() : Invalid(true) {} 267 268 explicit SubobjectDesignator(QualType T) 269 : Invalid(false), IsOnePastTheEnd(false), 270 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 271 MostDerivedPathLength(0), MostDerivedArraySize(0), 272 MostDerivedType(T) {} 273 274 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 275 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 276 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 277 MostDerivedPathLength(0), MostDerivedArraySize(0) { 278 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 279 if (!Invalid) { 280 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 281 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 282 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 283 if (V.getLValueBase()) { 284 bool IsArray = false; 285 bool FirstIsUnsizedArray = false; 286 MostDerivedPathLength = findMostDerivedSubobject( 287 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 288 MostDerivedType, IsArray, FirstIsUnsizedArray); 289 MostDerivedIsArrayElement = IsArray; 290 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 291 } 292 } 293 } 294 295 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 296 unsigned NewLength) { 297 if (Invalid) 298 return; 299 300 assert(Base && "cannot truncate path for null pointer"); 301 assert(NewLength <= Entries.size() && "not a truncation"); 302 303 if (NewLength == Entries.size()) 304 return; 305 Entries.resize(NewLength); 306 307 bool IsArray = false; 308 bool FirstIsUnsizedArray = false; 309 MostDerivedPathLength = findMostDerivedSubobject( 310 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 311 FirstIsUnsizedArray); 312 MostDerivedIsArrayElement = IsArray; 313 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 314 } 315 316 void setInvalid() { 317 Invalid = true; 318 Entries.clear(); 319 } 320 321 /// Determine whether the most derived subobject is an array without a 322 /// known bound. 323 bool isMostDerivedAnUnsizedArray() const { 324 assert(!Invalid && "Calling this makes no sense on invalid designators"); 325 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 326 } 327 328 /// Determine what the most derived array's size is. Results in an assertion 329 /// failure if the most derived array lacks a size. 330 uint64_t getMostDerivedArraySize() const { 331 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 332 return MostDerivedArraySize; 333 } 334 335 /// Determine whether this is a one-past-the-end pointer. 336 bool isOnePastTheEnd() const { 337 assert(!Invalid); 338 if (IsOnePastTheEnd) 339 return true; 340 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 341 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 342 MostDerivedArraySize) 343 return true; 344 return false; 345 } 346 347 /// Get the range of valid index adjustments in the form 348 /// {maximum value that can be subtracted from this pointer, 349 /// maximum value that can be added to this pointer} 350 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 351 if (Invalid || isMostDerivedAnUnsizedArray()) 352 return {0, 0}; 353 354 // [expr.add]p4: For the purposes of these operators, a pointer to a 355 // nonarray object behaves the same as a pointer to the first element of 356 // an array of length one with the type of the object as its element type. 357 bool IsArray = MostDerivedPathLength == Entries.size() && 358 MostDerivedIsArrayElement; 359 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 360 : (uint64_t)IsOnePastTheEnd; 361 uint64_t ArraySize = 362 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 363 return {ArrayIndex, ArraySize - ArrayIndex}; 364 } 365 366 /// Check that this refers to a valid subobject. 367 bool isValidSubobject() const { 368 if (Invalid) 369 return false; 370 return !isOnePastTheEnd(); 371 } 372 /// Check that this refers to a valid subobject, and if not, produce a 373 /// relevant diagnostic and set the designator as invalid. 374 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 375 376 /// Get the type of the designated object. 377 QualType getType(ASTContext &Ctx) const { 378 assert(!Invalid && "invalid designator has no subobject type"); 379 return MostDerivedPathLength == Entries.size() 380 ? MostDerivedType 381 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 382 } 383 384 /// Update this designator to refer to the first element within this array. 385 void addArrayUnchecked(const ConstantArrayType *CAT) { 386 Entries.push_back(PathEntry::ArrayIndex(0)); 387 388 // This is a most-derived object. 389 MostDerivedType = CAT->getElementType(); 390 MostDerivedIsArrayElement = true; 391 MostDerivedArraySize = CAT->getSize().getZExtValue(); 392 MostDerivedPathLength = Entries.size(); 393 } 394 /// Update this designator to refer to the first element within the array of 395 /// elements of type T. This is an array of unknown size. 396 void addUnsizedArrayUnchecked(QualType ElemTy) { 397 Entries.push_back(PathEntry::ArrayIndex(0)); 398 399 MostDerivedType = ElemTy; 400 MostDerivedIsArrayElement = true; 401 // The value in MostDerivedArraySize is undefined in this case. So, set it 402 // to an arbitrary value that's likely to loudly break things if it's 403 // used. 404 MostDerivedArraySize = AssumedSizeForUnsizedArray; 405 MostDerivedPathLength = Entries.size(); 406 } 407 /// Update this designator to refer to the given base or member of this 408 /// object. 409 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 410 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 411 412 // If this isn't a base class, it's a new most-derived object. 413 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 414 MostDerivedType = FD->getType(); 415 MostDerivedIsArrayElement = false; 416 MostDerivedArraySize = 0; 417 MostDerivedPathLength = Entries.size(); 418 } 419 } 420 /// Update this designator to refer to the given complex component. 421 void addComplexUnchecked(QualType EltTy, bool Imag) { 422 Entries.push_back(PathEntry::ArrayIndex(Imag)); 423 424 // This is technically a most-derived object, though in practice this 425 // is unlikely to matter. 426 MostDerivedType = EltTy; 427 MostDerivedIsArrayElement = true; 428 MostDerivedArraySize = 2; 429 MostDerivedPathLength = Entries.size(); 430 } 431 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 432 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 433 const APSInt &N); 434 /// Add N to the address of this subobject. 435 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 436 if (Invalid || !N) return; 437 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 438 if (isMostDerivedAnUnsizedArray()) { 439 diagnoseUnsizedArrayPointerArithmetic(Info, E); 440 // Can't verify -- trust that the user is doing the right thing (or if 441 // not, trust that the caller will catch the bad behavior). 442 // FIXME: Should we reject if this overflows, at least? 443 Entries.back() = PathEntry::ArrayIndex( 444 Entries.back().getAsArrayIndex() + TruncatedN); 445 return; 446 } 447 448 // [expr.add]p4: For the purposes of these operators, a pointer to a 449 // nonarray object behaves the same as a pointer to the first element of 450 // an array of length one with the type of the object as its element type. 451 bool IsArray = MostDerivedPathLength == Entries.size() && 452 MostDerivedIsArrayElement; 453 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 454 : (uint64_t)IsOnePastTheEnd; 455 uint64_t ArraySize = 456 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 457 458 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 459 // Calculate the actual index in a wide enough type, so we can include 460 // it in the note. 461 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 462 (llvm::APInt&)N += ArrayIndex; 463 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 464 diagnosePointerArithmetic(Info, E, N); 465 setInvalid(); 466 return; 467 } 468 469 ArrayIndex += TruncatedN; 470 assert(ArrayIndex <= ArraySize && 471 "bounds check succeeded for out-of-bounds index"); 472 473 if (IsArray) 474 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 475 else 476 IsOnePastTheEnd = (ArrayIndex != 0); 477 } 478 }; 479 480 /// A stack frame in the constexpr call stack. 481 class CallStackFrame : public interp::Frame { 482 public: 483 EvalInfo &Info; 484 485 /// Parent - The caller of this stack frame. 486 CallStackFrame *Caller; 487 488 /// Callee - The function which was called. 489 const FunctionDecl *Callee; 490 491 /// This - The binding for the this pointer in this call, if any. 492 const LValue *This; 493 494 /// Arguments - Parameter bindings for this function call, indexed by 495 /// parameters' function scope indices. 496 APValue *Arguments; 497 498 /// Source location information about the default argument or default 499 /// initializer expression we're evaluating, if any. 500 CurrentSourceLocExprScope CurSourceLocExprScope; 501 502 // Note that we intentionally use std::map here so that references to 503 // values are stable. 504 typedef std::pair<const void *, unsigned> MapKeyTy; 505 typedef std::map<MapKeyTy, APValue> MapTy; 506 /// Temporaries - Temporary lvalues materialized within this stack frame. 507 MapTy Temporaries; 508 509 /// CallLoc - The location of the call expression for this call. 510 SourceLocation CallLoc; 511 512 /// Index - The call index of this call. 513 unsigned Index; 514 515 /// The stack of integers for tracking version numbers for temporaries. 516 SmallVector<unsigned, 2> TempVersionStack = {1}; 517 unsigned CurTempVersion = TempVersionStack.back(); 518 519 unsigned getTempVersion() const { return TempVersionStack.back(); } 520 521 void pushTempVersion() { 522 TempVersionStack.push_back(++CurTempVersion); 523 } 524 525 void popTempVersion() { 526 TempVersionStack.pop_back(); 527 } 528 529 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 530 // on the overall stack usage of deeply-recursing constexpr evaluations. 531 // (We should cache this map rather than recomputing it repeatedly.) 532 // But let's try this and see how it goes; we can look into caching the map 533 // as a later change. 534 535 /// LambdaCaptureFields - Mapping from captured variables/this to 536 /// corresponding data members in the closure class. 537 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 538 FieldDecl *LambdaThisCaptureField; 539 540 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 541 const FunctionDecl *Callee, const LValue *This, 542 APValue *Arguments); 543 ~CallStackFrame(); 544 545 // Return the temporary for Key whose version number is Version. 546 APValue *getTemporary(const void *Key, unsigned Version) { 547 MapKeyTy KV(Key, Version); 548 auto LB = Temporaries.lower_bound(KV); 549 if (LB != Temporaries.end() && LB->first == KV) 550 return &LB->second; 551 // Pair (Key,Version) wasn't found in the map. Check that no elements 552 // in the map have 'Key' as their key. 553 assert((LB == Temporaries.end() || LB->first.first != Key) && 554 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 555 "Element with key 'Key' found in map"); 556 return nullptr; 557 } 558 559 // Return the current temporary for Key in the map. 560 APValue *getCurrentTemporary(const void *Key) { 561 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 562 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 563 return &std::prev(UB)->second; 564 return nullptr; 565 } 566 567 // Return the version number of the current temporary for Key. 568 unsigned getCurrentTemporaryVersion(const void *Key) const { 569 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 570 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 571 return std::prev(UB)->first.second; 572 return 0; 573 } 574 575 APValue &createTemporary(const void *Key, bool IsLifetimeExtended); 576 577 void describe(llvm::raw_ostream &OS) override; 578 579 Frame *getCaller() const override { return Caller; } 580 SourceLocation getCallLocation() const override { return CallLoc; } 581 const FunctionDecl *getCallee() const override { return Callee; } 582 }; 583 584 /// Temporarily override 'this'. 585 class ThisOverrideRAII { 586 public: 587 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 588 : Frame(Frame), OldThis(Frame.This) { 589 if (Enable) 590 Frame.This = NewThis; 591 } 592 ~ThisOverrideRAII() { 593 Frame.This = OldThis; 594 } 595 private: 596 CallStackFrame &Frame; 597 const LValue *OldThis; 598 }; 599 600 /// A cleanup, and a flag indicating whether it is lifetime-extended. 601 class Cleanup { 602 llvm::PointerIntPair<APValue*, 1, bool> Value; 603 604 public: 605 Cleanup(APValue *Val, bool IsLifetimeExtended) 606 : Value(Val, IsLifetimeExtended) {} 607 608 bool isLifetimeExtended() const { return Value.getInt(); } 609 void endLifetime() { 610 *Value.getPointer() = APValue(); 611 } 612 }; 613 614 /// A reference to an object whose construction we are currently evaluating. 615 struct ObjectUnderConstruction { 616 APValue::LValueBase Base; 617 ArrayRef<APValue::LValuePathEntry> Path; 618 friend bool operator==(const ObjectUnderConstruction &LHS, 619 const ObjectUnderConstruction &RHS) { 620 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 621 } 622 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 623 return llvm::hash_combine(Obj.Base, Obj.Path); 624 } 625 }; 626 enum class ConstructionPhase { None, Bases, AfterBases }; 627 } 628 629 namespace llvm { 630 template<> struct DenseMapInfo<ObjectUnderConstruction> { 631 using Base = DenseMapInfo<APValue::LValueBase>; 632 static ObjectUnderConstruction getEmptyKey() { 633 return {Base::getEmptyKey(), {}}; } 634 static ObjectUnderConstruction getTombstoneKey() { 635 return {Base::getTombstoneKey(), {}}; 636 } 637 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 638 return hash_value(Object); 639 } 640 static bool isEqual(const ObjectUnderConstruction &LHS, 641 const ObjectUnderConstruction &RHS) { 642 return LHS == RHS; 643 } 644 }; 645 } 646 647 namespace { 648 /// EvalInfo - This is a private struct used by the evaluator to capture 649 /// information about a subexpression as it is folded. It retains information 650 /// about the AST context, but also maintains information about the folded 651 /// expression. 652 /// 653 /// If an expression could be evaluated, it is still possible it is not a C 654 /// "integer constant expression" or constant expression. If not, this struct 655 /// captures information about how and why not. 656 /// 657 /// One bit of information passed *into* the request for constant folding 658 /// indicates whether the subexpression is "evaluated" or not according to C 659 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 660 /// evaluate the expression regardless of what the RHS is, but C only allows 661 /// certain things in certain situations. 662 class EvalInfo : public interp::State { 663 public: 664 ASTContext &Ctx; 665 666 /// EvalStatus - Contains information about the evaluation. 667 Expr::EvalStatus &EvalStatus; 668 669 /// CurrentCall - The top of the constexpr call stack. 670 CallStackFrame *CurrentCall; 671 672 /// CallStackDepth - The number of calls in the call stack right now. 673 unsigned CallStackDepth; 674 675 /// NextCallIndex - The next call index to assign. 676 unsigned NextCallIndex; 677 678 /// StepsLeft - The remaining number of evaluation steps we're permitted 679 /// to perform. This is essentially a limit for the number of statements 680 /// we will evaluate. 681 unsigned StepsLeft; 682 683 /// Force the use of the experimental new constant interpreter, bailing out 684 /// with an error if a feature is not supported. 685 bool ForceNewConstInterp; 686 687 /// Enable the experimental new constant interpreter. 688 bool EnableNewConstInterp; 689 690 /// BottomFrame - The frame in which evaluation started. This must be 691 /// initialized after CurrentCall and CallStackDepth. 692 CallStackFrame BottomFrame; 693 694 /// A stack of values whose lifetimes end at the end of some surrounding 695 /// evaluation frame. 696 llvm::SmallVector<Cleanup, 16> CleanupStack; 697 698 /// EvaluatingDecl - This is the declaration whose initializer is being 699 /// evaluated, if any. 700 APValue::LValueBase EvaluatingDecl; 701 702 /// EvaluatingDeclValue - This is the value being constructed for the 703 /// declaration whose initializer is being evaluated, if any. 704 APValue *EvaluatingDeclValue; 705 706 /// Set of objects that are currently being constructed. 707 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 708 ObjectsUnderConstruction; 709 710 struct EvaluatingConstructorRAII { 711 EvalInfo &EI; 712 ObjectUnderConstruction Object; 713 bool DidInsert; 714 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 715 bool HasBases) 716 : EI(EI), Object(Object) { 717 DidInsert = 718 EI.ObjectsUnderConstruction 719 .insert({Object, HasBases ? ConstructionPhase::Bases 720 : ConstructionPhase::AfterBases}) 721 .second; 722 } 723 void finishedConstructingBases() { 724 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 725 } 726 ~EvaluatingConstructorRAII() { 727 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 728 } 729 }; 730 731 ConstructionPhase 732 isEvaluatingConstructor(APValue::LValueBase Base, 733 ArrayRef<APValue::LValuePathEntry> Path) { 734 return ObjectsUnderConstruction.lookup({Base, Path}); 735 } 736 737 /// If we're currently speculatively evaluating, the outermost call stack 738 /// depth at which we can mutate state, otherwise 0. 739 unsigned SpeculativeEvaluationDepth = 0; 740 741 /// The current array initialization index, if we're performing array 742 /// initialization. 743 uint64_t ArrayInitIndex = -1; 744 745 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 746 /// notes attached to it will also be stored, otherwise they will not be. 747 bool HasActiveDiagnostic; 748 749 /// Have we emitted a diagnostic explaining why we couldn't constant 750 /// fold (not just why it's not strictly a constant expression)? 751 bool HasFoldFailureDiagnostic; 752 753 /// Whether or not we're in a context where the front end requires a 754 /// constant value. 755 bool InConstantContext; 756 757 /// Whether we're checking that an expression is a potential constant 758 /// expression. If so, do not fail on constructs that could become constant 759 /// later on (such as a use of an undefined global). 760 bool CheckingPotentialConstantExpression = false; 761 762 /// Whether we're checking for an expression that has undefined behavior. 763 /// If so, we will produce warnings if we encounter an operation that is 764 /// always undefined. 765 bool CheckingForUndefinedBehavior = false; 766 767 enum EvaluationMode { 768 /// Evaluate as a constant expression. Stop if we find that the expression 769 /// is not a constant expression. 770 EM_ConstantExpression, 771 772 /// Evaluate as a constant expression. Stop if we find that the expression 773 /// is not a constant expression. Some expressions can be retried in the 774 /// optimizer if we don't constant fold them here, but in an unevaluated 775 /// context we try to fold them immediately since the optimizer never 776 /// gets a chance to look at it. 777 EM_ConstantExpressionUnevaluated, 778 779 /// Fold the expression to a constant. Stop if we hit a side-effect that 780 /// we can't model. 781 EM_ConstantFold, 782 783 /// Evaluate in any way we know how. Don't worry about side-effects that 784 /// can't be modeled. 785 EM_IgnoreSideEffects, 786 } EvalMode; 787 788 /// Are we checking whether the expression is a potential constant 789 /// expression? 790 bool checkingPotentialConstantExpression() const override { 791 return CheckingPotentialConstantExpression; 792 } 793 794 /// Are we checking an expression for overflow? 795 // FIXME: We should check for any kind of undefined or suspicious behavior 796 // in such constructs, not just overflow. 797 bool checkingForUndefinedBehavior() const override { 798 return CheckingForUndefinedBehavior; 799 } 800 801 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 802 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 803 CallStackDepth(0), NextCallIndex(1), 804 StepsLeft(getLangOpts().ConstexprStepLimit), 805 ForceNewConstInterp(getLangOpts().ForceNewConstInterp), 806 EnableNewConstInterp(ForceNewConstInterp || 807 getLangOpts().EnableNewConstInterp), 808 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 809 EvaluatingDecl((const ValueDecl *)nullptr), 810 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 811 HasFoldFailureDiagnostic(false), InConstantContext(false), 812 EvalMode(Mode) {} 813 814 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) { 815 EvaluatingDecl = Base; 816 EvaluatingDeclValue = &Value; 817 } 818 819 bool CheckCallLimit(SourceLocation Loc) { 820 // Don't perform any constexpr calls (other than the call we're checking) 821 // when checking a potential constant expression. 822 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 823 return false; 824 if (NextCallIndex == 0) { 825 // NextCallIndex has wrapped around. 826 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 827 return false; 828 } 829 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 830 return true; 831 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 832 << getLangOpts().ConstexprCallDepth; 833 return false; 834 } 835 836 std::pair<CallStackFrame *, unsigned> 837 getCallFrameAndDepth(unsigned CallIndex) { 838 assert(CallIndex && "no call index in getCallFrameAndDepth"); 839 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 840 // be null in this loop. 841 unsigned Depth = CallStackDepth; 842 CallStackFrame *Frame = CurrentCall; 843 while (Frame->Index > CallIndex) { 844 Frame = Frame->Caller; 845 --Depth; 846 } 847 if (Frame->Index == CallIndex) 848 return {Frame, Depth}; 849 return {nullptr, 0}; 850 } 851 852 bool nextStep(const Stmt *S) { 853 if (!StepsLeft) { 854 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 855 return false; 856 } 857 --StepsLeft; 858 return true; 859 } 860 861 private: 862 interp::Frame *getCurrentFrame() override { return CurrentCall; } 863 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 864 865 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 866 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 867 868 void setFoldFailureDiagnostic(bool Flag) override { 869 HasFoldFailureDiagnostic = Flag; 870 } 871 872 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 873 874 ASTContext &getCtx() const override { return Ctx; } 875 876 // If we have a prior diagnostic, it will be noting that the expression 877 // isn't a constant expression. This diagnostic is more important, 878 // unless we require this evaluation to produce a constant expression. 879 // 880 // FIXME: We might want to show both diagnostics to the user in 881 // EM_ConstantFold mode. 882 bool hasPriorDiagnostic() override { 883 if (!EvalStatus.Diag->empty()) { 884 switch (EvalMode) { 885 case EM_ConstantFold: 886 case EM_IgnoreSideEffects: 887 if (!HasFoldFailureDiagnostic) 888 break; 889 // We've already failed to fold something. Keep that diagnostic. 890 LLVM_FALLTHROUGH; 891 case EM_ConstantExpression: 892 case EM_ConstantExpressionUnevaluated: 893 setActiveDiagnostic(false); 894 return true; 895 } 896 } 897 return false; 898 } 899 900 unsigned getCallStackDepth() override { return CallStackDepth; } 901 902 public: 903 /// Should we continue evaluation after encountering a side-effect that we 904 /// couldn't model? 905 bool keepEvaluatingAfterSideEffect() { 906 switch (EvalMode) { 907 case EM_IgnoreSideEffects: 908 return true; 909 910 case EM_ConstantExpression: 911 case EM_ConstantExpressionUnevaluated: 912 case EM_ConstantFold: 913 // By default, assume any side effect might be valid in some other 914 // evaluation of this expression from a different context. 915 return checkingPotentialConstantExpression() || 916 checkingForUndefinedBehavior(); 917 } 918 llvm_unreachable("Missed EvalMode case"); 919 } 920 921 /// Note that we have had a side-effect, and determine whether we should 922 /// keep evaluating. 923 bool noteSideEffect() { 924 EvalStatus.HasSideEffects = true; 925 return keepEvaluatingAfterSideEffect(); 926 } 927 928 /// Should we continue evaluation after encountering undefined behavior? 929 bool keepEvaluatingAfterUndefinedBehavior() { 930 switch (EvalMode) { 931 case EM_IgnoreSideEffects: 932 case EM_ConstantFold: 933 return true; 934 935 case EM_ConstantExpression: 936 case EM_ConstantExpressionUnevaluated: 937 return checkingForUndefinedBehavior(); 938 } 939 llvm_unreachable("Missed EvalMode case"); 940 } 941 942 /// Note that we hit something that was technically undefined behavior, but 943 /// that we can evaluate past it (such as signed overflow or floating-point 944 /// division by zero.) 945 bool noteUndefinedBehavior() override { 946 EvalStatus.HasUndefinedBehavior = true; 947 return keepEvaluatingAfterUndefinedBehavior(); 948 } 949 950 /// Should we continue evaluation as much as possible after encountering a 951 /// construct which can't be reduced to a value? 952 bool keepEvaluatingAfterFailure() const override { 953 if (!StepsLeft) 954 return false; 955 956 switch (EvalMode) { 957 case EM_ConstantExpression: 958 case EM_ConstantExpressionUnevaluated: 959 case EM_ConstantFold: 960 case EM_IgnoreSideEffects: 961 return checkingPotentialConstantExpression() || 962 checkingForUndefinedBehavior(); 963 } 964 llvm_unreachable("Missed EvalMode case"); 965 } 966 967 /// Notes that we failed to evaluate an expression that other expressions 968 /// directly depend on, and determine if we should keep evaluating. This 969 /// should only be called if we actually intend to keep evaluating. 970 /// 971 /// Call noteSideEffect() instead if we may be able to ignore the value that 972 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 973 /// 974 /// (Foo(), 1) // use noteSideEffect 975 /// (Foo() || true) // use noteSideEffect 976 /// Foo() + 1 // use noteFailure 977 LLVM_NODISCARD bool noteFailure() { 978 // Failure when evaluating some expression often means there is some 979 // subexpression whose evaluation was skipped. Therefore, (because we 980 // don't track whether we skipped an expression when unwinding after an 981 // evaluation failure) every evaluation failure that bubbles up from a 982 // subexpression implies that a side-effect has potentially happened. We 983 // skip setting the HasSideEffects flag to true until we decide to 984 // continue evaluating after that point, which happens here. 985 bool KeepGoing = keepEvaluatingAfterFailure(); 986 EvalStatus.HasSideEffects |= KeepGoing; 987 return KeepGoing; 988 } 989 990 class ArrayInitLoopIndex { 991 EvalInfo &Info; 992 uint64_t OuterIndex; 993 994 public: 995 ArrayInitLoopIndex(EvalInfo &Info) 996 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 997 Info.ArrayInitIndex = 0; 998 } 999 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1000 1001 operator uint64_t&() { return Info.ArrayInitIndex; } 1002 }; 1003 }; 1004 1005 /// Object used to treat all foldable expressions as constant expressions. 1006 struct FoldConstant { 1007 EvalInfo &Info; 1008 bool Enabled; 1009 bool HadNoPriorDiags; 1010 EvalInfo::EvaluationMode OldMode; 1011 1012 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1013 : Info(Info), 1014 Enabled(Enabled), 1015 HadNoPriorDiags(Info.EvalStatus.Diag && 1016 Info.EvalStatus.Diag->empty() && 1017 !Info.EvalStatus.HasSideEffects), 1018 OldMode(Info.EvalMode) { 1019 if (Enabled) 1020 Info.EvalMode = EvalInfo::EM_ConstantFold; 1021 } 1022 void keepDiagnostics() { Enabled = false; } 1023 ~FoldConstant() { 1024 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1025 !Info.EvalStatus.HasSideEffects) 1026 Info.EvalStatus.Diag->clear(); 1027 Info.EvalMode = OldMode; 1028 } 1029 }; 1030 1031 /// RAII object used to set the current evaluation mode to ignore 1032 /// side-effects. 1033 struct IgnoreSideEffectsRAII { 1034 EvalInfo &Info; 1035 EvalInfo::EvaluationMode OldMode; 1036 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1037 : Info(Info), OldMode(Info.EvalMode) { 1038 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1039 } 1040 1041 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1042 }; 1043 1044 /// RAII object used to optionally suppress diagnostics and side-effects from 1045 /// a speculative evaluation. 1046 class SpeculativeEvaluationRAII { 1047 EvalInfo *Info = nullptr; 1048 Expr::EvalStatus OldStatus; 1049 unsigned OldSpeculativeEvaluationDepth; 1050 1051 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1052 Info = Other.Info; 1053 OldStatus = Other.OldStatus; 1054 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1055 Other.Info = nullptr; 1056 } 1057 1058 void maybeRestoreState() { 1059 if (!Info) 1060 return; 1061 1062 Info->EvalStatus = OldStatus; 1063 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1064 } 1065 1066 public: 1067 SpeculativeEvaluationRAII() = default; 1068 1069 SpeculativeEvaluationRAII( 1070 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1071 : Info(&Info), OldStatus(Info.EvalStatus), 1072 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1073 Info.EvalStatus.Diag = NewDiag; 1074 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1075 } 1076 1077 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1078 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1079 moveFromAndCancel(std::move(Other)); 1080 } 1081 1082 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1083 maybeRestoreState(); 1084 moveFromAndCancel(std::move(Other)); 1085 return *this; 1086 } 1087 1088 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1089 }; 1090 1091 /// RAII object wrapping a full-expression or block scope, and handling 1092 /// the ending of the lifetime of temporaries created within it. 1093 template<bool IsFullExpression> 1094 class ScopeRAII { 1095 EvalInfo &Info; 1096 unsigned OldStackSize; 1097 public: 1098 ScopeRAII(EvalInfo &Info) 1099 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1100 // Push a new temporary version. This is needed to distinguish between 1101 // temporaries created in different iterations of a loop. 1102 Info.CurrentCall->pushTempVersion(); 1103 } 1104 ~ScopeRAII() { 1105 // Body moved to a static method to encourage the compiler to inline away 1106 // instances of this class. 1107 cleanup(Info, OldStackSize); 1108 Info.CurrentCall->popTempVersion(); 1109 } 1110 private: 1111 static void cleanup(EvalInfo &Info, unsigned OldStackSize) { 1112 unsigned NewEnd = OldStackSize; 1113 for (unsigned I = OldStackSize, N = Info.CleanupStack.size(); 1114 I != N; ++I) { 1115 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) { 1116 // Full-expression cleanup of a lifetime-extended temporary: nothing 1117 // to do, just move this cleanup to the right place in the stack. 1118 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]); 1119 ++NewEnd; 1120 } else { 1121 // End the lifetime of the object. 1122 Info.CleanupStack[I].endLifetime(); 1123 } 1124 } 1125 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd, 1126 Info.CleanupStack.end()); 1127 } 1128 }; 1129 typedef ScopeRAII<false> BlockScopeRAII; 1130 typedef ScopeRAII<true> FullExpressionRAII; 1131 } 1132 1133 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1134 CheckSubobjectKind CSK) { 1135 if (Invalid) 1136 return false; 1137 if (isOnePastTheEnd()) { 1138 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1139 << CSK; 1140 setInvalid(); 1141 return false; 1142 } 1143 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1144 // must actually be at least one array element; even a VLA cannot have a 1145 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1146 return true; 1147 } 1148 1149 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1150 const Expr *E) { 1151 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1152 // Do not set the designator as invalid: we can represent this situation, 1153 // and correct handling of __builtin_object_size requires us to do so. 1154 } 1155 1156 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1157 const Expr *E, 1158 const APSInt &N) { 1159 // If we're complaining, we must be able to statically determine the size of 1160 // the most derived array. 1161 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1162 Info.CCEDiag(E, diag::note_constexpr_array_index) 1163 << N << /*array*/ 0 1164 << static_cast<unsigned>(getMostDerivedArraySize()); 1165 else 1166 Info.CCEDiag(E, diag::note_constexpr_array_index) 1167 << N << /*non-array*/ 1; 1168 setInvalid(); 1169 } 1170 1171 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1172 const FunctionDecl *Callee, const LValue *This, 1173 APValue *Arguments) 1174 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1175 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1176 Info.CurrentCall = this; 1177 ++Info.CallStackDepth; 1178 } 1179 1180 CallStackFrame::~CallStackFrame() { 1181 assert(Info.CurrentCall == this && "calls retired out of order"); 1182 --Info.CallStackDepth; 1183 Info.CurrentCall = Caller; 1184 } 1185 1186 APValue &CallStackFrame::createTemporary(const void *Key, 1187 bool IsLifetimeExtended) { 1188 unsigned Version = Info.CurrentCall->getTempVersion(); 1189 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1190 assert(Result.isAbsent() && "temporary created multiple times"); 1191 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended)); 1192 return Result; 1193 } 1194 1195 static bool isModification(AccessKinds AK) { 1196 switch (AK) { 1197 case AK_Read: 1198 case AK_MemberCall: 1199 case AK_DynamicCast: 1200 case AK_TypeId: 1201 return false; 1202 case AK_Assign: 1203 case AK_Increment: 1204 case AK_Decrement: 1205 return true; 1206 } 1207 llvm_unreachable("unknown access kind"); 1208 } 1209 1210 /// Is this an access per the C++ definition? 1211 static bool isFormalAccess(AccessKinds AK) { 1212 return AK == AK_Read || isModification(AK); 1213 } 1214 1215 namespace { 1216 struct ComplexValue { 1217 private: 1218 bool IsInt; 1219 1220 public: 1221 APSInt IntReal, IntImag; 1222 APFloat FloatReal, FloatImag; 1223 1224 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1225 1226 void makeComplexFloat() { IsInt = false; } 1227 bool isComplexFloat() const { return !IsInt; } 1228 APFloat &getComplexFloatReal() { return FloatReal; } 1229 APFloat &getComplexFloatImag() { return FloatImag; } 1230 1231 void makeComplexInt() { IsInt = true; } 1232 bool isComplexInt() const { return IsInt; } 1233 APSInt &getComplexIntReal() { return IntReal; } 1234 APSInt &getComplexIntImag() { return IntImag; } 1235 1236 void moveInto(APValue &v) const { 1237 if (isComplexFloat()) 1238 v = APValue(FloatReal, FloatImag); 1239 else 1240 v = APValue(IntReal, IntImag); 1241 } 1242 void setFrom(const APValue &v) { 1243 assert(v.isComplexFloat() || v.isComplexInt()); 1244 if (v.isComplexFloat()) { 1245 makeComplexFloat(); 1246 FloatReal = v.getComplexFloatReal(); 1247 FloatImag = v.getComplexFloatImag(); 1248 } else { 1249 makeComplexInt(); 1250 IntReal = v.getComplexIntReal(); 1251 IntImag = v.getComplexIntImag(); 1252 } 1253 } 1254 }; 1255 1256 struct LValue { 1257 APValue::LValueBase Base; 1258 CharUnits Offset; 1259 SubobjectDesignator Designator; 1260 bool IsNullPtr : 1; 1261 bool InvalidBase : 1; 1262 1263 const APValue::LValueBase getLValueBase() const { return Base; } 1264 CharUnits &getLValueOffset() { return Offset; } 1265 const CharUnits &getLValueOffset() const { return Offset; } 1266 SubobjectDesignator &getLValueDesignator() { return Designator; } 1267 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1268 bool isNullPointer() const { return IsNullPtr;} 1269 1270 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1271 unsigned getLValueVersion() const { return Base.getVersion(); } 1272 1273 void moveInto(APValue &V) const { 1274 if (Designator.Invalid) 1275 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1276 else { 1277 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1278 V = APValue(Base, Offset, Designator.Entries, 1279 Designator.IsOnePastTheEnd, IsNullPtr); 1280 } 1281 } 1282 void setFrom(ASTContext &Ctx, const APValue &V) { 1283 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1284 Base = V.getLValueBase(); 1285 Offset = V.getLValueOffset(); 1286 InvalidBase = false; 1287 Designator = SubobjectDesignator(Ctx, V); 1288 IsNullPtr = V.isNullPointer(); 1289 } 1290 1291 void set(APValue::LValueBase B, bool BInvalid = false) { 1292 #ifndef NDEBUG 1293 // We only allow a few types of invalid bases. Enforce that here. 1294 if (BInvalid) { 1295 const auto *E = B.get<const Expr *>(); 1296 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1297 "Unexpected type of invalid base"); 1298 } 1299 #endif 1300 1301 Base = B; 1302 Offset = CharUnits::fromQuantity(0); 1303 InvalidBase = BInvalid; 1304 Designator = SubobjectDesignator(getType(B)); 1305 IsNullPtr = false; 1306 } 1307 1308 void setNull(QualType PointerTy, uint64_t TargetVal) { 1309 Base = (Expr *)nullptr; 1310 Offset = CharUnits::fromQuantity(TargetVal); 1311 InvalidBase = false; 1312 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1313 IsNullPtr = true; 1314 } 1315 1316 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1317 set(B, true); 1318 } 1319 1320 private: 1321 // Check that this LValue is not based on a null pointer. If it is, produce 1322 // a diagnostic and mark the designator as invalid. 1323 template <typename GenDiagType> 1324 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1325 if (Designator.Invalid) 1326 return false; 1327 if (IsNullPtr) { 1328 GenDiag(); 1329 Designator.setInvalid(); 1330 return false; 1331 } 1332 return true; 1333 } 1334 1335 public: 1336 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1337 CheckSubobjectKind CSK) { 1338 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1339 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1340 }); 1341 } 1342 1343 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1344 AccessKinds AK) { 1345 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1346 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1347 }); 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 /// Evaluate an integer or fixed point expression into an APResult. 1531 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1532 EvalInfo &Info); 1533 1534 /// Evaluate only a fixed point expression into an APResult. 1535 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1536 EvalInfo &Info); 1537 1538 //===----------------------------------------------------------------------===// 1539 // Misc utilities 1540 //===----------------------------------------------------------------------===// 1541 1542 /// A helper function to create a temporary and set an LValue. 1543 template <class KeyTy> 1544 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended, 1545 LValue &LV, CallStackFrame &Frame) { 1546 LV.set({Key, Frame.Info.CurrentCall->Index, 1547 Frame.Info.CurrentCall->getTempVersion()}); 1548 return Frame.createTemporary(Key, IsLifetimeExtended); 1549 } 1550 1551 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1552 /// preserving its value (by extending by up to one bit as needed). 1553 static void negateAsSigned(APSInt &Int) { 1554 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1555 Int = Int.extend(Int.getBitWidth() + 1); 1556 Int.setIsSigned(true); 1557 } 1558 Int = -Int; 1559 } 1560 1561 /// Produce a string describing the given constexpr call. 1562 void CallStackFrame::describe(raw_ostream &Out) { 1563 unsigned ArgIndex = 0; 1564 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1565 !isa<CXXConstructorDecl>(Callee) && 1566 cast<CXXMethodDecl>(Callee)->isInstance(); 1567 1568 if (!IsMemberCall) 1569 Out << *Callee << '('; 1570 1571 if (This && IsMemberCall) { 1572 APValue Val; 1573 This->moveInto(Val); 1574 Val.printPretty(Out, Info.Ctx, 1575 This->Designator.MostDerivedType); 1576 // FIXME: Add parens around Val if needed. 1577 Out << "->" << *Callee << '('; 1578 IsMemberCall = false; 1579 } 1580 1581 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1582 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1583 if (ArgIndex > (unsigned)IsMemberCall) 1584 Out << ", "; 1585 1586 const ParmVarDecl *Param = *I; 1587 const APValue &Arg = Arguments[ArgIndex]; 1588 Arg.printPretty(Out, Info.Ctx, Param->getType()); 1589 1590 if (ArgIndex == 0 && IsMemberCall) 1591 Out << "->" << *Callee << '('; 1592 } 1593 1594 Out << ')'; 1595 } 1596 1597 /// Evaluate an expression to see if it had side-effects, and discard its 1598 /// result. 1599 /// \return \c true if the caller should keep evaluating. 1600 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1601 APValue Scratch; 1602 if (!Evaluate(Scratch, Info, E)) 1603 // We don't need the value, but we might have skipped a side effect here. 1604 return Info.noteSideEffect(); 1605 return true; 1606 } 1607 1608 /// Should this call expression be treated as a string literal? 1609 static bool IsStringLiteralCall(const CallExpr *E) { 1610 unsigned Builtin = E->getBuiltinCallee(); 1611 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1612 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1613 } 1614 1615 static bool IsGlobalLValue(APValue::LValueBase B) { 1616 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1617 // constant expression of pointer type that evaluates to... 1618 1619 // ... a null pointer value, or a prvalue core constant expression of type 1620 // std::nullptr_t. 1621 if (!B) return true; 1622 1623 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1624 // ... the address of an object with static storage duration, 1625 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1626 return VD->hasGlobalStorage(); 1627 // ... the address of a function, 1628 return isa<FunctionDecl>(D); 1629 } 1630 1631 if (B.is<TypeInfoLValue>()) 1632 return true; 1633 1634 const Expr *E = B.get<const Expr*>(); 1635 switch (E->getStmtClass()) { 1636 default: 1637 return false; 1638 case Expr::CompoundLiteralExprClass: { 1639 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1640 return CLE->isFileScope() && CLE->isLValue(); 1641 } 1642 case Expr::MaterializeTemporaryExprClass: 1643 // A materialized temporary might have been lifetime-extended to static 1644 // storage duration. 1645 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1646 // A string literal has static storage duration. 1647 case Expr::StringLiteralClass: 1648 case Expr::PredefinedExprClass: 1649 case Expr::ObjCStringLiteralClass: 1650 case Expr::ObjCEncodeExprClass: 1651 case Expr::CXXUuidofExprClass: 1652 return true; 1653 case Expr::ObjCBoxedExprClass: 1654 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 1655 case Expr::CallExprClass: 1656 return IsStringLiteralCall(cast<CallExpr>(E)); 1657 // For GCC compatibility, &&label has static storage duration. 1658 case Expr::AddrLabelExprClass: 1659 return true; 1660 // A Block literal expression may be used as the initialization value for 1661 // Block variables at global or local static scope. 1662 case Expr::BlockExprClass: 1663 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1664 case Expr::ImplicitValueInitExprClass: 1665 // FIXME: 1666 // We can never form an lvalue with an implicit value initialization as its 1667 // base through expression evaluation, so these only appear in one case: the 1668 // implicit variable declaration we invent when checking whether a constexpr 1669 // constructor can produce a constant expression. We must assume that such 1670 // an expression might be a global lvalue. 1671 return true; 1672 } 1673 } 1674 1675 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1676 return LVal.Base.dyn_cast<const ValueDecl*>(); 1677 } 1678 1679 static bool IsLiteralLValue(const LValue &Value) { 1680 if (Value.getLValueCallIndex()) 1681 return false; 1682 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1683 return E && !isa<MaterializeTemporaryExpr>(E); 1684 } 1685 1686 static bool IsWeakLValue(const LValue &Value) { 1687 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1688 return Decl && Decl->isWeak(); 1689 } 1690 1691 static bool isZeroSized(const LValue &Value) { 1692 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1693 if (Decl && isa<VarDecl>(Decl)) { 1694 QualType Ty = Decl->getType(); 1695 if (Ty->isArrayType()) 1696 return Ty->isIncompleteType() || 1697 Decl->getASTContext().getTypeSize(Ty) == 0; 1698 } 1699 return false; 1700 } 1701 1702 static bool HasSameBase(const LValue &A, const LValue &B) { 1703 if (!A.getLValueBase()) 1704 return !B.getLValueBase(); 1705 if (!B.getLValueBase()) 1706 return false; 1707 1708 if (A.getLValueBase().getOpaqueValue() != 1709 B.getLValueBase().getOpaqueValue()) { 1710 const Decl *ADecl = GetLValueBaseDecl(A); 1711 if (!ADecl) 1712 return false; 1713 const Decl *BDecl = GetLValueBaseDecl(B); 1714 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 1715 return false; 1716 } 1717 1718 return IsGlobalLValue(A.getLValueBase()) || 1719 (A.getLValueCallIndex() == B.getLValueCallIndex() && 1720 A.getLValueVersion() == B.getLValueVersion()); 1721 } 1722 1723 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1724 assert(Base && "no location for a null lvalue"); 1725 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1726 if (VD) 1727 Info.Note(VD->getLocation(), diag::note_declared_at); 1728 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 1729 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 1730 // We have no information to show for a typeid(T) object. 1731 } 1732 1733 /// Check that this reference or pointer core constant expression is a valid 1734 /// value for an address or reference constant expression. Return true if we 1735 /// can fold this expression, whether or not it's a constant expression. 1736 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 1737 QualType Type, const LValue &LVal, 1738 Expr::ConstExprUsage Usage) { 1739 bool IsReferenceType = Type->isReferenceType(); 1740 1741 APValue::LValueBase Base = LVal.getLValueBase(); 1742 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 1743 1744 // Check that the object is a global. Note that the fake 'this' object we 1745 // manufacture when checking potential constant expressions is conservatively 1746 // assumed to be global here. 1747 if (!IsGlobalLValue(Base)) { 1748 if (Info.getLangOpts().CPlusPlus11) { 1749 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1750 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 1751 << IsReferenceType << !Designator.Entries.empty() 1752 << !!VD << VD; 1753 NoteLValueLocation(Info, Base); 1754 } else { 1755 Info.FFDiag(Loc); 1756 } 1757 // Don't allow references to temporaries to escape. 1758 return false; 1759 } 1760 assert((Info.checkingPotentialConstantExpression() || 1761 LVal.getLValueCallIndex() == 0) && 1762 "have call index for global lvalue"); 1763 1764 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 1765 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 1766 // Check if this is a thread-local variable. 1767 if (Var->getTLSKind()) 1768 return false; 1769 1770 // A dllimport variable never acts like a constant. 1771 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 1772 return false; 1773 } 1774 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 1775 // __declspec(dllimport) must be handled very carefully: 1776 // We must never initialize an expression with the thunk in C++. 1777 // Doing otherwise would allow the same id-expression to yield 1778 // different addresses for the same function in different translation 1779 // units. However, this means that we must dynamically initialize the 1780 // expression with the contents of the import address table at runtime. 1781 // 1782 // The C language has no notion of ODR; furthermore, it has no notion of 1783 // dynamic initialization. This means that we are permitted to 1784 // perform initialization with the address of the thunk. 1785 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 1786 FD->hasAttr<DLLImportAttr>()) 1787 return false; 1788 } 1789 } 1790 1791 // Allow address constant expressions to be past-the-end pointers. This is 1792 // an extension: the standard requires them to point to an object. 1793 if (!IsReferenceType) 1794 return true; 1795 1796 // A reference constant expression must refer to an object. 1797 if (!Base) { 1798 // FIXME: diagnostic 1799 Info.CCEDiag(Loc); 1800 return true; 1801 } 1802 1803 // Does this refer one past the end of some object? 1804 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 1805 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1806 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 1807 << !Designator.Entries.empty() << !!VD << VD; 1808 NoteLValueLocation(Info, Base); 1809 } 1810 1811 return true; 1812 } 1813 1814 /// Member pointers are constant expressions unless they point to a 1815 /// non-virtual dllimport member function. 1816 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 1817 SourceLocation Loc, 1818 QualType Type, 1819 const APValue &Value, 1820 Expr::ConstExprUsage Usage) { 1821 const ValueDecl *Member = Value.getMemberPointerDecl(); 1822 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 1823 if (!FD) 1824 return true; 1825 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 1826 !FD->hasAttr<DLLImportAttr>(); 1827 } 1828 1829 /// Check that this core constant expression is of literal type, and if not, 1830 /// produce an appropriate diagnostic. 1831 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 1832 const LValue *This = nullptr) { 1833 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 1834 return true; 1835 1836 // C++1y: A constant initializer for an object o [...] may also invoke 1837 // constexpr constructors for o and its subobjects even if those objects 1838 // are of non-literal class types. 1839 // 1840 // C++11 missed this detail for aggregates, so classes like this: 1841 // struct foo_t { union { int i; volatile int j; } u; }; 1842 // are not (obviously) initializable like so: 1843 // __attribute__((__require_constant_initialization__)) 1844 // static const foo_t x = {{0}}; 1845 // because "i" is a subobject with non-literal initialization (due to the 1846 // volatile member of the union). See: 1847 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 1848 // Therefore, we use the C++1y behavior. 1849 if (This && Info.EvaluatingDecl == This->getLValueBase()) 1850 return true; 1851 1852 // Prvalue constant expressions must be of literal types. 1853 if (Info.getLangOpts().CPlusPlus11) 1854 Info.FFDiag(E, diag::note_constexpr_nonliteral) 1855 << E->getType(); 1856 else 1857 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 1858 return false; 1859 } 1860 1861 /// Check that this core constant expression value is a valid value for a 1862 /// constant expression. If not, report an appropriate diagnostic. Does not 1863 /// check that the expression is of literal type. 1864 static bool 1865 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 1866 const APValue &Value, 1867 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen, 1868 SourceLocation SubobjectLoc = SourceLocation()) { 1869 if (!Value.hasValue()) { 1870 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 1871 << true << Type; 1872 if (SubobjectLoc.isValid()) 1873 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 1874 return false; 1875 } 1876 1877 // We allow _Atomic(T) to be initialized from anything that T can be 1878 // initialized from. 1879 if (const AtomicType *AT = Type->getAs<AtomicType>()) 1880 Type = AT->getValueType(); 1881 1882 // Core issue 1454: For a literal constant expression of array or class type, 1883 // each subobject of its value shall have been initialized by a constant 1884 // expression. 1885 if (Value.isArray()) { 1886 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 1887 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 1888 if (!CheckConstantExpression(Info, DiagLoc, EltTy, 1889 Value.getArrayInitializedElt(I), Usage, 1890 SubobjectLoc)) 1891 return false; 1892 } 1893 if (!Value.hasArrayFiller()) 1894 return true; 1895 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(), 1896 Usage, SubobjectLoc); 1897 } 1898 if (Value.isUnion() && Value.getUnionField()) { 1899 return CheckConstantExpression(Info, DiagLoc, 1900 Value.getUnionField()->getType(), 1901 Value.getUnionValue(), Usage, 1902 Value.getUnionField()->getLocation()); 1903 } 1904 if (Value.isStruct()) { 1905 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 1906 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 1907 unsigned BaseIndex = 0; 1908 for (const CXXBaseSpecifier &BS : CD->bases()) { 1909 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(), 1910 Value.getStructBase(BaseIndex), Usage, 1911 BS.getBeginLoc())) 1912 return false; 1913 ++BaseIndex; 1914 } 1915 } 1916 for (const auto *I : RD->fields()) { 1917 if (I->isUnnamedBitfield()) 1918 continue; 1919 1920 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 1921 Value.getStructField(I->getFieldIndex()), 1922 Usage, I->getLocation())) 1923 return false; 1924 } 1925 } 1926 1927 if (Value.isLValue()) { 1928 LValue LVal; 1929 LVal.setFrom(Info.Ctx, Value); 1930 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage); 1931 } 1932 1933 if (Value.isMemberPointer()) 1934 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 1935 1936 // Everything else is fine. 1937 return true; 1938 } 1939 1940 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 1941 // A null base expression indicates a null pointer. These are always 1942 // evaluatable, and they are false unless the offset is zero. 1943 if (!Value.getLValueBase()) { 1944 Result = !Value.getLValueOffset().isZero(); 1945 return true; 1946 } 1947 1948 // We have a non-null base. These are generally known to be true, but if it's 1949 // a weak declaration it can be null at runtime. 1950 Result = true; 1951 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 1952 return !Decl || !Decl->isWeak(); 1953 } 1954 1955 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 1956 switch (Val.getKind()) { 1957 case APValue::None: 1958 case APValue::Indeterminate: 1959 return false; 1960 case APValue::Int: 1961 Result = Val.getInt().getBoolValue(); 1962 return true; 1963 case APValue::FixedPoint: 1964 Result = Val.getFixedPoint().getBoolValue(); 1965 return true; 1966 case APValue::Float: 1967 Result = !Val.getFloat().isZero(); 1968 return true; 1969 case APValue::ComplexInt: 1970 Result = Val.getComplexIntReal().getBoolValue() || 1971 Val.getComplexIntImag().getBoolValue(); 1972 return true; 1973 case APValue::ComplexFloat: 1974 Result = !Val.getComplexFloatReal().isZero() || 1975 !Val.getComplexFloatImag().isZero(); 1976 return true; 1977 case APValue::LValue: 1978 return EvalPointerValueAsBool(Val, Result); 1979 case APValue::MemberPointer: 1980 Result = Val.getMemberPointerDecl(); 1981 return true; 1982 case APValue::Vector: 1983 case APValue::Array: 1984 case APValue::Struct: 1985 case APValue::Union: 1986 case APValue::AddrLabelDiff: 1987 return false; 1988 } 1989 1990 llvm_unreachable("unknown APValue kind"); 1991 } 1992 1993 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 1994 EvalInfo &Info) { 1995 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 1996 APValue Val; 1997 if (!Evaluate(Val, Info, E)) 1998 return false; 1999 return HandleConversionToBool(Val, Result); 2000 } 2001 2002 template<typename T> 2003 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2004 const T &SrcValue, QualType DestType) { 2005 Info.CCEDiag(E, diag::note_constexpr_overflow) 2006 << SrcValue << DestType; 2007 return Info.noteUndefinedBehavior(); 2008 } 2009 2010 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2011 QualType SrcType, const APFloat &Value, 2012 QualType DestType, APSInt &Result) { 2013 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2014 // Determine whether we are converting to unsigned or signed. 2015 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2016 2017 Result = APSInt(DestWidth, !DestSigned); 2018 bool ignored; 2019 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2020 & APFloat::opInvalidOp) 2021 return HandleOverflow(Info, E, Value, DestType); 2022 return true; 2023 } 2024 2025 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2026 QualType SrcType, QualType DestType, 2027 APFloat &Result) { 2028 APFloat Value = Result; 2029 bool ignored; 2030 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 2031 APFloat::rmNearestTiesToEven, &ignored); 2032 return true; 2033 } 2034 2035 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2036 QualType DestType, QualType SrcType, 2037 const APSInt &Value) { 2038 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2039 // Figure out if this is a truncate, extend or noop cast. 2040 // If the input is signed, do a sign extend, noop, or truncate. 2041 APSInt Result = Value.extOrTrunc(DestWidth); 2042 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2043 if (DestType->isBooleanType()) 2044 Result = Value.getBoolValue(); 2045 return Result; 2046 } 2047 2048 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2049 QualType SrcType, const APSInt &Value, 2050 QualType DestType, APFloat &Result) { 2051 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2052 Result.convertFromAPInt(Value, Value.isSigned(), 2053 APFloat::rmNearestTiesToEven); 2054 return true; 2055 } 2056 2057 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2058 APValue &Value, const FieldDecl *FD) { 2059 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2060 2061 if (!Value.isInt()) { 2062 // Trying to store a pointer-cast-to-integer into a bitfield. 2063 // FIXME: In this case, we should provide the diagnostic for casting 2064 // a pointer to an integer. 2065 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2066 Info.FFDiag(E); 2067 return false; 2068 } 2069 2070 APSInt &Int = Value.getInt(); 2071 unsigned OldBitWidth = Int.getBitWidth(); 2072 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2073 if (NewBitWidth < OldBitWidth) 2074 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2075 return true; 2076 } 2077 2078 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2079 llvm::APInt &Res) { 2080 APValue SVal; 2081 if (!Evaluate(SVal, Info, E)) 2082 return false; 2083 if (SVal.isInt()) { 2084 Res = SVal.getInt(); 2085 return true; 2086 } 2087 if (SVal.isFloat()) { 2088 Res = SVal.getFloat().bitcastToAPInt(); 2089 return true; 2090 } 2091 if (SVal.isVector()) { 2092 QualType VecTy = E->getType(); 2093 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2094 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2095 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2096 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2097 Res = llvm::APInt::getNullValue(VecSize); 2098 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2099 APValue &Elt = SVal.getVectorElt(i); 2100 llvm::APInt EltAsInt; 2101 if (Elt.isInt()) { 2102 EltAsInt = Elt.getInt(); 2103 } else if (Elt.isFloat()) { 2104 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2105 } else { 2106 // Don't try to handle vectors of anything other than int or float 2107 // (not sure if it's possible to hit this case). 2108 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2109 return false; 2110 } 2111 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2112 if (BigEndian) 2113 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2114 else 2115 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2116 } 2117 return true; 2118 } 2119 // Give up if the input isn't an int, float, or vector. For example, we 2120 // reject "(v4i16)(intptr_t)&a". 2121 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2122 return false; 2123 } 2124 2125 /// Perform the given integer operation, which is known to need at most BitWidth 2126 /// bits, and check for overflow in the original type (if that type was not an 2127 /// unsigned type). 2128 template<typename Operation> 2129 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2130 const APSInt &LHS, const APSInt &RHS, 2131 unsigned BitWidth, Operation Op, 2132 APSInt &Result) { 2133 if (LHS.isUnsigned()) { 2134 Result = Op(LHS, RHS); 2135 return true; 2136 } 2137 2138 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2139 Result = Value.trunc(LHS.getBitWidth()); 2140 if (Result.extend(BitWidth) != Value) { 2141 if (Info.checkingForUndefinedBehavior()) 2142 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2143 diag::warn_integer_constant_overflow) 2144 << Result.toString(10) << E->getType(); 2145 else 2146 return HandleOverflow(Info, E, Value, E->getType()); 2147 } 2148 return true; 2149 } 2150 2151 /// Perform the given binary integer operation. 2152 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2153 BinaryOperatorKind Opcode, APSInt RHS, 2154 APSInt &Result) { 2155 switch (Opcode) { 2156 default: 2157 Info.FFDiag(E); 2158 return false; 2159 case BO_Mul: 2160 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2161 std::multiplies<APSInt>(), Result); 2162 case BO_Add: 2163 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2164 std::plus<APSInt>(), Result); 2165 case BO_Sub: 2166 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2167 std::minus<APSInt>(), Result); 2168 case BO_And: Result = LHS & RHS; return true; 2169 case BO_Xor: Result = LHS ^ RHS; return true; 2170 case BO_Or: Result = LHS | RHS; return true; 2171 case BO_Div: 2172 case BO_Rem: 2173 if (RHS == 0) { 2174 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2175 return false; 2176 } 2177 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2178 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2179 // this operation and gives the two's complement result. 2180 if (RHS.isNegative() && RHS.isAllOnesValue() && 2181 LHS.isSigned() && LHS.isMinSignedValue()) 2182 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2183 E->getType()); 2184 return true; 2185 case BO_Shl: { 2186 if (Info.getLangOpts().OpenCL) 2187 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2188 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2189 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2190 RHS.isUnsigned()); 2191 else if (RHS.isSigned() && RHS.isNegative()) { 2192 // During constant-folding, a negative shift is an opposite shift. Such 2193 // a shift is not a constant expression. 2194 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2195 RHS = -RHS; 2196 goto shift_right; 2197 } 2198 shift_left: 2199 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2200 // the shifted type. 2201 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2202 if (SA != RHS) { 2203 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2204 << RHS << E->getType() << LHS.getBitWidth(); 2205 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) { 2206 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2207 // operand, and must not overflow the corresponding unsigned type. 2208 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2209 // E1 x 2^E2 module 2^N. 2210 if (LHS.isNegative()) 2211 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2212 else if (LHS.countLeadingZeros() < SA) 2213 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2214 } 2215 Result = LHS << SA; 2216 return true; 2217 } 2218 case BO_Shr: { 2219 if (Info.getLangOpts().OpenCL) 2220 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2221 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2222 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2223 RHS.isUnsigned()); 2224 else if (RHS.isSigned() && RHS.isNegative()) { 2225 // During constant-folding, a negative shift is an opposite shift. Such a 2226 // shift is not a constant expression. 2227 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2228 RHS = -RHS; 2229 goto shift_left; 2230 } 2231 shift_right: 2232 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2233 // shifted type. 2234 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2235 if (SA != RHS) 2236 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2237 << RHS << E->getType() << LHS.getBitWidth(); 2238 Result = LHS >> SA; 2239 return true; 2240 } 2241 2242 case BO_LT: Result = LHS < RHS; return true; 2243 case BO_GT: Result = LHS > RHS; return true; 2244 case BO_LE: Result = LHS <= RHS; return true; 2245 case BO_GE: Result = LHS >= RHS; return true; 2246 case BO_EQ: Result = LHS == RHS; return true; 2247 case BO_NE: Result = LHS != RHS; return true; 2248 case BO_Cmp: 2249 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2250 } 2251 } 2252 2253 /// Perform the given binary floating-point operation, in-place, on LHS. 2254 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2255 APFloat &LHS, BinaryOperatorKind Opcode, 2256 const APFloat &RHS) { 2257 switch (Opcode) { 2258 default: 2259 Info.FFDiag(E); 2260 return false; 2261 case BO_Mul: 2262 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2263 break; 2264 case BO_Add: 2265 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2266 break; 2267 case BO_Sub: 2268 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2269 break; 2270 case BO_Div: 2271 // [expr.mul]p4: 2272 // If the second operand of / or % is zero the behavior is undefined. 2273 if (RHS.isZero()) 2274 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2275 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2276 break; 2277 } 2278 2279 // [expr.pre]p4: 2280 // If during the evaluation of an expression, the result is not 2281 // mathematically defined [...], the behavior is undefined. 2282 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2283 if (LHS.isNaN()) { 2284 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2285 return Info.noteUndefinedBehavior(); 2286 } 2287 return true; 2288 } 2289 2290 /// Cast an lvalue referring to a base subobject to a derived class, by 2291 /// truncating the lvalue's path to the given length. 2292 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2293 const RecordDecl *TruncatedType, 2294 unsigned TruncatedElements) { 2295 SubobjectDesignator &D = Result.Designator; 2296 2297 // Check we actually point to a derived class object. 2298 if (TruncatedElements == D.Entries.size()) 2299 return true; 2300 assert(TruncatedElements >= D.MostDerivedPathLength && 2301 "not casting to a derived class"); 2302 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2303 return false; 2304 2305 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2306 const RecordDecl *RD = TruncatedType; 2307 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2308 if (RD->isInvalidDecl()) return false; 2309 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2310 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2311 if (isVirtualBaseClass(D.Entries[I])) 2312 Result.Offset -= Layout.getVBaseClassOffset(Base); 2313 else 2314 Result.Offset -= Layout.getBaseClassOffset(Base); 2315 RD = Base; 2316 } 2317 D.Entries.resize(TruncatedElements); 2318 return true; 2319 } 2320 2321 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2322 const CXXRecordDecl *Derived, 2323 const CXXRecordDecl *Base, 2324 const ASTRecordLayout *RL = nullptr) { 2325 if (!RL) { 2326 if (Derived->isInvalidDecl()) return false; 2327 RL = &Info.Ctx.getASTRecordLayout(Derived); 2328 } 2329 2330 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2331 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2332 return true; 2333 } 2334 2335 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2336 const CXXRecordDecl *DerivedDecl, 2337 const CXXBaseSpecifier *Base) { 2338 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2339 2340 if (!Base->isVirtual()) 2341 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2342 2343 SubobjectDesignator &D = Obj.Designator; 2344 if (D.Invalid) 2345 return false; 2346 2347 // Extract most-derived object and corresponding type. 2348 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2349 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2350 return false; 2351 2352 // Find the virtual base class. 2353 if (DerivedDecl->isInvalidDecl()) return false; 2354 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2355 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2356 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2357 return true; 2358 } 2359 2360 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2361 QualType Type, LValue &Result) { 2362 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2363 PathE = E->path_end(); 2364 PathI != PathE; ++PathI) { 2365 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2366 *PathI)) 2367 return false; 2368 Type = (*PathI)->getType(); 2369 } 2370 return true; 2371 } 2372 2373 /// Cast an lvalue referring to a derived class to a known base subobject. 2374 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 2375 const CXXRecordDecl *DerivedRD, 2376 const CXXRecordDecl *BaseRD) { 2377 CXXBasePaths Paths(/*FindAmbiguities=*/false, 2378 /*RecordPaths=*/true, /*DetectVirtual=*/false); 2379 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 2380 llvm_unreachable("Class must be derived from the passed in base class!"); 2381 2382 for (CXXBasePathElement &Elem : Paths.front()) 2383 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 2384 return false; 2385 return true; 2386 } 2387 2388 /// Update LVal to refer to the given field, which must be a member of the type 2389 /// currently described by LVal. 2390 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2391 const FieldDecl *FD, 2392 const ASTRecordLayout *RL = nullptr) { 2393 if (!RL) { 2394 if (FD->getParent()->isInvalidDecl()) return false; 2395 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2396 } 2397 2398 unsigned I = FD->getFieldIndex(); 2399 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2400 LVal.addDecl(Info, E, FD); 2401 return true; 2402 } 2403 2404 /// Update LVal to refer to the given indirect field. 2405 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2406 LValue &LVal, 2407 const IndirectFieldDecl *IFD) { 2408 for (const auto *C : IFD->chain()) 2409 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2410 return false; 2411 return true; 2412 } 2413 2414 /// Get the size of the given type in char units. 2415 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2416 QualType Type, CharUnits &Size) { 2417 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2418 // extension. 2419 if (Type->isVoidType() || Type->isFunctionType()) { 2420 Size = CharUnits::One(); 2421 return true; 2422 } 2423 2424 if (Type->isDependentType()) { 2425 Info.FFDiag(Loc); 2426 return false; 2427 } 2428 2429 if (!Type->isConstantSizeType()) { 2430 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2431 // FIXME: Better diagnostic. 2432 Info.FFDiag(Loc); 2433 return false; 2434 } 2435 2436 Size = Info.Ctx.getTypeSizeInChars(Type); 2437 return true; 2438 } 2439 2440 /// Update a pointer value to model pointer arithmetic. 2441 /// \param Info - Information about the ongoing evaluation. 2442 /// \param E - The expression being evaluated, for diagnostic purposes. 2443 /// \param LVal - The pointer value to be updated. 2444 /// \param EltTy - The pointee type represented by LVal. 2445 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2446 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2447 LValue &LVal, QualType EltTy, 2448 APSInt Adjustment) { 2449 CharUnits SizeOfPointee; 2450 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2451 return false; 2452 2453 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2454 return true; 2455 } 2456 2457 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2458 LValue &LVal, QualType EltTy, 2459 int64_t Adjustment) { 2460 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 2461 APSInt::get(Adjustment)); 2462 } 2463 2464 /// Update an lvalue to refer to a component of a complex number. 2465 /// \param Info - Information about the ongoing evaluation. 2466 /// \param LVal - The lvalue to be updated. 2467 /// \param EltTy - The complex number's component type. 2468 /// \param Imag - False for the real component, true for the imaginary. 2469 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 2470 LValue &LVal, QualType EltTy, 2471 bool Imag) { 2472 if (Imag) { 2473 CharUnits SizeOfComponent; 2474 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 2475 return false; 2476 LVal.Offset += SizeOfComponent; 2477 } 2478 LVal.addComplex(Info, E, EltTy, Imag); 2479 return true; 2480 } 2481 2482 /// Try to evaluate the initializer for a variable declaration. 2483 /// 2484 /// \param Info Information about the ongoing evaluation. 2485 /// \param E An expression to be used when printing diagnostics. 2486 /// \param VD The variable whose initializer should be obtained. 2487 /// \param Frame The frame in which the variable was created. Must be null 2488 /// if this variable is not local to the evaluation. 2489 /// \param Result Filled in with a pointer to the value of the variable. 2490 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 2491 const VarDecl *VD, CallStackFrame *Frame, 2492 APValue *&Result, const LValue *LVal) { 2493 2494 // If this is a parameter to an active constexpr function call, perform 2495 // argument substitution. 2496 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 2497 // Assume arguments of a potential constant expression are unknown 2498 // constant expressions. 2499 if (Info.checkingPotentialConstantExpression()) 2500 return false; 2501 if (!Frame || !Frame->Arguments) { 2502 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2503 return false; 2504 } 2505 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 2506 return true; 2507 } 2508 2509 // If this is a local variable, dig out its value. 2510 if (Frame) { 2511 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 2512 : Frame->getCurrentTemporary(VD); 2513 if (!Result) { 2514 // Assume variables referenced within a lambda's call operator that were 2515 // not declared within the call operator are captures and during checking 2516 // of a potential constant expression, assume they are unknown constant 2517 // expressions. 2518 assert(isLambdaCallOperator(Frame->Callee) && 2519 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 2520 "missing value for local variable"); 2521 if (Info.checkingPotentialConstantExpression()) 2522 return false; 2523 // FIXME: implement capture evaluation during constant expr evaluation. 2524 Info.FFDiag(E->getBeginLoc(), 2525 diag::note_unimplemented_constexpr_lambda_feature_ast) 2526 << "captures not currently allowed"; 2527 return false; 2528 } 2529 return true; 2530 } 2531 2532 // Dig out the initializer, and use the declaration which it's attached to. 2533 const Expr *Init = VD->getAnyInitializer(VD); 2534 if (!Init || Init->isValueDependent()) { 2535 // If we're checking a potential constant expression, the variable could be 2536 // initialized later. 2537 if (!Info.checkingPotentialConstantExpression()) 2538 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2539 return false; 2540 } 2541 2542 // If we're currently evaluating the initializer of this declaration, use that 2543 // in-flight value. 2544 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 2545 Result = Info.EvaluatingDeclValue; 2546 return true; 2547 } 2548 2549 // Never evaluate the initializer of a weak variable. We can't be sure that 2550 // this is the definition which will be used. 2551 if (VD->isWeak()) { 2552 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2553 return false; 2554 } 2555 2556 // Check that we can fold the initializer. In C++, we will have already done 2557 // this in the cases where it matters for conformance. 2558 SmallVector<PartialDiagnosticAt, 8> Notes; 2559 if (!VD->evaluateValue(Notes)) { 2560 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 2561 Notes.size() + 1) << VD; 2562 Info.Note(VD->getLocation(), diag::note_declared_at); 2563 Info.addNotes(Notes); 2564 return false; 2565 } else if (!VD->checkInitIsICE()) { 2566 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 2567 Notes.size() + 1) << VD; 2568 Info.Note(VD->getLocation(), diag::note_declared_at); 2569 Info.addNotes(Notes); 2570 } 2571 2572 Result = VD->getEvaluatedValue(); 2573 return true; 2574 } 2575 2576 static bool IsConstNonVolatile(QualType T) { 2577 Qualifiers Quals = T.getQualifiers(); 2578 return Quals.hasConst() && !Quals.hasVolatile(); 2579 } 2580 2581 /// Get the base index of the given base class within an APValue representing 2582 /// the given derived class. 2583 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 2584 const CXXRecordDecl *Base) { 2585 Base = Base->getCanonicalDecl(); 2586 unsigned Index = 0; 2587 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 2588 E = Derived->bases_end(); I != E; ++I, ++Index) { 2589 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 2590 return Index; 2591 } 2592 2593 llvm_unreachable("base class missing from derived class's bases list"); 2594 } 2595 2596 /// Extract the value of a character from a string literal. 2597 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 2598 uint64_t Index) { 2599 assert(!isa<SourceLocExpr>(Lit) && 2600 "SourceLocExpr should have already been converted to a StringLiteral"); 2601 2602 // FIXME: Support MakeStringConstant 2603 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 2604 std::string Str; 2605 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 2606 assert(Index <= Str.size() && "Index too large"); 2607 return APSInt::getUnsigned(Str.c_str()[Index]); 2608 } 2609 2610 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 2611 Lit = PE->getFunctionName(); 2612 const StringLiteral *S = cast<StringLiteral>(Lit); 2613 const ConstantArrayType *CAT = 2614 Info.Ctx.getAsConstantArrayType(S->getType()); 2615 assert(CAT && "string literal isn't an array"); 2616 QualType CharType = CAT->getElementType(); 2617 assert(CharType->isIntegerType() && "unexpected character type"); 2618 2619 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2620 CharType->isUnsignedIntegerType()); 2621 if (Index < S->getLength()) 2622 Value = S->getCodeUnit(Index); 2623 return Value; 2624 } 2625 2626 // Expand a string literal into an array of characters. 2627 // 2628 // FIXME: This is inefficient; we should probably introduce something similar 2629 // to the LLVM ConstantDataArray to make this cheaper. 2630 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 2631 APValue &Result) { 2632 const ConstantArrayType *CAT = 2633 Info.Ctx.getAsConstantArrayType(S->getType()); 2634 assert(CAT && "string literal isn't an array"); 2635 QualType CharType = CAT->getElementType(); 2636 assert(CharType->isIntegerType() && "unexpected character type"); 2637 2638 unsigned Elts = CAT->getSize().getZExtValue(); 2639 Result = APValue(APValue::UninitArray(), 2640 std::min(S->getLength(), Elts), Elts); 2641 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2642 CharType->isUnsignedIntegerType()); 2643 if (Result.hasArrayFiller()) 2644 Result.getArrayFiller() = APValue(Value); 2645 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 2646 Value = S->getCodeUnit(I); 2647 Result.getArrayInitializedElt(I) = APValue(Value); 2648 } 2649 } 2650 2651 // Expand an array so that it has more than Index filled elements. 2652 static void expandArray(APValue &Array, unsigned Index) { 2653 unsigned Size = Array.getArraySize(); 2654 assert(Index < Size); 2655 2656 // Always at least double the number of elements for which we store a value. 2657 unsigned OldElts = Array.getArrayInitializedElts(); 2658 unsigned NewElts = std::max(Index+1, OldElts * 2); 2659 NewElts = std::min(Size, std::max(NewElts, 8u)); 2660 2661 // Copy the data across. 2662 APValue NewValue(APValue::UninitArray(), NewElts, Size); 2663 for (unsigned I = 0; I != OldElts; ++I) 2664 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 2665 for (unsigned I = OldElts; I != NewElts; ++I) 2666 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 2667 if (NewValue.hasArrayFiller()) 2668 NewValue.getArrayFiller() = Array.getArrayFiller(); 2669 Array.swap(NewValue); 2670 } 2671 2672 /// Determine whether a type would actually be read by an lvalue-to-rvalue 2673 /// conversion. If it's of class type, we may assume that the copy operation 2674 /// is trivial. Note that this is never true for a union type with fields 2675 /// (because the copy always "reads" the active member) and always true for 2676 /// a non-class type. 2677 static bool isReadByLvalueToRvalueConversion(QualType T) { 2678 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2679 if (!RD || (RD->isUnion() && !RD->field_empty())) 2680 return true; 2681 if (RD->isEmpty()) 2682 return false; 2683 2684 for (auto *Field : RD->fields()) 2685 if (isReadByLvalueToRvalueConversion(Field->getType())) 2686 return true; 2687 2688 for (auto &BaseSpec : RD->bases()) 2689 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 2690 return true; 2691 2692 return false; 2693 } 2694 2695 /// Diagnose an attempt to read from any unreadable field within the specified 2696 /// type, which might be a class type. 2697 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E, 2698 QualType T) { 2699 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2700 if (!RD) 2701 return false; 2702 2703 if (!RD->hasMutableFields()) 2704 return false; 2705 2706 for (auto *Field : RD->fields()) { 2707 // If we're actually going to read this field in some way, then it can't 2708 // be mutable. If we're in a union, then assigning to a mutable field 2709 // (even an empty one) can change the active member, so that's not OK. 2710 // FIXME: Add core issue number for the union case. 2711 if (Field->isMutable() && 2712 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 2713 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field; 2714 Info.Note(Field->getLocation(), diag::note_declared_at); 2715 return true; 2716 } 2717 2718 if (diagnoseUnreadableFields(Info, E, Field->getType())) 2719 return true; 2720 } 2721 2722 for (auto &BaseSpec : RD->bases()) 2723 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType())) 2724 return true; 2725 2726 // All mutable fields were empty, and thus not actually read. 2727 return false; 2728 } 2729 2730 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 2731 APValue::LValueBase Base) { 2732 // A temporary we created. 2733 if (Base.getCallIndex()) 2734 return true; 2735 2736 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 2737 if (!Evaluating) 2738 return false; 2739 2740 // The variable whose initializer we're evaluating. 2741 if (auto *BaseD = Base.dyn_cast<const ValueDecl*>()) 2742 if (declaresSameEntity(Evaluating, BaseD)) 2743 return true; 2744 2745 // A temporary lifetime-extended by the variable whose initializer we're 2746 // evaluating. 2747 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 2748 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 2749 if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating)) 2750 return true; 2751 2752 return false; 2753 } 2754 2755 namespace { 2756 /// A handle to a complete object (an object that is not a subobject of 2757 /// another object). 2758 struct CompleteObject { 2759 /// The identity of the object. 2760 APValue::LValueBase Base; 2761 /// The value of the complete object. 2762 APValue *Value; 2763 /// The type of the complete object. 2764 QualType Type; 2765 2766 CompleteObject() : Value(nullptr) {} 2767 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 2768 : Base(Base), Value(Value), Type(Type) {} 2769 2770 bool mayReadMutableMembers(EvalInfo &Info) const { 2771 // In C++14 onwards, it is permitted to read a mutable member whose 2772 // lifetime began within the evaluation. 2773 // FIXME: Should we also allow this in C++11? 2774 if (!Info.getLangOpts().CPlusPlus14) 2775 return false; 2776 return lifetimeStartedInEvaluation(Info, Base); 2777 } 2778 2779 explicit operator bool() const { return !Type.isNull(); } 2780 }; 2781 } // end anonymous namespace 2782 2783 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 2784 bool IsMutable = false) { 2785 // C++ [basic.type.qualifier]p1: 2786 // - A const object is an object of type const T or a non-mutable subobject 2787 // of a const object. 2788 if (ObjType.isConstQualified() && !IsMutable) 2789 SubobjType.addConst(); 2790 // - A volatile object is an object of type const T or a subobject of a 2791 // volatile object. 2792 if (ObjType.isVolatileQualified()) 2793 SubobjType.addVolatile(); 2794 return SubobjType; 2795 } 2796 2797 /// Find the designated sub-object of an rvalue. 2798 template<typename SubobjectHandler> 2799 typename SubobjectHandler::result_type 2800 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 2801 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 2802 if (Sub.Invalid) 2803 // A diagnostic will have already been produced. 2804 return handler.failed(); 2805 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 2806 if (Info.getLangOpts().CPlusPlus11) 2807 Info.FFDiag(E, Sub.isOnePastTheEnd() 2808 ? diag::note_constexpr_access_past_end 2809 : diag::note_constexpr_access_unsized_array) 2810 << handler.AccessKind; 2811 else 2812 Info.FFDiag(E); 2813 return handler.failed(); 2814 } 2815 2816 APValue *O = Obj.Value; 2817 QualType ObjType = Obj.Type; 2818 const FieldDecl *LastField = nullptr; 2819 const FieldDecl *VolatileField = nullptr; 2820 2821 // Walk the designator's path to find the subobject. 2822 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 2823 // Reading an indeterminate value is undefined, but assigning over one is OK. 2824 if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) { 2825 if (!Info.checkingPotentialConstantExpression()) 2826 Info.FFDiag(E, diag::note_constexpr_access_uninit) 2827 << handler.AccessKind << O->isIndeterminate(); 2828 return handler.failed(); 2829 } 2830 2831 // C++ [class.ctor]p5: 2832 // const and volatile semantics are not applied on an object under 2833 // construction. 2834 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 2835 ObjType->isRecordType() && 2836 Info.isEvaluatingConstructor( 2837 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 2838 Sub.Entries.begin() + I)) != 2839 ConstructionPhase::None) { 2840 ObjType = Info.Ctx.getCanonicalType(ObjType); 2841 ObjType.removeLocalConst(); 2842 ObjType.removeLocalVolatile(); 2843 } 2844 2845 // If this is our last pass, check that the final object type is OK. 2846 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 2847 // Accesses to volatile objects are prohibited. 2848 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 2849 if (Info.getLangOpts().CPlusPlus) { 2850 int DiagKind; 2851 SourceLocation Loc; 2852 const NamedDecl *Decl = nullptr; 2853 if (VolatileField) { 2854 DiagKind = 2; 2855 Loc = VolatileField->getLocation(); 2856 Decl = VolatileField; 2857 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 2858 DiagKind = 1; 2859 Loc = VD->getLocation(); 2860 Decl = VD; 2861 } else { 2862 DiagKind = 0; 2863 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 2864 Loc = E->getExprLoc(); 2865 } 2866 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 2867 << handler.AccessKind << DiagKind << Decl; 2868 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 2869 } else { 2870 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2871 } 2872 return handler.failed(); 2873 } 2874 2875 // If we are reading an object of class type, there may still be more 2876 // things we need to check: if there are any mutable subobjects, we 2877 // cannot perform this read. (This only happens when performing a trivial 2878 // copy or assignment.) 2879 if (ObjType->isRecordType() && handler.AccessKind == AK_Read && 2880 !Obj.mayReadMutableMembers(Info) && 2881 diagnoseUnreadableFields(Info, E, ObjType)) 2882 return handler.failed(); 2883 } 2884 2885 if (I == N) { 2886 if (!handler.found(*O, ObjType)) 2887 return false; 2888 2889 // If we modified a bit-field, truncate it to the right width. 2890 if (isModification(handler.AccessKind) && 2891 LastField && LastField->isBitField() && 2892 !truncateBitfieldValue(Info, E, *O, LastField)) 2893 return false; 2894 2895 return true; 2896 } 2897 2898 LastField = nullptr; 2899 if (ObjType->isArrayType()) { 2900 // Next subobject is an array element. 2901 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 2902 assert(CAT && "vla in literal type?"); 2903 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 2904 if (CAT->getSize().ule(Index)) { 2905 // Note, it should not be possible to form a pointer with a valid 2906 // designator which points more than one past the end of the array. 2907 if (Info.getLangOpts().CPlusPlus11) 2908 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2909 << handler.AccessKind; 2910 else 2911 Info.FFDiag(E); 2912 return handler.failed(); 2913 } 2914 2915 ObjType = CAT->getElementType(); 2916 2917 if (O->getArrayInitializedElts() > Index) 2918 O = &O->getArrayInitializedElt(Index); 2919 else if (handler.AccessKind != AK_Read) { 2920 expandArray(*O, Index); 2921 O = &O->getArrayInitializedElt(Index); 2922 } else 2923 O = &O->getArrayFiller(); 2924 } else if (ObjType->isAnyComplexType()) { 2925 // Next subobject is a complex number. 2926 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 2927 if (Index > 1) { 2928 if (Info.getLangOpts().CPlusPlus11) 2929 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2930 << handler.AccessKind; 2931 else 2932 Info.FFDiag(E); 2933 return handler.failed(); 2934 } 2935 2936 ObjType = getSubobjectType( 2937 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 2938 2939 assert(I == N - 1 && "extracting subobject of scalar?"); 2940 if (O->isComplexInt()) { 2941 return handler.found(Index ? O->getComplexIntImag() 2942 : O->getComplexIntReal(), ObjType); 2943 } else { 2944 assert(O->isComplexFloat()); 2945 return handler.found(Index ? O->getComplexFloatImag() 2946 : O->getComplexFloatReal(), ObjType); 2947 } 2948 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 2949 if (Field->isMutable() && handler.AccessKind == AK_Read && 2950 !Obj.mayReadMutableMembers(Info)) { 2951 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) 2952 << Field; 2953 Info.Note(Field->getLocation(), diag::note_declared_at); 2954 return handler.failed(); 2955 } 2956 2957 // Next subobject is a class, struct or union field. 2958 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 2959 if (RD->isUnion()) { 2960 const FieldDecl *UnionField = O->getUnionField(); 2961 if (!UnionField || 2962 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 2963 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 2964 << handler.AccessKind << Field << !UnionField << UnionField; 2965 return handler.failed(); 2966 } 2967 O = &O->getUnionValue(); 2968 } else 2969 O = &O->getStructField(Field->getFieldIndex()); 2970 2971 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 2972 LastField = Field; 2973 if (Field->getType().isVolatileQualified()) 2974 VolatileField = Field; 2975 } else { 2976 // Next subobject is a base class. 2977 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 2978 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 2979 O = &O->getStructBase(getBaseIndex(Derived, Base)); 2980 2981 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 2982 } 2983 } 2984 } 2985 2986 namespace { 2987 struct ExtractSubobjectHandler { 2988 EvalInfo &Info; 2989 APValue &Result; 2990 2991 static const AccessKinds AccessKind = AK_Read; 2992 2993 typedef bool result_type; 2994 bool failed() { return false; } 2995 bool found(APValue &Subobj, QualType SubobjType) { 2996 Result = Subobj; 2997 return true; 2998 } 2999 bool found(APSInt &Value, QualType SubobjType) { 3000 Result = APValue(Value); 3001 return true; 3002 } 3003 bool found(APFloat &Value, QualType SubobjType) { 3004 Result = APValue(Value); 3005 return true; 3006 } 3007 }; 3008 } // end anonymous namespace 3009 3010 const AccessKinds ExtractSubobjectHandler::AccessKind; 3011 3012 /// Extract the designated sub-object of an rvalue. 3013 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3014 const CompleteObject &Obj, 3015 const SubobjectDesignator &Sub, 3016 APValue &Result) { 3017 ExtractSubobjectHandler Handler = { Info, Result }; 3018 return findSubobject(Info, E, Obj, Sub, Handler); 3019 } 3020 3021 namespace { 3022 struct ModifySubobjectHandler { 3023 EvalInfo &Info; 3024 APValue &NewVal; 3025 const Expr *E; 3026 3027 typedef bool result_type; 3028 static const AccessKinds AccessKind = AK_Assign; 3029 3030 bool checkConst(QualType QT) { 3031 // Assigning to a const object has undefined behavior. 3032 if (QT.isConstQualified()) { 3033 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3034 return false; 3035 } 3036 return true; 3037 } 3038 3039 bool failed() { return false; } 3040 bool found(APValue &Subobj, QualType SubobjType) { 3041 if (!checkConst(SubobjType)) 3042 return false; 3043 // We've been given ownership of NewVal, so just swap it in. 3044 Subobj.swap(NewVal); 3045 return true; 3046 } 3047 bool found(APSInt &Value, QualType SubobjType) { 3048 if (!checkConst(SubobjType)) 3049 return false; 3050 if (!NewVal.isInt()) { 3051 // Maybe trying to write a cast pointer value into a complex? 3052 Info.FFDiag(E); 3053 return false; 3054 } 3055 Value = NewVal.getInt(); 3056 return true; 3057 } 3058 bool found(APFloat &Value, QualType SubobjType) { 3059 if (!checkConst(SubobjType)) 3060 return false; 3061 Value = NewVal.getFloat(); 3062 return true; 3063 } 3064 }; 3065 } // end anonymous namespace 3066 3067 const AccessKinds ModifySubobjectHandler::AccessKind; 3068 3069 /// Update the designated sub-object of an rvalue to the given value. 3070 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3071 const CompleteObject &Obj, 3072 const SubobjectDesignator &Sub, 3073 APValue &NewVal) { 3074 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3075 return findSubobject(Info, E, Obj, Sub, Handler); 3076 } 3077 3078 /// Find the position where two subobject designators diverge, or equivalently 3079 /// the length of the common initial subsequence. 3080 static unsigned FindDesignatorMismatch(QualType ObjType, 3081 const SubobjectDesignator &A, 3082 const SubobjectDesignator &B, 3083 bool &WasArrayIndex) { 3084 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3085 for (/**/; I != N; ++I) { 3086 if (!ObjType.isNull() && 3087 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3088 // Next subobject is an array element. 3089 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3090 WasArrayIndex = true; 3091 return I; 3092 } 3093 if (ObjType->isAnyComplexType()) 3094 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3095 else 3096 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3097 } else { 3098 if (A.Entries[I].getAsBaseOrMember() != 3099 B.Entries[I].getAsBaseOrMember()) { 3100 WasArrayIndex = false; 3101 return I; 3102 } 3103 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3104 // Next subobject is a field. 3105 ObjType = FD->getType(); 3106 else 3107 // Next subobject is a base class. 3108 ObjType = QualType(); 3109 } 3110 } 3111 WasArrayIndex = false; 3112 return I; 3113 } 3114 3115 /// Determine whether the given subobject designators refer to elements of the 3116 /// same array object. 3117 static bool AreElementsOfSameArray(QualType ObjType, 3118 const SubobjectDesignator &A, 3119 const SubobjectDesignator &B) { 3120 if (A.Entries.size() != B.Entries.size()) 3121 return false; 3122 3123 bool IsArray = A.MostDerivedIsArrayElement; 3124 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3125 // A is a subobject of the array element. 3126 return false; 3127 3128 // If A (and B) designates an array element, the last entry will be the array 3129 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3130 // of length 1' case, and the entire path must match. 3131 bool WasArrayIndex; 3132 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3133 return CommonLength >= A.Entries.size() - IsArray; 3134 } 3135 3136 /// Find the complete object to which an LValue refers. 3137 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3138 AccessKinds AK, const LValue &LVal, 3139 QualType LValType) { 3140 if (LVal.InvalidBase) { 3141 Info.FFDiag(E); 3142 return CompleteObject(); 3143 } 3144 3145 if (!LVal.Base) { 3146 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3147 return CompleteObject(); 3148 } 3149 3150 CallStackFrame *Frame = nullptr; 3151 unsigned Depth = 0; 3152 if (LVal.getLValueCallIndex()) { 3153 std::tie(Frame, Depth) = 3154 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3155 if (!Frame) { 3156 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3157 << AK << LVal.Base.is<const ValueDecl*>(); 3158 NoteLValueLocation(Info, LVal.Base); 3159 return CompleteObject(); 3160 } 3161 } 3162 3163 bool IsAccess = isFormalAccess(AK); 3164 3165 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3166 // is not a constant expression (even if the object is non-volatile). We also 3167 // apply this rule to C++98, in order to conform to the expected 'volatile' 3168 // semantics. 3169 if (IsAccess && LValType.isVolatileQualified()) { 3170 if (Info.getLangOpts().CPlusPlus) 3171 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3172 << AK << LValType; 3173 else 3174 Info.FFDiag(E); 3175 return CompleteObject(); 3176 } 3177 3178 // Compute value storage location and type of base object. 3179 APValue *BaseVal = nullptr; 3180 QualType BaseType = getType(LVal.Base); 3181 3182 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 3183 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3184 // In C++11, constexpr, non-volatile variables initialized with constant 3185 // expressions are constant expressions too. Inside constexpr functions, 3186 // parameters are constant expressions even if they're non-const. 3187 // In C++1y, objects local to a constant expression (those with a Frame) are 3188 // both readable and writable inside constant expressions. 3189 // In C, such things can also be folded, although they are not ICEs. 3190 const VarDecl *VD = dyn_cast<VarDecl>(D); 3191 if (VD) { 3192 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3193 VD = VDef; 3194 } 3195 if (!VD || VD->isInvalidDecl()) { 3196 Info.FFDiag(E); 3197 return CompleteObject(); 3198 } 3199 3200 // Unless we're looking at a local variable or argument in a constexpr call, 3201 // the variable we're reading must be const. 3202 if (!Frame) { 3203 if (Info.getLangOpts().CPlusPlus14 && 3204 declaresSameEntity( 3205 VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) { 3206 // OK, we can read and modify an object if we're in the process of 3207 // evaluating its initializer, because its lifetime began in this 3208 // evaluation. 3209 } else if (isModification(AK)) { 3210 // All the remaining cases do not permit modification of the object. 3211 Info.FFDiag(E, diag::note_constexpr_modify_global); 3212 return CompleteObject(); 3213 } else if (VD->isConstexpr()) { 3214 // OK, we can read this variable. 3215 } else if (BaseType->isIntegralOrEnumerationType()) { 3216 // In OpenCL if a variable is in constant address space it is a const 3217 // value. 3218 if (!(BaseType.isConstQualified() || 3219 (Info.getLangOpts().OpenCL && 3220 BaseType.getAddressSpace() == LangAS::opencl_constant))) { 3221 if (!IsAccess) 3222 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3223 if (Info.getLangOpts().CPlusPlus) { 3224 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3225 Info.Note(VD->getLocation(), diag::note_declared_at); 3226 } else { 3227 Info.FFDiag(E); 3228 } 3229 return CompleteObject(); 3230 } 3231 } else if (!IsAccess) { 3232 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3233 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { 3234 // We support folding of const floating-point types, in order to make 3235 // static const data members of such types (supported as an extension) 3236 // more useful. 3237 if (Info.getLangOpts().CPlusPlus11) { 3238 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3239 Info.Note(VD->getLocation(), diag::note_declared_at); 3240 } else { 3241 Info.CCEDiag(E); 3242 } 3243 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { 3244 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; 3245 // Keep evaluating to see what we can do. 3246 } else { 3247 // FIXME: Allow folding of values of any literal type in all languages. 3248 if (Info.checkingPotentialConstantExpression() && 3249 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { 3250 // The definition of this variable could be constexpr. We can't 3251 // access it right now, but may be able to in future. 3252 } else if (Info.getLangOpts().CPlusPlus11) { 3253 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3254 Info.Note(VD->getLocation(), diag::note_declared_at); 3255 } else { 3256 Info.FFDiag(E); 3257 } 3258 return CompleteObject(); 3259 } 3260 } 3261 3262 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3263 return CompleteObject(); 3264 } else { 3265 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3266 3267 if (!Frame) { 3268 if (const MaterializeTemporaryExpr *MTE = 3269 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 3270 assert(MTE->getStorageDuration() == SD_Static && 3271 "should have a frame for a non-global materialized temporary"); 3272 3273 // Per C++1y [expr.const]p2: 3274 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3275 // - a [...] glvalue of integral or enumeration type that refers to 3276 // a non-volatile const object [...] 3277 // [...] 3278 // - a [...] glvalue of literal type that refers to a non-volatile 3279 // object whose lifetime began within the evaluation of e. 3280 // 3281 // C++11 misses the 'began within the evaluation of e' check and 3282 // instead allows all temporaries, including things like: 3283 // int &&r = 1; 3284 // int x = ++r; 3285 // constexpr int k = r; 3286 // Therefore we use the C++14 rules in C++11 too. 3287 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3288 const ValueDecl *ED = MTE->getExtendingDecl(); 3289 if (!(BaseType.isConstQualified() && 3290 BaseType->isIntegralOrEnumerationType()) && 3291 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) { 3292 if (!IsAccess) 3293 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3294 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3295 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3296 return CompleteObject(); 3297 } 3298 3299 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false); 3300 assert(BaseVal && "got reference to unevaluated temporary"); 3301 } else { 3302 if (!IsAccess) 3303 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3304 APValue Val; 3305 LVal.moveInto(Val); 3306 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 3307 << AK 3308 << Val.getAsString(Info.Ctx, 3309 Info.Ctx.getLValueReferenceType(LValType)); 3310 NoteLValueLocation(Info, LVal.Base); 3311 return CompleteObject(); 3312 } 3313 } else { 3314 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 3315 assert(BaseVal && "missing value for temporary"); 3316 } 3317 } 3318 3319 // In C++14, we can't safely access any mutable state when we might be 3320 // evaluating after an unmodeled side effect. 3321 // 3322 // FIXME: Not all local state is mutable. Allow local constant subobjects 3323 // to be read here (but take care with 'mutable' fields). 3324 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3325 Info.EvalStatus.HasSideEffects) || 3326 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth)) 3327 return CompleteObject(); 3328 3329 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 3330 } 3331 3332 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 3333 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3334 /// glvalue referred to by an entity of reference type. 3335 /// 3336 /// \param Info - Information about the ongoing evaluation. 3337 /// \param Conv - The expression for which we are performing the conversion. 3338 /// Used for diagnostics. 3339 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 3340 /// case of a non-class type). 3341 /// \param LVal - The glvalue on which we are attempting to perform this action. 3342 /// \param RVal - The produced value will be placed here. 3343 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 3344 QualType Type, 3345 const LValue &LVal, APValue &RVal) { 3346 if (LVal.Designator.Invalid) 3347 return false; 3348 3349 // Check for special cases where there is no existing APValue to look at. 3350 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3351 3352 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 3353 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 3354 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 3355 // initializer until now for such expressions. Such an expression can't be 3356 // an ICE in C, so this only matters for fold. 3357 if (Type.isVolatileQualified()) { 3358 Info.FFDiag(Conv); 3359 return false; 3360 } 3361 APValue Lit; 3362 if (!Evaluate(Lit, Info, CLE->getInitializer())) 3363 return false; 3364 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 3365 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal); 3366 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 3367 // Special-case character extraction so we don't have to construct an 3368 // APValue for the whole string. 3369 assert(LVal.Designator.Entries.size() <= 1 && 3370 "Can only read characters from string literals"); 3371 if (LVal.Designator.Entries.empty()) { 3372 // Fail for now for LValue to RValue conversion of an array. 3373 // (This shouldn't show up in C/C++, but it could be triggered by a 3374 // weird EvaluateAsRValue call from a tool.) 3375 Info.FFDiag(Conv); 3376 return false; 3377 } 3378 if (LVal.Designator.isOnePastTheEnd()) { 3379 if (Info.getLangOpts().CPlusPlus11) 3380 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read; 3381 else 3382 Info.FFDiag(Conv); 3383 return false; 3384 } 3385 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 3386 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 3387 return true; 3388 } 3389 } 3390 3391 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type); 3392 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal); 3393 } 3394 3395 /// Perform an assignment of Val to LVal. Takes ownership of Val. 3396 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 3397 QualType LValType, APValue &Val) { 3398 if (LVal.Designator.Invalid) 3399 return false; 3400 3401 if (!Info.getLangOpts().CPlusPlus14) { 3402 Info.FFDiag(E); 3403 return false; 3404 } 3405 3406 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3407 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 3408 } 3409 3410 namespace { 3411 struct CompoundAssignSubobjectHandler { 3412 EvalInfo &Info; 3413 const Expr *E; 3414 QualType PromotedLHSType; 3415 BinaryOperatorKind Opcode; 3416 const APValue &RHS; 3417 3418 static const AccessKinds AccessKind = AK_Assign; 3419 3420 typedef bool result_type; 3421 3422 bool checkConst(QualType QT) { 3423 // Assigning to a const object has undefined behavior. 3424 if (QT.isConstQualified()) { 3425 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3426 return false; 3427 } 3428 return true; 3429 } 3430 3431 bool failed() { return false; } 3432 bool found(APValue &Subobj, QualType SubobjType) { 3433 switch (Subobj.getKind()) { 3434 case APValue::Int: 3435 return found(Subobj.getInt(), SubobjType); 3436 case APValue::Float: 3437 return found(Subobj.getFloat(), SubobjType); 3438 case APValue::ComplexInt: 3439 case APValue::ComplexFloat: 3440 // FIXME: Implement complex compound assignment. 3441 Info.FFDiag(E); 3442 return false; 3443 case APValue::LValue: 3444 return foundPointer(Subobj, SubobjType); 3445 default: 3446 // FIXME: can this happen? 3447 Info.FFDiag(E); 3448 return false; 3449 } 3450 } 3451 bool found(APSInt &Value, QualType SubobjType) { 3452 if (!checkConst(SubobjType)) 3453 return false; 3454 3455 if (!SubobjType->isIntegerType()) { 3456 // We don't support compound assignment on integer-cast-to-pointer 3457 // values. 3458 Info.FFDiag(E); 3459 return false; 3460 } 3461 3462 if (RHS.isInt()) { 3463 APSInt LHS = 3464 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 3465 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 3466 return false; 3467 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 3468 return true; 3469 } else if (RHS.isFloat()) { 3470 APFloat FValue(0.0); 3471 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, 3472 FValue) && 3473 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 3474 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 3475 Value); 3476 } 3477 3478 Info.FFDiag(E); 3479 return false; 3480 } 3481 bool found(APFloat &Value, QualType SubobjType) { 3482 return checkConst(SubobjType) && 3483 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 3484 Value) && 3485 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 3486 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 3487 } 3488 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3489 if (!checkConst(SubobjType)) 3490 return false; 3491 3492 QualType PointeeType; 3493 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3494 PointeeType = PT->getPointeeType(); 3495 3496 if (PointeeType.isNull() || !RHS.isInt() || 3497 (Opcode != BO_Add && Opcode != BO_Sub)) { 3498 Info.FFDiag(E); 3499 return false; 3500 } 3501 3502 APSInt Offset = RHS.getInt(); 3503 if (Opcode == BO_Sub) 3504 negateAsSigned(Offset); 3505 3506 LValue LVal; 3507 LVal.setFrom(Info.Ctx, Subobj); 3508 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 3509 return false; 3510 LVal.moveInto(Subobj); 3511 return true; 3512 } 3513 }; 3514 } // end anonymous namespace 3515 3516 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 3517 3518 /// Perform a compound assignment of LVal <op>= RVal. 3519 static bool handleCompoundAssignment( 3520 EvalInfo &Info, const Expr *E, 3521 const LValue &LVal, QualType LValType, QualType PromotedLValType, 3522 BinaryOperatorKind Opcode, const APValue &RVal) { 3523 if (LVal.Designator.Invalid) 3524 return false; 3525 3526 if (!Info.getLangOpts().CPlusPlus14) { 3527 Info.FFDiag(E); 3528 return false; 3529 } 3530 3531 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3532 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 3533 RVal }; 3534 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3535 } 3536 3537 namespace { 3538 struct IncDecSubobjectHandler { 3539 EvalInfo &Info; 3540 const UnaryOperator *E; 3541 AccessKinds AccessKind; 3542 APValue *Old; 3543 3544 typedef bool result_type; 3545 3546 bool checkConst(QualType QT) { 3547 // Assigning to a const object has undefined behavior. 3548 if (QT.isConstQualified()) { 3549 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3550 return false; 3551 } 3552 return true; 3553 } 3554 3555 bool failed() { return false; } 3556 bool found(APValue &Subobj, QualType SubobjType) { 3557 // Stash the old value. Also clear Old, so we don't clobber it later 3558 // if we're post-incrementing a complex. 3559 if (Old) { 3560 *Old = Subobj; 3561 Old = nullptr; 3562 } 3563 3564 switch (Subobj.getKind()) { 3565 case APValue::Int: 3566 return found(Subobj.getInt(), SubobjType); 3567 case APValue::Float: 3568 return found(Subobj.getFloat(), SubobjType); 3569 case APValue::ComplexInt: 3570 return found(Subobj.getComplexIntReal(), 3571 SubobjType->castAs<ComplexType>()->getElementType() 3572 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3573 case APValue::ComplexFloat: 3574 return found(Subobj.getComplexFloatReal(), 3575 SubobjType->castAs<ComplexType>()->getElementType() 3576 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3577 case APValue::LValue: 3578 return foundPointer(Subobj, SubobjType); 3579 default: 3580 // FIXME: can this happen? 3581 Info.FFDiag(E); 3582 return false; 3583 } 3584 } 3585 bool found(APSInt &Value, QualType SubobjType) { 3586 if (!checkConst(SubobjType)) 3587 return false; 3588 3589 if (!SubobjType->isIntegerType()) { 3590 // We don't support increment / decrement on integer-cast-to-pointer 3591 // values. 3592 Info.FFDiag(E); 3593 return false; 3594 } 3595 3596 if (Old) *Old = APValue(Value); 3597 3598 // bool arithmetic promotes to int, and the conversion back to bool 3599 // doesn't reduce mod 2^n, so special-case it. 3600 if (SubobjType->isBooleanType()) { 3601 if (AccessKind == AK_Increment) 3602 Value = 1; 3603 else 3604 Value = !Value; 3605 return true; 3606 } 3607 3608 bool WasNegative = Value.isNegative(); 3609 if (AccessKind == AK_Increment) { 3610 ++Value; 3611 3612 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 3613 APSInt ActualValue(Value, /*IsUnsigned*/true); 3614 return HandleOverflow(Info, E, ActualValue, SubobjType); 3615 } 3616 } else { 3617 --Value; 3618 3619 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 3620 unsigned BitWidth = Value.getBitWidth(); 3621 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 3622 ActualValue.setBit(BitWidth); 3623 return HandleOverflow(Info, E, ActualValue, SubobjType); 3624 } 3625 } 3626 return true; 3627 } 3628 bool found(APFloat &Value, QualType SubobjType) { 3629 if (!checkConst(SubobjType)) 3630 return false; 3631 3632 if (Old) *Old = APValue(Value); 3633 3634 APFloat One(Value.getSemantics(), 1); 3635 if (AccessKind == AK_Increment) 3636 Value.add(One, APFloat::rmNearestTiesToEven); 3637 else 3638 Value.subtract(One, APFloat::rmNearestTiesToEven); 3639 return true; 3640 } 3641 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3642 if (!checkConst(SubobjType)) 3643 return false; 3644 3645 QualType PointeeType; 3646 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3647 PointeeType = PT->getPointeeType(); 3648 else { 3649 Info.FFDiag(E); 3650 return false; 3651 } 3652 3653 LValue LVal; 3654 LVal.setFrom(Info.Ctx, Subobj); 3655 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 3656 AccessKind == AK_Increment ? 1 : -1)) 3657 return false; 3658 LVal.moveInto(Subobj); 3659 return true; 3660 } 3661 }; 3662 } // end anonymous namespace 3663 3664 /// Perform an increment or decrement on LVal. 3665 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 3666 QualType LValType, bool IsIncrement, APValue *Old) { 3667 if (LVal.Designator.Invalid) 3668 return false; 3669 3670 if (!Info.getLangOpts().CPlusPlus14) { 3671 Info.FFDiag(E); 3672 return false; 3673 } 3674 3675 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 3676 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 3677 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 3678 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3679 } 3680 3681 /// Build an lvalue for the object argument of a member function call. 3682 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 3683 LValue &This) { 3684 if (Object->getType()->isPointerType()) 3685 return EvaluatePointer(Object, This, Info); 3686 3687 if (Object->isGLValue()) 3688 return EvaluateLValue(Object, This, Info); 3689 3690 if (Object->getType()->isLiteralType(Info.Ctx)) 3691 return EvaluateTemporary(Object, This, Info); 3692 3693 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 3694 return false; 3695 } 3696 3697 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 3698 /// lvalue referring to the result. 3699 /// 3700 /// \param Info - Information about the ongoing evaluation. 3701 /// \param LV - An lvalue referring to the base of the member pointer. 3702 /// \param RHS - The member pointer expression. 3703 /// \param IncludeMember - Specifies whether the member itself is included in 3704 /// the resulting LValue subobject designator. This is not possible when 3705 /// creating a bound member function. 3706 /// \return The field or method declaration to which the member pointer refers, 3707 /// or 0 if evaluation fails. 3708 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3709 QualType LVType, 3710 LValue &LV, 3711 const Expr *RHS, 3712 bool IncludeMember = true) { 3713 MemberPtr MemPtr; 3714 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 3715 return nullptr; 3716 3717 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 3718 // member value, the behavior is undefined. 3719 if (!MemPtr.getDecl()) { 3720 // FIXME: Specific diagnostic. 3721 Info.FFDiag(RHS); 3722 return nullptr; 3723 } 3724 3725 if (MemPtr.isDerivedMember()) { 3726 // This is a member of some derived class. Truncate LV appropriately. 3727 // The end of the derived-to-base path for the base object must match the 3728 // derived-to-base path for the member pointer. 3729 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 3730 LV.Designator.Entries.size()) { 3731 Info.FFDiag(RHS); 3732 return nullptr; 3733 } 3734 unsigned PathLengthToMember = 3735 LV.Designator.Entries.size() - MemPtr.Path.size(); 3736 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 3737 const CXXRecordDecl *LVDecl = getAsBaseClass( 3738 LV.Designator.Entries[PathLengthToMember + I]); 3739 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 3740 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 3741 Info.FFDiag(RHS); 3742 return nullptr; 3743 } 3744 } 3745 3746 // Truncate the lvalue to the appropriate derived class. 3747 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 3748 PathLengthToMember)) 3749 return nullptr; 3750 } else if (!MemPtr.Path.empty()) { 3751 // Extend the LValue path with the member pointer's path. 3752 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 3753 MemPtr.Path.size() + IncludeMember); 3754 3755 // Walk down to the appropriate base class. 3756 if (const PointerType *PT = LVType->getAs<PointerType>()) 3757 LVType = PT->getPointeeType(); 3758 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 3759 assert(RD && "member pointer access on non-class-type expression"); 3760 // The first class in the path is that of the lvalue. 3761 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 3762 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 3763 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 3764 return nullptr; 3765 RD = Base; 3766 } 3767 // Finally cast to the class containing the member. 3768 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 3769 MemPtr.getContainingRecord())) 3770 return nullptr; 3771 } 3772 3773 // Add the member. Note that we cannot build bound member functions here. 3774 if (IncludeMember) { 3775 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 3776 if (!HandleLValueMember(Info, RHS, LV, FD)) 3777 return nullptr; 3778 } else if (const IndirectFieldDecl *IFD = 3779 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 3780 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 3781 return nullptr; 3782 } else { 3783 llvm_unreachable("can't construct reference to bound member function"); 3784 } 3785 } 3786 3787 return MemPtr.getDecl(); 3788 } 3789 3790 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3791 const BinaryOperator *BO, 3792 LValue &LV, 3793 bool IncludeMember = true) { 3794 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 3795 3796 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 3797 if (Info.noteFailure()) { 3798 MemberPtr MemPtr; 3799 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 3800 } 3801 return nullptr; 3802 } 3803 3804 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 3805 BO->getRHS(), IncludeMember); 3806 } 3807 3808 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 3809 /// the provided lvalue, which currently refers to the base object. 3810 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 3811 LValue &Result) { 3812 SubobjectDesignator &D = Result.Designator; 3813 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 3814 return false; 3815 3816 QualType TargetQT = E->getType(); 3817 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 3818 TargetQT = PT->getPointeeType(); 3819 3820 // Check this cast lands within the final derived-to-base subobject path. 3821 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 3822 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3823 << D.MostDerivedType << TargetQT; 3824 return false; 3825 } 3826 3827 // Check the type of the final cast. We don't need to check the path, 3828 // since a cast can only be formed if the path is unique. 3829 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 3830 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 3831 const CXXRecordDecl *FinalType; 3832 if (NewEntriesSize == D.MostDerivedPathLength) 3833 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 3834 else 3835 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 3836 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 3837 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3838 << D.MostDerivedType << TargetQT; 3839 return false; 3840 } 3841 3842 // Truncate the lvalue to the appropriate derived class. 3843 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 3844 } 3845 3846 namespace { 3847 enum EvalStmtResult { 3848 /// Evaluation failed. 3849 ESR_Failed, 3850 /// Hit a 'return' statement. 3851 ESR_Returned, 3852 /// Evaluation succeeded. 3853 ESR_Succeeded, 3854 /// Hit a 'continue' statement. 3855 ESR_Continue, 3856 /// Hit a 'break' statement. 3857 ESR_Break, 3858 /// Still scanning for 'case' or 'default' statement. 3859 ESR_CaseNotFound 3860 }; 3861 } 3862 3863 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 3864 // We don't need to evaluate the initializer for a static local. 3865 if (!VD->hasLocalStorage()) 3866 return true; 3867 3868 LValue Result; 3869 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall); 3870 3871 const Expr *InitE = VD->getInit(); 3872 if (!InitE) { 3873 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized) 3874 << false << VD->getType(); 3875 Val = APValue(); 3876 return false; 3877 } 3878 3879 if (InitE->isValueDependent()) 3880 return false; 3881 3882 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 3883 // Wipe out any partially-computed value, to allow tracking that this 3884 // evaluation failed. 3885 Val = APValue(); 3886 return false; 3887 } 3888 3889 return true; 3890 } 3891 3892 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 3893 bool OK = true; 3894 3895 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 3896 OK &= EvaluateVarDecl(Info, VD); 3897 3898 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 3899 for (auto *BD : DD->bindings()) 3900 if (auto *VD = BD->getHoldingVar()) 3901 OK &= EvaluateDecl(Info, VD); 3902 3903 return OK; 3904 } 3905 3906 3907 /// Evaluate a condition (either a variable declaration or an expression). 3908 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 3909 const Expr *Cond, bool &Result) { 3910 FullExpressionRAII Scope(Info); 3911 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 3912 return false; 3913 return EvaluateAsBooleanCondition(Cond, Result, Info); 3914 } 3915 3916 namespace { 3917 /// A location where the result (returned value) of evaluating a 3918 /// statement should be stored. 3919 struct StmtResult { 3920 /// The APValue that should be filled in with the returned value. 3921 APValue &Value; 3922 /// The location containing the result, if any (used to support RVO). 3923 const LValue *Slot; 3924 }; 3925 3926 struct TempVersionRAII { 3927 CallStackFrame &Frame; 3928 3929 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 3930 Frame.pushTempVersion(); 3931 } 3932 3933 ~TempVersionRAII() { 3934 Frame.popTempVersion(); 3935 } 3936 }; 3937 3938 } 3939 3940 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 3941 const Stmt *S, 3942 const SwitchCase *SC = nullptr); 3943 3944 /// Evaluate the body of a loop, and translate the result as appropriate. 3945 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 3946 const Stmt *Body, 3947 const SwitchCase *Case = nullptr) { 3948 BlockScopeRAII Scope(Info); 3949 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) { 3950 case ESR_Break: 3951 return ESR_Succeeded; 3952 case ESR_Succeeded: 3953 case ESR_Continue: 3954 return ESR_Continue; 3955 case ESR_Failed: 3956 case ESR_Returned: 3957 case ESR_CaseNotFound: 3958 return ESR; 3959 } 3960 llvm_unreachable("Invalid EvalStmtResult!"); 3961 } 3962 3963 /// Evaluate a switch statement. 3964 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 3965 const SwitchStmt *SS) { 3966 BlockScopeRAII Scope(Info); 3967 3968 // Evaluate the switch condition. 3969 APSInt Value; 3970 { 3971 FullExpressionRAII Scope(Info); 3972 if (const Stmt *Init = SS->getInit()) { 3973 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 3974 if (ESR != ESR_Succeeded) 3975 return ESR; 3976 } 3977 if (SS->getConditionVariable() && 3978 !EvaluateDecl(Info, SS->getConditionVariable())) 3979 return ESR_Failed; 3980 if (!EvaluateInteger(SS->getCond(), Value, Info)) 3981 return ESR_Failed; 3982 } 3983 3984 // Find the switch case corresponding to the value of the condition. 3985 // FIXME: Cache this lookup. 3986 const SwitchCase *Found = nullptr; 3987 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 3988 SC = SC->getNextSwitchCase()) { 3989 if (isa<DefaultStmt>(SC)) { 3990 Found = SC; 3991 continue; 3992 } 3993 3994 const CaseStmt *CS = cast<CaseStmt>(SC); 3995 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 3996 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 3997 : LHS; 3998 if (LHS <= Value && Value <= RHS) { 3999 Found = SC; 4000 break; 4001 } 4002 } 4003 4004 if (!Found) 4005 return ESR_Succeeded; 4006 4007 // Search the switch body for the switch case and evaluate it from there. 4008 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) { 4009 case ESR_Break: 4010 return ESR_Succeeded; 4011 case ESR_Succeeded: 4012 case ESR_Continue: 4013 case ESR_Failed: 4014 case ESR_Returned: 4015 return ESR; 4016 case ESR_CaseNotFound: 4017 // This can only happen if the switch case is nested within a statement 4018 // expression. We have no intention of supporting that. 4019 Info.FFDiag(Found->getBeginLoc(), 4020 diag::note_constexpr_stmt_expr_unsupported); 4021 return ESR_Failed; 4022 } 4023 llvm_unreachable("Invalid EvalStmtResult!"); 4024 } 4025 4026 // Evaluate a statement. 4027 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4028 const Stmt *S, const SwitchCase *Case) { 4029 if (!Info.nextStep(S)) 4030 return ESR_Failed; 4031 4032 // If we're hunting down a 'case' or 'default' label, recurse through 4033 // substatements until we hit the label. 4034 if (Case) { 4035 // FIXME: We don't start the lifetime of objects whose initialization we 4036 // jump over. However, such objects must be of class type with a trivial 4037 // default constructor that initialize all subobjects, so must be empty, 4038 // so this almost never matters. 4039 switch (S->getStmtClass()) { 4040 case Stmt::CompoundStmtClass: 4041 // FIXME: Precompute which substatement of a compound statement we 4042 // would jump to, and go straight there rather than performing a 4043 // linear scan each time. 4044 case Stmt::LabelStmtClass: 4045 case Stmt::AttributedStmtClass: 4046 case Stmt::DoStmtClass: 4047 break; 4048 4049 case Stmt::CaseStmtClass: 4050 case Stmt::DefaultStmtClass: 4051 if (Case == S) 4052 Case = nullptr; 4053 break; 4054 4055 case Stmt::IfStmtClass: { 4056 // FIXME: Precompute which side of an 'if' we would jump to, and go 4057 // straight there rather than scanning both sides. 4058 const IfStmt *IS = cast<IfStmt>(S); 4059 4060 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4061 // preceded by our switch label. 4062 BlockScopeRAII Scope(Info); 4063 4064 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4065 if (ESR != ESR_CaseNotFound || !IS->getElse()) 4066 return ESR; 4067 return EvaluateStmt(Result, Info, IS->getElse(), Case); 4068 } 4069 4070 case Stmt::WhileStmtClass: { 4071 EvalStmtResult ESR = 4072 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4073 if (ESR != ESR_Continue) 4074 return ESR; 4075 break; 4076 } 4077 4078 case Stmt::ForStmtClass: { 4079 const ForStmt *FS = cast<ForStmt>(S); 4080 EvalStmtResult ESR = 4081 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4082 if (ESR != ESR_Continue) 4083 return ESR; 4084 if (FS->getInc()) { 4085 FullExpressionRAII IncScope(Info); 4086 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4087 return ESR_Failed; 4088 } 4089 break; 4090 } 4091 4092 case Stmt::DeclStmtClass: 4093 // FIXME: If the variable has initialization that can't be jumped over, 4094 // bail out of any immediately-surrounding compound-statement too. 4095 default: 4096 return ESR_CaseNotFound; 4097 } 4098 } 4099 4100 switch (S->getStmtClass()) { 4101 default: 4102 if (const Expr *E = dyn_cast<Expr>(S)) { 4103 // Don't bother evaluating beyond an expression-statement which couldn't 4104 // be evaluated. 4105 FullExpressionRAII Scope(Info); 4106 if (!EvaluateIgnoredValue(Info, E)) 4107 return ESR_Failed; 4108 return ESR_Succeeded; 4109 } 4110 4111 Info.FFDiag(S->getBeginLoc()); 4112 return ESR_Failed; 4113 4114 case Stmt::NullStmtClass: 4115 return ESR_Succeeded; 4116 4117 case Stmt::DeclStmtClass: { 4118 const DeclStmt *DS = cast<DeclStmt>(S); 4119 for (const auto *DclIt : DS->decls()) { 4120 // Each declaration initialization is its own full-expression. 4121 // FIXME: This isn't quite right; if we're performing aggregate 4122 // initialization, each braced subexpression is its own full-expression. 4123 FullExpressionRAII Scope(Info); 4124 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure()) 4125 return ESR_Failed; 4126 } 4127 return ESR_Succeeded; 4128 } 4129 4130 case Stmt::ReturnStmtClass: { 4131 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4132 FullExpressionRAII Scope(Info); 4133 if (RetExpr && 4134 !(Result.Slot 4135 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4136 : Evaluate(Result.Value, Info, RetExpr))) 4137 return ESR_Failed; 4138 return ESR_Returned; 4139 } 4140 4141 case Stmt::CompoundStmtClass: { 4142 BlockScopeRAII Scope(Info); 4143 4144 const CompoundStmt *CS = cast<CompoundStmt>(S); 4145 for (const auto *BI : CS->body()) { 4146 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4147 if (ESR == ESR_Succeeded) 4148 Case = nullptr; 4149 else if (ESR != ESR_CaseNotFound) 4150 return ESR; 4151 } 4152 return Case ? ESR_CaseNotFound : ESR_Succeeded; 4153 } 4154 4155 case Stmt::IfStmtClass: { 4156 const IfStmt *IS = cast<IfStmt>(S); 4157 4158 // Evaluate the condition, as either a var decl or as an expression. 4159 BlockScopeRAII Scope(Info); 4160 if (const Stmt *Init = IS->getInit()) { 4161 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4162 if (ESR != ESR_Succeeded) 4163 return ESR; 4164 } 4165 bool Cond; 4166 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 4167 return ESR_Failed; 4168 4169 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 4170 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 4171 if (ESR != ESR_Succeeded) 4172 return ESR; 4173 } 4174 return ESR_Succeeded; 4175 } 4176 4177 case Stmt::WhileStmtClass: { 4178 const WhileStmt *WS = cast<WhileStmt>(S); 4179 while (true) { 4180 BlockScopeRAII Scope(Info); 4181 bool Continue; 4182 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 4183 Continue)) 4184 return ESR_Failed; 4185 if (!Continue) 4186 break; 4187 4188 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 4189 if (ESR != ESR_Continue) 4190 return ESR; 4191 } 4192 return ESR_Succeeded; 4193 } 4194 4195 case Stmt::DoStmtClass: { 4196 const DoStmt *DS = cast<DoStmt>(S); 4197 bool Continue; 4198 do { 4199 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 4200 if (ESR != ESR_Continue) 4201 return ESR; 4202 Case = nullptr; 4203 4204 FullExpressionRAII CondScope(Info); 4205 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info)) 4206 return ESR_Failed; 4207 } while (Continue); 4208 return ESR_Succeeded; 4209 } 4210 4211 case Stmt::ForStmtClass: { 4212 const ForStmt *FS = cast<ForStmt>(S); 4213 BlockScopeRAII Scope(Info); 4214 if (FS->getInit()) { 4215 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4216 if (ESR != ESR_Succeeded) 4217 return ESR; 4218 } 4219 while (true) { 4220 BlockScopeRAII Scope(Info); 4221 bool Continue = true; 4222 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 4223 FS->getCond(), Continue)) 4224 return ESR_Failed; 4225 if (!Continue) 4226 break; 4227 4228 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4229 if (ESR != ESR_Continue) 4230 return ESR; 4231 4232 if (FS->getInc()) { 4233 FullExpressionRAII IncScope(Info); 4234 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4235 return ESR_Failed; 4236 } 4237 } 4238 return ESR_Succeeded; 4239 } 4240 4241 case Stmt::CXXForRangeStmtClass: { 4242 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 4243 BlockScopeRAII Scope(Info); 4244 4245 // Evaluate the init-statement if present. 4246 if (FS->getInit()) { 4247 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4248 if (ESR != ESR_Succeeded) 4249 return ESR; 4250 } 4251 4252 // Initialize the __range variable. 4253 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 4254 if (ESR != ESR_Succeeded) 4255 return ESR; 4256 4257 // Create the __begin and __end iterators. 4258 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 4259 if (ESR != ESR_Succeeded) 4260 return ESR; 4261 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 4262 if (ESR != ESR_Succeeded) 4263 return ESR; 4264 4265 while (true) { 4266 // Condition: __begin != __end. 4267 { 4268 bool Continue = true; 4269 FullExpressionRAII CondExpr(Info); 4270 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 4271 return ESR_Failed; 4272 if (!Continue) 4273 break; 4274 } 4275 4276 // User's variable declaration, initialized by *__begin. 4277 BlockScopeRAII InnerScope(Info); 4278 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 4279 if (ESR != ESR_Succeeded) 4280 return ESR; 4281 4282 // Loop body. 4283 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4284 if (ESR != ESR_Continue) 4285 return ESR; 4286 4287 // Increment: ++__begin 4288 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4289 return ESR_Failed; 4290 } 4291 4292 return ESR_Succeeded; 4293 } 4294 4295 case Stmt::SwitchStmtClass: 4296 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 4297 4298 case Stmt::ContinueStmtClass: 4299 return ESR_Continue; 4300 4301 case Stmt::BreakStmtClass: 4302 return ESR_Break; 4303 4304 case Stmt::LabelStmtClass: 4305 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 4306 4307 case Stmt::AttributedStmtClass: 4308 // As a general principle, C++11 attributes can be ignored without 4309 // any semantic impact. 4310 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 4311 Case); 4312 4313 case Stmt::CaseStmtClass: 4314 case Stmt::DefaultStmtClass: 4315 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 4316 case Stmt::CXXTryStmtClass: 4317 // Evaluate try blocks by evaluating all sub statements. 4318 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 4319 } 4320 } 4321 4322 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 4323 /// default constructor. If so, we'll fold it whether or not it's marked as 4324 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 4325 /// so we need special handling. 4326 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 4327 const CXXConstructorDecl *CD, 4328 bool IsValueInitialization) { 4329 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 4330 return false; 4331 4332 // Value-initialization does not call a trivial default constructor, so such a 4333 // call is a core constant expression whether or not the constructor is 4334 // constexpr. 4335 if (!CD->isConstexpr() && !IsValueInitialization) { 4336 if (Info.getLangOpts().CPlusPlus11) { 4337 // FIXME: If DiagDecl is an implicitly-declared special member function, 4338 // we should be much more explicit about why it's not constexpr. 4339 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 4340 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 4341 Info.Note(CD->getLocation(), diag::note_declared_at); 4342 } else { 4343 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 4344 } 4345 } 4346 return true; 4347 } 4348 4349 /// CheckConstexprFunction - Check that a function can be called in a constant 4350 /// expression. 4351 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 4352 const FunctionDecl *Declaration, 4353 const FunctionDecl *Definition, 4354 const Stmt *Body) { 4355 // Potential constant expressions can contain calls to declared, but not yet 4356 // defined, constexpr functions. 4357 if (Info.checkingPotentialConstantExpression() && !Definition && 4358 Declaration->isConstexpr()) 4359 return false; 4360 4361 // Bail out if the function declaration itself is invalid. We will 4362 // have produced a relevant diagnostic while parsing it, so just 4363 // note the problematic sub-expression. 4364 if (Declaration->isInvalidDecl()) { 4365 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4366 return false; 4367 } 4368 4369 // DR1872: An instantiated virtual constexpr function can't be called in a 4370 // constant expression (prior to C++20). We can still constant-fold such a 4371 // call. 4372 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) && 4373 cast<CXXMethodDecl>(Declaration)->isVirtual()) 4374 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 4375 4376 if (Definition && Definition->isInvalidDecl()) { 4377 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4378 return false; 4379 } 4380 4381 // Can we evaluate this function call? 4382 if (Definition && Definition->isConstexpr() && Body) 4383 return true; 4384 4385 if (Info.getLangOpts().CPlusPlus11) { 4386 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 4387 4388 // If this function is not constexpr because it is an inherited 4389 // non-constexpr constructor, diagnose that directly. 4390 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 4391 if (CD && CD->isInheritingConstructor()) { 4392 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 4393 if (!Inherited->isConstexpr()) 4394 DiagDecl = CD = Inherited; 4395 } 4396 4397 // FIXME: If DiagDecl is an implicitly-declared special member function 4398 // or an inheriting constructor, we should be much more explicit about why 4399 // it's not constexpr. 4400 if (CD && CD->isInheritingConstructor()) 4401 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 4402 << CD->getInheritedConstructor().getConstructor()->getParent(); 4403 else 4404 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 4405 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 4406 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 4407 } else { 4408 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4409 } 4410 return false; 4411 } 4412 4413 namespace { 4414 struct CheckDynamicTypeHandler { 4415 AccessKinds AccessKind; 4416 typedef bool result_type; 4417 bool failed() { return false; } 4418 bool found(APValue &Subobj, QualType SubobjType) { return true; } 4419 bool found(APSInt &Value, QualType SubobjType) { return true; } 4420 bool found(APFloat &Value, QualType SubobjType) { return true; } 4421 }; 4422 } // end anonymous namespace 4423 4424 /// Check that we can access the notional vptr of an object / determine its 4425 /// dynamic type. 4426 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 4427 AccessKinds AK, bool Polymorphic) { 4428 if (This.Designator.Invalid) 4429 return false; 4430 4431 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 4432 4433 if (!Obj) 4434 return false; 4435 4436 if (!Obj.Value) { 4437 // The object is not usable in constant expressions, so we can't inspect 4438 // its value to see if it's in-lifetime or what the active union members 4439 // are. We can still check for a one-past-the-end lvalue. 4440 if (This.Designator.isOnePastTheEnd() || 4441 This.Designator.isMostDerivedAnUnsizedArray()) { 4442 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 4443 ? diag::note_constexpr_access_past_end 4444 : diag::note_constexpr_access_unsized_array) 4445 << AK; 4446 return false; 4447 } else if (Polymorphic) { 4448 // Conservatively refuse to perform a polymorphic operation if we would 4449 // not be able to read a notional 'vptr' value. 4450 APValue Val; 4451 This.moveInto(Val); 4452 QualType StarThisType = 4453 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 4454 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 4455 << AK << Val.getAsString(Info.Ctx, StarThisType); 4456 return false; 4457 } 4458 return true; 4459 } 4460 4461 CheckDynamicTypeHandler Handler{AK}; 4462 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 4463 } 4464 4465 /// Check that the pointee of the 'this' pointer in a member function call is 4466 /// either within its lifetime or in its period of construction or destruction. 4467 static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 4468 const LValue &This) { 4469 return checkDynamicType(Info, E, This, AK_MemberCall, false); 4470 } 4471 4472 struct DynamicType { 4473 /// The dynamic class type of the object. 4474 const CXXRecordDecl *Type; 4475 /// The corresponding path length in the lvalue. 4476 unsigned PathLength; 4477 }; 4478 4479 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 4480 unsigned PathLength) { 4481 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 4482 Designator.Entries.size() && "invalid path length"); 4483 return (PathLength == Designator.MostDerivedPathLength) 4484 ? Designator.MostDerivedType->getAsCXXRecordDecl() 4485 : getAsBaseClass(Designator.Entries[PathLength - 1]); 4486 } 4487 4488 /// Determine the dynamic type of an object. 4489 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 4490 LValue &This, AccessKinds AK) { 4491 // If we don't have an lvalue denoting an object of class type, there is no 4492 // meaningful dynamic type. (We consider objects of non-class type to have no 4493 // dynamic type.) 4494 if (!checkDynamicType(Info, E, This, AK, true)) 4495 return None; 4496 4497 // Refuse to compute a dynamic type in the presence of virtual bases. This 4498 // shouldn't happen other than in constant-folding situations, since literal 4499 // types can't have virtual bases. 4500 // 4501 // Note that consumers of DynamicType assume that the type has no virtual 4502 // bases, and will need modifications if this restriction is relaxed. 4503 const CXXRecordDecl *Class = 4504 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 4505 if (!Class || Class->getNumVBases()) { 4506 Info.FFDiag(E); 4507 return None; 4508 } 4509 4510 // FIXME: For very deep class hierarchies, it might be beneficial to use a 4511 // binary search here instead. But the overwhelmingly common case is that 4512 // we're not in the middle of a constructor, so it probably doesn't matter 4513 // in practice. 4514 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 4515 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 4516 PathLength <= Path.size(); ++PathLength) { 4517 switch (Info.isEvaluatingConstructor(This.getLValueBase(), 4518 Path.slice(0, PathLength))) { 4519 case ConstructionPhase::Bases: 4520 // We're constructing a base class. This is not the dynamic type. 4521 break; 4522 4523 case ConstructionPhase::None: 4524 case ConstructionPhase::AfterBases: 4525 // We've finished constructing the base classes, so this is the dynamic 4526 // type. 4527 return DynamicType{getBaseClassType(This.Designator, PathLength), 4528 PathLength}; 4529 } 4530 } 4531 4532 // CWG issue 1517: we're constructing a base class of the object described by 4533 // 'This', so that object has not yet begun its period of construction and 4534 // any polymorphic operation on it results in undefined behavior. 4535 Info.FFDiag(E); 4536 return None; 4537 } 4538 4539 /// Perform virtual dispatch. 4540 static const CXXMethodDecl *HandleVirtualDispatch( 4541 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 4542 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 4543 Optional<DynamicType> DynType = 4544 ComputeDynamicType(Info, E, This, AK_MemberCall); 4545 if (!DynType) 4546 return nullptr; 4547 4548 // Find the final overrider. It must be declared in one of the classes on the 4549 // path from the dynamic type to the static type. 4550 // FIXME: If we ever allow literal types to have virtual base classes, that 4551 // won't be true. 4552 const CXXMethodDecl *Callee = Found; 4553 unsigned PathLength = DynType->PathLength; 4554 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 4555 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 4556 const CXXMethodDecl *Overrider = 4557 Found->getCorrespondingMethodDeclaredInClass(Class, false); 4558 if (Overrider) { 4559 Callee = Overrider; 4560 break; 4561 } 4562 } 4563 4564 // C++2a [class.abstract]p6: 4565 // the effect of making a virtual call to a pure virtual function [...] is 4566 // undefined 4567 if (Callee->isPure()) { 4568 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 4569 Info.Note(Callee->getLocation(), diag::note_declared_at); 4570 return nullptr; 4571 } 4572 4573 // If necessary, walk the rest of the path to determine the sequence of 4574 // covariant adjustment steps to apply. 4575 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 4576 Found->getReturnType())) { 4577 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 4578 for (unsigned CovariantPathLength = PathLength + 1; 4579 CovariantPathLength != This.Designator.Entries.size(); 4580 ++CovariantPathLength) { 4581 const CXXRecordDecl *NextClass = 4582 getBaseClassType(This.Designator, CovariantPathLength); 4583 const CXXMethodDecl *Next = 4584 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 4585 if (Next && !Info.Ctx.hasSameUnqualifiedType( 4586 Next->getReturnType(), CovariantAdjustmentPath.back())) 4587 CovariantAdjustmentPath.push_back(Next->getReturnType()); 4588 } 4589 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 4590 CovariantAdjustmentPath.back())) 4591 CovariantAdjustmentPath.push_back(Found->getReturnType()); 4592 } 4593 4594 // Perform 'this' adjustment. 4595 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 4596 return nullptr; 4597 4598 return Callee; 4599 } 4600 4601 /// Perform the adjustment from a value returned by a virtual function to 4602 /// a value of the statically expected type, which may be a pointer or 4603 /// reference to a base class of the returned type. 4604 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 4605 APValue &Result, 4606 ArrayRef<QualType> Path) { 4607 assert(Result.isLValue() && 4608 "unexpected kind of APValue for covariant return"); 4609 if (Result.isNullPointer()) 4610 return true; 4611 4612 LValue LVal; 4613 LVal.setFrom(Info.Ctx, Result); 4614 4615 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 4616 for (unsigned I = 1; I != Path.size(); ++I) { 4617 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 4618 assert(OldClass && NewClass && "unexpected kind of covariant return"); 4619 if (OldClass != NewClass && 4620 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 4621 return false; 4622 OldClass = NewClass; 4623 } 4624 4625 LVal.moveInto(Result); 4626 return true; 4627 } 4628 4629 /// Determine whether \p Base, which is known to be a direct base class of 4630 /// \p Derived, is a public base class. 4631 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 4632 const CXXRecordDecl *Base) { 4633 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 4634 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 4635 if (BaseClass && declaresSameEntity(BaseClass, Base)) 4636 return BaseSpec.getAccessSpecifier() == AS_public; 4637 } 4638 llvm_unreachable("Base is not a direct base of Derived"); 4639 } 4640 4641 /// Apply the given dynamic cast operation on the provided lvalue. 4642 /// 4643 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 4644 /// to find a suitable target subobject. 4645 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 4646 LValue &Ptr) { 4647 // We can't do anything with a non-symbolic pointer value. 4648 SubobjectDesignator &D = Ptr.Designator; 4649 if (D.Invalid) 4650 return false; 4651 4652 // C++ [expr.dynamic.cast]p6: 4653 // If v is a null pointer value, the result is a null pointer value. 4654 if (Ptr.isNullPointer() && !E->isGLValue()) 4655 return true; 4656 4657 // For all the other cases, we need the pointer to point to an object within 4658 // its lifetime / period of construction / destruction, and we need to know 4659 // its dynamic type. 4660 Optional<DynamicType> DynType = 4661 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 4662 if (!DynType) 4663 return false; 4664 4665 // C++ [expr.dynamic.cast]p7: 4666 // If T is "pointer to cv void", then the result is a pointer to the most 4667 // derived object 4668 if (E->getType()->isVoidPointerType()) 4669 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 4670 4671 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 4672 assert(C && "dynamic_cast target is not void pointer nor class"); 4673 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 4674 4675 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 4676 // C++ [expr.dynamic.cast]p9: 4677 if (!E->isGLValue()) { 4678 // The value of a failed cast to pointer type is the null pointer value 4679 // of the required result type. 4680 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); 4681 Ptr.setNull(E->getType(), TargetVal); 4682 return true; 4683 } 4684 4685 // A failed cast to reference type throws [...] std::bad_cast. 4686 unsigned DiagKind; 4687 if (!Paths && (declaresSameEntity(DynType->Type, C) || 4688 DynType->Type->isDerivedFrom(C))) 4689 DiagKind = 0; 4690 else if (!Paths || Paths->begin() == Paths->end()) 4691 DiagKind = 1; 4692 else if (Paths->isAmbiguous(CQT)) 4693 DiagKind = 2; 4694 else { 4695 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 4696 DiagKind = 3; 4697 } 4698 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 4699 << DiagKind << Ptr.Designator.getType(Info.Ctx) 4700 << Info.Ctx.getRecordType(DynType->Type) 4701 << E->getType().getUnqualifiedType(); 4702 return false; 4703 }; 4704 4705 // Runtime check, phase 1: 4706 // Walk from the base subobject towards the derived object looking for the 4707 // target type. 4708 for (int PathLength = Ptr.Designator.Entries.size(); 4709 PathLength >= (int)DynType->PathLength; --PathLength) { 4710 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 4711 if (declaresSameEntity(Class, C)) 4712 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 4713 // We can only walk across public inheritance edges. 4714 if (PathLength > (int)DynType->PathLength && 4715 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 4716 Class)) 4717 return RuntimeCheckFailed(nullptr); 4718 } 4719 4720 // Runtime check, phase 2: 4721 // Search the dynamic type for an unambiguous public base of type C. 4722 CXXBasePaths Paths(/*FindAmbiguities=*/true, 4723 /*RecordPaths=*/true, /*DetectVirtual=*/false); 4724 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 4725 Paths.front().Access == AS_public) { 4726 // Downcast to the dynamic type... 4727 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 4728 return false; 4729 // ... then upcast to the chosen base class subobject. 4730 for (CXXBasePathElement &Elem : Paths.front()) 4731 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 4732 return false; 4733 return true; 4734 } 4735 4736 // Otherwise, the runtime check fails. 4737 return RuntimeCheckFailed(&Paths); 4738 } 4739 4740 namespace { 4741 struct StartLifetimeOfUnionMemberHandler { 4742 const FieldDecl *Field; 4743 4744 static const AccessKinds AccessKind = AK_Assign; 4745 4746 APValue getDefaultInitValue(QualType SubobjType) { 4747 if (auto *RD = SubobjType->getAsCXXRecordDecl()) { 4748 if (RD->isUnion()) 4749 return APValue((const FieldDecl*)nullptr); 4750 4751 APValue Struct(APValue::UninitStruct(), RD->getNumBases(), 4752 std::distance(RD->field_begin(), RD->field_end())); 4753 4754 unsigned Index = 0; 4755 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4756 End = RD->bases_end(); I != End; ++I, ++Index) 4757 Struct.getStructBase(Index) = getDefaultInitValue(I->getType()); 4758 4759 for (const auto *I : RD->fields()) { 4760 if (I->isUnnamedBitfield()) 4761 continue; 4762 Struct.getStructField(I->getFieldIndex()) = 4763 getDefaultInitValue(I->getType()); 4764 } 4765 return Struct; 4766 } 4767 4768 if (auto *AT = dyn_cast_or_null<ConstantArrayType>( 4769 SubobjType->getAsArrayTypeUnsafe())) { 4770 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4771 if (Array.hasArrayFiller()) 4772 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType()); 4773 return Array; 4774 } 4775 4776 return APValue::IndeterminateValue(); 4777 } 4778 4779 typedef bool result_type; 4780 bool failed() { return false; } 4781 bool found(APValue &Subobj, QualType SubobjType) { 4782 // We are supposed to perform no initialization but begin the lifetime of 4783 // the object. We interpret that as meaning to do what default 4784 // initialization of the object would do if all constructors involved were 4785 // trivial: 4786 // * All base, non-variant member, and array element subobjects' lifetimes 4787 // begin 4788 // * No variant members' lifetimes begin 4789 // * All scalar subobjects whose lifetimes begin have indeterminate values 4790 assert(SubobjType->isUnionType()); 4791 if (!declaresSameEntity(Subobj.getUnionField(), Field)) 4792 Subobj.setUnion(Field, getDefaultInitValue(Field->getType())); 4793 return true; 4794 } 4795 bool found(APSInt &Value, QualType SubobjType) { 4796 llvm_unreachable("wrong value kind for union object"); 4797 } 4798 bool found(APFloat &Value, QualType SubobjType) { 4799 llvm_unreachable("wrong value kind for union object"); 4800 } 4801 }; 4802 } // end anonymous namespace 4803 4804 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 4805 4806 /// Handle a builtin simple-assignment or a call to a trivial assignment 4807 /// operator whose left-hand side might involve a union member access. If it 4808 /// does, implicitly start the lifetime of any accessed union elements per 4809 /// C++20 [class.union]5. 4810 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 4811 const LValue &LHS) { 4812 if (LHS.InvalidBase || LHS.Designator.Invalid) 4813 return false; 4814 4815 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 4816 // C++ [class.union]p5: 4817 // define the set S(E) of subexpressions of E as follows: 4818 unsigned PathLength = LHS.Designator.Entries.size(); 4819 for (const Expr *E = LHSExpr; E != nullptr;) { 4820 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 4821 if (auto *ME = dyn_cast<MemberExpr>(E)) { 4822 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 4823 if (!FD) 4824 break; 4825 4826 // ... and also contains A.B if B names a union member 4827 if (FD->getParent()->isUnion()) 4828 UnionPathLengths.push_back({PathLength - 1, FD}); 4829 4830 E = ME->getBase(); 4831 --PathLength; 4832 assert(declaresSameEntity(FD, 4833 LHS.Designator.Entries[PathLength] 4834 .getAsBaseOrMember().getPointer())); 4835 4836 // -- If E is of the form A[B] and is interpreted as a built-in array 4837 // subscripting operator, S(E) is [S(the array operand, if any)]. 4838 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 4839 // Step over an ArrayToPointerDecay implicit cast. 4840 auto *Base = ASE->getBase()->IgnoreImplicit(); 4841 if (!Base->getType()->isArrayType()) 4842 break; 4843 4844 E = Base; 4845 --PathLength; 4846 4847 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 4848 // Step over a derived-to-base conversion. 4849 E = ICE->getSubExpr(); 4850 if (ICE->getCastKind() == CK_NoOp) 4851 continue; 4852 if (ICE->getCastKind() != CK_DerivedToBase && 4853 ICE->getCastKind() != CK_UncheckedDerivedToBase) 4854 break; 4855 // Walk path backwards as we walk up from the base to the derived class. 4856 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 4857 --PathLength; 4858 (void)Elt; 4859 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 4860 LHS.Designator.Entries[PathLength] 4861 .getAsBaseOrMember().getPointer())); 4862 } 4863 4864 // -- Otherwise, S(E) is empty. 4865 } else { 4866 break; 4867 } 4868 } 4869 4870 // Common case: no unions' lifetimes are started. 4871 if (UnionPathLengths.empty()) 4872 return true; 4873 4874 // if modification of X [would access an inactive union member], an object 4875 // of the type of X is implicitly created 4876 CompleteObject Obj = 4877 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 4878 if (!Obj) 4879 return false; 4880 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 4881 llvm::reverse(UnionPathLengths)) { 4882 // Form a designator for the union object. 4883 SubobjectDesignator D = LHS.Designator; 4884 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 4885 4886 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second}; 4887 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 4888 return false; 4889 } 4890 4891 return true; 4892 } 4893 4894 /// Determine if a class has any fields that might need to be copied by a 4895 /// trivial copy or move operation. 4896 static bool hasFields(const CXXRecordDecl *RD) { 4897 if (!RD || RD->isEmpty()) 4898 return false; 4899 for (auto *FD : RD->fields()) { 4900 if (FD->isUnnamedBitfield()) 4901 continue; 4902 return true; 4903 } 4904 for (auto &Base : RD->bases()) 4905 if (hasFields(Base.getType()->getAsCXXRecordDecl())) 4906 return true; 4907 return false; 4908 } 4909 4910 namespace { 4911 typedef SmallVector<APValue, 8> ArgVector; 4912 } 4913 4914 /// EvaluateArgs - Evaluate the arguments to a function call. 4915 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues, 4916 EvalInfo &Info, const FunctionDecl *Callee) { 4917 bool Success = true; 4918 llvm::SmallBitVector ForbiddenNullArgs; 4919 if (Callee->hasAttr<NonNullAttr>()) { 4920 ForbiddenNullArgs.resize(Args.size()); 4921 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 4922 if (!Attr->args_size()) { 4923 ForbiddenNullArgs.set(); 4924 break; 4925 } else 4926 for (auto Idx : Attr->args()) { 4927 unsigned ASTIdx = Idx.getASTIndex(); 4928 if (ASTIdx >= Args.size()) 4929 continue; 4930 ForbiddenNullArgs[ASTIdx] = 1; 4931 } 4932 } 4933 } 4934 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 4935 I != E; ++I) { 4936 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) { 4937 // If we're checking for a potential constant expression, evaluate all 4938 // initializers even if some of them fail. 4939 if (!Info.noteFailure()) 4940 return false; 4941 Success = false; 4942 } else if (!ForbiddenNullArgs.empty() && 4943 ForbiddenNullArgs[I - Args.begin()] && 4944 ArgValues[I - Args.begin()].isNullPointer()) { 4945 Info.CCEDiag(*I, diag::note_non_null_attribute_failed); 4946 if (!Info.noteFailure()) 4947 return false; 4948 Success = false; 4949 } 4950 } 4951 return Success; 4952 } 4953 4954 /// Evaluate a function call. 4955 static bool HandleFunctionCall(SourceLocation CallLoc, 4956 const FunctionDecl *Callee, const LValue *This, 4957 ArrayRef<const Expr*> Args, const Stmt *Body, 4958 EvalInfo &Info, APValue &Result, 4959 const LValue *ResultSlot) { 4960 ArgVector ArgValues(Args.size()); 4961 if (!EvaluateArgs(Args, ArgValues, Info, Callee)) 4962 return false; 4963 4964 if (!Info.CheckCallLimit(CallLoc)) 4965 return false; 4966 4967 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 4968 4969 // For a trivial copy or move assignment, perform an APValue copy. This is 4970 // essential for unions, where the operations performed by the assignment 4971 // operator cannot be represented as statements. 4972 // 4973 // Skip this for non-union classes with no fields; in that case, the defaulted 4974 // copy/move does not actually read the object. 4975 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 4976 if (MD && MD->isDefaulted() && 4977 (MD->getParent()->isUnion() || 4978 (MD->isTrivial() && hasFields(MD->getParent())))) { 4979 assert(This && 4980 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 4981 LValue RHS; 4982 RHS.setFrom(Info.Ctx, ArgValues[0]); 4983 APValue RHSValue; 4984 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), 4985 RHS, RHSValue)) 4986 return false; 4987 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() && 4988 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 4989 return false; 4990 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 4991 RHSValue)) 4992 return false; 4993 This->moveInto(Result); 4994 return true; 4995 } else if (MD && isLambdaCallOperator(MD)) { 4996 // We're in a lambda; determine the lambda capture field maps unless we're 4997 // just constexpr checking a lambda's call operator. constexpr checking is 4998 // done before the captures have been added to the closure object (unless 4999 // we're inferring constexpr-ness), so we don't have access to them in this 5000 // case. But since we don't need the captures to constexpr check, we can 5001 // just ignore them. 5002 if (!Info.checkingPotentialConstantExpression()) 5003 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 5004 Frame.LambdaThisCaptureField); 5005 } 5006 5007 StmtResult Ret = {Result, ResultSlot}; 5008 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 5009 if (ESR == ESR_Succeeded) { 5010 if (Callee->getReturnType()->isVoidType()) 5011 return true; 5012 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 5013 } 5014 return ESR == ESR_Returned; 5015 } 5016 5017 /// Evaluate a constructor call. 5018 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5019 APValue *ArgValues, 5020 const CXXConstructorDecl *Definition, 5021 EvalInfo &Info, APValue &Result) { 5022 SourceLocation CallLoc = E->getExprLoc(); 5023 if (!Info.CheckCallLimit(CallLoc)) 5024 return false; 5025 5026 const CXXRecordDecl *RD = Definition->getParent(); 5027 if (RD->getNumVBases()) { 5028 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 5029 return false; 5030 } 5031 5032 EvalInfo::EvaluatingConstructorRAII EvalObj( 5033 Info, 5034 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 5035 RD->getNumBases()); 5036 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 5037 5038 // FIXME: Creating an APValue just to hold a nonexistent return value is 5039 // wasteful. 5040 APValue RetVal; 5041 StmtResult Ret = {RetVal, nullptr}; 5042 5043 // If it's a delegating constructor, delegate. 5044 if (Definition->isDelegatingConstructor()) { 5045 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 5046 { 5047 FullExpressionRAII InitScope(Info); 5048 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit())) 5049 return false; 5050 } 5051 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5052 } 5053 5054 // For a trivial copy or move constructor, perform an APValue copy. This is 5055 // essential for unions (or classes with anonymous union members), where the 5056 // operations performed by the constructor cannot be represented by 5057 // ctor-initializers. 5058 // 5059 // Skip this for empty non-union classes; we should not perform an 5060 // lvalue-to-rvalue conversion on them because their copy constructor does not 5061 // actually read them. 5062 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 5063 (Definition->getParent()->isUnion() || 5064 (Definition->isTrivial() && hasFields(Definition->getParent())))) { 5065 LValue RHS; 5066 RHS.setFrom(Info.Ctx, ArgValues[0]); 5067 return handleLValueToRValueConversion( 5068 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 5069 RHS, Result); 5070 } 5071 5072 // Reserve space for the struct members. 5073 if (!RD->isUnion() && !Result.hasValue()) 5074 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 5075 std::distance(RD->field_begin(), RD->field_end())); 5076 5077 if (RD->isInvalidDecl()) return false; 5078 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5079 5080 // A scope for temporaries lifetime-extended by reference members. 5081 BlockScopeRAII LifetimeExtendedScope(Info); 5082 5083 bool Success = true; 5084 unsigned BasesSeen = 0; 5085 #ifndef NDEBUG 5086 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 5087 #endif 5088 for (const auto *I : Definition->inits()) { 5089 LValue Subobject = This; 5090 LValue SubobjectParent = This; 5091 APValue *Value = &Result; 5092 5093 // Determine the subobject to initialize. 5094 FieldDecl *FD = nullptr; 5095 if (I->isBaseInitializer()) { 5096 QualType BaseType(I->getBaseClass(), 0); 5097 #ifndef NDEBUG 5098 // Non-virtual base classes are initialized in the order in the class 5099 // definition. We have already checked for virtual base classes. 5100 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 5101 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 5102 "base class initializers not in expected order"); 5103 ++BaseIt; 5104 #endif 5105 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 5106 BaseType->getAsCXXRecordDecl(), &Layout)) 5107 return false; 5108 Value = &Result.getStructBase(BasesSeen++); 5109 } else if ((FD = I->getMember())) { 5110 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 5111 return false; 5112 if (RD->isUnion()) { 5113 Result = APValue(FD); 5114 Value = &Result.getUnionValue(); 5115 } else { 5116 Value = &Result.getStructField(FD->getFieldIndex()); 5117 } 5118 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 5119 // Walk the indirect field decl's chain to find the object to initialize, 5120 // and make sure we've initialized every step along it. 5121 auto IndirectFieldChain = IFD->chain(); 5122 for (auto *C : IndirectFieldChain) { 5123 FD = cast<FieldDecl>(C); 5124 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 5125 // Switch the union field if it differs. This happens if we had 5126 // preceding zero-initialization, and we're now initializing a union 5127 // subobject other than the first. 5128 // FIXME: In this case, the values of the other subobjects are 5129 // specified, since zero-initialization sets all padding bits to zero. 5130 if (!Value->hasValue() || 5131 (Value->isUnion() && Value->getUnionField() != FD)) { 5132 if (CD->isUnion()) 5133 *Value = APValue(FD); 5134 else 5135 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(), 5136 std::distance(CD->field_begin(), CD->field_end())); 5137 } 5138 // Store Subobject as its parent before updating it for the last element 5139 // in the chain. 5140 if (C == IndirectFieldChain.back()) 5141 SubobjectParent = Subobject; 5142 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 5143 return false; 5144 if (CD->isUnion()) 5145 Value = &Value->getUnionValue(); 5146 else 5147 Value = &Value->getStructField(FD->getFieldIndex()); 5148 } 5149 } else { 5150 llvm_unreachable("unknown base initializer kind"); 5151 } 5152 5153 // Need to override This for implicit field initializers as in this case 5154 // This refers to innermost anonymous struct/union containing initializer, 5155 // not to currently constructed class. 5156 const Expr *Init = I->getInit(); 5157 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 5158 isa<CXXDefaultInitExpr>(Init)); 5159 FullExpressionRAII InitScope(Info); 5160 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 5161 (FD && FD->isBitField() && 5162 !truncateBitfieldValue(Info, Init, *Value, FD))) { 5163 // If we're checking for a potential constant expression, evaluate all 5164 // initializers even if some of them fail. 5165 if (!Info.noteFailure()) 5166 return false; 5167 Success = false; 5168 } 5169 5170 // This is the point at which the dynamic type of the object becomes this 5171 // class type. 5172 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 5173 EvalObj.finishedConstructingBases(); 5174 } 5175 5176 return Success && 5177 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5178 } 5179 5180 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5181 ArrayRef<const Expr*> Args, 5182 const CXXConstructorDecl *Definition, 5183 EvalInfo &Info, APValue &Result) { 5184 ArgVector ArgValues(Args.size()); 5185 if (!EvaluateArgs(Args, ArgValues, Info, Definition)) 5186 return false; 5187 5188 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 5189 Info, Result); 5190 } 5191 5192 //===----------------------------------------------------------------------===// 5193 // Generic Evaluation 5194 //===----------------------------------------------------------------------===// 5195 namespace { 5196 5197 class BitCastBuffer { 5198 // FIXME: We're going to need bit-level granularity when we support 5199 // bit-fields. 5200 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 5201 // we don't support a host or target where that is the case. Still, we should 5202 // use a more generic type in case we ever do. 5203 SmallVector<Optional<unsigned char>, 32> Bytes; 5204 5205 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 5206 "Need at least 8 bit unsigned char"); 5207 5208 bool TargetIsLittleEndian; 5209 5210 public: 5211 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 5212 : Bytes(Width.getQuantity()), 5213 TargetIsLittleEndian(TargetIsLittleEndian) {} 5214 5215 LLVM_NODISCARD 5216 bool readObject(CharUnits Offset, CharUnits Width, 5217 SmallVectorImpl<unsigned char> &Output) const { 5218 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 5219 // If a byte of an integer is uninitialized, then the whole integer is 5220 // uninitalized. 5221 if (!Bytes[I.getQuantity()]) 5222 return false; 5223 Output.push_back(*Bytes[I.getQuantity()]); 5224 } 5225 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 5226 std::reverse(Output.begin(), Output.end()); 5227 return true; 5228 } 5229 5230 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 5231 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 5232 std::reverse(Input.begin(), Input.end()); 5233 5234 size_t Index = 0; 5235 for (unsigned char Byte : Input) { 5236 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 5237 Bytes[Offset.getQuantity() + Index] = Byte; 5238 ++Index; 5239 } 5240 } 5241 5242 size_t size() { return Bytes.size(); } 5243 }; 5244 5245 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 5246 /// target would represent the value at runtime. 5247 class APValueToBufferConverter { 5248 EvalInfo &Info; 5249 BitCastBuffer Buffer; 5250 const CastExpr *BCE; 5251 5252 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 5253 const CastExpr *BCE) 5254 : Info(Info), 5255 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 5256 BCE(BCE) {} 5257 5258 bool visit(const APValue &Val, QualType Ty) { 5259 return visit(Val, Ty, CharUnits::fromQuantity(0)); 5260 } 5261 5262 // Write out Val with type Ty into Buffer starting at Offset. 5263 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 5264 assert((size_t)Offset.getQuantity() <= Buffer.size()); 5265 5266 // As a special case, nullptr_t has an indeterminate value. 5267 if (Ty->isNullPtrType()) 5268 return true; 5269 5270 // Dig through Src to find the byte at SrcOffset. 5271 switch (Val.getKind()) { 5272 case APValue::Indeterminate: 5273 case APValue::None: 5274 return true; 5275 5276 case APValue::Int: 5277 return visitInt(Val.getInt(), Ty, Offset); 5278 case APValue::Float: 5279 return visitFloat(Val.getFloat(), Ty, Offset); 5280 case APValue::Array: 5281 return visitArray(Val, Ty, Offset); 5282 case APValue::Struct: 5283 return visitRecord(Val, Ty, Offset); 5284 5285 case APValue::ComplexInt: 5286 case APValue::ComplexFloat: 5287 case APValue::Vector: 5288 case APValue::FixedPoint: 5289 // FIXME: We should support these. 5290 5291 case APValue::Union: 5292 case APValue::MemberPointer: 5293 case APValue::AddrLabelDiff: { 5294 Info.FFDiag(BCE->getBeginLoc(), 5295 diag::note_constexpr_bit_cast_unsupported_type) 5296 << Ty; 5297 return false; 5298 } 5299 5300 case APValue::LValue: 5301 llvm_unreachable("LValue subobject in bit_cast?"); 5302 } 5303 llvm_unreachable("Unhandled APValue::ValueKind"); 5304 } 5305 5306 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 5307 const RecordDecl *RD = Ty->getAsRecordDecl(); 5308 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5309 5310 // Visit the base classes. 5311 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 5312 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 5313 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 5314 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 5315 5316 if (!visitRecord(Val.getStructBase(I), BS.getType(), 5317 Layout.getBaseClassOffset(BaseDecl) + Offset)) 5318 return false; 5319 } 5320 } 5321 5322 // Visit the fields. 5323 unsigned FieldIdx = 0; 5324 for (FieldDecl *FD : RD->fields()) { 5325 if (FD->isBitField()) { 5326 Info.FFDiag(BCE->getBeginLoc(), 5327 diag::note_constexpr_bit_cast_unsupported_bitfield); 5328 return false; 5329 } 5330 5331 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 5332 5333 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 5334 "only bit-fields can have sub-char alignment"); 5335 CharUnits FieldOffset = 5336 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 5337 QualType FieldTy = FD->getType(); 5338 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 5339 return false; 5340 ++FieldIdx; 5341 } 5342 5343 return true; 5344 } 5345 5346 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 5347 const auto *CAT = 5348 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 5349 if (!CAT) 5350 return false; 5351 5352 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 5353 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 5354 unsigned ArraySize = Val.getArraySize(); 5355 // First, initialize the initialized elements. 5356 for (unsigned I = 0; I != NumInitializedElts; ++I) { 5357 const APValue &SubObj = Val.getArrayInitializedElt(I); 5358 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 5359 return false; 5360 } 5361 5362 // Next, initialize the rest of the array using the filler. 5363 if (Val.hasArrayFiller()) { 5364 const APValue &Filler = Val.getArrayFiller(); 5365 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 5366 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 5367 return false; 5368 } 5369 } 5370 5371 return true; 5372 } 5373 5374 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 5375 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty); 5376 SmallVector<unsigned char, 8> Bytes(Width.getQuantity()); 5377 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity()); 5378 Buffer.writeObject(Offset, Bytes); 5379 return true; 5380 } 5381 5382 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 5383 APSInt AsInt(Val.bitcastToAPInt()); 5384 return visitInt(AsInt, Ty, Offset); 5385 } 5386 5387 public: 5388 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 5389 const CastExpr *BCE) { 5390 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 5391 APValueToBufferConverter Converter(Info, DstSize, BCE); 5392 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 5393 return None; 5394 return Converter.Buffer; 5395 } 5396 }; 5397 5398 /// Write an BitCastBuffer into an APValue. 5399 class BufferToAPValueConverter { 5400 EvalInfo &Info; 5401 const BitCastBuffer &Buffer; 5402 const CastExpr *BCE; 5403 5404 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 5405 const CastExpr *BCE) 5406 : Info(Info), Buffer(Buffer), BCE(BCE) {} 5407 5408 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 5409 // with an invalid type, so anything left is a deficiency on our part (FIXME). 5410 // Ideally this will be unreachable. 5411 llvm::NoneType unsupportedType(QualType Ty) { 5412 Info.FFDiag(BCE->getBeginLoc(), 5413 diag::note_constexpr_bit_cast_unsupported_type) 5414 << Ty; 5415 return None; 5416 } 5417 5418 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 5419 const EnumType *EnumSugar = nullptr) { 5420 if (T->isNullPtrType()) { 5421 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 5422 return APValue((Expr *)nullptr, 5423 /*Offset=*/CharUnits::fromQuantity(NullValue), 5424 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 5425 } 5426 5427 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 5428 SmallVector<uint8_t, 8> Bytes; 5429 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 5430 // If this is std::byte or unsigned char, then its okay to store an 5431 // indeterminate value. 5432 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 5433 bool IsUChar = 5434 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 5435 T->isSpecificBuiltinType(BuiltinType::Char_U)); 5436 if (!IsStdByte && !IsUChar) { 5437 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 5438 Info.FFDiag(BCE->getExprLoc(), 5439 diag::note_constexpr_bit_cast_indet_dest) 5440 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 5441 return None; 5442 } 5443 5444 return APValue::IndeterminateValue(); 5445 } 5446 5447 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 5448 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 5449 5450 if (T->isIntegralOrEnumerationType()) { 5451 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 5452 return APValue(Val); 5453 } 5454 5455 if (T->isRealFloatingType()) { 5456 const llvm::fltSemantics &Semantics = 5457 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 5458 return APValue(APFloat(Semantics, Val)); 5459 } 5460 5461 return unsupportedType(QualType(T, 0)); 5462 } 5463 5464 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 5465 const RecordDecl *RD = RTy->getAsRecordDecl(); 5466 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5467 5468 unsigned NumBases = 0; 5469 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 5470 NumBases = CXXRD->getNumBases(); 5471 5472 APValue ResultVal(APValue::UninitStruct(), NumBases, 5473 std::distance(RD->field_begin(), RD->field_end())); 5474 5475 // Visit the base classes. 5476 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 5477 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 5478 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 5479 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 5480 if (BaseDecl->isEmpty() || 5481 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 5482 continue; 5483 5484 Optional<APValue> SubObj = visitType( 5485 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 5486 if (!SubObj) 5487 return None; 5488 ResultVal.getStructBase(I) = *SubObj; 5489 } 5490 } 5491 5492 // Visit the fields. 5493 unsigned FieldIdx = 0; 5494 for (FieldDecl *FD : RD->fields()) { 5495 // FIXME: We don't currently support bit-fields. A lot of the logic for 5496 // this is in CodeGen, so we need to factor it around. 5497 if (FD->isBitField()) { 5498 Info.FFDiag(BCE->getBeginLoc(), 5499 diag::note_constexpr_bit_cast_unsupported_bitfield); 5500 return None; 5501 } 5502 5503 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 5504 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 5505 5506 CharUnits FieldOffset = 5507 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 5508 Offset; 5509 QualType FieldTy = FD->getType(); 5510 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 5511 if (!SubObj) 5512 return None; 5513 ResultVal.getStructField(FieldIdx) = *SubObj; 5514 ++FieldIdx; 5515 } 5516 5517 return ResultVal; 5518 } 5519 5520 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 5521 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 5522 assert(!RepresentationType.isNull() && 5523 "enum forward decl should be caught by Sema"); 5524 const BuiltinType *AsBuiltin = 5525 RepresentationType.getCanonicalType()->getAs<BuiltinType>(); 5526 assert(AsBuiltin && "non-integral enum underlying type?"); 5527 // Recurse into the underlying type. Treat std::byte transparently as 5528 // unsigned char. 5529 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 5530 } 5531 5532 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 5533 size_t Size = Ty->getSize().getLimitedValue(); 5534 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 5535 5536 APValue ArrayValue(APValue::UninitArray(), Size, Size); 5537 for (size_t I = 0; I != Size; ++I) { 5538 Optional<APValue> ElementValue = 5539 visitType(Ty->getElementType(), Offset + I * ElementWidth); 5540 if (!ElementValue) 5541 return None; 5542 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 5543 } 5544 5545 return ArrayValue; 5546 } 5547 5548 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 5549 return unsupportedType(QualType(Ty, 0)); 5550 } 5551 5552 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 5553 QualType Can = Ty.getCanonicalType(); 5554 5555 switch (Can->getTypeClass()) { 5556 #define TYPE(Class, Base) \ 5557 case Type::Class: \ 5558 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 5559 #define ABSTRACT_TYPE(Class, Base) 5560 #define NON_CANONICAL_TYPE(Class, Base) \ 5561 case Type::Class: \ 5562 llvm_unreachable("non-canonical type should be impossible!"); 5563 #define DEPENDENT_TYPE(Class, Base) \ 5564 case Type::Class: \ 5565 llvm_unreachable( \ 5566 "dependent types aren't supported in the constant evaluator!"); 5567 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 5568 case Type::Class: \ 5569 llvm_unreachable("either dependent or not canonical!"); 5570 #include "clang/AST/TypeNodes.def" 5571 } 5572 llvm_unreachable("Unhandled Type::TypeClass"); 5573 } 5574 5575 public: 5576 // Pull out a full value of type DstType. 5577 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 5578 const CastExpr *BCE) { 5579 BufferToAPValueConverter Converter(Info, Buffer, BCE); 5580 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 5581 } 5582 }; 5583 5584 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 5585 QualType Ty, EvalInfo *Info, 5586 const ASTContext &Ctx, 5587 bool CheckingDest) { 5588 Ty = Ty.getCanonicalType(); 5589 5590 auto diag = [&](int Reason) { 5591 if (Info) 5592 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 5593 << CheckingDest << (Reason == 4) << Reason; 5594 return false; 5595 }; 5596 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 5597 if (Info) 5598 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 5599 << NoteTy << Construct << Ty; 5600 return false; 5601 }; 5602 5603 if (Ty->isUnionType()) 5604 return diag(0); 5605 if (Ty->isPointerType()) 5606 return diag(1); 5607 if (Ty->isMemberPointerType()) 5608 return diag(2); 5609 if (Ty.isVolatileQualified()) 5610 return diag(3); 5611 5612 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 5613 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 5614 for (CXXBaseSpecifier &BS : CXXRD->bases()) 5615 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 5616 CheckingDest)) 5617 return note(1, BS.getType(), BS.getBeginLoc()); 5618 } 5619 for (FieldDecl *FD : Record->fields()) { 5620 if (FD->getType()->isReferenceType()) 5621 return diag(4); 5622 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 5623 CheckingDest)) 5624 return note(0, FD->getType(), FD->getBeginLoc()); 5625 } 5626 } 5627 5628 if (Ty->isArrayType() && 5629 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 5630 Info, Ctx, CheckingDest)) 5631 return false; 5632 5633 return true; 5634 } 5635 5636 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 5637 const ASTContext &Ctx, 5638 const CastExpr *BCE) { 5639 bool DestOK = checkBitCastConstexprEligibilityType( 5640 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 5641 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 5642 BCE->getBeginLoc(), 5643 BCE->getSubExpr()->getType(), Info, Ctx, false); 5644 return SourceOK; 5645 } 5646 5647 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 5648 APValue &SourceValue, 5649 const CastExpr *BCE) { 5650 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 5651 "no host or target supports non 8-bit chars"); 5652 assert(SourceValue.isLValue() && 5653 "LValueToRValueBitcast requires an lvalue operand!"); 5654 5655 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 5656 return false; 5657 5658 LValue SourceLValue; 5659 APValue SourceRValue; 5660 SourceLValue.setFrom(Info.Ctx, SourceValue); 5661 if (!handleLValueToRValueConversion(Info, BCE, 5662 BCE->getSubExpr()->getType().withConst(), 5663 SourceLValue, SourceRValue)) 5664 return false; 5665 5666 // Read out SourceValue into a char buffer. 5667 Optional<BitCastBuffer> Buffer = 5668 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 5669 if (!Buffer) 5670 return false; 5671 5672 // Write out the buffer into a new APValue. 5673 Optional<APValue> MaybeDestValue = 5674 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 5675 if (!MaybeDestValue) 5676 return false; 5677 5678 DestValue = std::move(*MaybeDestValue); 5679 return true; 5680 } 5681 5682 template <class Derived> 5683 class ExprEvaluatorBase 5684 : public ConstStmtVisitor<Derived, bool> { 5685 private: 5686 Derived &getDerived() { return static_cast<Derived&>(*this); } 5687 bool DerivedSuccess(const APValue &V, const Expr *E) { 5688 return getDerived().Success(V, E); 5689 } 5690 bool DerivedZeroInitialization(const Expr *E) { 5691 return getDerived().ZeroInitialization(E); 5692 } 5693 5694 // Check whether a conditional operator with a non-constant condition is a 5695 // potential constant expression. If neither arm is a potential constant 5696 // expression, then the conditional operator is not either. 5697 template<typename ConditionalOperator> 5698 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 5699 assert(Info.checkingPotentialConstantExpression()); 5700 5701 // Speculatively evaluate both arms. 5702 SmallVector<PartialDiagnosticAt, 8> Diag; 5703 { 5704 SpeculativeEvaluationRAII Speculate(Info, &Diag); 5705 StmtVisitorTy::Visit(E->getFalseExpr()); 5706 if (Diag.empty()) 5707 return; 5708 } 5709 5710 { 5711 SpeculativeEvaluationRAII Speculate(Info, &Diag); 5712 Diag.clear(); 5713 StmtVisitorTy::Visit(E->getTrueExpr()); 5714 if (Diag.empty()) 5715 return; 5716 } 5717 5718 Error(E, diag::note_constexpr_conditional_never_const); 5719 } 5720 5721 5722 template<typename ConditionalOperator> 5723 bool HandleConditionalOperator(const ConditionalOperator *E) { 5724 bool BoolResult; 5725 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 5726 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 5727 CheckPotentialConstantConditional(E); 5728 return false; 5729 } 5730 if (Info.noteFailure()) { 5731 StmtVisitorTy::Visit(E->getTrueExpr()); 5732 StmtVisitorTy::Visit(E->getFalseExpr()); 5733 } 5734 return false; 5735 } 5736 5737 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 5738 return StmtVisitorTy::Visit(EvalExpr); 5739 } 5740 5741 protected: 5742 EvalInfo &Info; 5743 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 5744 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 5745 5746 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 5747 return Info.CCEDiag(E, D); 5748 } 5749 5750 bool ZeroInitialization(const Expr *E) { return Error(E); } 5751 5752 public: 5753 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 5754 5755 EvalInfo &getEvalInfo() { return Info; } 5756 5757 /// Report an evaluation error. This should only be called when an error is 5758 /// first discovered. When propagating an error, just return false. 5759 bool Error(const Expr *E, diag::kind D) { 5760 Info.FFDiag(E, D); 5761 return false; 5762 } 5763 bool Error(const Expr *E) { 5764 return Error(E, diag::note_invalid_subexpr_in_const_expr); 5765 } 5766 5767 bool VisitStmt(const Stmt *) { 5768 llvm_unreachable("Expression evaluator should not be called on stmts"); 5769 } 5770 bool VisitExpr(const Expr *E) { 5771 return Error(E); 5772 } 5773 5774 bool VisitConstantExpr(const ConstantExpr *E) 5775 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5776 bool VisitParenExpr(const ParenExpr *E) 5777 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5778 bool VisitUnaryExtension(const UnaryOperator *E) 5779 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5780 bool VisitUnaryPlus(const UnaryOperator *E) 5781 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5782 bool VisitChooseExpr(const ChooseExpr *E) 5783 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 5784 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 5785 { return StmtVisitorTy::Visit(E->getResultExpr()); } 5786 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 5787 { return StmtVisitorTy::Visit(E->getReplacement()); } 5788 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 5789 TempVersionRAII RAII(*Info.CurrentCall); 5790 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 5791 return StmtVisitorTy::Visit(E->getExpr()); 5792 } 5793 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 5794 TempVersionRAII RAII(*Info.CurrentCall); 5795 // The initializer may not have been parsed yet, or might be erroneous. 5796 if (!E->getExpr()) 5797 return Error(E); 5798 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 5799 return StmtVisitorTy::Visit(E->getExpr()); 5800 } 5801 5802 // We cannot create any objects for which cleanups are required, so there is 5803 // nothing to do here; all cleanups must come from unevaluated subexpressions. 5804 bool VisitExprWithCleanups(const ExprWithCleanups *E) 5805 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5806 5807 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 5808 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 5809 return static_cast<Derived*>(this)->VisitCastExpr(E); 5810 } 5811 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 5812 if (!Info.Ctx.getLangOpts().CPlusPlus2a) 5813 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 5814 return static_cast<Derived*>(this)->VisitCastExpr(E); 5815 } 5816 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 5817 return static_cast<Derived*>(this)->VisitCastExpr(E); 5818 } 5819 5820 bool VisitBinaryOperator(const BinaryOperator *E) { 5821 switch (E->getOpcode()) { 5822 default: 5823 return Error(E); 5824 5825 case BO_Comma: 5826 VisitIgnoredValue(E->getLHS()); 5827 return StmtVisitorTy::Visit(E->getRHS()); 5828 5829 case BO_PtrMemD: 5830 case BO_PtrMemI: { 5831 LValue Obj; 5832 if (!HandleMemberPointerAccess(Info, E, Obj)) 5833 return false; 5834 APValue Result; 5835 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 5836 return false; 5837 return DerivedSuccess(Result, E); 5838 } 5839 } 5840 } 5841 5842 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 5843 // Evaluate and cache the common expression. We treat it as a temporary, 5844 // even though it's not quite the same thing. 5845 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false), 5846 Info, E->getCommon())) 5847 return false; 5848 5849 return HandleConditionalOperator(E); 5850 } 5851 5852 bool VisitConditionalOperator(const ConditionalOperator *E) { 5853 bool IsBcpCall = false; 5854 // If the condition (ignoring parens) is a __builtin_constant_p call, 5855 // the result is a constant expression if it can be folded without 5856 // side-effects. This is an important GNU extension. See GCC PR38377 5857 // for discussion. 5858 if (const CallExpr *CallCE = 5859 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 5860 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 5861 IsBcpCall = true; 5862 5863 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 5864 // constant expression; we can't check whether it's potentially foldable. 5865 // FIXME: We should instead treat __builtin_constant_p as non-constant if 5866 // it would return 'false' in this mode. 5867 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 5868 return false; 5869 5870 FoldConstant Fold(Info, IsBcpCall); 5871 if (!HandleConditionalOperator(E)) { 5872 Fold.keepDiagnostics(); 5873 return false; 5874 } 5875 5876 return true; 5877 } 5878 5879 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 5880 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 5881 return DerivedSuccess(*Value, E); 5882 5883 const Expr *Source = E->getSourceExpr(); 5884 if (!Source) 5885 return Error(E); 5886 if (Source == E) { // sanity checking. 5887 assert(0 && "OpaqueValueExpr recursively refers to itself"); 5888 return Error(E); 5889 } 5890 return StmtVisitorTy::Visit(Source); 5891 } 5892 5893 bool VisitCallExpr(const CallExpr *E) { 5894 APValue Result; 5895 if (!handleCallExpr(E, Result, nullptr)) 5896 return false; 5897 return DerivedSuccess(Result, E); 5898 } 5899 5900 bool handleCallExpr(const CallExpr *E, APValue &Result, 5901 const LValue *ResultSlot) { 5902 const Expr *Callee = E->getCallee()->IgnoreParens(); 5903 QualType CalleeType = Callee->getType(); 5904 5905 const FunctionDecl *FD = nullptr; 5906 LValue *This = nullptr, ThisVal; 5907 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 5908 bool HasQualifier = false; 5909 5910 // Extract function decl and 'this' pointer from the callee. 5911 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 5912 const CXXMethodDecl *Member = nullptr; 5913 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 5914 // Explicit bound member calls, such as x.f() or p->g(); 5915 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 5916 return false; 5917 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 5918 if (!Member) 5919 return Error(Callee); 5920 This = &ThisVal; 5921 HasQualifier = ME->hasQualifier(); 5922 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 5923 // Indirect bound member calls ('.*' or '->*'). 5924 Member = dyn_cast_or_null<CXXMethodDecl>( 5925 HandleMemberPointerAccess(Info, BE, ThisVal, false)); 5926 if (!Member) 5927 return Error(Callee); 5928 This = &ThisVal; 5929 } else 5930 return Error(Callee); 5931 FD = Member; 5932 } else if (CalleeType->isFunctionPointerType()) { 5933 LValue Call; 5934 if (!EvaluatePointer(Callee, Call, Info)) 5935 return false; 5936 5937 if (!Call.getLValueOffset().isZero()) 5938 return Error(Callee); 5939 FD = dyn_cast_or_null<FunctionDecl>( 5940 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 5941 if (!FD) 5942 return Error(Callee); 5943 // Don't call function pointers which have been cast to some other type. 5944 // Per DR (no number yet), the caller and callee can differ in noexcept. 5945 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 5946 CalleeType->getPointeeType(), FD->getType())) { 5947 return Error(E); 5948 } 5949 5950 // Overloaded operator calls to member functions are represented as normal 5951 // calls with '*this' as the first argument. 5952 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 5953 if (MD && !MD->isStatic()) { 5954 // FIXME: When selecting an implicit conversion for an overloaded 5955 // operator delete, we sometimes try to evaluate calls to conversion 5956 // operators without a 'this' parameter! 5957 if (Args.empty()) 5958 return Error(E); 5959 5960 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 5961 return false; 5962 This = &ThisVal; 5963 Args = Args.slice(1); 5964 } else if (MD && MD->isLambdaStaticInvoker()) { 5965 // Map the static invoker for the lambda back to the call operator. 5966 // Conveniently, we don't have to slice out the 'this' argument (as is 5967 // being done for the non-static case), since a static member function 5968 // doesn't have an implicit argument passed in. 5969 const CXXRecordDecl *ClosureClass = MD->getParent(); 5970 assert( 5971 ClosureClass->captures_begin() == ClosureClass->captures_end() && 5972 "Number of captures must be zero for conversion to function-ptr"); 5973 5974 const CXXMethodDecl *LambdaCallOp = 5975 ClosureClass->getLambdaCallOperator(); 5976 5977 // Set 'FD', the function that will be called below, to the call 5978 // operator. If the closure object represents a generic lambda, find 5979 // the corresponding specialization of the call operator. 5980 5981 if (ClosureClass->isGenericLambda()) { 5982 assert(MD->isFunctionTemplateSpecialization() && 5983 "A generic lambda's static-invoker function must be a " 5984 "template specialization"); 5985 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 5986 FunctionTemplateDecl *CallOpTemplate = 5987 LambdaCallOp->getDescribedFunctionTemplate(); 5988 void *InsertPos = nullptr; 5989 FunctionDecl *CorrespondingCallOpSpecialization = 5990 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 5991 assert(CorrespondingCallOpSpecialization && 5992 "We must always have a function call operator specialization " 5993 "that corresponds to our static invoker specialization"); 5994 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 5995 } else 5996 FD = LambdaCallOp; 5997 } 5998 } else 5999 return Error(E); 6000 6001 SmallVector<QualType, 4> CovariantAdjustmentPath; 6002 if (This) { 6003 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 6004 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 6005 // Perform virtual dispatch, if necessary. 6006 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 6007 CovariantAdjustmentPath); 6008 if (!FD) 6009 return false; 6010 } else { 6011 // Check that the 'this' pointer points to an object of the right type. 6012 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This)) 6013 return false; 6014 } 6015 } 6016 6017 const FunctionDecl *Definition = nullptr; 6018 Stmt *Body = FD->getBody(Definition); 6019 6020 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 6021 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 6022 Result, ResultSlot)) 6023 return false; 6024 6025 if (!CovariantAdjustmentPath.empty() && 6026 !HandleCovariantReturnAdjustment(Info, E, Result, 6027 CovariantAdjustmentPath)) 6028 return false; 6029 6030 return true; 6031 } 6032 6033 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 6034 return StmtVisitorTy::Visit(E->getInitializer()); 6035 } 6036 bool VisitInitListExpr(const InitListExpr *E) { 6037 if (E->getNumInits() == 0) 6038 return DerivedZeroInitialization(E); 6039 if (E->getNumInits() == 1) 6040 return StmtVisitorTy::Visit(E->getInit(0)); 6041 return Error(E); 6042 } 6043 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 6044 return DerivedZeroInitialization(E); 6045 } 6046 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 6047 return DerivedZeroInitialization(E); 6048 } 6049 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 6050 return DerivedZeroInitialization(E); 6051 } 6052 6053 /// A member expression where the object is a prvalue is itself a prvalue. 6054 bool VisitMemberExpr(const MemberExpr *E) { 6055 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 6056 "missing temporary materialization conversion"); 6057 assert(!E->isArrow() && "missing call to bound member function?"); 6058 6059 APValue Val; 6060 if (!Evaluate(Val, Info, E->getBase())) 6061 return false; 6062 6063 QualType BaseTy = E->getBase()->getType(); 6064 6065 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 6066 if (!FD) return Error(E); 6067 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 6068 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 6069 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 6070 6071 // Note: there is no lvalue base here. But this case should only ever 6072 // happen in C or in C++98, where we cannot be evaluating a constexpr 6073 // constructor, which is the only case the base matters. 6074 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 6075 SubobjectDesignator Designator(BaseTy); 6076 Designator.addDeclUnchecked(FD); 6077 6078 APValue Result; 6079 return extractSubobject(Info, E, Obj, Designator, Result) && 6080 DerivedSuccess(Result, E); 6081 } 6082 6083 bool VisitCastExpr(const CastExpr *E) { 6084 switch (E->getCastKind()) { 6085 default: 6086 break; 6087 6088 case CK_AtomicToNonAtomic: { 6089 APValue AtomicVal; 6090 // This does not need to be done in place even for class/array types: 6091 // atomic-to-non-atomic conversion implies copying the object 6092 // representation. 6093 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 6094 return false; 6095 return DerivedSuccess(AtomicVal, E); 6096 } 6097 6098 case CK_NoOp: 6099 case CK_UserDefinedConversion: 6100 return StmtVisitorTy::Visit(E->getSubExpr()); 6101 6102 case CK_LValueToRValue: { 6103 LValue LVal; 6104 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 6105 return false; 6106 APValue RVal; 6107 // Note, we use the subexpression's type in order to retain cv-qualifiers. 6108 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 6109 LVal, RVal)) 6110 return false; 6111 return DerivedSuccess(RVal, E); 6112 } 6113 case CK_LValueToRValueBitCast: { 6114 APValue DestValue, SourceValue; 6115 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 6116 return false; 6117 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 6118 return false; 6119 return DerivedSuccess(DestValue, E); 6120 } 6121 } 6122 6123 return Error(E); 6124 } 6125 6126 bool VisitUnaryPostInc(const UnaryOperator *UO) { 6127 return VisitUnaryPostIncDec(UO); 6128 } 6129 bool VisitUnaryPostDec(const UnaryOperator *UO) { 6130 return VisitUnaryPostIncDec(UO); 6131 } 6132 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 6133 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 6134 return Error(UO); 6135 6136 LValue LVal; 6137 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 6138 return false; 6139 APValue RVal; 6140 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 6141 UO->isIncrementOp(), &RVal)) 6142 return false; 6143 return DerivedSuccess(RVal, UO); 6144 } 6145 6146 bool VisitStmtExpr(const StmtExpr *E) { 6147 // We will have checked the full-expressions inside the statement expression 6148 // when they were completed, and don't need to check them again now. 6149 if (Info.checkingForUndefinedBehavior()) 6150 return Error(E); 6151 6152 BlockScopeRAII Scope(Info); 6153 const CompoundStmt *CS = E->getSubStmt(); 6154 if (CS->body_empty()) 6155 return true; 6156 6157 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 6158 BE = CS->body_end(); 6159 /**/; ++BI) { 6160 if (BI + 1 == BE) { 6161 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 6162 if (!FinalExpr) { 6163 Info.FFDiag((*BI)->getBeginLoc(), 6164 diag::note_constexpr_stmt_expr_unsupported); 6165 return false; 6166 } 6167 return this->Visit(FinalExpr); 6168 } 6169 6170 APValue ReturnValue; 6171 StmtResult Result = { ReturnValue, nullptr }; 6172 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 6173 if (ESR != ESR_Succeeded) { 6174 // FIXME: If the statement-expression terminated due to 'return', 6175 // 'break', or 'continue', it would be nice to propagate that to 6176 // the outer statement evaluation rather than bailing out. 6177 if (ESR != ESR_Failed) 6178 Info.FFDiag((*BI)->getBeginLoc(), 6179 diag::note_constexpr_stmt_expr_unsupported); 6180 return false; 6181 } 6182 } 6183 6184 llvm_unreachable("Return from function from the loop above."); 6185 } 6186 6187 /// Visit a value which is evaluated, but whose value is ignored. 6188 void VisitIgnoredValue(const Expr *E) { 6189 EvaluateIgnoredValue(Info, E); 6190 } 6191 6192 /// Potentially visit a MemberExpr's base expression. 6193 void VisitIgnoredBaseExpression(const Expr *E) { 6194 // While MSVC doesn't evaluate the base expression, it does diagnose the 6195 // presence of side-effecting behavior. 6196 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 6197 return; 6198 VisitIgnoredValue(E); 6199 } 6200 }; 6201 6202 } // namespace 6203 6204 //===----------------------------------------------------------------------===// 6205 // Common base class for lvalue and temporary evaluation. 6206 //===----------------------------------------------------------------------===// 6207 namespace { 6208 template<class Derived> 6209 class LValueExprEvaluatorBase 6210 : public ExprEvaluatorBase<Derived> { 6211 protected: 6212 LValue &Result; 6213 bool InvalidBaseOK; 6214 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 6215 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 6216 6217 bool Success(APValue::LValueBase B) { 6218 Result.set(B); 6219 return true; 6220 } 6221 6222 bool evaluatePointer(const Expr *E, LValue &Result) { 6223 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 6224 } 6225 6226 public: 6227 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 6228 : ExprEvaluatorBaseTy(Info), Result(Result), 6229 InvalidBaseOK(InvalidBaseOK) {} 6230 6231 bool Success(const APValue &V, const Expr *E) { 6232 Result.setFrom(this->Info.Ctx, V); 6233 return true; 6234 } 6235 6236 bool VisitMemberExpr(const MemberExpr *E) { 6237 // Handle non-static data members. 6238 QualType BaseTy; 6239 bool EvalOK; 6240 if (E->isArrow()) { 6241 EvalOK = evaluatePointer(E->getBase(), Result); 6242 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 6243 } else if (E->getBase()->isRValue()) { 6244 assert(E->getBase()->getType()->isRecordType()); 6245 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 6246 BaseTy = E->getBase()->getType(); 6247 } else { 6248 EvalOK = this->Visit(E->getBase()); 6249 BaseTy = E->getBase()->getType(); 6250 } 6251 if (!EvalOK) { 6252 if (!InvalidBaseOK) 6253 return false; 6254 Result.setInvalid(E); 6255 return true; 6256 } 6257 6258 const ValueDecl *MD = E->getMemberDecl(); 6259 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 6260 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 6261 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 6262 (void)BaseTy; 6263 if (!HandleLValueMember(this->Info, E, Result, FD)) 6264 return false; 6265 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 6266 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 6267 return false; 6268 } else 6269 return this->Error(E); 6270 6271 if (MD->getType()->isReferenceType()) { 6272 APValue RefValue; 6273 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 6274 RefValue)) 6275 return false; 6276 return Success(RefValue, E); 6277 } 6278 return true; 6279 } 6280 6281 bool VisitBinaryOperator(const BinaryOperator *E) { 6282 switch (E->getOpcode()) { 6283 default: 6284 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 6285 6286 case BO_PtrMemD: 6287 case BO_PtrMemI: 6288 return HandleMemberPointerAccess(this->Info, E, Result); 6289 } 6290 } 6291 6292 bool VisitCastExpr(const CastExpr *E) { 6293 switch (E->getCastKind()) { 6294 default: 6295 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6296 6297 case CK_DerivedToBase: 6298 case CK_UncheckedDerivedToBase: 6299 if (!this->Visit(E->getSubExpr())) 6300 return false; 6301 6302 // Now figure out the necessary offset to add to the base LV to get from 6303 // the derived class to the base class. 6304 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 6305 Result); 6306 } 6307 } 6308 }; 6309 } 6310 6311 //===----------------------------------------------------------------------===// 6312 // LValue Evaluation 6313 // 6314 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 6315 // function designators (in C), decl references to void objects (in C), and 6316 // temporaries (if building with -Wno-address-of-temporary). 6317 // 6318 // LValue evaluation produces values comprising a base expression of one of the 6319 // following types: 6320 // - Declarations 6321 // * VarDecl 6322 // * FunctionDecl 6323 // - Literals 6324 // * CompoundLiteralExpr in C (and in global scope in C++) 6325 // * StringLiteral 6326 // * PredefinedExpr 6327 // * ObjCStringLiteralExpr 6328 // * ObjCEncodeExpr 6329 // * AddrLabelExpr 6330 // * BlockExpr 6331 // * CallExpr for a MakeStringConstant builtin 6332 // - typeid(T) expressions, as TypeInfoLValues 6333 // - Locals and temporaries 6334 // * MaterializeTemporaryExpr 6335 // * Any Expr, with a CallIndex indicating the function in which the temporary 6336 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 6337 // from the AST (FIXME). 6338 // * A MaterializeTemporaryExpr that has static storage duration, with no 6339 // CallIndex, for a lifetime-extended temporary. 6340 // plus an offset in bytes. 6341 //===----------------------------------------------------------------------===// 6342 namespace { 6343 class LValueExprEvaluator 6344 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 6345 public: 6346 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 6347 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 6348 6349 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 6350 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 6351 6352 bool VisitDeclRefExpr(const DeclRefExpr *E); 6353 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 6354 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 6355 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 6356 bool VisitMemberExpr(const MemberExpr *E); 6357 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 6358 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 6359 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 6360 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 6361 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 6362 bool VisitUnaryDeref(const UnaryOperator *E); 6363 bool VisitUnaryReal(const UnaryOperator *E); 6364 bool VisitUnaryImag(const UnaryOperator *E); 6365 bool VisitUnaryPreInc(const UnaryOperator *UO) { 6366 return VisitUnaryPreIncDec(UO); 6367 } 6368 bool VisitUnaryPreDec(const UnaryOperator *UO) { 6369 return VisitUnaryPreIncDec(UO); 6370 } 6371 bool VisitBinAssign(const BinaryOperator *BO); 6372 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 6373 6374 bool VisitCastExpr(const CastExpr *E) { 6375 switch (E->getCastKind()) { 6376 default: 6377 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 6378 6379 case CK_LValueBitCast: 6380 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 6381 if (!Visit(E->getSubExpr())) 6382 return false; 6383 Result.Designator.setInvalid(); 6384 return true; 6385 6386 case CK_BaseToDerived: 6387 if (!Visit(E->getSubExpr())) 6388 return false; 6389 return HandleBaseToDerivedCast(Info, E, Result); 6390 6391 case CK_Dynamic: 6392 if (!Visit(E->getSubExpr())) 6393 return false; 6394 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 6395 } 6396 } 6397 }; 6398 } // end anonymous namespace 6399 6400 /// Evaluate an expression as an lvalue. This can be legitimately called on 6401 /// expressions which are not glvalues, in three cases: 6402 /// * function designators in C, and 6403 /// * "extern void" objects 6404 /// * @selector() expressions in Objective-C 6405 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 6406 bool InvalidBaseOK) { 6407 assert(E->isGLValue() || E->getType()->isFunctionType() || 6408 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 6409 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 6410 } 6411 6412 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 6413 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 6414 return Success(FD); 6415 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 6416 return VisitVarDecl(E, VD); 6417 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 6418 return Visit(BD->getBinding()); 6419 return Error(E); 6420 } 6421 6422 6423 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 6424 6425 // If we are within a lambda's call operator, check whether the 'VD' referred 6426 // to within 'E' actually represents a lambda-capture that maps to a 6427 // data-member/field within the closure object, and if so, evaluate to the 6428 // field or what the field refers to. 6429 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 6430 isa<DeclRefExpr>(E) && 6431 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 6432 // We don't always have a complete capture-map when checking or inferring if 6433 // the function call operator meets the requirements of a constexpr function 6434 // - but we don't need to evaluate the captures to determine constexprness 6435 // (dcl.constexpr C++17). 6436 if (Info.checkingPotentialConstantExpression()) 6437 return false; 6438 6439 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 6440 // Start with 'Result' referring to the complete closure object... 6441 Result = *Info.CurrentCall->This; 6442 // ... then update it to refer to the field of the closure object 6443 // that represents the capture. 6444 if (!HandleLValueMember(Info, E, Result, FD)) 6445 return false; 6446 // And if the field is of reference type, update 'Result' to refer to what 6447 // the field refers to. 6448 if (FD->getType()->isReferenceType()) { 6449 APValue RVal; 6450 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 6451 RVal)) 6452 return false; 6453 Result.setFrom(Info.Ctx, RVal); 6454 } 6455 return true; 6456 } 6457 } 6458 CallStackFrame *Frame = nullptr; 6459 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 6460 // Only if a local variable was declared in the function currently being 6461 // evaluated, do we expect to be able to find its value in the current 6462 // frame. (Otherwise it was likely declared in an enclosing context and 6463 // could either have a valid evaluatable value (for e.g. a constexpr 6464 // variable) or be ill-formed (and trigger an appropriate evaluation 6465 // diagnostic)). 6466 if (Info.CurrentCall->Callee && 6467 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 6468 Frame = Info.CurrentCall; 6469 } 6470 } 6471 6472 if (!VD->getType()->isReferenceType()) { 6473 if (Frame) { 6474 Result.set({VD, Frame->Index, 6475 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 6476 return true; 6477 } 6478 return Success(VD); 6479 } 6480 6481 APValue *V; 6482 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 6483 return false; 6484 if (!V->hasValue()) { 6485 // FIXME: Is it possible for V to be indeterminate here? If so, we should 6486 // adjust the diagnostic to say that. 6487 if (!Info.checkingPotentialConstantExpression()) 6488 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 6489 return false; 6490 } 6491 return Success(*V, E); 6492 } 6493 6494 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 6495 const MaterializeTemporaryExpr *E) { 6496 // Walk through the expression to find the materialized temporary itself. 6497 SmallVector<const Expr *, 2> CommaLHSs; 6498 SmallVector<SubobjectAdjustment, 2> Adjustments; 6499 const Expr *Inner = E->GetTemporaryExpr()-> 6500 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 6501 6502 // If we passed any comma operators, evaluate their LHSs. 6503 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 6504 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 6505 return false; 6506 6507 // A materialized temporary with static storage duration can appear within the 6508 // result of a constant expression evaluation, so we need to preserve its 6509 // value for use outside this evaluation. 6510 APValue *Value; 6511 if (E->getStorageDuration() == SD_Static) { 6512 Value = Info.Ctx.getMaterializedTemporaryValue(E, true); 6513 *Value = APValue(); 6514 Result.set(E); 6515 } else { 6516 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result, 6517 *Info.CurrentCall); 6518 } 6519 6520 QualType Type = Inner->getType(); 6521 6522 // Materialize the temporary itself. 6523 if (!EvaluateInPlace(*Value, Info, Result, Inner) || 6524 (E->getStorageDuration() == SD_Static && 6525 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) { 6526 *Value = APValue(); 6527 return false; 6528 } 6529 6530 // Adjust our lvalue to refer to the desired subobject. 6531 for (unsigned I = Adjustments.size(); I != 0; /**/) { 6532 --I; 6533 switch (Adjustments[I].Kind) { 6534 case SubobjectAdjustment::DerivedToBaseAdjustment: 6535 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 6536 Type, Result)) 6537 return false; 6538 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 6539 break; 6540 6541 case SubobjectAdjustment::FieldAdjustment: 6542 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 6543 return false; 6544 Type = Adjustments[I].Field->getType(); 6545 break; 6546 6547 case SubobjectAdjustment::MemberPointerAdjustment: 6548 if (!HandleMemberPointerAccess(this->Info, Type, Result, 6549 Adjustments[I].Ptr.RHS)) 6550 return false; 6551 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 6552 break; 6553 } 6554 } 6555 6556 return true; 6557 } 6558 6559 bool 6560 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 6561 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 6562 "lvalue compound literal in c++?"); 6563 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 6564 // only see this when folding in C, so there's no standard to follow here. 6565 return Success(E); 6566 } 6567 6568 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 6569 TypeInfoLValue TypeInfo; 6570 6571 if (!E->isPotentiallyEvaluated()) { 6572 if (E->isTypeOperand()) 6573 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 6574 else 6575 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 6576 } else { 6577 if (!Info.Ctx.getLangOpts().CPlusPlus2a) { 6578 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 6579 << E->getExprOperand()->getType() 6580 << E->getExprOperand()->getSourceRange(); 6581 } 6582 6583 if (!Visit(E->getExprOperand())) 6584 return false; 6585 6586 Optional<DynamicType> DynType = 6587 ComputeDynamicType(Info, E, Result, AK_TypeId); 6588 if (!DynType) 6589 return false; 6590 6591 TypeInfo = 6592 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 6593 } 6594 6595 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 6596 } 6597 6598 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 6599 return Success(E); 6600 } 6601 6602 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 6603 // Handle static data members. 6604 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 6605 VisitIgnoredBaseExpression(E->getBase()); 6606 return VisitVarDecl(E, VD); 6607 } 6608 6609 // Handle static member functions. 6610 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 6611 if (MD->isStatic()) { 6612 VisitIgnoredBaseExpression(E->getBase()); 6613 return Success(MD); 6614 } 6615 } 6616 6617 // Handle non-static data members. 6618 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 6619 } 6620 6621 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 6622 // FIXME: Deal with vectors as array subscript bases. 6623 if (E->getBase()->getType()->isVectorType()) 6624 return Error(E); 6625 6626 bool Success = true; 6627 if (!evaluatePointer(E->getBase(), Result)) { 6628 if (!Info.noteFailure()) 6629 return false; 6630 Success = false; 6631 } 6632 6633 APSInt Index; 6634 if (!EvaluateInteger(E->getIdx(), Index, Info)) 6635 return false; 6636 6637 return Success && 6638 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 6639 } 6640 6641 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 6642 return evaluatePointer(E->getSubExpr(), Result); 6643 } 6644 6645 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 6646 if (!Visit(E->getSubExpr())) 6647 return false; 6648 // __real is a no-op on scalar lvalues. 6649 if (E->getSubExpr()->getType()->isAnyComplexType()) 6650 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 6651 return true; 6652 } 6653 6654 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 6655 assert(E->getSubExpr()->getType()->isAnyComplexType() && 6656 "lvalue __imag__ on scalar?"); 6657 if (!Visit(E->getSubExpr())) 6658 return false; 6659 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 6660 return true; 6661 } 6662 6663 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 6664 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 6665 return Error(UO); 6666 6667 if (!this->Visit(UO->getSubExpr())) 6668 return false; 6669 6670 return handleIncDec( 6671 this->Info, UO, Result, UO->getSubExpr()->getType(), 6672 UO->isIncrementOp(), nullptr); 6673 } 6674 6675 bool LValueExprEvaluator::VisitCompoundAssignOperator( 6676 const CompoundAssignOperator *CAO) { 6677 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 6678 return Error(CAO); 6679 6680 APValue RHS; 6681 6682 // The overall lvalue result is the result of evaluating the LHS. 6683 if (!this->Visit(CAO->getLHS())) { 6684 if (Info.noteFailure()) 6685 Evaluate(RHS, this->Info, CAO->getRHS()); 6686 return false; 6687 } 6688 6689 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 6690 return false; 6691 6692 return handleCompoundAssignment( 6693 this->Info, CAO, 6694 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 6695 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 6696 } 6697 6698 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 6699 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 6700 return Error(E); 6701 6702 APValue NewVal; 6703 6704 if (!this->Visit(E->getLHS())) { 6705 if (Info.noteFailure()) 6706 Evaluate(NewVal, this->Info, E->getRHS()); 6707 return false; 6708 } 6709 6710 if (!Evaluate(NewVal, this->Info, E->getRHS())) 6711 return false; 6712 6713 if (Info.getLangOpts().CPlusPlus2a && 6714 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 6715 return false; 6716 6717 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 6718 NewVal); 6719 } 6720 6721 //===----------------------------------------------------------------------===// 6722 // Pointer Evaluation 6723 //===----------------------------------------------------------------------===// 6724 6725 /// Attempts to compute the number of bytes available at the pointer 6726 /// returned by a function with the alloc_size attribute. Returns true if we 6727 /// were successful. Places an unsigned number into `Result`. 6728 /// 6729 /// This expects the given CallExpr to be a call to a function with an 6730 /// alloc_size attribute. 6731 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 6732 const CallExpr *Call, 6733 llvm::APInt &Result) { 6734 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 6735 6736 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 6737 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 6738 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 6739 if (Call->getNumArgs() <= SizeArgNo) 6740 return false; 6741 6742 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 6743 Expr::EvalResult ExprResult; 6744 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 6745 return false; 6746 Into = ExprResult.Val.getInt(); 6747 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 6748 return false; 6749 Into = Into.zextOrSelf(BitsInSizeT); 6750 return true; 6751 }; 6752 6753 APSInt SizeOfElem; 6754 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 6755 return false; 6756 6757 if (!AllocSize->getNumElemsParam().isValid()) { 6758 Result = std::move(SizeOfElem); 6759 return true; 6760 } 6761 6762 APSInt NumberOfElems; 6763 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 6764 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 6765 return false; 6766 6767 bool Overflow; 6768 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 6769 if (Overflow) 6770 return false; 6771 6772 Result = std::move(BytesAvailable); 6773 return true; 6774 } 6775 6776 /// Convenience function. LVal's base must be a call to an alloc_size 6777 /// function. 6778 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 6779 const LValue &LVal, 6780 llvm::APInt &Result) { 6781 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 6782 "Can't get the size of a non alloc_size function"); 6783 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 6784 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 6785 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 6786 } 6787 6788 /// Attempts to evaluate the given LValueBase as the result of a call to 6789 /// a function with the alloc_size attribute. If it was possible to do so, this 6790 /// function will return true, make Result's Base point to said function call, 6791 /// and mark Result's Base as invalid. 6792 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 6793 LValue &Result) { 6794 if (Base.isNull()) 6795 return false; 6796 6797 // Because we do no form of static analysis, we only support const variables. 6798 // 6799 // Additionally, we can't support parameters, nor can we support static 6800 // variables (in the latter case, use-before-assign isn't UB; in the former, 6801 // we have no clue what they'll be assigned to). 6802 const auto *VD = 6803 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 6804 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 6805 return false; 6806 6807 const Expr *Init = VD->getAnyInitializer(); 6808 if (!Init) 6809 return false; 6810 6811 const Expr *E = Init->IgnoreParens(); 6812 if (!tryUnwrapAllocSizeCall(E)) 6813 return false; 6814 6815 // Store E instead of E unwrapped so that the type of the LValue's base is 6816 // what the user wanted. 6817 Result.setInvalid(E); 6818 6819 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 6820 Result.addUnsizedArray(Info, E, Pointee); 6821 return true; 6822 } 6823 6824 namespace { 6825 class PointerExprEvaluator 6826 : public ExprEvaluatorBase<PointerExprEvaluator> { 6827 LValue &Result; 6828 bool InvalidBaseOK; 6829 6830 bool Success(const Expr *E) { 6831 Result.set(E); 6832 return true; 6833 } 6834 6835 bool evaluateLValue(const Expr *E, LValue &Result) { 6836 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 6837 } 6838 6839 bool evaluatePointer(const Expr *E, LValue &Result) { 6840 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 6841 } 6842 6843 bool visitNonBuiltinCallExpr(const CallExpr *E); 6844 public: 6845 6846 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 6847 : ExprEvaluatorBaseTy(info), Result(Result), 6848 InvalidBaseOK(InvalidBaseOK) {} 6849 6850 bool Success(const APValue &V, const Expr *E) { 6851 Result.setFrom(Info.Ctx, V); 6852 return true; 6853 } 6854 bool ZeroInitialization(const Expr *E) { 6855 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); 6856 Result.setNull(E->getType(), TargetVal); 6857 return true; 6858 } 6859 6860 bool VisitBinaryOperator(const BinaryOperator *E); 6861 bool VisitCastExpr(const CastExpr* E); 6862 bool VisitUnaryAddrOf(const UnaryOperator *E); 6863 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 6864 { return Success(E); } 6865 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 6866 if (E->isExpressibleAsConstantInitializer()) 6867 return Success(E); 6868 if (Info.noteFailure()) 6869 EvaluateIgnoredValue(Info, E->getSubExpr()); 6870 return Error(E); 6871 } 6872 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 6873 { return Success(E); } 6874 bool VisitCallExpr(const CallExpr *E); 6875 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 6876 bool VisitBlockExpr(const BlockExpr *E) { 6877 if (!E->getBlockDecl()->hasCaptures()) 6878 return Success(E); 6879 return Error(E); 6880 } 6881 bool VisitCXXThisExpr(const CXXThisExpr *E) { 6882 // Can't look at 'this' when checking a potential constant expression. 6883 if (Info.checkingPotentialConstantExpression()) 6884 return false; 6885 if (!Info.CurrentCall->This) { 6886 if (Info.getLangOpts().CPlusPlus11) 6887 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 6888 else 6889 Info.FFDiag(E); 6890 return false; 6891 } 6892 Result = *Info.CurrentCall->This; 6893 // If we are inside a lambda's call operator, the 'this' expression refers 6894 // to the enclosing '*this' object (either by value or reference) which is 6895 // either copied into the closure object's field that represents the '*this' 6896 // or refers to '*this'. 6897 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 6898 // Update 'Result' to refer to the data member/field of the closure object 6899 // that represents the '*this' capture. 6900 if (!HandleLValueMember(Info, E, Result, 6901 Info.CurrentCall->LambdaThisCaptureField)) 6902 return false; 6903 // If we captured '*this' by reference, replace the field with its referent. 6904 if (Info.CurrentCall->LambdaThisCaptureField->getType() 6905 ->isPointerType()) { 6906 APValue RVal; 6907 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 6908 RVal)) 6909 return false; 6910 6911 Result.setFrom(Info.Ctx, RVal); 6912 } 6913 } 6914 return true; 6915 } 6916 6917 bool VisitSourceLocExpr(const SourceLocExpr *E) { 6918 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 6919 APValue LValResult = E->EvaluateInContext( 6920 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 6921 Result.setFrom(Info.Ctx, LValResult); 6922 return true; 6923 } 6924 6925 // FIXME: Missing: @protocol, @selector 6926 }; 6927 } // end anonymous namespace 6928 6929 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 6930 bool InvalidBaseOK) { 6931 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 6932 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 6933 } 6934 6935 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 6936 if (E->getOpcode() != BO_Add && 6937 E->getOpcode() != BO_Sub) 6938 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 6939 6940 const Expr *PExp = E->getLHS(); 6941 const Expr *IExp = E->getRHS(); 6942 if (IExp->getType()->isPointerType()) 6943 std::swap(PExp, IExp); 6944 6945 bool EvalPtrOK = evaluatePointer(PExp, Result); 6946 if (!EvalPtrOK && !Info.noteFailure()) 6947 return false; 6948 6949 llvm::APSInt Offset; 6950 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 6951 return false; 6952 6953 if (E->getOpcode() == BO_Sub) 6954 negateAsSigned(Offset); 6955 6956 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 6957 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 6958 } 6959 6960 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 6961 return evaluateLValue(E->getSubExpr(), Result); 6962 } 6963 6964 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 6965 const Expr *SubExpr = E->getSubExpr(); 6966 6967 switch (E->getCastKind()) { 6968 default: 6969 break; 6970 case CK_BitCast: 6971 case CK_CPointerToObjCPointerCast: 6972 case CK_BlockPointerToObjCPointerCast: 6973 case CK_AnyPointerToBlockPointerCast: 6974 case CK_AddressSpaceConversion: 6975 if (!Visit(SubExpr)) 6976 return false; 6977 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 6978 // permitted in constant expressions in C++11. Bitcasts from cv void* are 6979 // also static_casts, but we disallow them as a resolution to DR1312. 6980 if (!E->getType()->isVoidPointerType()) { 6981 Result.Designator.setInvalid(); 6982 if (SubExpr->getType()->isVoidPointerType()) 6983 CCEDiag(E, diag::note_constexpr_invalid_cast) 6984 << 3 << SubExpr->getType(); 6985 else 6986 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 6987 } 6988 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 6989 ZeroInitialization(E); 6990 return true; 6991 6992 case CK_DerivedToBase: 6993 case CK_UncheckedDerivedToBase: 6994 if (!evaluatePointer(E->getSubExpr(), Result)) 6995 return false; 6996 if (!Result.Base && Result.Offset.isZero()) 6997 return true; 6998 6999 // Now figure out the necessary offset to add to the base LV to get from 7000 // the derived class to the base class. 7001 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 7002 castAs<PointerType>()->getPointeeType(), 7003 Result); 7004 7005 case CK_BaseToDerived: 7006 if (!Visit(E->getSubExpr())) 7007 return false; 7008 if (!Result.Base && Result.Offset.isZero()) 7009 return true; 7010 return HandleBaseToDerivedCast(Info, E, Result); 7011 7012 case CK_Dynamic: 7013 if (!Visit(E->getSubExpr())) 7014 return false; 7015 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 7016 7017 case CK_NullToPointer: 7018 VisitIgnoredValue(E->getSubExpr()); 7019 return ZeroInitialization(E); 7020 7021 case CK_IntegralToPointer: { 7022 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7023 7024 APValue Value; 7025 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 7026 break; 7027 7028 if (Value.isInt()) { 7029 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 7030 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 7031 Result.Base = (Expr*)nullptr; 7032 Result.InvalidBase = false; 7033 Result.Offset = CharUnits::fromQuantity(N); 7034 Result.Designator.setInvalid(); 7035 Result.IsNullPtr = false; 7036 return true; 7037 } else { 7038 // Cast is of an lvalue, no need to change value. 7039 Result.setFrom(Info.Ctx, Value); 7040 return true; 7041 } 7042 } 7043 7044 case CK_ArrayToPointerDecay: { 7045 if (SubExpr->isGLValue()) { 7046 if (!evaluateLValue(SubExpr, Result)) 7047 return false; 7048 } else { 7049 APValue &Value = createTemporary(SubExpr, false, Result, 7050 *Info.CurrentCall); 7051 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 7052 return false; 7053 } 7054 // The result is a pointer to the first element of the array. 7055 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 7056 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 7057 Result.addArray(Info, E, CAT); 7058 else 7059 Result.addUnsizedArray(Info, E, AT->getElementType()); 7060 return true; 7061 } 7062 7063 case CK_FunctionToPointerDecay: 7064 return evaluateLValue(SubExpr, Result); 7065 7066 case CK_LValueToRValue: { 7067 LValue LVal; 7068 if (!evaluateLValue(E->getSubExpr(), LVal)) 7069 return false; 7070 7071 APValue RVal; 7072 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7073 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7074 LVal, RVal)) 7075 return InvalidBaseOK && 7076 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 7077 return Success(RVal, E); 7078 } 7079 } 7080 7081 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7082 } 7083 7084 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 7085 UnaryExprOrTypeTrait ExprKind) { 7086 // C++ [expr.alignof]p3: 7087 // When alignof is applied to a reference type, the result is the 7088 // alignment of the referenced type. 7089 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 7090 T = Ref->getPointeeType(); 7091 7092 if (T.getQualifiers().hasUnaligned()) 7093 return CharUnits::One(); 7094 7095 const bool AlignOfReturnsPreferred = 7096 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 7097 7098 // __alignof is defined to return the preferred alignment. 7099 // Before 8, clang returned the preferred alignment for alignof and _Alignof 7100 // as well. 7101 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 7102 return Info.Ctx.toCharUnitsFromBits( 7103 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 7104 // alignof and _Alignof are defined to return the ABI alignment. 7105 else if (ExprKind == UETT_AlignOf) 7106 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 7107 else 7108 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 7109 } 7110 7111 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 7112 UnaryExprOrTypeTrait ExprKind) { 7113 E = E->IgnoreParens(); 7114 7115 // The kinds of expressions that we have special-case logic here for 7116 // should be kept up to date with the special checks for those 7117 // expressions in Sema. 7118 7119 // alignof decl is always accepted, even if it doesn't make sense: we default 7120 // to 1 in those cases. 7121 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 7122 return Info.Ctx.getDeclAlign(DRE->getDecl(), 7123 /*RefAsPointee*/true); 7124 7125 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 7126 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 7127 /*RefAsPointee*/true); 7128 7129 return GetAlignOfType(Info, E->getType(), ExprKind); 7130 } 7131 7132 // To be clear: this happily visits unsupported builtins. Better name welcomed. 7133 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 7134 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 7135 return true; 7136 7137 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 7138 return false; 7139 7140 Result.setInvalid(E); 7141 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 7142 Result.addUnsizedArray(Info, E, PointeeTy); 7143 return true; 7144 } 7145 7146 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 7147 if (IsStringLiteralCall(E)) 7148 return Success(E); 7149 7150 if (unsigned BuiltinOp = E->getBuiltinCallee()) 7151 return VisitBuiltinCallExpr(E, BuiltinOp); 7152 7153 return visitNonBuiltinCallExpr(E); 7154 } 7155 7156 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 7157 unsigned BuiltinOp) { 7158 switch (BuiltinOp) { 7159 case Builtin::BI__builtin_addressof: 7160 return evaluateLValue(E->getArg(0), Result); 7161 case Builtin::BI__builtin_assume_aligned: { 7162 // We need to be very careful here because: if the pointer does not have the 7163 // asserted alignment, then the behavior is undefined, and undefined 7164 // behavior is non-constant. 7165 if (!evaluatePointer(E->getArg(0), Result)) 7166 return false; 7167 7168 LValue OffsetResult(Result); 7169 APSInt Alignment; 7170 if (!EvaluateInteger(E->getArg(1), Alignment, Info)) 7171 return false; 7172 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 7173 7174 if (E->getNumArgs() > 2) { 7175 APSInt Offset; 7176 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 7177 return false; 7178 7179 int64_t AdditionalOffset = -Offset.getZExtValue(); 7180 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 7181 } 7182 7183 // If there is a base object, then it must have the correct alignment. 7184 if (OffsetResult.Base) { 7185 CharUnits BaseAlignment; 7186 if (const ValueDecl *VD = 7187 OffsetResult.Base.dyn_cast<const ValueDecl*>()) { 7188 BaseAlignment = Info.Ctx.getDeclAlign(VD); 7189 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) { 7190 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf); 7191 } else { 7192 BaseAlignment = GetAlignOfType( 7193 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf); 7194 } 7195 7196 if (BaseAlignment < Align) { 7197 Result.Designator.setInvalid(); 7198 // FIXME: Add support to Diagnostic for long / long long. 7199 CCEDiag(E->getArg(0), 7200 diag::note_constexpr_baa_insufficient_alignment) << 0 7201 << (unsigned)BaseAlignment.getQuantity() 7202 << (unsigned)Align.getQuantity(); 7203 return false; 7204 } 7205 } 7206 7207 // The offset must also have the correct alignment. 7208 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 7209 Result.Designator.setInvalid(); 7210 7211 (OffsetResult.Base 7212 ? CCEDiag(E->getArg(0), 7213 diag::note_constexpr_baa_insufficient_alignment) << 1 7214 : CCEDiag(E->getArg(0), 7215 diag::note_constexpr_baa_value_insufficient_alignment)) 7216 << (int)OffsetResult.Offset.getQuantity() 7217 << (unsigned)Align.getQuantity(); 7218 return false; 7219 } 7220 7221 return true; 7222 } 7223 case Builtin::BI__builtin_launder: 7224 return evaluatePointer(E->getArg(0), Result); 7225 case Builtin::BIstrchr: 7226 case Builtin::BIwcschr: 7227 case Builtin::BImemchr: 7228 case Builtin::BIwmemchr: 7229 if (Info.getLangOpts().CPlusPlus11) 7230 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 7231 << /*isConstexpr*/0 << /*isConstructor*/0 7232 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 7233 else 7234 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 7235 LLVM_FALLTHROUGH; 7236 case Builtin::BI__builtin_strchr: 7237 case Builtin::BI__builtin_wcschr: 7238 case Builtin::BI__builtin_memchr: 7239 case Builtin::BI__builtin_char_memchr: 7240 case Builtin::BI__builtin_wmemchr: { 7241 if (!Visit(E->getArg(0))) 7242 return false; 7243 APSInt Desired; 7244 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 7245 return false; 7246 uint64_t MaxLength = uint64_t(-1); 7247 if (BuiltinOp != Builtin::BIstrchr && 7248 BuiltinOp != Builtin::BIwcschr && 7249 BuiltinOp != Builtin::BI__builtin_strchr && 7250 BuiltinOp != Builtin::BI__builtin_wcschr) { 7251 APSInt N; 7252 if (!EvaluateInteger(E->getArg(2), N, Info)) 7253 return false; 7254 MaxLength = N.getExtValue(); 7255 } 7256 // We cannot find the value if there are no candidates to match against. 7257 if (MaxLength == 0u) 7258 return ZeroInitialization(E); 7259 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 7260 Result.Designator.Invalid) 7261 return false; 7262 QualType CharTy = Result.Designator.getType(Info.Ctx); 7263 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 7264 BuiltinOp == Builtin::BI__builtin_memchr; 7265 assert(IsRawByte || 7266 Info.Ctx.hasSameUnqualifiedType( 7267 CharTy, E->getArg(0)->getType()->getPointeeType())); 7268 // Pointers to const void may point to objects of incomplete type. 7269 if (IsRawByte && CharTy->isIncompleteType()) { 7270 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 7271 return false; 7272 } 7273 // Give up on byte-oriented matching against multibyte elements. 7274 // FIXME: We can compare the bytes in the correct order. 7275 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One()) 7276 return false; 7277 // Figure out what value we're actually looking for (after converting to 7278 // the corresponding unsigned type if necessary). 7279 uint64_t DesiredVal; 7280 bool StopAtNull = false; 7281 switch (BuiltinOp) { 7282 case Builtin::BIstrchr: 7283 case Builtin::BI__builtin_strchr: 7284 // strchr compares directly to the passed integer, and therefore 7285 // always fails if given an int that is not a char. 7286 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 7287 E->getArg(1)->getType(), 7288 Desired), 7289 Desired)) 7290 return ZeroInitialization(E); 7291 StopAtNull = true; 7292 LLVM_FALLTHROUGH; 7293 case Builtin::BImemchr: 7294 case Builtin::BI__builtin_memchr: 7295 case Builtin::BI__builtin_char_memchr: 7296 // memchr compares by converting both sides to unsigned char. That's also 7297 // correct for strchr if we get this far (to cope with plain char being 7298 // unsigned in the strchr case). 7299 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 7300 break; 7301 7302 case Builtin::BIwcschr: 7303 case Builtin::BI__builtin_wcschr: 7304 StopAtNull = true; 7305 LLVM_FALLTHROUGH; 7306 case Builtin::BIwmemchr: 7307 case Builtin::BI__builtin_wmemchr: 7308 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 7309 DesiredVal = Desired.getZExtValue(); 7310 break; 7311 } 7312 7313 for (; MaxLength; --MaxLength) { 7314 APValue Char; 7315 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 7316 !Char.isInt()) 7317 return false; 7318 if (Char.getInt().getZExtValue() == DesiredVal) 7319 return true; 7320 if (StopAtNull && !Char.getInt()) 7321 break; 7322 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 7323 return false; 7324 } 7325 // Not found: return nullptr. 7326 return ZeroInitialization(E); 7327 } 7328 7329 case Builtin::BImemcpy: 7330 case Builtin::BImemmove: 7331 case Builtin::BIwmemcpy: 7332 case Builtin::BIwmemmove: 7333 if (Info.getLangOpts().CPlusPlus11) 7334 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 7335 << /*isConstexpr*/0 << /*isConstructor*/0 7336 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 7337 else 7338 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 7339 LLVM_FALLTHROUGH; 7340 case Builtin::BI__builtin_memcpy: 7341 case Builtin::BI__builtin_memmove: 7342 case Builtin::BI__builtin_wmemcpy: 7343 case Builtin::BI__builtin_wmemmove: { 7344 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 7345 BuiltinOp == Builtin::BIwmemmove || 7346 BuiltinOp == Builtin::BI__builtin_wmemcpy || 7347 BuiltinOp == Builtin::BI__builtin_wmemmove; 7348 bool Move = BuiltinOp == Builtin::BImemmove || 7349 BuiltinOp == Builtin::BIwmemmove || 7350 BuiltinOp == Builtin::BI__builtin_memmove || 7351 BuiltinOp == Builtin::BI__builtin_wmemmove; 7352 7353 // The result of mem* is the first argument. 7354 if (!Visit(E->getArg(0))) 7355 return false; 7356 LValue Dest = Result; 7357 7358 LValue Src; 7359 if (!EvaluatePointer(E->getArg(1), Src, Info)) 7360 return false; 7361 7362 APSInt N; 7363 if (!EvaluateInteger(E->getArg(2), N, Info)) 7364 return false; 7365 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 7366 7367 // If the size is zero, we treat this as always being a valid no-op. 7368 // (Even if one of the src and dest pointers is null.) 7369 if (!N) 7370 return true; 7371 7372 // Otherwise, if either of the operands is null, we can't proceed. Don't 7373 // try to determine the type of the copied objects, because there aren't 7374 // any. 7375 if (!Src.Base || !Dest.Base) { 7376 APValue Val; 7377 (!Src.Base ? Src : Dest).moveInto(Val); 7378 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 7379 << Move << WChar << !!Src.Base 7380 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 7381 return false; 7382 } 7383 if (Src.Designator.Invalid || Dest.Designator.Invalid) 7384 return false; 7385 7386 // We require that Src and Dest are both pointers to arrays of 7387 // trivially-copyable type. (For the wide version, the designator will be 7388 // invalid if the designated object is not a wchar_t.) 7389 QualType T = Dest.Designator.getType(Info.Ctx); 7390 QualType SrcT = Src.Designator.getType(Info.Ctx); 7391 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 7392 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 7393 return false; 7394 } 7395 if (T->isIncompleteType()) { 7396 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 7397 return false; 7398 } 7399 if (!T.isTriviallyCopyableType(Info.Ctx)) { 7400 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 7401 return false; 7402 } 7403 7404 // Figure out how many T's we're copying. 7405 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 7406 if (!WChar) { 7407 uint64_t Remainder; 7408 llvm::APInt OrigN = N; 7409 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 7410 if (Remainder) { 7411 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 7412 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 7413 << (unsigned)TSize; 7414 return false; 7415 } 7416 } 7417 7418 // Check that the copying will remain within the arrays, just so that we 7419 // can give a more meaningful diagnostic. This implicitly also checks that 7420 // N fits into 64 bits. 7421 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 7422 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 7423 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 7424 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 7425 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 7426 << N.toString(10, /*Signed*/false); 7427 return false; 7428 } 7429 uint64_t NElems = N.getZExtValue(); 7430 uint64_t NBytes = NElems * TSize; 7431 7432 // Check for overlap. 7433 int Direction = 1; 7434 if (HasSameBase(Src, Dest)) { 7435 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 7436 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 7437 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 7438 // Dest is inside the source region. 7439 if (!Move) { 7440 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 7441 return false; 7442 } 7443 // For memmove and friends, copy backwards. 7444 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 7445 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 7446 return false; 7447 Direction = -1; 7448 } else if (!Move && SrcOffset >= DestOffset && 7449 SrcOffset - DestOffset < NBytes) { 7450 // Src is inside the destination region for memcpy: invalid. 7451 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 7452 return false; 7453 } 7454 } 7455 7456 while (true) { 7457 APValue Val; 7458 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 7459 !handleAssignment(Info, E, Dest, T, Val)) 7460 return false; 7461 // Do not iterate past the last element; if we're copying backwards, that 7462 // might take us off the start of the array. 7463 if (--NElems == 0) 7464 return true; 7465 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 7466 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 7467 return false; 7468 } 7469 } 7470 7471 default: 7472 return visitNonBuiltinCallExpr(E); 7473 } 7474 } 7475 7476 //===----------------------------------------------------------------------===// 7477 // Member Pointer Evaluation 7478 //===----------------------------------------------------------------------===// 7479 7480 namespace { 7481 class MemberPointerExprEvaluator 7482 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 7483 MemberPtr &Result; 7484 7485 bool Success(const ValueDecl *D) { 7486 Result = MemberPtr(D); 7487 return true; 7488 } 7489 public: 7490 7491 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 7492 : ExprEvaluatorBaseTy(Info), Result(Result) {} 7493 7494 bool Success(const APValue &V, const Expr *E) { 7495 Result.setFrom(V); 7496 return true; 7497 } 7498 bool ZeroInitialization(const Expr *E) { 7499 return Success((const ValueDecl*)nullptr); 7500 } 7501 7502 bool VisitCastExpr(const CastExpr *E); 7503 bool VisitUnaryAddrOf(const UnaryOperator *E); 7504 }; 7505 } // end anonymous namespace 7506 7507 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 7508 EvalInfo &Info) { 7509 assert(E->isRValue() && E->getType()->isMemberPointerType()); 7510 return MemberPointerExprEvaluator(Info, Result).Visit(E); 7511 } 7512 7513 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 7514 switch (E->getCastKind()) { 7515 default: 7516 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7517 7518 case CK_NullToMemberPointer: 7519 VisitIgnoredValue(E->getSubExpr()); 7520 return ZeroInitialization(E); 7521 7522 case CK_BaseToDerivedMemberPointer: { 7523 if (!Visit(E->getSubExpr())) 7524 return false; 7525 if (E->path_empty()) 7526 return true; 7527 // Base-to-derived member pointer casts store the path in derived-to-base 7528 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 7529 // the wrong end of the derived->base arc, so stagger the path by one class. 7530 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 7531 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 7532 PathI != PathE; ++PathI) { 7533 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 7534 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 7535 if (!Result.castToDerived(Derived)) 7536 return Error(E); 7537 } 7538 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 7539 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 7540 return Error(E); 7541 return true; 7542 } 7543 7544 case CK_DerivedToBaseMemberPointer: 7545 if (!Visit(E->getSubExpr())) 7546 return false; 7547 for (CastExpr::path_const_iterator PathI = E->path_begin(), 7548 PathE = E->path_end(); PathI != PathE; ++PathI) { 7549 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 7550 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 7551 if (!Result.castToBase(Base)) 7552 return Error(E); 7553 } 7554 return true; 7555 } 7556 } 7557 7558 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 7559 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 7560 // member can be formed. 7561 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 7562 } 7563 7564 //===----------------------------------------------------------------------===// 7565 // Record Evaluation 7566 //===----------------------------------------------------------------------===// 7567 7568 namespace { 7569 class RecordExprEvaluator 7570 : public ExprEvaluatorBase<RecordExprEvaluator> { 7571 const LValue &This; 7572 APValue &Result; 7573 public: 7574 7575 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 7576 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 7577 7578 bool Success(const APValue &V, const Expr *E) { 7579 Result = V; 7580 return true; 7581 } 7582 bool ZeroInitialization(const Expr *E) { 7583 return ZeroInitialization(E, E->getType()); 7584 } 7585 bool ZeroInitialization(const Expr *E, QualType T); 7586 7587 bool VisitCallExpr(const CallExpr *E) { 7588 return handleCallExpr(E, Result, &This); 7589 } 7590 bool VisitCastExpr(const CastExpr *E); 7591 bool VisitInitListExpr(const InitListExpr *E); 7592 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 7593 return VisitCXXConstructExpr(E, E->getType()); 7594 } 7595 bool VisitLambdaExpr(const LambdaExpr *E); 7596 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 7597 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 7598 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 7599 7600 bool VisitBinCmp(const BinaryOperator *E); 7601 }; 7602 } 7603 7604 /// Perform zero-initialization on an object of non-union class type. 7605 /// C++11 [dcl.init]p5: 7606 /// To zero-initialize an object or reference of type T means: 7607 /// [...] 7608 /// -- if T is a (possibly cv-qualified) non-union class type, 7609 /// each non-static data member and each base-class subobject is 7610 /// zero-initialized 7611 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 7612 const RecordDecl *RD, 7613 const LValue &This, APValue &Result) { 7614 assert(!RD->isUnion() && "Expected non-union class type"); 7615 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 7616 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 7617 std::distance(RD->field_begin(), RD->field_end())); 7618 7619 if (RD->isInvalidDecl()) return false; 7620 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7621 7622 if (CD) { 7623 unsigned Index = 0; 7624 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 7625 End = CD->bases_end(); I != End; ++I, ++Index) { 7626 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 7627 LValue Subobject = This; 7628 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 7629 return false; 7630 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 7631 Result.getStructBase(Index))) 7632 return false; 7633 } 7634 } 7635 7636 for (const auto *I : RD->fields()) { 7637 // -- if T is a reference type, no initialization is performed. 7638 if (I->getType()->isReferenceType()) 7639 continue; 7640 7641 LValue Subobject = This; 7642 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 7643 return false; 7644 7645 ImplicitValueInitExpr VIE(I->getType()); 7646 if (!EvaluateInPlace( 7647 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 7648 return false; 7649 } 7650 7651 return true; 7652 } 7653 7654 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 7655 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 7656 if (RD->isInvalidDecl()) return false; 7657 if (RD->isUnion()) { 7658 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 7659 // object's first non-static named data member is zero-initialized 7660 RecordDecl::field_iterator I = RD->field_begin(); 7661 if (I == RD->field_end()) { 7662 Result = APValue((const FieldDecl*)nullptr); 7663 return true; 7664 } 7665 7666 LValue Subobject = This; 7667 if (!HandleLValueMember(Info, E, Subobject, *I)) 7668 return false; 7669 Result = APValue(*I); 7670 ImplicitValueInitExpr VIE(I->getType()); 7671 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 7672 } 7673 7674 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 7675 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 7676 return false; 7677 } 7678 7679 return HandleClassZeroInitialization(Info, E, RD, This, Result); 7680 } 7681 7682 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 7683 switch (E->getCastKind()) { 7684 default: 7685 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7686 7687 case CK_ConstructorConversion: 7688 return Visit(E->getSubExpr()); 7689 7690 case CK_DerivedToBase: 7691 case CK_UncheckedDerivedToBase: { 7692 APValue DerivedObject; 7693 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 7694 return false; 7695 if (!DerivedObject.isStruct()) 7696 return Error(E->getSubExpr()); 7697 7698 // Derived-to-base rvalue conversion: just slice off the derived part. 7699 APValue *Value = &DerivedObject; 7700 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 7701 for (CastExpr::path_const_iterator PathI = E->path_begin(), 7702 PathE = E->path_end(); PathI != PathE; ++PathI) { 7703 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 7704 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 7705 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 7706 RD = Base; 7707 } 7708 Result = *Value; 7709 return true; 7710 } 7711 } 7712 } 7713 7714 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 7715 if (E->isTransparent()) 7716 return Visit(E->getInit(0)); 7717 7718 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 7719 if (RD->isInvalidDecl()) return false; 7720 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7721 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 7722 7723 EvalInfo::EvaluatingConstructorRAII EvalObj( 7724 Info, 7725 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 7726 CXXRD && CXXRD->getNumBases()); 7727 7728 if (RD->isUnion()) { 7729 const FieldDecl *Field = E->getInitializedFieldInUnion(); 7730 Result = APValue(Field); 7731 if (!Field) 7732 return true; 7733 7734 // If the initializer list for a union does not contain any elements, the 7735 // first element of the union is value-initialized. 7736 // FIXME: The element should be initialized from an initializer list. 7737 // Is this difference ever observable for initializer lists which 7738 // we don't build? 7739 ImplicitValueInitExpr VIE(Field->getType()); 7740 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 7741 7742 LValue Subobject = This; 7743 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 7744 return false; 7745 7746 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 7747 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 7748 isa<CXXDefaultInitExpr>(InitExpr)); 7749 7750 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 7751 } 7752 7753 if (!Result.hasValue()) 7754 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 7755 std::distance(RD->field_begin(), RD->field_end())); 7756 unsigned ElementNo = 0; 7757 bool Success = true; 7758 7759 // Initialize base classes. 7760 if (CXXRD && CXXRD->getNumBases()) { 7761 for (const auto &Base : CXXRD->bases()) { 7762 assert(ElementNo < E->getNumInits() && "missing init for base class"); 7763 const Expr *Init = E->getInit(ElementNo); 7764 7765 LValue Subobject = This; 7766 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 7767 return false; 7768 7769 APValue &FieldVal = Result.getStructBase(ElementNo); 7770 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 7771 if (!Info.noteFailure()) 7772 return false; 7773 Success = false; 7774 } 7775 ++ElementNo; 7776 } 7777 7778 EvalObj.finishedConstructingBases(); 7779 } 7780 7781 // Initialize members. 7782 for (const auto *Field : RD->fields()) { 7783 // Anonymous bit-fields are not considered members of the class for 7784 // purposes of aggregate initialization. 7785 if (Field->isUnnamedBitfield()) 7786 continue; 7787 7788 LValue Subobject = This; 7789 7790 bool HaveInit = ElementNo < E->getNumInits(); 7791 7792 // FIXME: Diagnostics here should point to the end of the initializer 7793 // list, not the start. 7794 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 7795 Subobject, Field, &Layout)) 7796 return false; 7797 7798 // Perform an implicit value-initialization for members beyond the end of 7799 // the initializer list. 7800 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 7801 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 7802 7803 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 7804 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 7805 isa<CXXDefaultInitExpr>(Init)); 7806 7807 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 7808 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 7809 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 7810 FieldVal, Field))) { 7811 if (!Info.noteFailure()) 7812 return false; 7813 Success = false; 7814 } 7815 } 7816 7817 return Success; 7818 } 7819 7820 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 7821 QualType T) { 7822 // Note that E's type is not necessarily the type of our class here; we might 7823 // be initializing an array element instead. 7824 const CXXConstructorDecl *FD = E->getConstructor(); 7825 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 7826 7827 bool ZeroInit = E->requiresZeroInitialization(); 7828 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 7829 // If we've already performed zero-initialization, we're already done. 7830 if (Result.hasValue()) 7831 return true; 7832 7833 // We can get here in two different ways: 7834 // 1) We're performing value-initialization, and should zero-initialize 7835 // the object, or 7836 // 2) We're performing default-initialization of an object with a trivial 7837 // constexpr default constructor, in which case we should start the 7838 // lifetimes of all the base subobjects (there can be no data member 7839 // subobjects in this case) per [basic.life]p1. 7840 // Either way, ZeroInitialization is appropriate. 7841 return ZeroInitialization(E, T); 7842 } 7843 7844 const FunctionDecl *Definition = nullptr; 7845 auto Body = FD->getBody(Definition); 7846 7847 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 7848 return false; 7849 7850 // Avoid materializing a temporary for an elidable copy/move constructor. 7851 if (E->isElidable() && !ZeroInit) 7852 if (const MaterializeTemporaryExpr *ME 7853 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 7854 return Visit(ME->GetTemporaryExpr()); 7855 7856 if (ZeroInit && !ZeroInitialization(E, T)) 7857 return false; 7858 7859 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7860 return HandleConstructorCall(E, This, Args, 7861 cast<CXXConstructorDecl>(Definition), Info, 7862 Result); 7863 } 7864 7865 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 7866 const CXXInheritedCtorInitExpr *E) { 7867 if (!Info.CurrentCall) { 7868 assert(Info.checkingPotentialConstantExpression()); 7869 return false; 7870 } 7871 7872 const CXXConstructorDecl *FD = E->getConstructor(); 7873 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 7874 return false; 7875 7876 const FunctionDecl *Definition = nullptr; 7877 auto Body = FD->getBody(Definition); 7878 7879 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 7880 return false; 7881 7882 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 7883 cast<CXXConstructorDecl>(Definition), Info, 7884 Result); 7885 } 7886 7887 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 7888 const CXXStdInitializerListExpr *E) { 7889 const ConstantArrayType *ArrayType = 7890 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 7891 7892 LValue Array; 7893 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 7894 return false; 7895 7896 // Get a pointer to the first element of the array. 7897 Array.addArray(Info, E, ArrayType); 7898 7899 // FIXME: Perform the checks on the field types in SemaInit. 7900 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 7901 RecordDecl::field_iterator Field = Record->field_begin(); 7902 if (Field == Record->field_end()) 7903 return Error(E); 7904 7905 // Start pointer. 7906 if (!Field->getType()->isPointerType() || 7907 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 7908 ArrayType->getElementType())) 7909 return Error(E); 7910 7911 // FIXME: What if the initializer_list type has base classes, etc? 7912 Result = APValue(APValue::UninitStruct(), 0, 2); 7913 Array.moveInto(Result.getStructField(0)); 7914 7915 if (++Field == Record->field_end()) 7916 return Error(E); 7917 7918 if (Field->getType()->isPointerType() && 7919 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 7920 ArrayType->getElementType())) { 7921 // End pointer. 7922 if (!HandleLValueArrayAdjustment(Info, E, Array, 7923 ArrayType->getElementType(), 7924 ArrayType->getSize().getZExtValue())) 7925 return false; 7926 Array.moveInto(Result.getStructField(1)); 7927 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 7928 // Length. 7929 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 7930 else 7931 return Error(E); 7932 7933 if (++Field != Record->field_end()) 7934 return Error(E); 7935 7936 return true; 7937 } 7938 7939 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 7940 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 7941 if (ClosureClass->isInvalidDecl()) return false; 7942 7943 if (Info.checkingPotentialConstantExpression()) return true; 7944 7945 const size_t NumFields = 7946 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 7947 7948 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 7949 E->capture_init_end()) && 7950 "The number of lambda capture initializers should equal the number of " 7951 "fields within the closure type"); 7952 7953 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 7954 // Iterate through all the lambda's closure object's fields and initialize 7955 // them. 7956 auto *CaptureInitIt = E->capture_init_begin(); 7957 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 7958 bool Success = true; 7959 for (const auto *Field : ClosureClass->fields()) { 7960 assert(CaptureInitIt != E->capture_init_end()); 7961 // Get the initializer for this field 7962 Expr *const CurFieldInit = *CaptureInitIt++; 7963 7964 // If there is no initializer, either this is a VLA or an error has 7965 // occurred. 7966 if (!CurFieldInit) 7967 return Error(E); 7968 7969 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 7970 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 7971 if (!Info.keepEvaluatingAfterFailure()) 7972 return false; 7973 Success = false; 7974 } 7975 ++CaptureIt; 7976 } 7977 return Success; 7978 } 7979 7980 static bool EvaluateRecord(const Expr *E, const LValue &This, 7981 APValue &Result, EvalInfo &Info) { 7982 assert(E->isRValue() && E->getType()->isRecordType() && 7983 "can't evaluate expression as a record rvalue"); 7984 return RecordExprEvaluator(Info, This, Result).Visit(E); 7985 } 7986 7987 //===----------------------------------------------------------------------===// 7988 // Temporary Evaluation 7989 // 7990 // Temporaries are represented in the AST as rvalues, but generally behave like 7991 // lvalues. The full-object of which the temporary is a subobject is implicitly 7992 // materialized so that a reference can bind to it. 7993 //===----------------------------------------------------------------------===// 7994 namespace { 7995 class TemporaryExprEvaluator 7996 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 7997 public: 7998 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 7999 LValueExprEvaluatorBaseTy(Info, Result, false) {} 8000 8001 /// Visit an expression which constructs the value of this temporary. 8002 bool VisitConstructExpr(const Expr *E) { 8003 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall); 8004 return EvaluateInPlace(Value, Info, Result, E); 8005 } 8006 8007 bool VisitCastExpr(const CastExpr *E) { 8008 switch (E->getCastKind()) { 8009 default: 8010 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8011 8012 case CK_ConstructorConversion: 8013 return VisitConstructExpr(E->getSubExpr()); 8014 } 8015 } 8016 bool VisitInitListExpr(const InitListExpr *E) { 8017 return VisitConstructExpr(E); 8018 } 8019 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 8020 return VisitConstructExpr(E); 8021 } 8022 bool VisitCallExpr(const CallExpr *E) { 8023 return VisitConstructExpr(E); 8024 } 8025 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 8026 return VisitConstructExpr(E); 8027 } 8028 bool VisitLambdaExpr(const LambdaExpr *E) { 8029 return VisitConstructExpr(E); 8030 } 8031 }; 8032 } // end anonymous namespace 8033 8034 /// Evaluate an expression of record type as a temporary. 8035 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 8036 assert(E->isRValue() && E->getType()->isRecordType()); 8037 return TemporaryExprEvaluator(Info, Result).Visit(E); 8038 } 8039 8040 //===----------------------------------------------------------------------===// 8041 // Vector Evaluation 8042 //===----------------------------------------------------------------------===// 8043 8044 namespace { 8045 class VectorExprEvaluator 8046 : public ExprEvaluatorBase<VectorExprEvaluator> { 8047 APValue &Result; 8048 public: 8049 8050 VectorExprEvaluator(EvalInfo &info, APValue &Result) 8051 : ExprEvaluatorBaseTy(info), Result(Result) {} 8052 8053 bool Success(ArrayRef<APValue> V, const Expr *E) { 8054 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 8055 // FIXME: remove this APValue copy. 8056 Result = APValue(V.data(), V.size()); 8057 return true; 8058 } 8059 bool Success(const APValue &V, const Expr *E) { 8060 assert(V.isVector()); 8061 Result = V; 8062 return true; 8063 } 8064 bool ZeroInitialization(const Expr *E); 8065 8066 bool VisitUnaryReal(const UnaryOperator *E) 8067 { return Visit(E->getSubExpr()); } 8068 bool VisitCastExpr(const CastExpr* E); 8069 bool VisitInitListExpr(const InitListExpr *E); 8070 bool VisitUnaryImag(const UnaryOperator *E); 8071 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 8072 // binary comparisons, binary and/or/xor, 8073 // shufflevector, ExtVectorElementExpr 8074 }; 8075 } // end anonymous namespace 8076 8077 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 8078 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 8079 return VectorExprEvaluator(Info, Result).Visit(E); 8080 } 8081 8082 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 8083 const VectorType *VTy = E->getType()->castAs<VectorType>(); 8084 unsigned NElts = VTy->getNumElements(); 8085 8086 const Expr *SE = E->getSubExpr(); 8087 QualType SETy = SE->getType(); 8088 8089 switch (E->getCastKind()) { 8090 case CK_VectorSplat: { 8091 APValue Val = APValue(); 8092 if (SETy->isIntegerType()) { 8093 APSInt IntResult; 8094 if (!EvaluateInteger(SE, IntResult, Info)) 8095 return false; 8096 Val = APValue(std::move(IntResult)); 8097 } else if (SETy->isRealFloatingType()) { 8098 APFloat FloatResult(0.0); 8099 if (!EvaluateFloat(SE, FloatResult, Info)) 8100 return false; 8101 Val = APValue(std::move(FloatResult)); 8102 } else { 8103 return Error(E); 8104 } 8105 8106 // Splat and create vector APValue. 8107 SmallVector<APValue, 4> Elts(NElts, Val); 8108 return Success(Elts, E); 8109 } 8110 case CK_BitCast: { 8111 // Evaluate the operand into an APInt we can extract from. 8112 llvm::APInt SValInt; 8113 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 8114 return false; 8115 // Extract the elements 8116 QualType EltTy = VTy->getElementType(); 8117 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 8118 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 8119 SmallVector<APValue, 4> Elts; 8120 if (EltTy->isRealFloatingType()) { 8121 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 8122 unsigned FloatEltSize = EltSize; 8123 if (&Sem == &APFloat::x87DoubleExtended()) 8124 FloatEltSize = 80; 8125 for (unsigned i = 0; i < NElts; i++) { 8126 llvm::APInt Elt; 8127 if (BigEndian) 8128 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 8129 else 8130 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 8131 Elts.push_back(APValue(APFloat(Sem, Elt))); 8132 } 8133 } else if (EltTy->isIntegerType()) { 8134 for (unsigned i = 0; i < NElts; i++) { 8135 llvm::APInt Elt; 8136 if (BigEndian) 8137 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 8138 else 8139 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 8140 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 8141 } 8142 } else { 8143 return Error(E); 8144 } 8145 return Success(Elts, E); 8146 } 8147 default: 8148 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8149 } 8150 } 8151 8152 bool 8153 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 8154 const VectorType *VT = E->getType()->castAs<VectorType>(); 8155 unsigned NumInits = E->getNumInits(); 8156 unsigned NumElements = VT->getNumElements(); 8157 8158 QualType EltTy = VT->getElementType(); 8159 SmallVector<APValue, 4> Elements; 8160 8161 // The number of initializers can be less than the number of 8162 // vector elements. For OpenCL, this can be due to nested vector 8163 // initialization. For GCC compatibility, missing trailing elements 8164 // should be initialized with zeroes. 8165 unsigned CountInits = 0, CountElts = 0; 8166 while (CountElts < NumElements) { 8167 // Handle nested vector initialization. 8168 if (CountInits < NumInits 8169 && E->getInit(CountInits)->getType()->isVectorType()) { 8170 APValue v; 8171 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 8172 return Error(E); 8173 unsigned vlen = v.getVectorLength(); 8174 for (unsigned j = 0; j < vlen; j++) 8175 Elements.push_back(v.getVectorElt(j)); 8176 CountElts += vlen; 8177 } else if (EltTy->isIntegerType()) { 8178 llvm::APSInt sInt(32); 8179 if (CountInits < NumInits) { 8180 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 8181 return false; 8182 } else // trailing integer zero. 8183 sInt = Info.Ctx.MakeIntValue(0, EltTy); 8184 Elements.push_back(APValue(sInt)); 8185 CountElts++; 8186 } else { 8187 llvm::APFloat f(0.0); 8188 if (CountInits < NumInits) { 8189 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 8190 return false; 8191 } else // trailing float zero. 8192 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 8193 Elements.push_back(APValue(f)); 8194 CountElts++; 8195 } 8196 CountInits++; 8197 } 8198 return Success(Elements, E); 8199 } 8200 8201 bool 8202 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 8203 const VectorType *VT = E->getType()->getAs<VectorType>(); 8204 QualType EltTy = VT->getElementType(); 8205 APValue ZeroElement; 8206 if (EltTy->isIntegerType()) 8207 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 8208 else 8209 ZeroElement = 8210 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 8211 8212 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 8213 return Success(Elements, E); 8214 } 8215 8216 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8217 VisitIgnoredValue(E->getSubExpr()); 8218 return ZeroInitialization(E); 8219 } 8220 8221 //===----------------------------------------------------------------------===// 8222 // Array Evaluation 8223 //===----------------------------------------------------------------------===// 8224 8225 namespace { 8226 class ArrayExprEvaluator 8227 : public ExprEvaluatorBase<ArrayExprEvaluator> { 8228 const LValue &This; 8229 APValue &Result; 8230 public: 8231 8232 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 8233 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 8234 8235 bool Success(const APValue &V, const Expr *E) { 8236 assert(V.isArray() && "expected array"); 8237 Result = V; 8238 return true; 8239 } 8240 8241 bool ZeroInitialization(const Expr *E) { 8242 const ConstantArrayType *CAT = 8243 Info.Ctx.getAsConstantArrayType(E->getType()); 8244 if (!CAT) 8245 return Error(E); 8246 8247 Result = APValue(APValue::UninitArray(), 0, 8248 CAT->getSize().getZExtValue()); 8249 if (!Result.hasArrayFiller()) return true; 8250 8251 // Zero-initialize all elements. 8252 LValue Subobject = This; 8253 Subobject.addArray(Info, E, CAT); 8254 ImplicitValueInitExpr VIE(CAT->getElementType()); 8255 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 8256 } 8257 8258 bool VisitCallExpr(const CallExpr *E) { 8259 return handleCallExpr(E, Result, &This); 8260 } 8261 bool VisitInitListExpr(const InitListExpr *E); 8262 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 8263 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 8264 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 8265 const LValue &Subobject, 8266 APValue *Value, QualType Type); 8267 bool VisitStringLiteral(const StringLiteral *E) { 8268 expandStringLiteral(Info, E, Result); 8269 return true; 8270 } 8271 }; 8272 } // end anonymous namespace 8273 8274 static bool EvaluateArray(const Expr *E, const LValue &This, 8275 APValue &Result, EvalInfo &Info) { 8276 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 8277 return ArrayExprEvaluator(Info, This, Result).Visit(E); 8278 } 8279 8280 // Return true iff the given array filler may depend on the element index. 8281 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 8282 // For now, just whitelist non-class value-initialization and initialization 8283 // lists comprised of them. 8284 if (isa<ImplicitValueInitExpr>(FillerExpr)) 8285 return false; 8286 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 8287 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 8288 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 8289 return true; 8290 } 8291 return false; 8292 } 8293 return true; 8294 } 8295 8296 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 8297 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 8298 if (!CAT) 8299 return Error(E); 8300 8301 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 8302 // an appropriately-typed string literal enclosed in braces. 8303 if (E->isStringLiteralInit()) 8304 return Visit(E->getInit(0)); 8305 8306 bool Success = true; 8307 8308 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 8309 "zero-initialized array shouldn't have any initialized elts"); 8310 APValue Filler; 8311 if (Result.isArray() && Result.hasArrayFiller()) 8312 Filler = Result.getArrayFiller(); 8313 8314 unsigned NumEltsToInit = E->getNumInits(); 8315 unsigned NumElts = CAT->getSize().getZExtValue(); 8316 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 8317 8318 // If the initializer might depend on the array index, run it for each 8319 // array element. 8320 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 8321 NumEltsToInit = NumElts; 8322 8323 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 8324 << NumEltsToInit << ".\n"); 8325 8326 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 8327 8328 // If the array was previously zero-initialized, preserve the 8329 // zero-initialized values. 8330 if (Filler.hasValue()) { 8331 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 8332 Result.getArrayInitializedElt(I) = Filler; 8333 if (Result.hasArrayFiller()) 8334 Result.getArrayFiller() = Filler; 8335 } 8336 8337 LValue Subobject = This; 8338 Subobject.addArray(Info, E, CAT); 8339 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 8340 const Expr *Init = 8341 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 8342 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 8343 Info, Subobject, Init) || 8344 !HandleLValueArrayAdjustment(Info, Init, Subobject, 8345 CAT->getElementType(), 1)) { 8346 if (!Info.noteFailure()) 8347 return false; 8348 Success = false; 8349 } 8350 } 8351 8352 if (!Result.hasArrayFiller()) 8353 return Success; 8354 8355 // If we get here, we have a trivial filler, which we can just evaluate 8356 // once and splat over the rest of the array elements. 8357 assert(FillerExpr && "no array filler for incomplete init list"); 8358 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 8359 FillerExpr) && Success; 8360 } 8361 8362 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 8363 if (E->getCommonExpr() && 8364 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false), 8365 Info, E->getCommonExpr()->getSourceExpr())) 8366 return false; 8367 8368 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 8369 8370 uint64_t Elements = CAT->getSize().getZExtValue(); 8371 Result = APValue(APValue::UninitArray(), Elements, Elements); 8372 8373 LValue Subobject = This; 8374 Subobject.addArray(Info, E, CAT); 8375 8376 bool Success = true; 8377 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 8378 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 8379 Info, Subobject, E->getSubExpr()) || 8380 !HandleLValueArrayAdjustment(Info, E, Subobject, 8381 CAT->getElementType(), 1)) { 8382 if (!Info.noteFailure()) 8383 return false; 8384 Success = false; 8385 } 8386 } 8387 8388 return Success; 8389 } 8390 8391 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 8392 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 8393 } 8394 8395 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 8396 const LValue &Subobject, 8397 APValue *Value, 8398 QualType Type) { 8399 bool HadZeroInit = Value->hasValue(); 8400 8401 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 8402 unsigned N = CAT->getSize().getZExtValue(); 8403 8404 // Preserve the array filler if we had prior zero-initialization. 8405 APValue Filler = 8406 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 8407 : APValue(); 8408 8409 *Value = APValue(APValue::UninitArray(), N, N); 8410 8411 if (HadZeroInit) 8412 for (unsigned I = 0; I != N; ++I) 8413 Value->getArrayInitializedElt(I) = Filler; 8414 8415 // Initialize the elements. 8416 LValue ArrayElt = Subobject; 8417 ArrayElt.addArray(Info, E, CAT); 8418 for (unsigned I = 0; I != N; ++I) 8419 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 8420 CAT->getElementType()) || 8421 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 8422 CAT->getElementType(), 1)) 8423 return false; 8424 8425 return true; 8426 } 8427 8428 if (!Type->isRecordType()) 8429 return Error(E); 8430 8431 return RecordExprEvaluator(Info, Subobject, *Value) 8432 .VisitCXXConstructExpr(E, Type); 8433 } 8434 8435 //===----------------------------------------------------------------------===// 8436 // Integer Evaluation 8437 // 8438 // As a GNU extension, we support casting pointers to sufficiently-wide integer 8439 // types and back in constant folding. Integer values are thus represented 8440 // either as an integer-valued APValue, or as an lvalue-valued APValue. 8441 //===----------------------------------------------------------------------===// 8442 8443 namespace { 8444 class IntExprEvaluator 8445 : public ExprEvaluatorBase<IntExprEvaluator> { 8446 APValue &Result; 8447 public: 8448 IntExprEvaluator(EvalInfo &info, APValue &result) 8449 : ExprEvaluatorBaseTy(info), Result(result) {} 8450 8451 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 8452 assert(E->getType()->isIntegralOrEnumerationType() && 8453 "Invalid evaluation result."); 8454 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 8455 "Invalid evaluation result."); 8456 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 8457 "Invalid evaluation result."); 8458 Result = APValue(SI); 8459 return true; 8460 } 8461 bool Success(const llvm::APSInt &SI, const Expr *E) { 8462 return Success(SI, E, Result); 8463 } 8464 8465 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 8466 assert(E->getType()->isIntegralOrEnumerationType() && 8467 "Invalid evaluation result."); 8468 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 8469 "Invalid evaluation result."); 8470 Result = APValue(APSInt(I)); 8471 Result.getInt().setIsUnsigned( 8472 E->getType()->isUnsignedIntegerOrEnumerationType()); 8473 return true; 8474 } 8475 bool Success(const llvm::APInt &I, const Expr *E) { 8476 return Success(I, E, Result); 8477 } 8478 8479 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 8480 assert(E->getType()->isIntegralOrEnumerationType() && 8481 "Invalid evaluation result."); 8482 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 8483 return true; 8484 } 8485 bool Success(uint64_t Value, const Expr *E) { 8486 return Success(Value, E, Result); 8487 } 8488 8489 bool Success(CharUnits Size, const Expr *E) { 8490 return Success(Size.getQuantity(), E); 8491 } 8492 8493 bool Success(const APValue &V, const Expr *E) { 8494 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 8495 Result = V; 8496 return true; 8497 } 8498 return Success(V.getInt(), E); 8499 } 8500 8501 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 8502 8503 //===--------------------------------------------------------------------===// 8504 // Visitor Methods 8505 //===--------------------------------------------------------------------===// 8506 8507 bool VisitConstantExpr(const ConstantExpr *E); 8508 8509 bool VisitIntegerLiteral(const IntegerLiteral *E) { 8510 return Success(E->getValue(), E); 8511 } 8512 bool VisitCharacterLiteral(const CharacterLiteral *E) { 8513 return Success(E->getValue(), E); 8514 } 8515 8516 bool CheckReferencedDecl(const Expr *E, const Decl *D); 8517 bool VisitDeclRefExpr(const DeclRefExpr *E) { 8518 if (CheckReferencedDecl(E, E->getDecl())) 8519 return true; 8520 8521 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 8522 } 8523 bool VisitMemberExpr(const MemberExpr *E) { 8524 if (CheckReferencedDecl(E, E->getMemberDecl())) { 8525 VisitIgnoredBaseExpression(E->getBase()); 8526 return true; 8527 } 8528 8529 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 8530 } 8531 8532 bool VisitCallExpr(const CallExpr *E); 8533 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8534 bool VisitBinaryOperator(const BinaryOperator *E); 8535 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 8536 bool VisitUnaryOperator(const UnaryOperator *E); 8537 8538 bool VisitCastExpr(const CastExpr* E); 8539 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 8540 8541 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 8542 return Success(E->getValue(), E); 8543 } 8544 8545 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 8546 return Success(E->getValue(), E); 8547 } 8548 8549 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 8550 if (Info.ArrayInitIndex == uint64_t(-1)) { 8551 // We were asked to evaluate this subexpression independent of the 8552 // enclosing ArrayInitLoopExpr. We can't do that. 8553 Info.FFDiag(E); 8554 return false; 8555 } 8556 return Success(Info.ArrayInitIndex, E); 8557 } 8558 8559 // Note, GNU defines __null as an integer, not a pointer. 8560 bool VisitGNUNullExpr(const GNUNullExpr *E) { 8561 return ZeroInitialization(E); 8562 } 8563 8564 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 8565 return Success(E->getValue(), E); 8566 } 8567 8568 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 8569 return Success(E->getValue(), E); 8570 } 8571 8572 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 8573 return Success(E->getValue(), E); 8574 } 8575 8576 bool VisitUnaryReal(const UnaryOperator *E); 8577 bool VisitUnaryImag(const UnaryOperator *E); 8578 8579 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 8580 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 8581 bool VisitSourceLocExpr(const SourceLocExpr *E); 8582 // FIXME: Missing: array subscript of vector, member of vector 8583 }; 8584 8585 class FixedPointExprEvaluator 8586 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 8587 APValue &Result; 8588 8589 public: 8590 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 8591 : ExprEvaluatorBaseTy(info), Result(result) {} 8592 8593 bool Success(const llvm::APInt &I, const Expr *E) { 8594 return Success( 8595 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 8596 } 8597 8598 bool Success(uint64_t Value, const Expr *E) { 8599 return Success( 8600 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 8601 } 8602 8603 bool Success(const APValue &V, const Expr *E) { 8604 return Success(V.getFixedPoint(), E); 8605 } 8606 8607 bool Success(const APFixedPoint &V, const Expr *E) { 8608 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 8609 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 8610 "Invalid evaluation result."); 8611 Result = APValue(V); 8612 return true; 8613 } 8614 8615 //===--------------------------------------------------------------------===// 8616 // Visitor Methods 8617 //===--------------------------------------------------------------------===// 8618 8619 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 8620 return Success(E->getValue(), E); 8621 } 8622 8623 bool VisitCastExpr(const CastExpr *E); 8624 bool VisitUnaryOperator(const UnaryOperator *E); 8625 bool VisitBinaryOperator(const BinaryOperator *E); 8626 }; 8627 } // end anonymous namespace 8628 8629 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 8630 /// produce either the integer value or a pointer. 8631 /// 8632 /// GCC has a heinous extension which folds casts between pointer types and 8633 /// pointer-sized integral types. We support this by allowing the evaluation of 8634 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 8635 /// Some simple arithmetic on such values is supported (they are treated much 8636 /// like char*). 8637 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 8638 EvalInfo &Info) { 8639 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 8640 return IntExprEvaluator(Info, Result).Visit(E); 8641 } 8642 8643 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 8644 APValue Val; 8645 if (!EvaluateIntegerOrLValue(E, Val, Info)) 8646 return false; 8647 if (!Val.isInt()) { 8648 // FIXME: It would be better to produce the diagnostic for casting 8649 // a pointer to an integer. 8650 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 8651 return false; 8652 } 8653 Result = Val.getInt(); 8654 return true; 8655 } 8656 8657 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 8658 APValue Evaluated = E->EvaluateInContext( 8659 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8660 return Success(Evaluated, E); 8661 } 8662 8663 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 8664 EvalInfo &Info) { 8665 if (E->getType()->isFixedPointType()) { 8666 APValue Val; 8667 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 8668 return false; 8669 if (!Val.isFixedPoint()) 8670 return false; 8671 8672 Result = Val.getFixedPoint(); 8673 return true; 8674 } 8675 return false; 8676 } 8677 8678 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 8679 EvalInfo &Info) { 8680 if (E->getType()->isIntegerType()) { 8681 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 8682 APSInt Val; 8683 if (!EvaluateInteger(E, Val, Info)) 8684 return false; 8685 Result = APFixedPoint(Val, FXSema); 8686 return true; 8687 } else if (E->getType()->isFixedPointType()) { 8688 return EvaluateFixedPoint(E, Result, Info); 8689 } 8690 return false; 8691 } 8692 8693 /// Check whether the given declaration can be directly converted to an integral 8694 /// rvalue. If not, no diagnostic is produced; there are other things we can 8695 /// try. 8696 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 8697 // Enums are integer constant exprs. 8698 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 8699 // Check for signedness/width mismatches between E type and ECD value. 8700 bool SameSign = (ECD->getInitVal().isSigned() 8701 == E->getType()->isSignedIntegerOrEnumerationType()); 8702 bool SameWidth = (ECD->getInitVal().getBitWidth() 8703 == Info.Ctx.getIntWidth(E->getType())); 8704 if (SameSign && SameWidth) 8705 return Success(ECD->getInitVal(), E); 8706 else { 8707 // Get rid of mismatch (otherwise Success assertions will fail) 8708 // by computing a new value matching the type of E. 8709 llvm::APSInt Val = ECD->getInitVal(); 8710 if (!SameSign) 8711 Val.setIsSigned(!ECD->getInitVal().isSigned()); 8712 if (!SameWidth) 8713 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 8714 return Success(Val, E); 8715 } 8716 } 8717 return false; 8718 } 8719 8720 /// Values returned by __builtin_classify_type, chosen to match the values 8721 /// produced by GCC's builtin. 8722 enum class GCCTypeClass { 8723 None = -1, 8724 Void = 0, 8725 Integer = 1, 8726 // GCC reserves 2 for character types, but instead classifies them as 8727 // integers. 8728 Enum = 3, 8729 Bool = 4, 8730 Pointer = 5, 8731 // GCC reserves 6 for references, but appears to never use it (because 8732 // expressions never have reference type, presumably). 8733 PointerToDataMember = 7, 8734 RealFloat = 8, 8735 Complex = 9, 8736 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 8737 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 8738 // GCC claims to reserve 11 for pointers to member functions, but *actually* 8739 // uses 12 for that purpose, same as for a class or struct. Maybe it 8740 // internally implements a pointer to member as a struct? Who knows. 8741 PointerToMemberFunction = 12, // Not a bug, see above. 8742 ClassOrStruct = 12, 8743 Union = 13, 8744 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 8745 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 8746 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 8747 // literals. 8748 }; 8749 8750 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 8751 /// as GCC. 8752 static GCCTypeClass 8753 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 8754 assert(!T->isDependentType() && "unexpected dependent type"); 8755 8756 QualType CanTy = T.getCanonicalType(); 8757 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 8758 8759 switch (CanTy->getTypeClass()) { 8760 #define TYPE(ID, BASE) 8761 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 8762 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 8763 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 8764 #include "clang/AST/TypeNodes.def" 8765 case Type::Auto: 8766 case Type::DeducedTemplateSpecialization: 8767 llvm_unreachable("unexpected non-canonical or dependent type"); 8768 8769 case Type::Builtin: 8770 switch (BT->getKind()) { 8771 #define BUILTIN_TYPE(ID, SINGLETON_ID) 8772 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 8773 case BuiltinType::ID: return GCCTypeClass::Integer; 8774 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 8775 case BuiltinType::ID: return GCCTypeClass::RealFloat; 8776 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 8777 case BuiltinType::ID: break; 8778 #include "clang/AST/BuiltinTypes.def" 8779 case BuiltinType::Void: 8780 return GCCTypeClass::Void; 8781 8782 case BuiltinType::Bool: 8783 return GCCTypeClass::Bool; 8784 8785 case BuiltinType::Char_U: 8786 case BuiltinType::UChar: 8787 case BuiltinType::WChar_U: 8788 case BuiltinType::Char8: 8789 case BuiltinType::Char16: 8790 case BuiltinType::Char32: 8791 case BuiltinType::UShort: 8792 case BuiltinType::UInt: 8793 case BuiltinType::ULong: 8794 case BuiltinType::ULongLong: 8795 case BuiltinType::UInt128: 8796 return GCCTypeClass::Integer; 8797 8798 case BuiltinType::UShortAccum: 8799 case BuiltinType::UAccum: 8800 case BuiltinType::ULongAccum: 8801 case BuiltinType::UShortFract: 8802 case BuiltinType::UFract: 8803 case BuiltinType::ULongFract: 8804 case BuiltinType::SatUShortAccum: 8805 case BuiltinType::SatUAccum: 8806 case BuiltinType::SatULongAccum: 8807 case BuiltinType::SatUShortFract: 8808 case BuiltinType::SatUFract: 8809 case BuiltinType::SatULongFract: 8810 return GCCTypeClass::None; 8811 8812 case BuiltinType::NullPtr: 8813 8814 case BuiltinType::ObjCId: 8815 case BuiltinType::ObjCClass: 8816 case BuiltinType::ObjCSel: 8817 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 8818 case BuiltinType::Id: 8819 #include "clang/Basic/OpenCLImageTypes.def" 8820 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 8821 case BuiltinType::Id: 8822 #include "clang/Basic/OpenCLExtensionTypes.def" 8823 case BuiltinType::OCLSampler: 8824 case BuiltinType::OCLEvent: 8825 case BuiltinType::OCLClkEvent: 8826 case BuiltinType::OCLQueue: 8827 case BuiltinType::OCLReserveID: 8828 #define SVE_TYPE(Name, Id, SingletonId) \ 8829 case BuiltinType::Id: 8830 #include "clang/Basic/AArch64SVEACLETypes.def" 8831 return GCCTypeClass::None; 8832 8833 case BuiltinType::Dependent: 8834 llvm_unreachable("unexpected dependent type"); 8835 }; 8836 llvm_unreachable("unexpected placeholder type"); 8837 8838 case Type::Enum: 8839 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 8840 8841 case Type::Pointer: 8842 case Type::ConstantArray: 8843 case Type::VariableArray: 8844 case Type::IncompleteArray: 8845 case Type::FunctionNoProto: 8846 case Type::FunctionProto: 8847 return GCCTypeClass::Pointer; 8848 8849 case Type::MemberPointer: 8850 return CanTy->isMemberDataPointerType() 8851 ? GCCTypeClass::PointerToDataMember 8852 : GCCTypeClass::PointerToMemberFunction; 8853 8854 case Type::Complex: 8855 return GCCTypeClass::Complex; 8856 8857 case Type::Record: 8858 return CanTy->isUnionType() ? GCCTypeClass::Union 8859 : GCCTypeClass::ClassOrStruct; 8860 8861 case Type::Atomic: 8862 // GCC classifies _Atomic T the same as T. 8863 return EvaluateBuiltinClassifyType( 8864 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 8865 8866 case Type::BlockPointer: 8867 case Type::Vector: 8868 case Type::ExtVector: 8869 case Type::ObjCObject: 8870 case Type::ObjCInterface: 8871 case Type::ObjCObjectPointer: 8872 case Type::Pipe: 8873 // GCC classifies vectors as None. We follow its lead and classify all 8874 // other types that don't fit into the regular classification the same way. 8875 return GCCTypeClass::None; 8876 8877 case Type::LValueReference: 8878 case Type::RValueReference: 8879 llvm_unreachable("invalid type for expression"); 8880 } 8881 8882 llvm_unreachable("unexpected type class"); 8883 } 8884 8885 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 8886 /// as GCC. 8887 static GCCTypeClass 8888 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 8889 // If no argument was supplied, default to None. This isn't 8890 // ideal, however it is what gcc does. 8891 if (E->getNumArgs() == 0) 8892 return GCCTypeClass::None; 8893 8894 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 8895 // being an ICE, but still folds it to a constant using the type of the first 8896 // argument. 8897 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 8898 } 8899 8900 /// EvaluateBuiltinConstantPForLValue - Determine the result of 8901 /// __builtin_constant_p when applied to the given pointer. 8902 /// 8903 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 8904 /// or it points to the first character of a string literal. 8905 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 8906 APValue::LValueBase Base = LV.getLValueBase(); 8907 if (Base.isNull()) { 8908 // A null base is acceptable. 8909 return true; 8910 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 8911 if (!isa<StringLiteral>(E)) 8912 return false; 8913 return LV.getLValueOffset().isZero(); 8914 } else if (Base.is<TypeInfoLValue>()) { 8915 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 8916 // evaluate to true. 8917 return true; 8918 } else { 8919 // Any other base is not constant enough for GCC. 8920 return false; 8921 } 8922 } 8923 8924 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 8925 /// GCC as we can manage. 8926 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 8927 // This evaluation is not permitted to have side-effects, so evaluate it in 8928 // a speculative evaluation context. 8929 SpeculativeEvaluationRAII SpeculativeEval(Info); 8930 8931 // Constant-folding is always enabled for the operand of __builtin_constant_p 8932 // (even when the enclosing evaluation context otherwise requires a strict 8933 // language-specific constant expression). 8934 FoldConstant Fold(Info, true); 8935 8936 QualType ArgType = Arg->getType(); 8937 8938 // __builtin_constant_p always has one operand. The rules which gcc follows 8939 // are not precisely documented, but are as follows: 8940 // 8941 // - If the operand is of integral, floating, complex or enumeration type, 8942 // and can be folded to a known value of that type, it returns 1. 8943 // - If the operand can be folded to a pointer to the first character 8944 // of a string literal (or such a pointer cast to an integral type) 8945 // or to a null pointer or an integer cast to a pointer, it returns 1. 8946 // 8947 // Otherwise, it returns 0. 8948 // 8949 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 8950 // its support for this did not work prior to GCC 9 and is not yet well 8951 // understood. 8952 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 8953 ArgType->isAnyComplexType() || ArgType->isPointerType() || 8954 ArgType->isNullPtrType()) { 8955 APValue V; 8956 if (!::EvaluateAsRValue(Info, Arg, V)) { 8957 Fold.keepDiagnostics(); 8958 return false; 8959 } 8960 8961 // For a pointer (possibly cast to integer), there are special rules. 8962 if (V.getKind() == APValue::LValue) 8963 return EvaluateBuiltinConstantPForLValue(V); 8964 8965 // Otherwise, any constant value is good enough. 8966 return V.hasValue(); 8967 } 8968 8969 // Anything else isn't considered to be sufficiently constant. 8970 return false; 8971 } 8972 8973 /// Retrieves the "underlying object type" of the given expression, 8974 /// as used by __builtin_object_size. 8975 static QualType getObjectType(APValue::LValueBase B) { 8976 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 8977 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8978 return VD->getType(); 8979 } else if (const Expr *E = B.get<const Expr*>()) { 8980 if (isa<CompoundLiteralExpr>(E)) 8981 return E->getType(); 8982 } else if (B.is<TypeInfoLValue>()) { 8983 return B.getTypeInfoType(); 8984 } 8985 8986 return QualType(); 8987 } 8988 8989 /// A more selective version of E->IgnoreParenCasts for 8990 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 8991 /// to change the type of E. 8992 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 8993 /// 8994 /// Always returns an RValue with a pointer representation. 8995 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 8996 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8997 8998 auto *NoParens = E->IgnoreParens(); 8999 auto *Cast = dyn_cast<CastExpr>(NoParens); 9000 if (Cast == nullptr) 9001 return NoParens; 9002 9003 // We only conservatively allow a few kinds of casts, because this code is 9004 // inherently a simple solution that seeks to support the common case. 9005 auto CastKind = Cast->getCastKind(); 9006 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 9007 CastKind != CK_AddressSpaceConversion) 9008 return NoParens; 9009 9010 auto *SubExpr = Cast->getSubExpr(); 9011 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 9012 return NoParens; 9013 return ignorePointerCastsAndParens(SubExpr); 9014 } 9015 9016 /// Checks to see if the given LValue's Designator is at the end of the LValue's 9017 /// record layout. e.g. 9018 /// struct { struct { int a, b; } fst, snd; } obj; 9019 /// obj.fst // no 9020 /// obj.snd // yes 9021 /// obj.fst.a // no 9022 /// obj.fst.b // no 9023 /// obj.snd.a // no 9024 /// obj.snd.b // yes 9025 /// 9026 /// Please note: this function is specialized for how __builtin_object_size 9027 /// views "objects". 9028 /// 9029 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 9030 /// correct result, it will always return true. 9031 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 9032 assert(!LVal.Designator.Invalid); 9033 9034 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 9035 const RecordDecl *Parent = FD->getParent(); 9036 Invalid = Parent->isInvalidDecl(); 9037 if (Invalid || Parent->isUnion()) 9038 return true; 9039 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 9040 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 9041 }; 9042 9043 auto &Base = LVal.getLValueBase(); 9044 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 9045 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 9046 bool Invalid; 9047 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 9048 return Invalid; 9049 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 9050 for (auto *FD : IFD->chain()) { 9051 bool Invalid; 9052 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 9053 return Invalid; 9054 } 9055 } 9056 } 9057 9058 unsigned I = 0; 9059 QualType BaseType = getType(Base); 9060 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 9061 // If we don't know the array bound, conservatively assume we're looking at 9062 // the final array element. 9063 ++I; 9064 if (BaseType->isIncompleteArrayType()) 9065 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 9066 else 9067 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 9068 } 9069 9070 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 9071 const auto &Entry = LVal.Designator.Entries[I]; 9072 if (BaseType->isArrayType()) { 9073 // Because __builtin_object_size treats arrays as objects, we can ignore 9074 // the index iff this is the last array in the Designator. 9075 if (I + 1 == E) 9076 return true; 9077 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 9078 uint64_t Index = Entry.getAsArrayIndex(); 9079 if (Index + 1 != CAT->getSize()) 9080 return false; 9081 BaseType = CAT->getElementType(); 9082 } else if (BaseType->isAnyComplexType()) { 9083 const auto *CT = BaseType->castAs<ComplexType>(); 9084 uint64_t Index = Entry.getAsArrayIndex(); 9085 if (Index != 1) 9086 return false; 9087 BaseType = CT->getElementType(); 9088 } else if (auto *FD = getAsField(Entry)) { 9089 bool Invalid; 9090 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 9091 return Invalid; 9092 BaseType = FD->getType(); 9093 } else { 9094 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 9095 return false; 9096 } 9097 } 9098 return true; 9099 } 9100 9101 /// Tests to see if the LValue has a user-specified designator (that isn't 9102 /// necessarily valid). Note that this always returns 'true' if the LValue has 9103 /// an unsized array as its first designator entry, because there's currently no 9104 /// way to tell if the user typed *foo or foo[0]. 9105 static bool refersToCompleteObject(const LValue &LVal) { 9106 if (LVal.Designator.Invalid) 9107 return false; 9108 9109 if (!LVal.Designator.Entries.empty()) 9110 return LVal.Designator.isMostDerivedAnUnsizedArray(); 9111 9112 if (!LVal.InvalidBase) 9113 return true; 9114 9115 // If `E` is a MemberExpr, then the first part of the designator is hiding in 9116 // the LValueBase. 9117 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 9118 return !E || !isa<MemberExpr>(E); 9119 } 9120 9121 /// Attempts to detect a user writing into a piece of memory that's impossible 9122 /// to figure out the size of by just using types. 9123 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 9124 const SubobjectDesignator &Designator = LVal.Designator; 9125 // Notes: 9126 // - Users can only write off of the end when we have an invalid base. Invalid 9127 // bases imply we don't know where the memory came from. 9128 // - We used to be a bit more aggressive here; we'd only be conservative if 9129 // the array at the end was flexible, or if it had 0 or 1 elements. This 9130 // broke some common standard library extensions (PR30346), but was 9131 // otherwise seemingly fine. It may be useful to reintroduce this behavior 9132 // with some sort of whitelist. OTOH, it seems that GCC is always 9133 // conservative with the last element in structs (if it's an array), so our 9134 // current behavior is more compatible than a whitelisting approach would 9135 // be. 9136 return LVal.InvalidBase && 9137 Designator.Entries.size() == Designator.MostDerivedPathLength && 9138 Designator.MostDerivedIsArrayElement && 9139 isDesignatorAtObjectEnd(Ctx, LVal); 9140 } 9141 9142 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 9143 /// Fails if the conversion would cause loss of precision. 9144 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 9145 CharUnits &Result) { 9146 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 9147 if (Int.ugt(CharUnitsMax)) 9148 return false; 9149 Result = CharUnits::fromQuantity(Int.getZExtValue()); 9150 return true; 9151 } 9152 9153 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 9154 /// determine how many bytes exist from the beginning of the object to either 9155 /// the end of the current subobject, or the end of the object itself, depending 9156 /// on what the LValue looks like + the value of Type. 9157 /// 9158 /// If this returns false, the value of Result is undefined. 9159 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 9160 unsigned Type, const LValue &LVal, 9161 CharUnits &EndOffset) { 9162 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 9163 9164 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 9165 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 9166 return false; 9167 return HandleSizeof(Info, ExprLoc, Ty, Result); 9168 }; 9169 9170 // We want to evaluate the size of the entire object. This is a valid fallback 9171 // for when Type=1 and the designator is invalid, because we're asked for an 9172 // upper-bound. 9173 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 9174 // Type=3 wants a lower bound, so we can't fall back to this. 9175 if (Type == 3 && !DetermineForCompleteObject) 9176 return false; 9177 9178 llvm::APInt APEndOffset; 9179 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 9180 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 9181 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 9182 9183 if (LVal.InvalidBase) 9184 return false; 9185 9186 QualType BaseTy = getObjectType(LVal.getLValueBase()); 9187 return CheckedHandleSizeof(BaseTy, EndOffset); 9188 } 9189 9190 // We want to evaluate the size of a subobject. 9191 const SubobjectDesignator &Designator = LVal.Designator; 9192 9193 // The following is a moderately common idiom in C: 9194 // 9195 // struct Foo { int a; char c[1]; }; 9196 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 9197 // strcpy(&F->c[0], Bar); 9198 // 9199 // In order to not break too much legacy code, we need to support it. 9200 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 9201 // If we can resolve this to an alloc_size call, we can hand that back, 9202 // because we know for certain how many bytes there are to write to. 9203 llvm::APInt APEndOffset; 9204 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 9205 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 9206 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 9207 9208 // If we cannot determine the size of the initial allocation, then we can't 9209 // given an accurate upper-bound. However, we are still able to give 9210 // conservative lower-bounds for Type=3. 9211 if (Type == 1) 9212 return false; 9213 } 9214 9215 CharUnits BytesPerElem; 9216 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 9217 return false; 9218 9219 // According to the GCC documentation, we want the size of the subobject 9220 // denoted by the pointer. But that's not quite right -- what we actually 9221 // want is the size of the immediately-enclosing array, if there is one. 9222 int64_t ElemsRemaining; 9223 if (Designator.MostDerivedIsArrayElement && 9224 Designator.Entries.size() == Designator.MostDerivedPathLength) { 9225 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 9226 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 9227 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 9228 } else { 9229 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 9230 } 9231 9232 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 9233 return true; 9234 } 9235 9236 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 9237 /// returns true and stores the result in @p Size. 9238 /// 9239 /// If @p WasError is non-null, this will report whether the failure to evaluate 9240 /// is to be treated as an Error in IntExprEvaluator. 9241 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 9242 EvalInfo &Info, uint64_t &Size) { 9243 // Determine the denoted object. 9244 LValue LVal; 9245 { 9246 // The operand of __builtin_object_size is never evaluated for side-effects. 9247 // If there are any, but we can determine the pointed-to object anyway, then 9248 // ignore the side-effects. 9249 SpeculativeEvaluationRAII SpeculativeEval(Info); 9250 IgnoreSideEffectsRAII Fold(Info); 9251 9252 if (E->isGLValue()) { 9253 // It's possible for us to be given GLValues if we're called via 9254 // Expr::tryEvaluateObjectSize. 9255 APValue RVal; 9256 if (!EvaluateAsRValue(Info, E, RVal)) 9257 return false; 9258 LVal.setFrom(Info.Ctx, RVal); 9259 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 9260 /*InvalidBaseOK=*/true)) 9261 return false; 9262 } 9263 9264 // If we point to before the start of the object, there are no accessible 9265 // bytes. 9266 if (LVal.getLValueOffset().isNegative()) { 9267 Size = 0; 9268 return true; 9269 } 9270 9271 CharUnits EndOffset; 9272 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 9273 return false; 9274 9275 // If we've fallen outside of the end offset, just pretend there's nothing to 9276 // write to/read from. 9277 if (EndOffset <= LVal.getLValueOffset()) 9278 Size = 0; 9279 else 9280 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 9281 return true; 9282 } 9283 9284 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) { 9285 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true); 9286 if (E->getResultAPValueKind() != APValue::None) 9287 return Success(E->getAPValueResult(), E); 9288 return ExprEvaluatorBaseTy::VisitConstantExpr(E); 9289 } 9290 9291 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 9292 if (unsigned BuiltinOp = E->getBuiltinCallee()) 9293 return VisitBuiltinCallExpr(E, BuiltinOp); 9294 9295 return ExprEvaluatorBaseTy::VisitCallExpr(E); 9296 } 9297 9298 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 9299 unsigned BuiltinOp) { 9300 switch (unsigned BuiltinOp = E->getBuiltinCallee()) { 9301 default: 9302 return ExprEvaluatorBaseTy::VisitCallExpr(E); 9303 9304 case Builtin::BI__builtin_dynamic_object_size: 9305 case Builtin::BI__builtin_object_size: { 9306 // The type was checked when we built the expression. 9307 unsigned Type = 9308 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 9309 assert(Type <= 3 && "unexpected type"); 9310 9311 uint64_t Size; 9312 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 9313 return Success(Size, E); 9314 9315 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 9316 return Success((Type & 2) ? 0 : -1, E); 9317 9318 // Expression had no side effects, but we couldn't statically determine the 9319 // size of the referenced object. 9320 switch (Info.EvalMode) { 9321 case EvalInfo::EM_ConstantExpression: 9322 case EvalInfo::EM_ConstantFold: 9323 case EvalInfo::EM_IgnoreSideEffects: 9324 // Leave it to IR generation. 9325 return Error(E); 9326 case EvalInfo::EM_ConstantExpressionUnevaluated: 9327 // Reduce it to a constant now. 9328 return Success((Type & 2) ? 0 : -1, E); 9329 } 9330 9331 llvm_unreachable("unexpected EvalMode"); 9332 } 9333 9334 case Builtin::BI__builtin_os_log_format_buffer_size: { 9335 analyze_os_log::OSLogBufferLayout Layout; 9336 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 9337 return Success(Layout.size().getQuantity(), E); 9338 } 9339 9340 case Builtin::BI__builtin_bswap16: 9341 case Builtin::BI__builtin_bswap32: 9342 case Builtin::BI__builtin_bswap64: { 9343 APSInt Val; 9344 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9345 return false; 9346 9347 return Success(Val.byteSwap(), E); 9348 } 9349 9350 case Builtin::BI__builtin_classify_type: 9351 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 9352 9353 case Builtin::BI__builtin_clrsb: 9354 case Builtin::BI__builtin_clrsbl: 9355 case Builtin::BI__builtin_clrsbll: { 9356 APSInt Val; 9357 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9358 return false; 9359 9360 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 9361 } 9362 9363 case Builtin::BI__builtin_clz: 9364 case Builtin::BI__builtin_clzl: 9365 case Builtin::BI__builtin_clzll: 9366 case Builtin::BI__builtin_clzs: { 9367 APSInt Val; 9368 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9369 return false; 9370 if (!Val) 9371 return Error(E); 9372 9373 return Success(Val.countLeadingZeros(), E); 9374 } 9375 9376 case Builtin::BI__builtin_constant_p: { 9377 const Expr *Arg = E->getArg(0); 9378 if (EvaluateBuiltinConstantP(Info, Arg)) 9379 return Success(true, E); 9380 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 9381 // Outside a constant context, eagerly evaluate to false in the presence 9382 // of side-effects in order to avoid -Wunsequenced false-positives in 9383 // a branch on __builtin_constant_p(expr). 9384 return Success(false, E); 9385 } 9386 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 9387 return false; 9388 } 9389 9390 case Builtin::BI__builtin_is_constant_evaluated: 9391 return Success(Info.InConstantContext, E); 9392 9393 case Builtin::BI__builtin_ctz: 9394 case Builtin::BI__builtin_ctzl: 9395 case Builtin::BI__builtin_ctzll: 9396 case Builtin::BI__builtin_ctzs: { 9397 APSInt Val; 9398 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9399 return false; 9400 if (!Val) 9401 return Error(E); 9402 9403 return Success(Val.countTrailingZeros(), E); 9404 } 9405 9406 case Builtin::BI__builtin_eh_return_data_regno: { 9407 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 9408 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 9409 return Success(Operand, E); 9410 } 9411 9412 case Builtin::BI__builtin_expect: 9413 return Visit(E->getArg(0)); 9414 9415 case Builtin::BI__builtin_ffs: 9416 case Builtin::BI__builtin_ffsl: 9417 case Builtin::BI__builtin_ffsll: { 9418 APSInt Val; 9419 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9420 return false; 9421 9422 unsigned N = Val.countTrailingZeros(); 9423 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 9424 } 9425 9426 case Builtin::BI__builtin_fpclassify: { 9427 APFloat Val(0.0); 9428 if (!EvaluateFloat(E->getArg(5), Val, Info)) 9429 return false; 9430 unsigned Arg; 9431 switch (Val.getCategory()) { 9432 case APFloat::fcNaN: Arg = 0; break; 9433 case APFloat::fcInfinity: Arg = 1; break; 9434 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 9435 case APFloat::fcZero: Arg = 4; break; 9436 } 9437 return Visit(E->getArg(Arg)); 9438 } 9439 9440 case Builtin::BI__builtin_isinf_sign: { 9441 APFloat Val(0.0); 9442 return EvaluateFloat(E->getArg(0), Val, Info) && 9443 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 9444 } 9445 9446 case Builtin::BI__builtin_isinf: { 9447 APFloat Val(0.0); 9448 return EvaluateFloat(E->getArg(0), Val, Info) && 9449 Success(Val.isInfinity() ? 1 : 0, E); 9450 } 9451 9452 case Builtin::BI__builtin_isfinite: { 9453 APFloat Val(0.0); 9454 return EvaluateFloat(E->getArg(0), Val, Info) && 9455 Success(Val.isFinite() ? 1 : 0, E); 9456 } 9457 9458 case Builtin::BI__builtin_isnan: { 9459 APFloat Val(0.0); 9460 return EvaluateFloat(E->getArg(0), Val, Info) && 9461 Success(Val.isNaN() ? 1 : 0, E); 9462 } 9463 9464 case Builtin::BI__builtin_isnormal: { 9465 APFloat Val(0.0); 9466 return EvaluateFloat(E->getArg(0), Val, Info) && 9467 Success(Val.isNormal() ? 1 : 0, E); 9468 } 9469 9470 case Builtin::BI__builtin_parity: 9471 case Builtin::BI__builtin_parityl: 9472 case Builtin::BI__builtin_parityll: { 9473 APSInt Val; 9474 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9475 return false; 9476 9477 return Success(Val.countPopulation() % 2, E); 9478 } 9479 9480 case Builtin::BI__builtin_popcount: 9481 case Builtin::BI__builtin_popcountl: 9482 case Builtin::BI__builtin_popcountll: { 9483 APSInt Val; 9484 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9485 return false; 9486 9487 return Success(Val.countPopulation(), E); 9488 } 9489 9490 case Builtin::BIstrlen: 9491 case Builtin::BIwcslen: 9492 // A call to strlen is not a constant expression. 9493 if (Info.getLangOpts().CPlusPlus11) 9494 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9495 << /*isConstexpr*/0 << /*isConstructor*/0 9496 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9497 else 9498 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9499 LLVM_FALLTHROUGH; 9500 case Builtin::BI__builtin_strlen: 9501 case Builtin::BI__builtin_wcslen: { 9502 // As an extension, we support __builtin_strlen() as a constant expression, 9503 // and support folding strlen() to a constant. 9504 LValue String; 9505 if (!EvaluatePointer(E->getArg(0), String, Info)) 9506 return false; 9507 9508 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 9509 9510 // Fast path: if it's a string literal, search the string value. 9511 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 9512 String.getLValueBase().dyn_cast<const Expr *>())) { 9513 // The string literal may have embedded null characters. Find the first 9514 // one and truncate there. 9515 StringRef Str = S->getBytes(); 9516 int64_t Off = String.Offset.getQuantity(); 9517 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 9518 S->getCharByteWidth() == 1 && 9519 // FIXME: Add fast-path for wchar_t too. 9520 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 9521 Str = Str.substr(Off); 9522 9523 StringRef::size_type Pos = Str.find(0); 9524 if (Pos != StringRef::npos) 9525 Str = Str.substr(0, Pos); 9526 9527 return Success(Str.size(), E); 9528 } 9529 9530 // Fall through to slow path to issue appropriate diagnostic. 9531 } 9532 9533 // Slow path: scan the bytes of the string looking for the terminating 0. 9534 for (uint64_t Strlen = 0; /**/; ++Strlen) { 9535 APValue Char; 9536 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 9537 !Char.isInt()) 9538 return false; 9539 if (!Char.getInt()) 9540 return Success(Strlen, E); 9541 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 9542 return false; 9543 } 9544 } 9545 9546 case Builtin::BIstrcmp: 9547 case Builtin::BIwcscmp: 9548 case Builtin::BIstrncmp: 9549 case Builtin::BIwcsncmp: 9550 case Builtin::BImemcmp: 9551 case Builtin::BIbcmp: 9552 case Builtin::BIwmemcmp: 9553 // A call to strlen is not a constant expression. 9554 if (Info.getLangOpts().CPlusPlus11) 9555 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9556 << /*isConstexpr*/0 << /*isConstructor*/0 9557 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9558 else 9559 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9560 LLVM_FALLTHROUGH; 9561 case Builtin::BI__builtin_strcmp: 9562 case Builtin::BI__builtin_wcscmp: 9563 case Builtin::BI__builtin_strncmp: 9564 case Builtin::BI__builtin_wcsncmp: 9565 case Builtin::BI__builtin_memcmp: 9566 case Builtin::BI__builtin_bcmp: 9567 case Builtin::BI__builtin_wmemcmp: { 9568 LValue String1, String2; 9569 if (!EvaluatePointer(E->getArg(0), String1, Info) || 9570 !EvaluatePointer(E->getArg(1), String2, Info)) 9571 return false; 9572 9573 uint64_t MaxLength = uint64_t(-1); 9574 if (BuiltinOp != Builtin::BIstrcmp && 9575 BuiltinOp != Builtin::BIwcscmp && 9576 BuiltinOp != Builtin::BI__builtin_strcmp && 9577 BuiltinOp != Builtin::BI__builtin_wcscmp) { 9578 APSInt N; 9579 if (!EvaluateInteger(E->getArg(2), N, Info)) 9580 return false; 9581 MaxLength = N.getExtValue(); 9582 } 9583 9584 // Empty substrings compare equal by definition. 9585 if (MaxLength == 0u) 9586 return Success(0, E); 9587 9588 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9589 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9590 String1.Designator.Invalid || String2.Designator.Invalid) 9591 return false; 9592 9593 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 9594 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 9595 9596 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 9597 BuiltinOp == Builtin::BIbcmp || 9598 BuiltinOp == Builtin::BI__builtin_memcmp || 9599 BuiltinOp == Builtin::BI__builtin_bcmp; 9600 9601 assert(IsRawByte || 9602 (Info.Ctx.hasSameUnqualifiedType( 9603 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 9604 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 9605 9606 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 9607 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 9608 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 9609 Char1.isInt() && Char2.isInt(); 9610 }; 9611 const auto &AdvanceElems = [&] { 9612 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 9613 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 9614 }; 9615 9616 if (IsRawByte) { 9617 uint64_t BytesRemaining = MaxLength; 9618 // Pointers to const void may point to objects of incomplete type. 9619 if (CharTy1->isIncompleteType()) { 9620 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1; 9621 return false; 9622 } 9623 if (CharTy2->isIncompleteType()) { 9624 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2; 9625 return false; 9626 } 9627 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)}; 9628 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width); 9629 // Give up on comparing between elements with disparate widths. 9630 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2)) 9631 return false; 9632 uint64_t BytesPerElement = CharTy1Size.getQuantity(); 9633 assert(BytesRemaining && "BytesRemaining should not be zero: the " 9634 "following loop considers at least one element"); 9635 while (true) { 9636 APValue Char1, Char2; 9637 if (!ReadCurElems(Char1, Char2)) 9638 return false; 9639 // We have compatible in-memory widths, but a possible type and 9640 // (for `bool`) internal representation mismatch. 9641 // Assuming two's complement representation, including 0 for `false` and 9642 // 1 for `true`, we can check an appropriate number of elements for 9643 // equality even if they are not byte-sized. 9644 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width); 9645 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width); 9646 if (Char1InMem.ne(Char2InMem)) { 9647 // If the elements are byte-sized, then we can produce a three-way 9648 // comparison result in a straightforward manner. 9649 if (BytesPerElement == 1u) { 9650 // memcmp always compares unsigned chars. 9651 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E); 9652 } 9653 // The result is byte-order sensitive, and we have multibyte elements. 9654 // FIXME: We can compare the remaining bytes in the correct order. 9655 return false; 9656 } 9657 if (!AdvanceElems()) 9658 return false; 9659 if (BytesRemaining <= BytesPerElement) 9660 break; 9661 BytesRemaining -= BytesPerElement; 9662 } 9663 // Enough elements are equal to account for the memcmp limit. 9664 return Success(0, E); 9665 } 9666 9667 bool StopAtNull = 9668 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 9669 BuiltinOp != Builtin::BIwmemcmp && 9670 BuiltinOp != Builtin::BI__builtin_memcmp && 9671 BuiltinOp != Builtin::BI__builtin_bcmp && 9672 BuiltinOp != Builtin::BI__builtin_wmemcmp); 9673 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 9674 BuiltinOp == Builtin::BIwcsncmp || 9675 BuiltinOp == Builtin::BIwmemcmp || 9676 BuiltinOp == Builtin::BI__builtin_wcscmp || 9677 BuiltinOp == Builtin::BI__builtin_wcsncmp || 9678 BuiltinOp == Builtin::BI__builtin_wmemcmp; 9679 9680 for (; MaxLength; --MaxLength) { 9681 APValue Char1, Char2; 9682 if (!ReadCurElems(Char1, Char2)) 9683 return false; 9684 if (Char1.getInt() != Char2.getInt()) { 9685 if (IsWide) // wmemcmp compares with wchar_t signedness. 9686 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 9687 // memcmp always compares unsigned chars. 9688 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 9689 } 9690 if (StopAtNull && !Char1.getInt()) 9691 return Success(0, E); 9692 assert(!(StopAtNull && !Char2.getInt())); 9693 if (!AdvanceElems()) 9694 return false; 9695 } 9696 // We hit the strncmp / memcmp limit. 9697 return Success(0, E); 9698 } 9699 9700 case Builtin::BI__atomic_always_lock_free: 9701 case Builtin::BI__atomic_is_lock_free: 9702 case Builtin::BI__c11_atomic_is_lock_free: { 9703 APSInt SizeVal; 9704 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 9705 return false; 9706 9707 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 9708 // of two less than the maximum inline atomic width, we know it is 9709 // lock-free. If the size isn't a power of two, or greater than the 9710 // maximum alignment where we promote atomics, we know it is not lock-free 9711 // (at least not in the sense of atomic_is_lock_free). Otherwise, 9712 // the answer can only be determined at runtime; for example, 16-byte 9713 // atomics have lock-free implementations on some, but not all, 9714 // x86-64 processors. 9715 9716 // Check power-of-two. 9717 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 9718 if (Size.isPowerOfTwo()) { 9719 // Check against inlining width. 9720 unsigned InlineWidthBits = 9721 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 9722 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 9723 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 9724 Size == CharUnits::One() || 9725 E->getArg(1)->isNullPointerConstant(Info.Ctx, 9726 Expr::NPC_NeverValueDependent)) 9727 // OK, we will inline appropriately-aligned operations of this size, 9728 // and _Atomic(T) is appropriately-aligned. 9729 return Success(1, E); 9730 9731 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 9732 castAs<PointerType>()->getPointeeType(); 9733 if (!PointeeType->isIncompleteType() && 9734 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 9735 // OK, we will inline operations on this object. 9736 return Success(1, E); 9737 } 9738 } 9739 } 9740 9741 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 9742 Success(0, E) : Error(E); 9743 } 9744 case Builtin::BIomp_is_initial_device: 9745 // We can decide statically which value the runtime would return if called. 9746 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 9747 case Builtin::BI__builtin_add_overflow: 9748 case Builtin::BI__builtin_sub_overflow: 9749 case Builtin::BI__builtin_mul_overflow: 9750 case Builtin::BI__builtin_sadd_overflow: 9751 case Builtin::BI__builtin_uadd_overflow: 9752 case Builtin::BI__builtin_uaddl_overflow: 9753 case Builtin::BI__builtin_uaddll_overflow: 9754 case Builtin::BI__builtin_usub_overflow: 9755 case Builtin::BI__builtin_usubl_overflow: 9756 case Builtin::BI__builtin_usubll_overflow: 9757 case Builtin::BI__builtin_umul_overflow: 9758 case Builtin::BI__builtin_umull_overflow: 9759 case Builtin::BI__builtin_umulll_overflow: 9760 case Builtin::BI__builtin_saddl_overflow: 9761 case Builtin::BI__builtin_saddll_overflow: 9762 case Builtin::BI__builtin_ssub_overflow: 9763 case Builtin::BI__builtin_ssubl_overflow: 9764 case Builtin::BI__builtin_ssubll_overflow: 9765 case Builtin::BI__builtin_smul_overflow: 9766 case Builtin::BI__builtin_smull_overflow: 9767 case Builtin::BI__builtin_smulll_overflow: { 9768 LValue ResultLValue; 9769 APSInt LHS, RHS; 9770 9771 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 9772 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 9773 !EvaluateInteger(E->getArg(1), RHS, Info) || 9774 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 9775 return false; 9776 9777 APSInt Result; 9778 bool DidOverflow = false; 9779 9780 // If the types don't have to match, enlarge all 3 to the largest of them. 9781 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 9782 BuiltinOp == Builtin::BI__builtin_sub_overflow || 9783 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 9784 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 9785 ResultType->isSignedIntegerOrEnumerationType(); 9786 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 9787 ResultType->isSignedIntegerOrEnumerationType(); 9788 uint64_t LHSSize = LHS.getBitWidth(); 9789 uint64_t RHSSize = RHS.getBitWidth(); 9790 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 9791 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 9792 9793 // Add an additional bit if the signedness isn't uniformly agreed to. We 9794 // could do this ONLY if there is a signed and an unsigned that both have 9795 // MaxBits, but the code to check that is pretty nasty. The issue will be 9796 // caught in the shrink-to-result later anyway. 9797 if (IsSigned && !AllSigned) 9798 ++MaxBits; 9799 9800 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 9801 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 9802 Result = APSInt(MaxBits, !IsSigned); 9803 } 9804 9805 // Find largest int. 9806 switch (BuiltinOp) { 9807 default: 9808 llvm_unreachable("Invalid value for BuiltinOp"); 9809 case Builtin::BI__builtin_add_overflow: 9810 case Builtin::BI__builtin_sadd_overflow: 9811 case Builtin::BI__builtin_saddl_overflow: 9812 case Builtin::BI__builtin_saddll_overflow: 9813 case Builtin::BI__builtin_uadd_overflow: 9814 case Builtin::BI__builtin_uaddl_overflow: 9815 case Builtin::BI__builtin_uaddll_overflow: 9816 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 9817 : LHS.uadd_ov(RHS, DidOverflow); 9818 break; 9819 case Builtin::BI__builtin_sub_overflow: 9820 case Builtin::BI__builtin_ssub_overflow: 9821 case Builtin::BI__builtin_ssubl_overflow: 9822 case Builtin::BI__builtin_ssubll_overflow: 9823 case Builtin::BI__builtin_usub_overflow: 9824 case Builtin::BI__builtin_usubl_overflow: 9825 case Builtin::BI__builtin_usubll_overflow: 9826 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 9827 : LHS.usub_ov(RHS, DidOverflow); 9828 break; 9829 case Builtin::BI__builtin_mul_overflow: 9830 case Builtin::BI__builtin_smul_overflow: 9831 case Builtin::BI__builtin_smull_overflow: 9832 case Builtin::BI__builtin_smulll_overflow: 9833 case Builtin::BI__builtin_umul_overflow: 9834 case Builtin::BI__builtin_umull_overflow: 9835 case Builtin::BI__builtin_umulll_overflow: 9836 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 9837 : LHS.umul_ov(RHS, DidOverflow); 9838 break; 9839 } 9840 9841 // In the case where multiple sizes are allowed, truncate and see if 9842 // the values are the same. 9843 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 9844 BuiltinOp == Builtin::BI__builtin_sub_overflow || 9845 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 9846 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 9847 // since it will give us the behavior of a TruncOrSelf in the case where 9848 // its parameter <= its size. We previously set Result to be at least the 9849 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 9850 // will work exactly like TruncOrSelf. 9851 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 9852 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 9853 9854 if (!APSInt::isSameValue(Temp, Result)) 9855 DidOverflow = true; 9856 Result = Temp; 9857 } 9858 9859 APValue APV{Result}; 9860 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 9861 return false; 9862 return Success(DidOverflow, E); 9863 } 9864 } 9865 } 9866 9867 /// Determine whether this is a pointer past the end of the complete 9868 /// object referred to by the lvalue. 9869 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 9870 const LValue &LV) { 9871 // A null pointer can be viewed as being "past the end" but we don't 9872 // choose to look at it that way here. 9873 if (!LV.getLValueBase()) 9874 return false; 9875 9876 // If the designator is valid and refers to a subobject, we're not pointing 9877 // past the end. 9878 if (!LV.getLValueDesignator().Invalid && 9879 !LV.getLValueDesignator().isOnePastTheEnd()) 9880 return false; 9881 9882 // A pointer to an incomplete type might be past-the-end if the type's size is 9883 // zero. We cannot tell because the type is incomplete. 9884 QualType Ty = getType(LV.getLValueBase()); 9885 if (Ty->isIncompleteType()) 9886 return true; 9887 9888 // We're a past-the-end pointer if we point to the byte after the object, 9889 // no matter what our type or path is. 9890 auto Size = Ctx.getTypeSizeInChars(Ty); 9891 return LV.getLValueOffset() == Size; 9892 } 9893 9894 namespace { 9895 9896 /// Data recursive integer evaluator of certain binary operators. 9897 /// 9898 /// We use a data recursive algorithm for binary operators so that we are able 9899 /// to handle extreme cases of chained binary operators without causing stack 9900 /// overflow. 9901 class DataRecursiveIntBinOpEvaluator { 9902 struct EvalResult { 9903 APValue Val; 9904 bool Failed; 9905 9906 EvalResult() : Failed(false) { } 9907 9908 void swap(EvalResult &RHS) { 9909 Val.swap(RHS.Val); 9910 Failed = RHS.Failed; 9911 RHS.Failed = false; 9912 } 9913 }; 9914 9915 struct Job { 9916 const Expr *E; 9917 EvalResult LHSResult; // meaningful only for binary operator expression. 9918 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 9919 9920 Job() = default; 9921 Job(Job &&) = default; 9922 9923 void startSpeculativeEval(EvalInfo &Info) { 9924 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 9925 } 9926 9927 private: 9928 SpeculativeEvaluationRAII SpecEvalRAII; 9929 }; 9930 9931 SmallVector<Job, 16> Queue; 9932 9933 IntExprEvaluator &IntEval; 9934 EvalInfo &Info; 9935 APValue &FinalResult; 9936 9937 public: 9938 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 9939 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 9940 9941 /// True if \param E is a binary operator that we are going to handle 9942 /// data recursively. 9943 /// We handle binary operators that are comma, logical, or that have operands 9944 /// with integral or enumeration type. 9945 static bool shouldEnqueue(const BinaryOperator *E) { 9946 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 9947 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 9948 E->getLHS()->getType()->isIntegralOrEnumerationType() && 9949 E->getRHS()->getType()->isIntegralOrEnumerationType()); 9950 } 9951 9952 bool Traverse(const BinaryOperator *E) { 9953 enqueue(E); 9954 EvalResult PrevResult; 9955 while (!Queue.empty()) 9956 process(PrevResult); 9957 9958 if (PrevResult.Failed) return false; 9959 9960 FinalResult.swap(PrevResult.Val); 9961 return true; 9962 } 9963 9964 private: 9965 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 9966 return IntEval.Success(Value, E, Result); 9967 } 9968 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 9969 return IntEval.Success(Value, E, Result); 9970 } 9971 bool Error(const Expr *E) { 9972 return IntEval.Error(E); 9973 } 9974 bool Error(const Expr *E, diag::kind D) { 9975 return IntEval.Error(E, D); 9976 } 9977 9978 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 9979 return Info.CCEDiag(E, D); 9980 } 9981 9982 // Returns true if visiting the RHS is necessary, false otherwise. 9983 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 9984 bool &SuppressRHSDiags); 9985 9986 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 9987 const BinaryOperator *E, APValue &Result); 9988 9989 void EvaluateExpr(const Expr *E, EvalResult &Result) { 9990 Result.Failed = !Evaluate(Result.Val, Info, E); 9991 if (Result.Failed) 9992 Result.Val = APValue(); 9993 } 9994 9995 void process(EvalResult &Result); 9996 9997 void enqueue(const Expr *E) { 9998 E = E->IgnoreParens(); 9999 Queue.resize(Queue.size()+1); 10000 Queue.back().E = E; 10001 Queue.back().Kind = Job::AnyExprKind; 10002 } 10003 }; 10004 10005 } 10006 10007 bool DataRecursiveIntBinOpEvaluator:: 10008 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 10009 bool &SuppressRHSDiags) { 10010 if (E->getOpcode() == BO_Comma) { 10011 // Ignore LHS but note if we could not evaluate it. 10012 if (LHSResult.Failed) 10013 return Info.noteSideEffect(); 10014 return true; 10015 } 10016 10017 if (E->isLogicalOp()) { 10018 bool LHSAsBool; 10019 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 10020 // We were able to evaluate the LHS, see if we can get away with not 10021 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 10022 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 10023 Success(LHSAsBool, E, LHSResult.Val); 10024 return false; // Ignore RHS 10025 } 10026 } else { 10027 LHSResult.Failed = true; 10028 10029 // Since we weren't able to evaluate the left hand side, it 10030 // might have had side effects. 10031 if (!Info.noteSideEffect()) 10032 return false; 10033 10034 // We can't evaluate the LHS; however, sometimes the result 10035 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 10036 // Don't ignore RHS and suppress diagnostics from this arm. 10037 SuppressRHSDiags = true; 10038 } 10039 10040 return true; 10041 } 10042 10043 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 10044 E->getRHS()->getType()->isIntegralOrEnumerationType()); 10045 10046 if (LHSResult.Failed && !Info.noteFailure()) 10047 return false; // Ignore RHS; 10048 10049 return true; 10050 } 10051 10052 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 10053 bool IsSub) { 10054 // Compute the new offset in the appropriate width, wrapping at 64 bits. 10055 // FIXME: When compiling for a 32-bit target, we should use 32-bit 10056 // offsets. 10057 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 10058 CharUnits &Offset = LVal.getLValueOffset(); 10059 uint64_t Offset64 = Offset.getQuantity(); 10060 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 10061 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 10062 : Offset64 + Index64); 10063 } 10064 10065 bool DataRecursiveIntBinOpEvaluator:: 10066 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 10067 const BinaryOperator *E, APValue &Result) { 10068 if (E->getOpcode() == BO_Comma) { 10069 if (RHSResult.Failed) 10070 return false; 10071 Result = RHSResult.Val; 10072 return true; 10073 } 10074 10075 if (E->isLogicalOp()) { 10076 bool lhsResult, rhsResult; 10077 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 10078 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 10079 10080 if (LHSIsOK) { 10081 if (RHSIsOK) { 10082 if (E->getOpcode() == BO_LOr) 10083 return Success(lhsResult || rhsResult, E, Result); 10084 else 10085 return Success(lhsResult && rhsResult, E, Result); 10086 } 10087 } else { 10088 if (RHSIsOK) { 10089 // We can't evaluate the LHS; however, sometimes the result 10090 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 10091 if (rhsResult == (E->getOpcode() == BO_LOr)) 10092 return Success(rhsResult, E, Result); 10093 } 10094 } 10095 10096 return false; 10097 } 10098 10099 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 10100 E->getRHS()->getType()->isIntegralOrEnumerationType()); 10101 10102 if (LHSResult.Failed || RHSResult.Failed) 10103 return false; 10104 10105 const APValue &LHSVal = LHSResult.Val; 10106 const APValue &RHSVal = RHSResult.Val; 10107 10108 // Handle cases like (unsigned long)&a + 4. 10109 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 10110 Result = LHSVal; 10111 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 10112 return true; 10113 } 10114 10115 // Handle cases like 4 + (unsigned long)&a 10116 if (E->getOpcode() == BO_Add && 10117 RHSVal.isLValue() && LHSVal.isInt()) { 10118 Result = RHSVal; 10119 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 10120 return true; 10121 } 10122 10123 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 10124 // Handle (intptr_t)&&A - (intptr_t)&&B. 10125 if (!LHSVal.getLValueOffset().isZero() || 10126 !RHSVal.getLValueOffset().isZero()) 10127 return false; 10128 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 10129 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 10130 if (!LHSExpr || !RHSExpr) 10131 return false; 10132 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 10133 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 10134 if (!LHSAddrExpr || !RHSAddrExpr) 10135 return false; 10136 // Make sure both labels come from the same function. 10137 if (LHSAddrExpr->getLabel()->getDeclContext() != 10138 RHSAddrExpr->getLabel()->getDeclContext()) 10139 return false; 10140 Result = APValue(LHSAddrExpr, RHSAddrExpr); 10141 return true; 10142 } 10143 10144 // All the remaining cases expect both operands to be an integer 10145 if (!LHSVal.isInt() || !RHSVal.isInt()) 10146 return Error(E); 10147 10148 // Set up the width and signedness manually, in case it can't be deduced 10149 // from the operation we're performing. 10150 // FIXME: Don't do this in the cases where we can deduce it. 10151 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 10152 E->getType()->isUnsignedIntegerOrEnumerationType()); 10153 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 10154 RHSVal.getInt(), Value)) 10155 return false; 10156 return Success(Value, E, Result); 10157 } 10158 10159 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 10160 Job &job = Queue.back(); 10161 10162 switch (job.Kind) { 10163 case Job::AnyExprKind: { 10164 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 10165 if (shouldEnqueue(Bop)) { 10166 job.Kind = Job::BinOpKind; 10167 enqueue(Bop->getLHS()); 10168 return; 10169 } 10170 } 10171 10172 EvaluateExpr(job.E, Result); 10173 Queue.pop_back(); 10174 return; 10175 } 10176 10177 case Job::BinOpKind: { 10178 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 10179 bool SuppressRHSDiags = false; 10180 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 10181 Queue.pop_back(); 10182 return; 10183 } 10184 if (SuppressRHSDiags) 10185 job.startSpeculativeEval(Info); 10186 job.LHSResult.swap(Result); 10187 job.Kind = Job::BinOpVisitedLHSKind; 10188 enqueue(Bop->getRHS()); 10189 return; 10190 } 10191 10192 case Job::BinOpVisitedLHSKind: { 10193 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 10194 EvalResult RHS; 10195 RHS.swap(Result); 10196 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 10197 Queue.pop_back(); 10198 return; 10199 } 10200 } 10201 10202 llvm_unreachable("Invalid Job::Kind!"); 10203 } 10204 10205 namespace { 10206 /// Used when we determine that we should fail, but can keep evaluating prior to 10207 /// noting that we had a failure. 10208 class DelayedNoteFailureRAII { 10209 EvalInfo &Info; 10210 bool NoteFailure; 10211 10212 public: 10213 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 10214 : Info(Info), NoteFailure(NoteFailure) {} 10215 ~DelayedNoteFailureRAII() { 10216 if (NoteFailure) { 10217 bool ContinueAfterFailure = Info.noteFailure(); 10218 (void)ContinueAfterFailure; 10219 assert(ContinueAfterFailure && 10220 "Shouldn't have kept evaluating on failure."); 10221 } 10222 } 10223 }; 10224 } 10225 10226 template <class SuccessCB, class AfterCB> 10227 static bool 10228 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 10229 SuccessCB &&Success, AfterCB &&DoAfter) { 10230 assert(E->isComparisonOp() && "expected comparison operator"); 10231 assert((E->getOpcode() == BO_Cmp || 10232 E->getType()->isIntegralOrEnumerationType()) && 10233 "unsupported binary expression evaluation"); 10234 auto Error = [&](const Expr *E) { 10235 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10236 return false; 10237 }; 10238 10239 using CCR = ComparisonCategoryResult; 10240 bool IsRelational = E->isRelationalOp(); 10241 bool IsEquality = E->isEqualityOp(); 10242 if (E->getOpcode() == BO_Cmp) { 10243 const ComparisonCategoryInfo &CmpInfo = 10244 Info.Ctx.CompCategories.getInfoForType(E->getType()); 10245 IsRelational = CmpInfo.isOrdered(); 10246 IsEquality = CmpInfo.isEquality(); 10247 } 10248 10249 QualType LHSTy = E->getLHS()->getType(); 10250 QualType RHSTy = E->getRHS()->getType(); 10251 10252 if (LHSTy->isIntegralOrEnumerationType() && 10253 RHSTy->isIntegralOrEnumerationType()) { 10254 APSInt LHS, RHS; 10255 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 10256 if (!LHSOK && !Info.noteFailure()) 10257 return false; 10258 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 10259 return false; 10260 if (LHS < RHS) 10261 return Success(CCR::Less, E); 10262 if (LHS > RHS) 10263 return Success(CCR::Greater, E); 10264 return Success(CCR::Equal, E); 10265 } 10266 10267 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 10268 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 10269 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 10270 10271 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 10272 if (!LHSOK && !Info.noteFailure()) 10273 return false; 10274 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 10275 return false; 10276 if (LHSFX < RHSFX) 10277 return Success(CCR::Less, E); 10278 if (LHSFX > RHSFX) 10279 return Success(CCR::Greater, E); 10280 return Success(CCR::Equal, E); 10281 } 10282 10283 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 10284 ComplexValue LHS, RHS; 10285 bool LHSOK; 10286 if (E->isAssignmentOp()) { 10287 LValue LV; 10288 EvaluateLValue(E->getLHS(), LV, Info); 10289 LHSOK = false; 10290 } else if (LHSTy->isRealFloatingType()) { 10291 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 10292 if (LHSOK) { 10293 LHS.makeComplexFloat(); 10294 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 10295 } 10296 } else { 10297 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 10298 } 10299 if (!LHSOK && !Info.noteFailure()) 10300 return false; 10301 10302 if (E->getRHS()->getType()->isRealFloatingType()) { 10303 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 10304 return false; 10305 RHS.makeComplexFloat(); 10306 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 10307 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 10308 return false; 10309 10310 if (LHS.isComplexFloat()) { 10311 APFloat::cmpResult CR_r = 10312 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 10313 APFloat::cmpResult CR_i = 10314 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 10315 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 10316 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 10317 } else { 10318 assert(IsEquality && "invalid complex comparison"); 10319 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 10320 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 10321 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 10322 } 10323 } 10324 10325 if (LHSTy->isRealFloatingType() && 10326 RHSTy->isRealFloatingType()) { 10327 APFloat RHS(0.0), LHS(0.0); 10328 10329 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 10330 if (!LHSOK && !Info.noteFailure()) 10331 return false; 10332 10333 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 10334 return false; 10335 10336 assert(E->isComparisonOp() && "Invalid binary operator!"); 10337 auto GetCmpRes = [&]() { 10338 switch (LHS.compare(RHS)) { 10339 case APFloat::cmpEqual: 10340 return CCR::Equal; 10341 case APFloat::cmpLessThan: 10342 return CCR::Less; 10343 case APFloat::cmpGreaterThan: 10344 return CCR::Greater; 10345 case APFloat::cmpUnordered: 10346 return CCR::Unordered; 10347 } 10348 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 10349 }; 10350 return Success(GetCmpRes(), E); 10351 } 10352 10353 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 10354 LValue LHSValue, RHSValue; 10355 10356 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 10357 if (!LHSOK && !Info.noteFailure()) 10358 return false; 10359 10360 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 10361 return false; 10362 10363 // Reject differing bases from the normal codepath; we special-case 10364 // comparisons to null. 10365 if (!HasSameBase(LHSValue, RHSValue)) { 10366 // Inequalities and subtractions between unrelated pointers have 10367 // unspecified or undefined behavior. 10368 if (!IsEquality) 10369 return Error(E); 10370 // A constant address may compare equal to the address of a symbol. 10371 // The one exception is that address of an object cannot compare equal 10372 // to a null pointer constant. 10373 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 10374 (!RHSValue.Base && !RHSValue.Offset.isZero())) 10375 return Error(E); 10376 // It's implementation-defined whether distinct literals will have 10377 // distinct addresses. In clang, the result of such a comparison is 10378 // unspecified, so it is not a constant expression. However, we do know 10379 // that the address of a literal will be non-null. 10380 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 10381 LHSValue.Base && RHSValue.Base) 10382 return Error(E); 10383 // We can't tell whether weak symbols will end up pointing to the same 10384 // object. 10385 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 10386 return Error(E); 10387 // We can't compare the address of the start of one object with the 10388 // past-the-end address of another object, per C++ DR1652. 10389 if ((LHSValue.Base && LHSValue.Offset.isZero() && 10390 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 10391 (RHSValue.Base && RHSValue.Offset.isZero() && 10392 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 10393 return Error(E); 10394 // We can't tell whether an object is at the same address as another 10395 // zero sized object. 10396 if ((RHSValue.Base && isZeroSized(LHSValue)) || 10397 (LHSValue.Base && isZeroSized(RHSValue))) 10398 return Error(E); 10399 return Success(CCR::Nonequal, E); 10400 } 10401 10402 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 10403 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 10404 10405 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 10406 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 10407 10408 // C++11 [expr.rel]p3: 10409 // Pointers to void (after pointer conversions) can be compared, with a 10410 // result defined as follows: If both pointers represent the same 10411 // address or are both the null pointer value, the result is true if the 10412 // operator is <= or >= and false otherwise; otherwise the result is 10413 // unspecified. 10414 // We interpret this as applying to pointers to *cv* void. 10415 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 10416 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 10417 10418 // C++11 [expr.rel]p2: 10419 // - If two pointers point to non-static data members of the same object, 10420 // or to subobjects or array elements fo such members, recursively, the 10421 // pointer to the later declared member compares greater provided the 10422 // two members have the same access control and provided their class is 10423 // not a union. 10424 // [...] 10425 // - Otherwise pointer comparisons are unspecified. 10426 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 10427 bool WasArrayIndex; 10428 unsigned Mismatch = FindDesignatorMismatch( 10429 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 10430 // At the point where the designators diverge, the comparison has a 10431 // specified value if: 10432 // - we are comparing array indices 10433 // - we are comparing fields of a union, or fields with the same access 10434 // Otherwise, the result is unspecified and thus the comparison is not a 10435 // constant expression. 10436 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 10437 Mismatch < RHSDesignator.Entries.size()) { 10438 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 10439 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 10440 if (!LF && !RF) 10441 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 10442 else if (!LF) 10443 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 10444 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 10445 << RF->getParent() << RF; 10446 else if (!RF) 10447 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 10448 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 10449 << LF->getParent() << LF; 10450 else if (!LF->getParent()->isUnion() && 10451 LF->getAccess() != RF->getAccess()) 10452 Info.CCEDiag(E, 10453 diag::note_constexpr_pointer_comparison_differing_access) 10454 << LF << LF->getAccess() << RF << RF->getAccess() 10455 << LF->getParent(); 10456 } 10457 } 10458 10459 // The comparison here must be unsigned, and performed with the same 10460 // width as the pointer. 10461 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 10462 uint64_t CompareLHS = LHSOffset.getQuantity(); 10463 uint64_t CompareRHS = RHSOffset.getQuantity(); 10464 assert(PtrSize <= 64 && "Unexpected pointer width"); 10465 uint64_t Mask = ~0ULL >> (64 - PtrSize); 10466 CompareLHS &= Mask; 10467 CompareRHS &= Mask; 10468 10469 // If there is a base and this is a relational operator, we can only 10470 // compare pointers within the object in question; otherwise, the result 10471 // depends on where the object is located in memory. 10472 if (!LHSValue.Base.isNull() && IsRelational) { 10473 QualType BaseTy = getType(LHSValue.Base); 10474 if (BaseTy->isIncompleteType()) 10475 return Error(E); 10476 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 10477 uint64_t OffsetLimit = Size.getQuantity(); 10478 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 10479 return Error(E); 10480 } 10481 10482 if (CompareLHS < CompareRHS) 10483 return Success(CCR::Less, E); 10484 if (CompareLHS > CompareRHS) 10485 return Success(CCR::Greater, E); 10486 return Success(CCR::Equal, E); 10487 } 10488 10489 if (LHSTy->isMemberPointerType()) { 10490 assert(IsEquality && "unexpected member pointer operation"); 10491 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 10492 10493 MemberPtr LHSValue, RHSValue; 10494 10495 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 10496 if (!LHSOK && !Info.noteFailure()) 10497 return false; 10498 10499 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 10500 return false; 10501 10502 // C++11 [expr.eq]p2: 10503 // If both operands are null, they compare equal. Otherwise if only one is 10504 // null, they compare unequal. 10505 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 10506 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 10507 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 10508 } 10509 10510 // Otherwise if either is a pointer to a virtual member function, the 10511 // result is unspecified. 10512 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 10513 if (MD->isVirtual()) 10514 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 10515 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 10516 if (MD->isVirtual()) 10517 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 10518 10519 // Otherwise they compare equal if and only if they would refer to the 10520 // same member of the same most derived object or the same subobject if 10521 // they were dereferenced with a hypothetical object of the associated 10522 // class type. 10523 bool Equal = LHSValue == RHSValue; 10524 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 10525 } 10526 10527 if (LHSTy->isNullPtrType()) { 10528 assert(E->isComparisonOp() && "unexpected nullptr operation"); 10529 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 10530 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 10531 // are compared, the result is true of the operator is <=, >= or ==, and 10532 // false otherwise. 10533 return Success(CCR::Equal, E); 10534 } 10535 10536 return DoAfter(); 10537 } 10538 10539 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 10540 if (!CheckLiteralType(Info, E)) 10541 return false; 10542 10543 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 10544 const BinaryOperator *E) { 10545 // Evaluation succeeded. Lookup the information for the comparison category 10546 // type and fetch the VarDecl for the result. 10547 const ComparisonCategoryInfo &CmpInfo = 10548 Info.Ctx.CompCategories.getInfoForType(E->getType()); 10549 const VarDecl *VD = 10550 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD; 10551 // Check and evaluate the result as a constant expression. 10552 LValue LV; 10553 LV.set(VD); 10554 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 10555 return false; 10556 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 10557 }; 10558 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 10559 return ExprEvaluatorBaseTy::VisitBinCmp(E); 10560 }); 10561 } 10562 10563 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10564 // We don't call noteFailure immediately because the assignment happens after 10565 // we evaluate LHS and RHS. 10566 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 10567 return Error(E); 10568 10569 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 10570 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 10571 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 10572 10573 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 10574 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 10575 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 10576 10577 if (E->isComparisonOp()) { 10578 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way 10579 // comparisons and then translating the result. 10580 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 10581 const BinaryOperator *E) { 10582 using CCR = ComparisonCategoryResult; 10583 bool IsEqual = ResKind == CCR::Equal, 10584 IsLess = ResKind == CCR::Less, 10585 IsGreater = ResKind == CCR::Greater; 10586 auto Op = E->getOpcode(); 10587 switch (Op) { 10588 default: 10589 llvm_unreachable("unsupported binary operator"); 10590 case BO_EQ: 10591 case BO_NE: 10592 return Success(IsEqual == (Op == BO_EQ), E); 10593 case BO_LT: return Success(IsLess, E); 10594 case BO_GT: return Success(IsGreater, E); 10595 case BO_LE: return Success(IsEqual || IsLess, E); 10596 case BO_GE: return Success(IsEqual || IsGreater, E); 10597 } 10598 }; 10599 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 10600 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10601 }); 10602 } 10603 10604 QualType LHSTy = E->getLHS()->getType(); 10605 QualType RHSTy = E->getRHS()->getType(); 10606 10607 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 10608 E->getOpcode() == BO_Sub) { 10609 LValue LHSValue, RHSValue; 10610 10611 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 10612 if (!LHSOK && !Info.noteFailure()) 10613 return false; 10614 10615 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 10616 return false; 10617 10618 // Reject differing bases from the normal codepath; we special-case 10619 // comparisons to null. 10620 if (!HasSameBase(LHSValue, RHSValue)) { 10621 // Handle &&A - &&B. 10622 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 10623 return Error(E); 10624 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 10625 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 10626 if (!LHSExpr || !RHSExpr) 10627 return Error(E); 10628 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 10629 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 10630 if (!LHSAddrExpr || !RHSAddrExpr) 10631 return Error(E); 10632 // Make sure both labels come from the same function. 10633 if (LHSAddrExpr->getLabel()->getDeclContext() != 10634 RHSAddrExpr->getLabel()->getDeclContext()) 10635 return Error(E); 10636 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 10637 } 10638 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 10639 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 10640 10641 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 10642 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 10643 10644 // C++11 [expr.add]p6: 10645 // Unless both pointers point to elements of the same array object, or 10646 // one past the last element of the array object, the behavior is 10647 // undefined. 10648 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 10649 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 10650 RHSDesignator)) 10651 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 10652 10653 QualType Type = E->getLHS()->getType(); 10654 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 10655 10656 CharUnits ElementSize; 10657 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 10658 return false; 10659 10660 // As an extension, a type may have zero size (empty struct or union in 10661 // C, array of zero length). Pointer subtraction in such cases has 10662 // undefined behavior, so is not constant. 10663 if (ElementSize.isZero()) { 10664 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 10665 << ElementType; 10666 return false; 10667 } 10668 10669 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 10670 // and produce incorrect results when it overflows. Such behavior 10671 // appears to be non-conforming, but is common, so perhaps we should 10672 // assume the standard intended for such cases to be undefined behavior 10673 // and check for them. 10674 10675 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 10676 // overflow in the final conversion to ptrdiff_t. 10677 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 10678 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 10679 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 10680 false); 10681 APSInt TrueResult = (LHS - RHS) / ElemSize; 10682 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 10683 10684 if (Result.extend(65) != TrueResult && 10685 !HandleOverflow(Info, E, TrueResult, E->getType())) 10686 return false; 10687 return Success(Result, E); 10688 } 10689 10690 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10691 } 10692 10693 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 10694 /// a result as the expression's type. 10695 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 10696 const UnaryExprOrTypeTraitExpr *E) { 10697 switch(E->getKind()) { 10698 case UETT_PreferredAlignOf: 10699 case UETT_AlignOf: { 10700 if (E->isArgumentType()) 10701 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 10702 E); 10703 else 10704 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 10705 E); 10706 } 10707 10708 case UETT_VecStep: { 10709 QualType Ty = E->getTypeOfArgument(); 10710 10711 if (Ty->isVectorType()) { 10712 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 10713 10714 // The vec_step built-in functions that take a 3-component 10715 // vector return 4. (OpenCL 1.1 spec 6.11.12) 10716 if (n == 3) 10717 n = 4; 10718 10719 return Success(n, E); 10720 } else 10721 return Success(1, E); 10722 } 10723 10724 case UETT_SizeOf: { 10725 QualType SrcTy = E->getTypeOfArgument(); 10726 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 10727 // the result is the size of the referenced type." 10728 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 10729 SrcTy = Ref->getPointeeType(); 10730 10731 CharUnits Sizeof; 10732 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 10733 return false; 10734 return Success(Sizeof, E); 10735 } 10736 case UETT_OpenMPRequiredSimdAlign: 10737 assert(E->isArgumentType()); 10738 return Success( 10739 Info.Ctx.toCharUnitsFromBits( 10740 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 10741 .getQuantity(), 10742 E); 10743 } 10744 10745 llvm_unreachable("unknown expr/type trait"); 10746 } 10747 10748 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 10749 CharUnits Result; 10750 unsigned n = OOE->getNumComponents(); 10751 if (n == 0) 10752 return Error(OOE); 10753 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 10754 for (unsigned i = 0; i != n; ++i) { 10755 OffsetOfNode ON = OOE->getComponent(i); 10756 switch (ON.getKind()) { 10757 case OffsetOfNode::Array: { 10758 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 10759 APSInt IdxResult; 10760 if (!EvaluateInteger(Idx, IdxResult, Info)) 10761 return false; 10762 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 10763 if (!AT) 10764 return Error(OOE); 10765 CurrentType = AT->getElementType(); 10766 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 10767 Result += IdxResult.getSExtValue() * ElementSize; 10768 break; 10769 } 10770 10771 case OffsetOfNode::Field: { 10772 FieldDecl *MemberDecl = ON.getField(); 10773 const RecordType *RT = CurrentType->getAs<RecordType>(); 10774 if (!RT) 10775 return Error(OOE); 10776 RecordDecl *RD = RT->getDecl(); 10777 if (RD->isInvalidDecl()) return false; 10778 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 10779 unsigned i = MemberDecl->getFieldIndex(); 10780 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 10781 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 10782 CurrentType = MemberDecl->getType().getNonReferenceType(); 10783 break; 10784 } 10785 10786 case OffsetOfNode::Identifier: 10787 llvm_unreachable("dependent __builtin_offsetof"); 10788 10789 case OffsetOfNode::Base: { 10790 CXXBaseSpecifier *BaseSpec = ON.getBase(); 10791 if (BaseSpec->isVirtual()) 10792 return Error(OOE); 10793 10794 // Find the layout of the class whose base we are looking into. 10795 const RecordType *RT = CurrentType->getAs<RecordType>(); 10796 if (!RT) 10797 return Error(OOE); 10798 RecordDecl *RD = RT->getDecl(); 10799 if (RD->isInvalidDecl()) return false; 10800 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 10801 10802 // Find the base class itself. 10803 CurrentType = BaseSpec->getType(); 10804 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 10805 if (!BaseRT) 10806 return Error(OOE); 10807 10808 // Add the offset to the base. 10809 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 10810 break; 10811 } 10812 } 10813 } 10814 return Success(Result, OOE); 10815 } 10816 10817 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10818 switch (E->getOpcode()) { 10819 default: 10820 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 10821 // See C99 6.6p3. 10822 return Error(E); 10823 case UO_Extension: 10824 // FIXME: Should extension allow i-c-e extension expressions in its scope? 10825 // If so, we could clear the diagnostic ID. 10826 return Visit(E->getSubExpr()); 10827 case UO_Plus: 10828 // The result is just the value. 10829 return Visit(E->getSubExpr()); 10830 case UO_Minus: { 10831 if (!Visit(E->getSubExpr())) 10832 return false; 10833 if (!Result.isInt()) return Error(E); 10834 const APSInt &Value = Result.getInt(); 10835 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 10836 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 10837 E->getType())) 10838 return false; 10839 return Success(-Value, E); 10840 } 10841 case UO_Not: { 10842 if (!Visit(E->getSubExpr())) 10843 return false; 10844 if (!Result.isInt()) return Error(E); 10845 return Success(~Result.getInt(), E); 10846 } 10847 case UO_LNot: { 10848 bool bres; 10849 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 10850 return false; 10851 return Success(!bres, E); 10852 } 10853 } 10854 } 10855 10856 /// HandleCast - This is used to evaluate implicit or explicit casts where the 10857 /// result type is integer. 10858 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 10859 const Expr *SubExpr = E->getSubExpr(); 10860 QualType DestType = E->getType(); 10861 QualType SrcType = SubExpr->getType(); 10862 10863 switch (E->getCastKind()) { 10864 case CK_BaseToDerived: 10865 case CK_DerivedToBase: 10866 case CK_UncheckedDerivedToBase: 10867 case CK_Dynamic: 10868 case CK_ToUnion: 10869 case CK_ArrayToPointerDecay: 10870 case CK_FunctionToPointerDecay: 10871 case CK_NullToPointer: 10872 case CK_NullToMemberPointer: 10873 case CK_BaseToDerivedMemberPointer: 10874 case CK_DerivedToBaseMemberPointer: 10875 case CK_ReinterpretMemberPointer: 10876 case CK_ConstructorConversion: 10877 case CK_IntegralToPointer: 10878 case CK_ToVoid: 10879 case CK_VectorSplat: 10880 case CK_IntegralToFloating: 10881 case CK_FloatingCast: 10882 case CK_CPointerToObjCPointerCast: 10883 case CK_BlockPointerToObjCPointerCast: 10884 case CK_AnyPointerToBlockPointerCast: 10885 case CK_ObjCObjectLValueCast: 10886 case CK_FloatingRealToComplex: 10887 case CK_FloatingComplexToReal: 10888 case CK_FloatingComplexCast: 10889 case CK_FloatingComplexToIntegralComplex: 10890 case CK_IntegralRealToComplex: 10891 case CK_IntegralComplexCast: 10892 case CK_IntegralComplexToFloatingComplex: 10893 case CK_BuiltinFnToFnPtr: 10894 case CK_ZeroToOCLOpaqueType: 10895 case CK_NonAtomicToAtomic: 10896 case CK_AddressSpaceConversion: 10897 case CK_IntToOCLSampler: 10898 case CK_FixedPointCast: 10899 case CK_IntegralToFixedPoint: 10900 llvm_unreachable("invalid cast kind for integral value"); 10901 10902 case CK_BitCast: 10903 case CK_Dependent: 10904 case CK_LValueBitCast: 10905 case CK_ARCProduceObject: 10906 case CK_ARCConsumeObject: 10907 case CK_ARCReclaimReturnedObject: 10908 case CK_ARCExtendBlockObject: 10909 case CK_CopyAndAutoreleaseBlockObject: 10910 return Error(E); 10911 10912 case CK_UserDefinedConversion: 10913 case CK_LValueToRValue: 10914 case CK_AtomicToNonAtomic: 10915 case CK_NoOp: 10916 case CK_LValueToRValueBitCast: 10917 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10918 10919 case CK_MemberPointerToBoolean: 10920 case CK_PointerToBoolean: 10921 case CK_IntegralToBoolean: 10922 case CK_FloatingToBoolean: 10923 case CK_BooleanToSignedIntegral: 10924 case CK_FloatingComplexToBoolean: 10925 case CK_IntegralComplexToBoolean: { 10926 bool BoolResult; 10927 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 10928 return false; 10929 uint64_t IntResult = BoolResult; 10930 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 10931 IntResult = (uint64_t)-1; 10932 return Success(IntResult, E); 10933 } 10934 10935 case CK_FixedPointToIntegral: { 10936 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 10937 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 10938 return false; 10939 bool Overflowed; 10940 llvm::APSInt Result = Src.convertToInt( 10941 Info.Ctx.getIntWidth(DestType), 10942 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 10943 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 10944 return false; 10945 return Success(Result, E); 10946 } 10947 10948 case CK_FixedPointToBoolean: { 10949 // Unsigned padding does not affect this. 10950 APValue Val; 10951 if (!Evaluate(Val, Info, SubExpr)) 10952 return false; 10953 return Success(Val.getFixedPoint().getBoolValue(), E); 10954 } 10955 10956 case CK_IntegralCast: { 10957 if (!Visit(SubExpr)) 10958 return false; 10959 10960 if (!Result.isInt()) { 10961 // Allow casts of address-of-label differences if they are no-ops 10962 // or narrowing. (The narrowing case isn't actually guaranteed to 10963 // be constant-evaluatable except in some narrow cases which are hard 10964 // to detect here. We let it through on the assumption the user knows 10965 // what they are doing.) 10966 if (Result.isAddrLabelDiff()) 10967 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 10968 // Only allow casts of lvalues if they are lossless. 10969 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 10970 } 10971 10972 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 10973 Result.getInt()), E); 10974 } 10975 10976 case CK_PointerToIntegral: { 10977 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 10978 10979 LValue LV; 10980 if (!EvaluatePointer(SubExpr, LV, Info)) 10981 return false; 10982 10983 if (LV.getLValueBase()) { 10984 // Only allow based lvalue casts if they are lossless. 10985 // FIXME: Allow a larger integer size than the pointer size, and allow 10986 // narrowing back down to pointer width in subsequent integral casts. 10987 // FIXME: Check integer type's active bits, not its type size. 10988 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 10989 return Error(E); 10990 10991 LV.Designator.setInvalid(); 10992 LV.moveInto(Result); 10993 return true; 10994 } 10995 10996 APSInt AsInt; 10997 APValue V; 10998 LV.moveInto(V); 10999 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 11000 llvm_unreachable("Can't cast this!"); 11001 11002 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 11003 } 11004 11005 case CK_IntegralComplexToReal: { 11006 ComplexValue C; 11007 if (!EvaluateComplex(SubExpr, C, Info)) 11008 return false; 11009 return Success(C.getComplexIntReal(), E); 11010 } 11011 11012 case CK_FloatingToIntegral: { 11013 APFloat F(0.0); 11014 if (!EvaluateFloat(SubExpr, F, Info)) 11015 return false; 11016 11017 APSInt Value; 11018 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 11019 return false; 11020 return Success(Value, E); 11021 } 11022 } 11023 11024 llvm_unreachable("unknown cast resulting in integral value"); 11025 } 11026 11027 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 11028 if (E->getSubExpr()->getType()->isAnyComplexType()) { 11029 ComplexValue LV; 11030 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 11031 return false; 11032 if (!LV.isComplexInt()) 11033 return Error(E); 11034 return Success(LV.getComplexIntReal(), E); 11035 } 11036 11037 return Visit(E->getSubExpr()); 11038 } 11039 11040 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 11041 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 11042 ComplexValue LV; 11043 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 11044 return false; 11045 if (!LV.isComplexInt()) 11046 return Error(E); 11047 return Success(LV.getComplexIntImag(), E); 11048 } 11049 11050 VisitIgnoredValue(E->getSubExpr()); 11051 return Success(0, E); 11052 } 11053 11054 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 11055 return Success(E->getPackLength(), E); 11056 } 11057 11058 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 11059 return Success(E->getValue(), E); 11060 } 11061 11062 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 11063 switch (E->getOpcode()) { 11064 default: 11065 // Invalid unary operators 11066 return Error(E); 11067 case UO_Plus: 11068 // The result is just the value. 11069 return Visit(E->getSubExpr()); 11070 case UO_Minus: { 11071 if (!Visit(E->getSubExpr())) return false; 11072 if (!Result.isFixedPoint()) 11073 return Error(E); 11074 bool Overflowed; 11075 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 11076 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 11077 return false; 11078 return Success(Negated, E); 11079 } 11080 case UO_LNot: { 11081 bool bres; 11082 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 11083 return false; 11084 return Success(!bres, E); 11085 } 11086 } 11087 } 11088 11089 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 11090 const Expr *SubExpr = E->getSubExpr(); 11091 QualType DestType = E->getType(); 11092 assert(DestType->isFixedPointType() && 11093 "Expected destination type to be a fixed point type"); 11094 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 11095 11096 switch (E->getCastKind()) { 11097 case CK_FixedPointCast: { 11098 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 11099 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 11100 return false; 11101 bool Overflowed; 11102 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 11103 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 11104 return false; 11105 return Success(Result, E); 11106 } 11107 case CK_IntegralToFixedPoint: { 11108 APSInt Src; 11109 if (!EvaluateInteger(SubExpr, Src, Info)) 11110 return false; 11111 11112 bool Overflowed; 11113 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11114 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 11115 11116 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType)) 11117 return false; 11118 11119 return Success(IntResult, E); 11120 } 11121 case CK_NoOp: 11122 case CK_LValueToRValue: 11123 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11124 default: 11125 return Error(E); 11126 } 11127 } 11128 11129 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 11130 const Expr *LHS = E->getLHS(); 11131 const Expr *RHS = E->getRHS(); 11132 FixedPointSemantics ResultFXSema = 11133 Info.Ctx.getFixedPointSemantics(E->getType()); 11134 11135 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 11136 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 11137 return false; 11138 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 11139 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 11140 return false; 11141 11142 switch (E->getOpcode()) { 11143 case BO_Add: { 11144 bool AddOverflow, ConversionOverflow; 11145 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow) 11146 .convert(ResultFXSema, &ConversionOverflow); 11147 if ((AddOverflow || ConversionOverflow) && 11148 !HandleOverflow(Info, E, Result, E->getType())) 11149 return false; 11150 return Success(Result, E); 11151 } 11152 default: 11153 return false; 11154 } 11155 llvm_unreachable("Should've exited before this"); 11156 } 11157 11158 //===----------------------------------------------------------------------===// 11159 // Float Evaluation 11160 //===----------------------------------------------------------------------===// 11161 11162 namespace { 11163 class FloatExprEvaluator 11164 : public ExprEvaluatorBase<FloatExprEvaluator> { 11165 APFloat &Result; 11166 public: 11167 FloatExprEvaluator(EvalInfo &info, APFloat &result) 11168 : ExprEvaluatorBaseTy(info), Result(result) {} 11169 11170 bool Success(const APValue &V, const Expr *e) { 11171 Result = V.getFloat(); 11172 return true; 11173 } 11174 11175 bool ZeroInitialization(const Expr *E) { 11176 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 11177 return true; 11178 } 11179 11180 bool VisitCallExpr(const CallExpr *E); 11181 11182 bool VisitUnaryOperator(const UnaryOperator *E); 11183 bool VisitBinaryOperator(const BinaryOperator *E); 11184 bool VisitFloatingLiteral(const FloatingLiteral *E); 11185 bool VisitCastExpr(const CastExpr *E); 11186 11187 bool VisitUnaryReal(const UnaryOperator *E); 11188 bool VisitUnaryImag(const UnaryOperator *E); 11189 11190 // FIXME: Missing: array subscript of vector, member of vector 11191 }; 11192 } // end anonymous namespace 11193 11194 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 11195 assert(E->isRValue() && E->getType()->isRealFloatingType()); 11196 return FloatExprEvaluator(Info, Result).Visit(E); 11197 } 11198 11199 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 11200 QualType ResultTy, 11201 const Expr *Arg, 11202 bool SNaN, 11203 llvm::APFloat &Result) { 11204 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 11205 if (!S) return false; 11206 11207 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 11208 11209 llvm::APInt fill; 11210 11211 // Treat empty strings as if they were zero. 11212 if (S->getString().empty()) 11213 fill = llvm::APInt(32, 0); 11214 else if (S->getString().getAsInteger(0, fill)) 11215 return false; 11216 11217 if (Context.getTargetInfo().isNan2008()) { 11218 if (SNaN) 11219 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 11220 else 11221 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 11222 } else { 11223 // Prior to IEEE 754-2008, architectures were allowed to choose whether 11224 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 11225 // a different encoding to what became a standard in 2008, and for pre- 11226 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 11227 // sNaN. This is now known as "legacy NaN" encoding. 11228 if (SNaN) 11229 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 11230 else 11231 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 11232 } 11233 11234 return true; 11235 } 11236 11237 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 11238 switch (E->getBuiltinCallee()) { 11239 default: 11240 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11241 11242 case Builtin::BI__builtin_huge_val: 11243 case Builtin::BI__builtin_huge_valf: 11244 case Builtin::BI__builtin_huge_vall: 11245 case Builtin::BI__builtin_huge_valf128: 11246 case Builtin::BI__builtin_inf: 11247 case Builtin::BI__builtin_inff: 11248 case Builtin::BI__builtin_infl: 11249 case Builtin::BI__builtin_inff128: { 11250 const llvm::fltSemantics &Sem = 11251 Info.Ctx.getFloatTypeSemantics(E->getType()); 11252 Result = llvm::APFloat::getInf(Sem); 11253 return true; 11254 } 11255 11256 case Builtin::BI__builtin_nans: 11257 case Builtin::BI__builtin_nansf: 11258 case Builtin::BI__builtin_nansl: 11259 case Builtin::BI__builtin_nansf128: 11260 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 11261 true, Result)) 11262 return Error(E); 11263 return true; 11264 11265 case Builtin::BI__builtin_nan: 11266 case Builtin::BI__builtin_nanf: 11267 case Builtin::BI__builtin_nanl: 11268 case Builtin::BI__builtin_nanf128: 11269 // If this is __builtin_nan() turn this into a nan, otherwise we 11270 // can't constant fold it. 11271 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 11272 false, Result)) 11273 return Error(E); 11274 return true; 11275 11276 case Builtin::BI__builtin_fabs: 11277 case Builtin::BI__builtin_fabsf: 11278 case Builtin::BI__builtin_fabsl: 11279 case Builtin::BI__builtin_fabsf128: 11280 if (!EvaluateFloat(E->getArg(0), Result, Info)) 11281 return false; 11282 11283 if (Result.isNegative()) 11284 Result.changeSign(); 11285 return true; 11286 11287 // FIXME: Builtin::BI__builtin_powi 11288 // FIXME: Builtin::BI__builtin_powif 11289 // FIXME: Builtin::BI__builtin_powil 11290 11291 case Builtin::BI__builtin_copysign: 11292 case Builtin::BI__builtin_copysignf: 11293 case Builtin::BI__builtin_copysignl: 11294 case Builtin::BI__builtin_copysignf128: { 11295 APFloat RHS(0.); 11296 if (!EvaluateFloat(E->getArg(0), Result, Info) || 11297 !EvaluateFloat(E->getArg(1), RHS, Info)) 11298 return false; 11299 Result.copySign(RHS); 11300 return true; 11301 } 11302 } 11303 } 11304 11305 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 11306 if (E->getSubExpr()->getType()->isAnyComplexType()) { 11307 ComplexValue CV; 11308 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 11309 return false; 11310 Result = CV.FloatReal; 11311 return true; 11312 } 11313 11314 return Visit(E->getSubExpr()); 11315 } 11316 11317 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 11318 if (E->getSubExpr()->getType()->isAnyComplexType()) { 11319 ComplexValue CV; 11320 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 11321 return false; 11322 Result = CV.FloatImag; 11323 return true; 11324 } 11325 11326 VisitIgnoredValue(E->getSubExpr()); 11327 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 11328 Result = llvm::APFloat::getZero(Sem); 11329 return true; 11330 } 11331 11332 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 11333 switch (E->getOpcode()) { 11334 default: return Error(E); 11335 case UO_Plus: 11336 return EvaluateFloat(E->getSubExpr(), Result, Info); 11337 case UO_Minus: 11338 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 11339 return false; 11340 Result.changeSign(); 11341 return true; 11342 } 11343 } 11344 11345 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 11346 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 11347 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 11348 11349 APFloat RHS(0.0); 11350 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 11351 if (!LHSOK && !Info.noteFailure()) 11352 return false; 11353 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 11354 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 11355 } 11356 11357 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 11358 Result = E->getValue(); 11359 return true; 11360 } 11361 11362 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 11363 const Expr* SubExpr = E->getSubExpr(); 11364 11365 switch (E->getCastKind()) { 11366 default: 11367 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11368 11369 case CK_IntegralToFloating: { 11370 APSInt IntResult; 11371 return EvaluateInteger(SubExpr, IntResult, Info) && 11372 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 11373 E->getType(), Result); 11374 } 11375 11376 case CK_FloatingCast: { 11377 if (!Visit(SubExpr)) 11378 return false; 11379 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 11380 Result); 11381 } 11382 11383 case CK_FloatingComplexToReal: { 11384 ComplexValue V; 11385 if (!EvaluateComplex(SubExpr, V, Info)) 11386 return false; 11387 Result = V.getComplexFloatReal(); 11388 return true; 11389 } 11390 } 11391 } 11392 11393 //===----------------------------------------------------------------------===// 11394 // Complex Evaluation (for float and integer) 11395 //===----------------------------------------------------------------------===// 11396 11397 namespace { 11398 class ComplexExprEvaluator 11399 : public ExprEvaluatorBase<ComplexExprEvaluator> { 11400 ComplexValue &Result; 11401 11402 public: 11403 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 11404 : ExprEvaluatorBaseTy(info), Result(Result) {} 11405 11406 bool Success(const APValue &V, const Expr *e) { 11407 Result.setFrom(V); 11408 return true; 11409 } 11410 11411 bool ZeroInitialization(const Expr *E); 11412 11413 //===--------------------------------------------------------------------===// 11414 // Visitor Methods 11415 //===--------------------------------------------------------------------===// 11416 11417 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 11418 bool VisitCastExpr(const CastExpr *E); 11419 bool VisitBinaryOperator(const BinaryOperator *E); 11420 bool VisitUnaryOperator(const UnaryOperator *E); 11421 bool VisitInitListExpr(const InitListExpr *E); 11422 }; 11423 } // end anonymous namespace 11424 11425 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 11426 EvalInfo &Info) { 11427 assert(E->isRValue() && E->getType()->isAnyComplexType()); 11428 return ComplexExprEvaluator(Info, Result).Visit(E); 11429 } 11430 11431 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 11432 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 11433 if (ElemTy->isRealFloatingType()) { 11434 Result.makeComplexFloat(); 11435 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 11436 Result.FloatReal = Zero; 11437 Result.FloatImag = Zero; 11438 } else { 11439 Result.makeComplexInt(); 11440 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 11441 Result.IntReal = Zero; 11442 Result.IntImag = Zero; 11443 } 11444 return true; 11445 } 11446 11447 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 11448 const Expr* SubExpr = E->getSubExpr(); 11449 11450 if (SubExpr->getType()->isRealFloatingType()) { 11451 Result.makeComplexFloat(); 11452 APFloat &Imag = Result.FloatImag; 11453 if (!EvaluateFloat(SubExpr, Imag, Info)) 11454 return false; 11455 11456 Result.FloatReal = APFloat(Imag.getSemantics()); 11457 return true; 11458 } else { 11459 assert(SubExpr->getType()->isIntegerType() && 11460 "Unexpected imaginary literal."); 11461 11462 Result.makeComplexInt(); 11463 APSInt &Imag = Result.IntImag; 11464 if (!EvaluateInteger(SubExpr, Imag, Info)) 11465 return false; 11466 11467 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 11468 return true; 11469 } 11470 } 11471 11472 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 11473 11474 switch (E->getCastKind()) { 11475 case CK_BitCast: 11476 case CK_BaseToDerived: 11477 case CK_DerivedToBase: 11478 case CK_UncheckedDerivedToBase: 11479 case CK_Dynamic: 11480 case CK_ToUnion: 11481 case CK_ArrayToPointerDecay: 11482 case CK_FunctionToPointerDecay: 11483 case CK_NullToPointer: 11484 case CK_NullToMemberPointer: 11485 case CK_BaseToDerivedMemberPointer: 11486 case CK_DerivedToBaseMemberPointer: 11487 case CK_MemberPointerToBoolean: 11488 case CK_ReinterpretMemberPointer: 11489 case CK_ConstructorConversion: 11490 case CK_IntegralToPointer: 11491 case CK_PointerToIntegral: 11492 case CK_PointerToBoolean: 11493 case CK_ToVoid: 11494 case CK_VectorSplat: 11495 case CK_IntegralCast: 11496 case CK_BooleanToSignedIntegral: 11497 case CK_IntegralToBoolean: 11498 case CK_IntegralToFloating: 11499 case CK_FloatingToIntegral: 11500 case CK_FloatingToBoolean: 11501 case CK_FloatingCast: 11502 case CK_CPointerToObjCPointerCast: 11503 case CK_BlockPointerToObjCPointerCast: 11504 case CK_AnyPointerToBlockPointerCast: 11505 case CK_ObjCObjectLValueCast: 11506 case CK_FloatingComplexToReal: 11507 case CK_FloatingComplexToBoolean: 11508 case CK_IntegralComplexToReal: 11509 case CK_IntegralComplexToBoolean: 11510 case CK_ARCProduceObject: 11511 case CK_ARCConsumeObject: 11512 case CK_ARCReclaimReturnedObject: 11513 case CK_ARCExtendBlockObject: 11514 case CK_CopyAndAutoreleaseBlockObject: 11515 case CK_BuiltinFnToFnPtr: 11516 case CK_ZeroToOCLOpaqueType: 11517 case CK_NonAtomicToAtomic: 11518 case CK_AddressSpaceConversion: 11519 case CK_IntToOCLSampler: 11520 case CK_FixedPointCast: 11521 case CK_FixedPointToBoolean: 11522 case CK_FixedPointToIntegral: 11523 case CK_IntegralToFixedPoint: 11524 llvm_unreachable("invalid cast kind for complex value"); 11525 11526 case CK_LValueToRValue: 11527 case CK_AtomicToNonAtomic: 11528 case CK_NoOp: 11529 case CK_LValueToRValueBitCast: 11530 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11531 11532 case CK_Dependent: 11533 case CK_LValueBitCast: 11534 case CK_UserDefinedConversion: 11535 return Error(E); 11536 11537 case CK_FloatingRealToComplex: { 11538 APFloat &Real = Result.FloatReal; 11539 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 11540 return false; 11541 11542 Result.makeComplexFloat(); 11543 Result.FloatImag = APFloat(Real.getSemantics()); 11544 return true; 11545 } 11546 11547 case CK_FloatingComplexCast: { 11548 if (!Visit(E->getSubExpr())) 11549 return false; 11550 11551 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 11552 QualType From 11553 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 11554 11555 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 11556 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 11557 } 11558 11559 case CK_FloatingComplexToIntegralComplex: { 11560 if (!Visit(E->getSubExpr())) 11561 return false; 11562 11563 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 11564 QualType From 11565 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 11566 Result.makeComplexInt(); 11567 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 11568 To, Result.IntReal) && 11569 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 11570 To, Result.IntImag); 11571 } 11572 11573 case CK_IntegralRealToComplex: { 11574 APSInt &Real = Result.IntReal; 11575 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 11576 return false; 11577 11578 Result.makeComplexInt(); 11579 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 11580 return true; 11581 } 11582 11583 case CK_IntegralComplexCast: { 11584 if (!Visit(E->getSubExpr())) 11585 return false; 11586 11587 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 11588 QualType From 11589 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 11590 11591 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 11592 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 11593 return true; 11594 } 11595 11596 case CK_IntegralComplexToFloatingComplex: { 11597 if (!Visit(E->getSubExpr())) 11598 return false; 11599 11600 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 11601 QualType From 11602 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 11603 Result.makeComplexFloat(); 11604 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 11605 To, Result.FloatReal) && 11606 HandleIntToFloatCast(Info, E, From, Result.IntImag, 11607 To, Result.FloatImag); 11608 } 11609 } 11610 11611 llvm_unreachable("unknown cast resulting in complex value"); 11612 } 11613 11614 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 11615 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 11616 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 11617 11618 // Track whether the LHS or RHS is real at the type system level. When this is 11619 // the case we can simplify our evaluation strategy. 11620 bool LHSReal = false, RHSReal = false; 11621 11622 bool LHSOK; 11623 if (E->getLHS()->getType()->isRealFloatingType()) { 11624 LHSReal = true; 11625 APFloat &Real = Result.FloatReal; 11626 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 11627 if (LHSOK) { 11628 Result.makeComplexFloat(); 11629 Result.FloatImag = APFloat(Real.getSemantics()); 11630 } 11631 } else { 11632 LHSOK = Visit(E->getLHS()); 11633 } 11634 if (!LHSOK && !Info.noteFailure()) 11635 return false; 11636 11637 ComplexValue RHS; 11638 if (E->getRHS()->getType()->isRealFloatingType()) { 11639 RHSReal = true; 11640 APFloat &Real = RHS.FloatReal; 11641 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 11642 return false; 11643 RHS.makeComplexFloat(); 11644 RHS.FloatImag = APFloat(Real.getSemantics()); 11645 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 11646 return false; 11647 11648 assert(!(LHSReal && RHSReal) && 11649 "Cannot have both operands of a complex operation be real."); 11650 switch (E->getOpcode()) { 11651 default: return Error(E); 11652 case BO_Add: 11653 if (Result.isComplexFloat()) { 11654 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 11655 APFloat::rmNearestTiesToEven); 11656 if (LHSReal) 11657 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 11658 else if (!RHSReal) 11659 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 11660 APFloat::rmNearestTiesToEven); 11661 } else { 11662 Result.getComplexIntReal() += RHS.getComplexIntReal(); 11663 Result.getComplexIntImag() += RHS.getComplexIntImag(); 11664 } 11665 break; 11666 case BO_Sub: 11667 if (Result.isComplexFloat()) { 11668 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 11669 APFloat::rmNearestTiesToEven); 11670 if (LHSReal) { 11671 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 11672 Result.getComplexFloatImag().changeSign(); 11673 } else if (!RHSReal) { 11674 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 11675 APFloat::rmNearestTiesToEven); 11676 } 11677 } else { 11678 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 11679 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 11680 } 11681 break; 11682 case BO_Mul: 11683 if (Result.isComplexFloat()) { 11684 // This is an implementation of complex multiplication according to the 11685 // constraints laid out in C11 Annex G. The implementation uses the 11686 // following naming scheme: 11687 // (a + ib) * (c + id) 11688 ComplexValue LHS = Result; 11689 APFloat &A = LHS.getComplexFloatReal(); 11690 APFloat &B = LHS.getComplexFloatImag(); 11691 APFloat &C = RHS.getComplexFloatReal(); 11692 APFloat &D = RHS.getComplexFloatImag(); 11693 APFloat &ResR = Result.getComplexFloatReal(); 11694 APFloat &ResI = Result.getComplexFloatImag(); 11695 if (LHSReal) { 11696 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 11697 ResR = A * C; 11698 ResI = A * D; 11699 } else if (RHSReal) { 11700 ResR = C * A; 11701 ResI = C * B; 11702 } else { 11703 // In the fully general case, we need to handle NaNs and infinities 11704 // robustly. 11705 APFloat AC = A * C; 11706 APFloat BD = B * D; 11707 APFloat AD = A * D; 11708 APFloat BC = B * C; 11709 ResR = AC - BD; 11710 ResI = AD + BC; 11711 if (ResR.isNaN() && ResI.isNaN()) { 11712 bool Recalc = false; 11713 if (A.isInfinity() || B.isInfinity()) { 11714 A = APFloat::copySign( 11715 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 11716 B = APFloat::copySign( 11717 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 11718 if (C.isNaN()) 11719 C = APFloat::copySign(APFloat(C.getSemantics()), C); 11720 if (D.isNaN()) 11721 D = APFloat::copySign(APFloat(D.getSemantics()), D); 11722 Recalc = true; 11723 } 11724 if (C.isInfinity() || D.isInfinity()) { 11725 C = APFloat::copySign( 11726 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 11727 D = APFloat::copySign( 11728 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 11729 if (A.isNaN()) 11730 A = APFloat::copySign(APFloat(A.getSemantics()), A); 11731 if (B.isNaN()) 11732 B = APFloat::copySign(APFloat(B.getSemantics()), B); 11733 Recalc = true; 11734 } 11735 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 11736 AD.isInfinity() || BC.isInfinity())) { 11737 if (A.isNaN()) 11738 A = APFloat::copySign(APFloat(A.getSemantics()), A); 11739 if (B.isNaN()) 11740 B = APFloat::copySign(APFloat(B.getSemantics()), B); 11741 if (C.isNaN()) 11742 C = APFloat::copySign(APFloat(C.getSemantics()), C); 11743 if (D.isNaN()) 11744 D = APFloat::copySign(APFloat(D.getSemantics()), D); 11745 Recalc = true; 11746 } 11747 if (Recalc) { 11748 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 11749 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 11750 } 11751 } 11752 } 11753 } else { 11754 ComplexValue LHS = Result; 11755 Result.getComplexIntReal() = 11756 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 11757 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 11758 Result.getComplexIntImag() = 11759 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 11760 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 11761 } 11762 break; 11763 case BO_Div: 11764 if (Result.isComplexFloat()) { 11765 // This is an implementation of complex division according to the 11766 // constraints laid out in C11 Annex G. The implementation uses the 11767 // following naming scheme: 11768 // (a + ib) / (c + id) 11769 ComplexValue LHS = Result; 11770 APFloat &A = LHS.getComplexFloatReal(); 11771 APFloat &B = LHS.getComplexFloatImag(); 11772 APFloat &C = RHS.getComplexFloatReal(); 11773 APFloat &D = RHS.getComplexFloatImag(); 11774 APFloat &ResR = Result.getComplexFloatReal(); 11775 APFloat &ResI = Result.getComplexFloatImag(); 11776 if (RHSReal) { 11777 ResR = A / C; 11778 ResI = B / C; 11779 } else { 11780 if (LHSReal) { 11781 // No real optimizations we can do here, stub out with zero. 11782 B = APFloat::getZero(A.getSemantics()); 11783 } 11784 int DenomLogB = 0; 11785 APFloat MaxCD = maxnum(abs(C), abs(D)); 11786 if (MaxCD.isFinite()) { 11787 DenomLogB = ilogb(MaxCD); 11788 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 11789 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 11790 } 11791 APFloat Denom = C * C + D * D; 11792 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 11793 APFloat::rmNearestTiesToEven); 11794 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 11795 APFloat::rmNearestTiesToEven); 11796 if (ResR.isNaN() && ResI.isNaN()) { 11797 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 11798 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 11799 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 11800 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 11801 D.isFinite()) { 11802 A = APFloat::copySign( 11803 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 11804 B = APFloat::copySign( 11805 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 11806 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 11807 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 11808 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 11809 C = APFloat::copySign( 11810 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 11811 D = APFloat::copySign( 11812 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 11813 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 11814 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 11815 } 11816 } 11817 } 11818 } else { 11819 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 11820 return Error(E, diag::note_expr_divide_by_zero); 11821 11822 ComplexValue LHS = Result; 11823 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 11824 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 11825 Result.getComplexIntReal() = 11826 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 11827 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 11828 Result.getComplexIntImag() = 11829 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 11830 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 11831 } 11832 break; 11833 } 11834 11835 return true; 11836 } 11837 11838 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 11839 // Get the operand value into 'Result'. 11840 if (!Visit(E->getSubExpr())) 11841 return false; 11842 11843 switch (E->getOpcode()) { 11844 default: 11845 return Error(E); 11846 case UO_Extension: 11847 return true; 11848 case UO_Plus: 11849 // The result is always just the subexpr. 11850 return true; 11851 case UO_Minus: 11852 if (Result.isComplexFloat()) { 11853 Result.getComplexFloatReal().changeSign(); 11854 Result.getComplexFloatImag().changeSign(); 11855 } 11856 else { 11857 Result.getComplexIntReal() = -Result.getComplexIntReal(); 11858 Result.getComplexIntImag() = -Result.getComplexIntImag(); 11859 } 11860 return true; 11861 case UO_Not: 11862 if (Result.isComplexFloat()) 11863 Result.getComplexFloatImag().changeSign(); 11864 else 11865 Result.getComplexIntImag() = -Result.getComplexIntImag(); 11866 return true; 11867 } 11868 } 11869 11870 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 11871 if (E->getNumInits() == 2) { 11872 if (E->getType()->isComplexType()) { 11873 Result.makeComplexFloat(); 11874 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 11875 return false; 11876 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 11877 return false; 11878 } else { 11879 Result.makeComplexInt(); 11880 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 11881 return false; 11882 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 11883 return false; 11884 } 11885 return true; 11886 } 11887 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 11888 } 11889 11890 //===----------------------------------------------------------------------===// 11891 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 11892 // implicit conversion. 11893 //===----------------------------------------------------------------------===// 11894 11895 namespace { 11896 class AtomicExprEvaluator : 11897 public ExprEvaluatorBase<AtomicExprEvaluator> { 11898 const LValue *This; 11899 APValue &Result; 11900 public: 11901 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 11902 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 11903 11904 bool Success(const APValue &V, const Expr *E) { 11905 Result = V; 11906 return true; 11907 } 11908 11909 bool ZeroInitialization(const Expr *E) { 11910 ImplicitValueInitExpr VIE( 11911 E->getType()->castAs<AtomicType>()->getValueType()); 11912 // For atomic-qualified class (and array) types in C++, initialize the 11913 // _Atomic-wrapped subobject directly, in-place. 11914 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 11915 : Evaluate(Result, Info, &VIE); 11916 } 11917 11918 bool VisitCastExpr(const CastExpr *E) { 11919 switch (E->getCastKind()) { 11920 default: 11921 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11922 case CK_NonAtomicToAtomic: 11923 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 11924 : Evaluate(Result, Info, E->getSubExpr()); 11925 } 11926 } 11927 }; 11928 } // end anonymous namespace 11929 11930 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 11931 EvalInfo &Info) { 11932 assert(E->isRValue() && E->getType()->isAtomicType()); 11933 return AtomicExprEvaluator(Info, This, Result).Visit(E); 11934 } 11935 11936 //===----------------------------------------------------------------------===// 11937 // Void expression evaluation, primarily for a cast to void on the LHS of a 11938 // comma operator 11939 //===----------------------------------------------------------------------===// 11940 11941 namespace { 11942 class VoidExprEvaluator 11943 : public ExprEvaluatorBase<VoidExprEvaluator> { 11944 public: 11945 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 11946 11947 bool Success(const APValue &V, const Expr *e) { return true; } 11948 11949 bool ZeroInitialization(const Expr *E) { return true; } 11950 11951 bool VisitCastExpr(const CastExpr *E) { 11952 switch (E->getCastKind()) { 11953 default: 11954 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11955 case CK_ToVoid: 11956 VisitIgnoredValue(E->getSubExpr()); 11957 return true; 11958 } 11959 } 11960 11961 bool VisitCallExpr(const CallExpr *E) { 11962 switch (E->getBuiltinCallee()) { 11963 default: 11964 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11965 case Builtin::BI__assume: 11966 case Builtin::BI__builtin_assume: 11967 // The argument is not evaluated! 11968 return true; 11969 } 11970 } 11971 }; 11972 } // end anonymous namespace 11973 11974 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 11975 assert(E->isRValue() && E->getType()->isVoidType()); 11976 return VoidExprEvaluator(Info).Visit(E); 11977 } 11978 11979 //===----------------------------------------------------------------------===// 11980 // Top level Expr::EvaluateAsRValue method. 11981 //===----------------------------------------------------------------------===// 11982 11983 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 11984 // In C, function designators are not lvalues, but we evaluate them as if they 11985 // are. 11986 QualType T = E->getType(); 11987 if (E->isGLValue() || T->isFunctionType()) { 11988 LValue LV; 11989 if (!EvaluateLValue(E, LV, Info)) 11990 return false; 11991 LV.moveInto(Result); 11992 } else if (T->isVectorType()) { 11993 if (!EvaluateVector(E, Result, Info)) 11994 return false; 11995 } else if (T->isIntegralOrEnumerationType()) { 11996 if (!IntExprEvaluator(Info, Result).Visit(E)) 11997 return false; 11998 } else if (T->hasPointerRepresentation()) { 11999 LValue LV; 12000 if (!EvaluatePointer(E, LV, Info)) 12001 return false; 12002 LV.moveInto(Result); 12003 } else if (T->isRealFloatingType()) { 12004 llvm::APFloat F(0.0); 12005 if (!EvaluateFloat(E, F, Info)) 12006 return false; 12007 Result = APValue(F); 12008 } else if (T->isAnyComplexType()) { 12009 ComplexValue C; 12010 if (!EvaluateComplex(E, C, Info)) 12011 return false; 12012 C.moveInto(Result); 12013 } else if (T->isFixedPointType()) { 12014 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 12015 } else if (T->isMemberPointerType()) { 12016 MemberPtr P; 12017 if (!EvaluateMemberPointer(E, P, Info)) 12018 return false; 12019 P.moveInto(Result); 12020 return true; 12021 } else if (T->isArrayType()) { 12022 LValue LV; 12023 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 12024 if (!EvaluateArray(E, LV, Value, Info)) 12025 return false; 12026 Result = Value; 12027 } else if (T->isRecordType()) { 12028 LValue LV; 12029 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 12030 if (!EvaluateRecord(E, LV, Value, Info)) 12031 return false; 12032 Result = Value; 12033 } else if (T->isVoidType()) { 12034 if (!Info.getLangOpts().CPlusPlus11) 12035 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 12036 << E->getType(); 12037 if (!EvaluateVoid(E, Info)) 12038 return false; 12039 } else if (T->isAtomicType()) { 12040 QualType Unqual = T.getAtomicUnqualifiedType(); 12041 if (Unqual->isArrayType() || Unqual->isRecordType()) { 12042 LValue LV; 12043 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 12044 if (!EvaluateAtomic(E, &LV, Value, Info)) 12045 return false; 12046 } else { 12047 if (!EvaluateAtomic(E, nullptr, Result, Info)) 12048 return false; 12049 } 12050 } else if (Info.getLangOpts().CPlusPlus11) { 12051 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 12052 return false; 12053 } else { 12054 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12055 return false; 12056 } 12057 12058 return true; 12059 } 12060 12061 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 12062 /// cases, the in-place evaluation is essential, since later initializers for 12063 /// an object can indirectly refer to subobjects which were initialized earlier. 12064 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 12065 const Expr *E, bool AllowNonLiteralTypes) { 12066 assert(!E->isValueDependent()); 12067 12068 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 12069 return false; 12070 12071 if (E->isRValue()) { 12072 // Evaluate arrays and record types in-place, so that later initializers can 12073 // refer to earlier-initialized members of the object. 12074 QualType T = E->getType(); 12075 if (T->isArrayType()) 12076 return EvaluateArray(E, This, Result, Info); 12077 else if (T->isRecordType()) 12078 return EvaluateRecord(E, This, Result, Info); 12079 else if (T->isAtomicType()) { 12080 QualType Unqual = T.getAtomicUnqualifiedType(); 12081 if (Unqual->isArrayType() || Unqual->isRecordType()) 12082 return EvaluateAtomic(E, &This, Result, Info); 12083 } 12084 } 12085 12086 // For any other type, in-place evaluation is unimportant. 12087 return Evaluate(Result, Info, E); 12088 } 12089 12090 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 12091 /// lvalue-to-rvalue cast if it is an lvalue. 12092 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 12093 if (Info.EnableNewConstInterp) { 12094 auto &InterpCtx = Info.Ctx.getInterpContext(); 12095 switch (InterpCtx.evaluateAsRValue(Info, E, Result)) { 12096 case interp::InterpResult::Success: 12097 return true; 12098 case interp::InterpResult::Fail: 12099 return false; 12100 case interp::InterpResult::Bail: 12101 break; 12102 } 12103 } 12104 12105 if (E->getType().isNull()) 12106 return false; 12107 12108 if (!CheckLiteralType(Info, E)) 12109 return false; 12110 12111 if (!::Evaluate(Result, Info, E)) 12112 return false; 12113 12114 if (E->isGLValue()) { 12115 LValue LV; 12116 LV.setFrom(Info.Ctx, Result); 12117 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12118 return false; 12119 } 12120 12121 // Check this core constant expression is a constant expression. 12122 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 12123 } 12124 12125 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 12126 const ASTContext &Ctx, bool &IsConst) { 12127 // Fast-path evaluations of integer literals, since we sometimes see files 12128 // containing vast quantities of these. 12129 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 12130 Result.Val = APValue(APSInt(L->getValue(), 12131 L->getType()->isUnsignedIntegerType())); 12132 IsConst = true; 12133 return true; 12134 } 12135 12136 // This case should be rare, but we need to check it before we check on 12137 // the type below. 12138 if (Exp->getType().isNull()) { 12139 IsConst = false; 12140 return true; 12141 } 12142 12143 // FIXME: Evaluating values of large array and record types can cause 12144 // performance problems. Only do so in C++11 for now. 12145 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 12146 Exp->getType()->isRecordType()) && 12147 !Ctx.getLangOpts().CPlusPlus11) { 12148 IsConst = false; 12149 return true; 12150 } 12151 return false; 12152 } 12153 12154 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 12155 Expr::SideEffectsKind SEK) { 12156 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 12157 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 12158 } 12159 12160 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 12161 const ASTContext &Ctx, EvalInfo &Info) { 12162 bool IsConst; 12163 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 12164 return IsConst; 12165 12166 return EvaluateAsRValue(Info, E, Result.Val); 12167 } 12168 12169 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 12170 const ASTContext &Ctx, 12171 Expr::SideEffectsKind AllowSideEffects, 12172 EvalInfo &Info) { 12173 if (!E->getType()->isIntegralOrEnumerationType()) 12174 return false; 12175 12176 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 12177 !ExprResult.Val.isInt() || 12178 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 12179 return false; 12180 12181 return true; 12182 } 12183 12184 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 12185 const ASTContext &Ctx, 12186 Expr::SideEffectsKind AllowSideEffects, 12187 EvalInfo &Info) { 12188 if (!E->getType()->isFixedPointType()) 12189 return false; 12190 12191 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 12192 return false; 12193 12194 if (!ExprResult.Val.isFixedPoint() || 12195 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 12196 return false; 12197 12198 return true; 12199 } 12200 12201 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 12202 /// any crazy technique (that has nothing to do with language standards) that 12203 /// we want to. If this function returns true, it returns the folded constant 12204 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 12205 /// will be applied to the result. 12206 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 12207 bool InConstantContext) const { 12208 assert(!isValueDependent() && 12209 "Expression evaluator can't be called on a dependent expression."); 12210 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 12211 Info.InConstantContext = InConstantContext; 12212 return ::EvaluateAsRValue(this, Result, Ctx, Info); 12213 } 12214 12215 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 12216 bool InConstantContext) const { 12217 assert(!isValueDependent() && 12218 "Expression evaluator can't be called on a dependent expression."); 12219 EvalResult Scratch; 12220 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 12221 HandleConversionToBool(Scratch.Val, Result); 12222 } 12223 12224 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 12225 SideEffectsKind AllowSideEffects, 12226 bool InConstantContext) const { 12227 assert(!isValueDependent() && 12228 "Expression evaluator can't be called on a dependent expression."); 12229 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 12230 Info.InConstantContext = InConstantContext; 12231 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 12232 } 12233 12234 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 12235 SideEffectsKind AllowSideEffects, 12236 bool InConstantContext) const { 12237 assert(!isValueDependent() && 12238 "Expression evaluator can't be called on a dependent expression."); 12239 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 12240 Info.InConstantContext = InConstantContext; 12241 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 12242 } 12243 12244 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 12245 SideEffectsKind AllowSideEffects, 12246 bool InConstantContext) const { 12247 assert(!isValueDependent() && 12248 "Expression evaluator can't be called on a dependent expression."); 12249 12250 if (!getType()->isRealFloatingType()) 12251 return false; 12252 12253 EvalResult ExprResult; 12254 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 12255 !ExprResult.Val.isFloat() || 12256 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 12257 return false; 12258 12259 Result = ExprResult.Val.getFloat(); 12260 return true; 12261 } 12262 12263 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 12264 bool InConstantContext) const { 12265 assert(!isValueDependent() && 12266 "Expression evaluator can't be called on a dependent expression."); 12267 12268 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 12269 Info.InConstantContext = InConstantContext; 12270 LValue LV; 12271 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects || 12272 !CheckLValueConstantExpression(Info, getExprLoc(), 12273 Ctx.getLValueReferenceType(getType()), LV, 12274 Expr::EvaluateForCodeGen)) 12275 return false; 12276 12277 LV.moveInto(Result.Val); 12278 return true; 12279 } 12280 12281 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 12282 const ASTContext &Ctx) const { 12283 assert(!isValueDependent() && 12284 "Expression evaluator can't be called on a dependent expression."); 12285 12286 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 12287 EvalInfo Info(Ctx, Result, EM); 12288 Info.InConstantContext = true; 12289 12290 if (!::Evaluate(Result.Val, Info, this)) 12291 return false; 12292 12293 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val, 12294 Usage); 12295 } 12296 12297 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 12298 const VarDecl *VD, 12299 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 12300 assert(!isValueDependent() && 12301 "Expression evaluator can't be called on a dependent expression."); 12302 12303 // FIXME: Evaluating initializers for large array and record types can cause 12304 // performance problems. Only do so in C++11 for now. 12305 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 12306 !Ctx.getLangOpts().CPlusPlus11) 12307 return false; 12308 12309 Expr::EvalStatus EStatus; 12310 EStatus.Diag = &Notes; 12311 12312 EvalInfo Info(Ctx, EStatus, VD->isConstexpr() 12313 ? EvalInfo::EM_ConstantExpression 12314 : EvalInfo::EM_ConstantFold); 12315 Info.setEvaluatingDecl(VD, Value); 12316 Info.InConstantContext = true; 12317 12318 SourceLocation DeclLoc = VD->getLocation(); 12319 QualType DeclTy = VD->getType(); 12320 12321 if (Info.EnableNewConstInterp) { 12322 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 12323 switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) { 12324 case interp::InterpResult::Fail: 12325 // Bail out if an error was encountered. 12326 return false; 12327 case interp::InterpResult::Success: 12328 // Evaluation succeeded and value was set. 12329 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value); 12330 case interp::InterpResult::Bail: 12331 // Evaluate the value again for the tree evaluator to use. 12332 break; 12333 } 12334 } 12335 12336 LValue LVal; 12337 LVal.set(VD); 12338 12339 // C++11 [basic.start.init]p2: 12340 // Variables with static storage duration or thread storage duration shall be 12341 // zero-initialized before any other initialization takes place. 12342 // This behavior is not present in C. 12343 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && 12344 !DeclTy->isReferenceType()) { 12345 ImplicitValueInitExpr VIE(DeclTy); 12346 if (!EvaluateInPlace(Value, Info, LVal, &VIE, 12347 /*AllowNonLiteralTypes=*/true)) 12348 return false; 12349 } 12350 12351 if (!EvaluateInPlace(Value, Info, LVal, this, 12352 /*AllowNonLiteralTypes=*/true) || 12353 EStatus.HasSideEffects) 12354 return false; 12355 12356 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value); 12357 } 12358 12359 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 12360 /// constant folded, but discard the result. 12361 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 12362 assert(!isValueDependent() && 12363 "Expression evaluator can't be called on a dependent expression."); 12364 12365 EvalResult Result; 12366 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 12367 !hasUnacceptableSideEffect(Result, SEK); 12368 } 12369 12370 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 12371 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 12372 assert(!isValueDependent() && 12373 "Expression evaluator can't be called on a dependent expression."); 12374 12375 EvalResult EVResult; 12376 EVResult.Diag = Diag; 12377 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 12378 Info.InConstantContext = true; 12379 12380 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 12381 (void)Result; 12382 assert(Result && "Could not evaluate expression"); 12383 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 12384 12385 return EVResult.Val.getInt(); 12386 } 12387 12388 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 12389 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 12390 assert(!isValueDependent() && 12391 "Expression evaluator can't be called on a dependent expression."); 12392 12393 EvalResult EVResult; 12394 EVResult.Diag = Diag; 12395 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 12396 Info.InConstantContext = true; 12397 Info.CheckingForUndefinedBehavior = true; 12398 12399 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 12400 (void)Result; 12401 assert(Result && "Could not evaluate expression"); 12402 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 12403 12404 return EVResult.Val.getInt(); 12405 } 12406 12407 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 12408 assert(!isValueDependent() && 12409 "Expression evaluator can't be called on a dependent expression."); 12410 12411 bool IsConst; 12412 EvalResult EVResult; 12413 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 12414 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 12415 Info.CheckingForUndefinedBehavior = true; 12416 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 12417 } 12418 } 12419 12420 bool Expr::EvalResult::isGlobalLValue() const { 12421 assert(Val.isLValue()); 12422 return IsGlobalLValue(Val.getLValueBase()); 12423 } 12424 12425 12426 /// isIntegerConstantExpr - this recursive routine will test if an expression is 12427 /// an integer constant expression. 12428 12429 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 12430 /// comma, etc 12431 12432 // CheckICE - This function does the fundamental ICE checking: the returned 12433 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 12434 // and a (possibly null) SourceLocation indicating the location of the problem. 12435 // 12436 // Note that to reduce code duplication, this helper does no evaluation 12437 // itself; the caller checks whether the expression is evaluatable, and 12438 // in the rare cases where CheckICE actually cares about the evaluated 12439 // value, it calls into Evaluate. 12440 12441 namespace { 12442 12443 enum ICEKind { 12444 /// This expression is an ICE. 12445 IK_ICE, 12446 /// This expression is not an ICE, but if it isn't evaluated, it's 12447 /// a legal subexpression for an ICE. This return value is used to handle 12448 /// the comma operator in C99 mode, and non-constant subexpressions. 12449 IK_ICEIfUnevaluated, 12450 /// This expression is not an ICE, and is not a legal subexpression for one. 12451 IK_NotICE 12452 }; 12453 12454 struct ICEDiag { 12455 ICEKind Kind; 12456 SourceLocation Loc; 12457 12458 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 12459 }; 12460 12461 } 12462 12463 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 12464 12465 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 12466 12467 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 12468 Expr::EvalResult EVResult; 12469 Expr::EvalStatus Status; 12470 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 12471 12472 Info.InConstantContext = true; 12473 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 12474 !EVResult.Val.isInt()) 12475 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12476 12477 return NoDiag(); 12478 } 12479 12480 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 12481 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 12482 if (!E->getType()->isIntegralOrEnumerationType()) 12483 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12484 12485 switch (E->getStmtClass()) { 12486 #define ABSTRACT_STMT(Node) 12487 #define STMT(Node, Base) case Expr::Node##Class: 12488 #define EXPR(Node, Base) 12489 #include "clang/AST/StmtNodes.inc" 12490 case Expr::PredefinedExprClass: 12491 case Expr::FloatingLiteralClass: 12492 case Expr::ImaginaryLiteralClass: 12493 case Expr::StringLiteralClass: 12494 case Expr::ArraySubscriptExprClass: 12495 case Expr::OMPArraySectionExprClass: 12496 case Expr::MemberExprClass: 12497 case Expr::CompoundAssignOperatorClass: 12498 case Expr::CompoundLiteralExprClass: 12499 case Expr::ExtVectorElementExprClass: 12500 case Expr::DesignatedInitExprClass: 12501 case Expr::ArrayInitLoopExprClass: 12502 case Expr::ArrayInitIndexExprClass: 12503 case Expr::NoInitExprClass: 12504 case Expr::DesignatedInitUpdateExprClass: 12505 case Expr::ImplicitValueInitExprClass: 12506 case Expr::ParenListExprClass: 12507 case Expr::VAArgExprClass: 12508 case Expr::AddrLabelExprClass: 12509 case Expr::StmtExprClass: 12510 case Expr::CXXMemberCallExprClass: 12511 case Expr::CUDAKernelCallExprClass: 12512 case Expr::CXXDynamicCastExprClass: 12513 case Expr::CXXTypeidExprClass: 12514 case Expr::CXXUuidofExprClass: 12515 case Expr::MSPropertyRefExprClass: 12516 case Expr::MSPropertySubscriptExprClass: 12517 case Expr::CXXNullPtrLiteralExprClass: 12518 case Expr::UserDefinedLiteralClass: 12519 case Expr::CXXThisExprClass: 12520 case Expr::CXXThrowExprClass: 12521 case Expr::CXXNewExprClass: 12522 case Expr::CXXDeleteExprClass: 12523 case Expr::CXXPseudoDestructorExprClass: 12524 case Expr::UnresolvedLookupExprClass: 12525 case Expr::TypoExprClass: 12526 case Expr::DependentScopeDeclRefExprClass: 12527 case Expr::CXXConstructExprClass: 12528 case Expr::CXXInheritedCtorInitExprClass: 12529 case Expr::CXXStdInitializerListExprClass: 12530 case Expr::CXXBindTemporaryExprClass: 12531 case Expr::ExprWithCleanupsClass: 12532 case Expr::CXXTemporaryObjectExprClass: 12533 case Expr::CXXUnresolvedConstructExprClass: 12534 case Expr::CXXDependentScopeMemberExprClass: 12535 case Expr::UnresolvedMemberExprClass: 12536 case Expr::ObjCStringLiteralClass: 12537 case Expr::ObjCBoxedExprClass: 12538 case Expr::ObjCArrayLiteralClass: 12539 case Expr::ObjCDictionaryLiteralClass: 12540 case Expr::ObjCEncodeExprClass: 12541 case Expr::ObjCMessageExprClass: 12542 case Expr::ObjCSelectorExprClass: 12543 case Expr::ObjCProtocolExprClass: 12544 case Expr::ObjCIvarRefExprClass: 12545 case Expr::ObjCPropertyRefExprClass: 12546 case Expr::ObjCSubscriptRefExprClass: 12547 case Expr::ObjCIsaExprClass: 12548 case Expr::ObjCAvailabilityCheckExprClass: 12549 case Expr::ShuffleVectorExprClass: 12550 case Expr::ConvertVectorExprClass: 12551 case Expr::BlockExprClass: 12552 case Expr::NoStmtClass: 12553 case Expr::OpaqueValueExprClass: 12554 case Expr::PackExpansionExprClass: 12555 case Expr::SubstNonTypeTemplateParmPackExprClass: 12556 case Expr::FunctionParmPackExprClass: 12557 case Expr::AsTypeExprClass: 12558 case Expr::ObjCIndirectCopyRestoreExprClass: 12559 case Expr::MaterializeTemporaryExprClass: 12560 case Expr::PseudoObjectExprClass: 12561 case Expr::AtomicExprClass: 12562 case Expr::LambdaExprClass: 12563 case Expr::CXXFoldExprClass: 12564 case Expr::CoawaitExprClass: 12565 case Expr::DependentCoawaitExprClass: 12566 case Expr::CoyieldExprClass: 12567 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12568 12569 case Expr::InitListExprClass: { 12570 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 12571 // form "T x = { a };" is equivalent to "T x = a;". 12572 // Unless we're initializing a reference, T is a scalar as it is known to be 12573 // of integral or enumeration type. 12574 if (E->isRValue()) 12575 if (cast<InitListExpr>(E)->getNumInits() == 1) 12576 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 12577 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12578 } 12579 12580 case Expr::SizeOfPackExprClass: 12581 case Expr::GNUNullExprClass: 12582 case Expr::SourceLocExprClass: 12583 return NoDiag(); 12584 12585 case Expr::SubstNonTypeTemplateParmExprClass: 12586 return 12587 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 12588 12589 case Expr::ConstantExprClass: 12590 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 12591 12592 case Expr::ParenExprClass: 12593 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 12594 case Expr::GenericSelectionExprClass: 12595 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 12596 case Expr::IntegerLiteralClass: 12597 case Expr::FixedPointLiteralClass: 12598 case Expr::CharacterLiteralClass: 12599 case Expr::ObjCBoolLiteralExprClass: 12600 case Expr::CXXBoolLiteralExprClass: 12601 case Expr::CXXScalarValueInitExprClass: 12602 case Expr::TypeTraitExprClass: 12603 case Expr::ArrayTypeTraitExprClass: 12604 case Expr::ExpressionTraitExprClass: 12605 case Expr::CXXNoexceptExprClass: 12606 return NoDiag(); 12607 case Expr::CallExprClass: 12608 case Expr::CXXOperatorCallExprClass: { 12609 // C99 6.6/3 allows function calls within unevaluated subexpressions of 12610 // constant expressions, but they can never be ICEs because an ICE cannot 12611 // contain an operand of (pointer to) function type. 12612 const CallExpr *CE = cast<CallExpr>(E); 12613 if (CE->getBuiltinCallee()) 12614 return CheckEvalInICE(E, Ctx); 12615 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12616 } 12617 case Expr::DeclRefExprClass: { 12618 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 12619 return NoDiag(); 12620 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 12621 if (Ctx.getLangOpts().CPlusPlus && 12622 D && IsConstNonVolatile(D->getType())) { 12623 // Parameter variables are never constants. Without this check, 12624 // getAnyInitializer() can find a default argument, which leads 12625 // to chaos. 12626 if (isa<ParmVarDecl>(D)) 12627 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 12628 12629 // C++ 7.1.5.1p2 12630 // A variable of non-volatile const-qualified integral or enumeration 12631 // type initialized by an ICE can be used in ICEs. 12632 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 12633 if (!Dcl->getType()->isIntegralOrEnumerationType()) 12634 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 12635 12636 const VarDecl *VD; 12637 // Look for a declaration of this variable that has an initializer, and 12638 // check whether it is an ICE. 12639 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 12640 return NoDiag(); 12641 else 12642 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 12643 } 12644 } 12645 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12646 } 12647 case Expr::UnaryOperatorClass: { 12648 const UnaryOperator *Exp = cast<UnaryOperator>(E); 12649 switch (Exp->getOpcode()) { 12650 case UO_PostInc: 12651 case UO_PostDec: 12652 case UO_PreInc: 12653 case UO_PreDec: 12654 case UO_AddrOf: 12655 case UO_Deref: 12656 case UO_Coawait: 12657 // C99 6.6/3 allows increment and decrement within unevaluated 12658 // subexpressions of constant expressions, but they can never be ICEs 12659 // because an ICE cannot contain an lvalue operand. 12660 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12661 case UO_Extension: 12662 case UO_LNot: 12663 case UO_Plus: 12664 case UO_Minus: 12665 case UO_Not: 12666 case UO_Real: 12667 case UO_Imag: 12668 return CheckICE(Exp->getSubExpr(), Ctx); 12669 } 12670 llvm_unreachable("invalid unary operator class"); 12671 } 12672 case Expr::OffsetOfExprClass: { 12673 // Note that per C99, offsetof must be an ICE. And AFAIK, using 12674 // EvaluateAsRValue matches the proposed gcc behavior for cases like 12675 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 12676 // compliance: we should warn earlier for offsetof expressions with 12677 // array subscripts that aren't ICEs, and if the array subscripts 12678 // are ICEs, the value of the offsetof must be an integer constant. 12679 return CheckEvalInICE(E, Ctx); 12680 } 12681 case Expr::UnaryExprOrTypeTraitExprClass: { 12682 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 12683 if ((Exp->getKind() == UETT_SizeOf) && 12684 Exp->getTypeOfArgument()->isVariableArrayType()) 12685 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12686 return NoDiag(); 12687 } 12688 case Expr::BinaryOperatorClass: { 12689 const BinaryOperator *Exp = cast<BinaryOperator>(E); 12690 switch (Exp->getOpcode()) { 12691 case BO_PtrMemD: 12692 case BO_PtrMemI: 12693 case BO_Assign: 12694 case BO_MulAssign: 12695 case BO_DivAssign: 12696 case BO_RemAssign: 12697 case BO_AddAssign: 12698 case BO_SubAssign: 12699 case BO_ShlAssign: 12700 case BO_ShrAssign: 12701 case BO_AndAssign: 12702 case BO_XorAssign: 12703 case BO_OrAssign: 12704 // C99 6.6/3 allows assignments within unevaluated subexpressions of 12705 // constant expressions, but they can never be ICEs because an ICE cannot 12706 // contain an lvalue operand. 12707 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12708 12709 case BO_Mul: 12710 case BO_Div: 12711 case BO_Rem: 12712 case BO_Add: 12713 case BO_Sub: 12714 case BO_Shl: 12715 case BO_Shr: 12716 case BO_LT: 12717 case BO_GT: 12718 case BO_LE: 12719 case BO_GE: 12720 case BO_EQ: 12721 case BO_NE: 12722 case BO_And: 12723 case BO_Xor: 12724 case BO_Or: 12725 case BO_Comma: 12726 case BO_Cmp: { 12727 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 12728 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 12729 if (Exp->getOpcode() == BO_Div || 12730 Exp->getOpcode() == BO_Rem) { 12731 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 12732 // we don't evaluate one. 12733 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 12734 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 12735 if (REval == 0) 12736 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 12737 if (REval.isSigned() && REval.isAllOnesValue()) { 12738 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 12739 if (LEval.isMinSignedValue()) 12740 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 12741 } 12742 } 12743 } 12744 if (Exp->getOpcode() == BO_Comma) { 12745 if (Ctx.getLangOpts().C99) { 12746 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 12747 // if it isn't evaluated. 12748 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 12749 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 12750 } else { 12751 // In both C89 and C++, commas in ICEs are illegal. 12752 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12753 } 12754 } 12755 return Worst(LHSResult, RHSResult); 12756 } 12757 case BO_LAnd: 12758 case BO_LOr: { 12759 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 12760 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 12761 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 12762 // Rare case where the RHS has a comma "side-effect"; we need 12763 // to actually check the condition to see whether the side 12764 // with the comma is evaluated. 12765 if ((Exp->getOpcode() == BO_LAnd) != 12766 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 12767 return RHSResult; 12768 return NoDiag(); 12769 } 12770 12771 return Worst(LHSResult, RHSResult); 12772 } 12773 } 12774 llvm_unreachable("invalid binary operator kind"); 12775 } 12776 case Expr::ImplicitCastExprClass: 12777 case Expr::CStyleCastExprClass: 12778 case Expr::CXXFunctionalCastExprClass: 12779 case Expr::CXXStaticCastExprClass: 12780 case Expr::CXXReinterpretCastExprClass: 12781 case Expr::CXXConstCastExprClass: 12782 case Expr::ObjCBridgedCastExprClass: { 12783 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 12784 if (isa<ExplicitCastExpr>(E)) { 12785 if (const FloatingLiteral *FL 12786 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 12787 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 12788 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 12789 APSInt IgnoredVal(DestWidth, !DestSigned); 12790 bool Ignored; 12791 // If the value does not fit in the destination type, the behavior is 12792 // undefined, so we are not required to treat it as a constant 12793 // expression. 12794 if (FL->getValue().convertToInteger(IgnoredVal, 12795 llvm::APFloat::rmTowardZero, 12796 &Ignored) & APFloat::opInvalidOp) 12797 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12798 return NoDiag(); 12799 } 12800 } 12801 switch (cast<CastExpr>(E)->getCastKind()) { 12802 case CK_LValueToRValue: 12803 case CK_AtomicToNonAtomic: 12804 case CK_NonAtomicToAtomic: 12805 case CK_NoOp: 12806 case CK_IntegralToBoolean: 12807 case CK_IntegralCast: 12808 return CheckICE(SubExpr, Ctx); 12809 default: 12810 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12811 } 12812 } 12813 case Expr::BinaryConditionalOperatorClass: { 12814 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 12815 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 12816 if (CommonResult.Kind == IK_NotICE) return CommonResult; 12817 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 12818 if (FalseResult.Kind == IK_NotICE) return FalseResult; 12819 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 12820 if (FalseResult.Kind == IK_ICEIfUnevaluated && 12821 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 12822 return FalseResult; 12823 } 12824 case Expr::ConditionalOperatorClass: { 12825 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 12826 // If the condition (ignoring parens) is a __builtin_constant_p call, 12827 // then only the true side is actually considered in an integer constant 12828 // expression, and it is fully evaluated. This is an important GNU 12829 // extension. See GCC PR38377 for discussion. 12830 if (const CallExpr *CallCE 12831 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 12832 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 12833 return CheckEvalInICE(E, Ctx); 12834 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 12835 if (CondResult.Kind == IK_NotICE) 12836 return CondResult; 12837 12838 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 12839 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 12840 12841 if (TrueResult.Kind == IK_NotICE) 12842 return TrueResult; 12843 if (FalseResult.Kind == IK_NotICE) 12844 return FalseResult; 12845 if (CondResult.Kind == IK_ICEIfUnevaluated) 12846 return CondResult; 12847 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 12848 return NoDiag(); 12849 // Rare case where the diagnostics depend on which side is evaluated 12850 // Note that if we get here, CondResult is 0, and at least one of 12851 // TrueResult and FalseResult is non-zero. 12852 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 12853 return FalseResult; 12854 return TrueResult; 12855 } 12856 case Expr::CXXDefaultArgExprClass: 12857 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 12858 case Expr::CXXDefaultInitExprClass: 12859 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 12860 case Expr::ChooseExprClass: { 12861 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 12862 } 12863 case Expr::BuiltinBitCastExprClass: { 12864 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 12865 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12866 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 12867 } 12868 } 12869 12870 llvm_unreachable("Invalid StmtClass!"); 12871 } 12872 12873 /// Evaluate an expression as a C++11 integral constant expression. 12874 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 12875 const Expr *E, 12876 llvm::APSInt *Value, 12877 SourceLocation *Loc) { 12878 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12879 if (Loc) *Loc = E->getExprLoc(); 12880 return false; 12881 } 12882 12883 APValue Result; 12884 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 12885 return false; 12886 12887 if (!Result.isInt()) { 12888 if (Loc) *Loc = E->getExprLoc(); 12889 return false; 12890 } 12891 12892 if (Value) *Value = Result.getInt(); 12893 return true; 12894 } 12895 12896 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 12897 SourceLocation *Loc) const { 12898 assert(!isValueDependent() && 12899 "Expression evaluator can't be called on a dependent expression."); 12900 12901 if (Ctx.getLangOpts().CPlusPlus11) 12902 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 12903 12904 ICEDiag D = CheckICE(this, Ctx); 12905 if (D.Kind != IK_ICE) { 12906 if (Loc) *Loc = D.Loc; 12907 return false; 12908 } 12909 return true; 12910 } 12911 12912 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, 12913 SourceLocation *Loc, bool isEvaluated) const { 12914 assert(!isValueDependent() && 12915 "Expression evaluator can't be called on a dependent expression."); 12916 12917 if (Ctx.getLangOpts().CPlusPlus11) 12918 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 12919 12920 if (!isIntegerConstantExpr(Ctx, Loc)) 12921 return false; 12922 12923 // The only possible side-effects here are due to UB discovered in the 12924 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 12925 // required to treat the expression as an ICE, so we produce the folded 12926 // value. 12927 EvalResult ExprResult; 12928 Expr::EvalStatus Status; 12929 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 12930 Info.InConstantContext = true; 12931 12932 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 12933 llvm_unreachable("ICE cannot be evaluated!"); 12934 12935 Value = ExprResult.Val.getInt(); 12936 return true; 12937 } 12938 12939 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 12940 assert(!isValueDependent() && 12941 "Expression evaluator can't be called on a dependent expression."); 12942 12943 return CheckICE(this, Ctx).Kind == IK_ICE; 12944 } 12945 12946 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 12947 SourceLocation *Loc) const { 12948 assert(!isValueDependent() && 12949 "Expression evaluator can't be called on a dependent expression."); 12950 12951 // We support this checking in C++98 mode in order to diagnose compatibility 12952 // issues. 12953 assert(Ctx.getLangOpts().CPlusPlus); 12954 12955 // Build evaluation settings. 12956 Expr::EvalStatus Status; 12957 SmallVector<PartialDiagnosticAt, 8> Diags; 12958 Status.Diag = &Diags; 12959 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 12960 12961 APValue Scratch; 12962 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch); 12963 12964 if (!Diags.empty()) { 12965 IsConstExpr = false; 12966 if (Loc) *Loc = Diags[0].first; 12967 } else if (!IsConstExpr) { 12968 // FIXME: This shouldn't happen. 12969 if (Loc) *Loc = getExprLoc(); 12970 } 12971 12972 return IsConstExpr; 12973 } 12974 12975 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 12976 const FunctionDecl *Callee, 12977 ArrayRef<const Expr*> Args, 12978 const Expr *This) const { 12979 assert(!isValueDependent() && 12980 "Expression evaluator can't be called on a dependent expression."); 12981 12982 Expr::EvalStatus Status; 12983 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 12984 Info.InConstantContext = true; 12985 12986 LValue ThisVal; 12987 const LValue *ThisPtr = nullptr; 12988 if (This) { 12989 #ifndef NDEBUG 12990 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 12991 assert(MD && "Don't provide `this` for non-methods."); 12992 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 12993 #endif 12994 if (EvaluateObjectArgument(Info, This, ThisVal)) 12995 ThisPtr = &ThisVal; 12996 if (Info.EvalStatus.HasSideEffects) 12997 return false; 12998 } 12999 13000 ArgVector ArgValues(Args.size()); 13001 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 13002 I != E; ++I) { 13003 if ((*I)->isValueDependent() || 13004 !Evaluate(ArgValues[I - Args.begin()], Info, *I)) 13005 // If evaluation fails, throw away the argument entirely. 13006 ArgValues[I - Args.begin()] = APValue(); 13007 if (Info.EvalStatus.HasSideEffects) 13008 return false; 13009 } 13010 13011 // Build fake call to Callee. 13012 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 13013 ArgValues.data()); 13014 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects; 13015 } 13016 13017 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 13018 SmallVectorImpl< 13019 PartialDiagnosticAt> &Diags) { 13020 // FIXME: It would be useful to check constexpr function templates, but at the 13021 // moment the constant expression evaluator cannot cope with the non-rigorous 13022 // ASTs which we build for dependent expressions. 13023 if (FD->isDependentContext()) 13024 return true; 13025 13026 Expr::EvalStatus Status; 13027 Status.Diag = &Diags; 13028 13029 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 13030 Info.InConstantContext = true; 13031 Info.CheckingPotentialConstantExpression = true; 13032 13033 // The constexpr VM attempts to compile all methods to bytecode here. 13034 if (Info.EnableNewConstInterp) { 13035 auto &InterpCtx = Info.Ctx.getInterpContext(); 13036 switch (InterpCtx.isPotentialConstantExpr(Info, FD)) { 13037 case interp::InterpResult::Success: 13038 case interp::InterpResult::Fail: 13039 return Diags.empty(); 13040 case interp::InterpResult::Bail: 13041 break; 13042 } 13043 } 13044 13045 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 13046 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 13047 13048 // Fabricate an arbitrary expression on the stack and pretend that it 13049 // is a temporary being used as the 'this' pointer. 13050 LValue This; 13051 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 13052 This.set({&VIE, Info.CurrentCall->Index}); 13053 13054 ArrayRef<const Expr*> Args; 13055 13056 APValue Scratch; 13057 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 13058 // Evaluate the call as a constant initializer, to allow the construction 13059 // of objects of non-literal types. 13060 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 13061 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 13062 } else { 13063 SourceLocation Loc = FD->getLocation(); 13064 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 13065 Args, FD->getBody(), Info, Scratch, nullptr); 13066 } 13067 13068 return Diags.empty(); 13069 } 13070 13071 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 13072 const FunctionDecl *FD, 13073 SmallVectorImpl< 13074 PartialDiagnosticAt> &Diags) { 13075 assert(!E->isValueDependent() && 13076 "Expression evaluator can't be called on a dependent expression."); 13077 13078 Expr::EvalStatus Status; 13079 Status.Diag = &Diags; 13080 13081 EvalInfo Info(FD->getASTContext(), Status, 13082 EvalInfo::EM_ConstantExpressionUnevaluated); 13083 Info.InConstantContext = true; 13084 Info.CheckingPotentialConstantExpression = true; 13085 13086 // Fabricate a call stack frame to give the arguments a plausible cover story. 13087 ArrayRef<const Expr*> Args; 13088 ArgVector ArgValues(0); 13089 bool Success = EvaluateArgs(Args, ArgValues, Info, FD); 13090 (void)Success; 13091 assert(Success && 13092 "Failed to set up arguments for potential constant evaluation"); 13093 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 13094 13095 APValue ResultScratch; 13096 Evaluate(ResultScratch, Info, E); 13097 return Diags.empty(); 13098 } 13099 13100 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 13101 unsigned Type) const { 13102 if (!getType()->isPointerType()) 13103 return false; 13104 13105 Expr::EvalStatus Status; 13106 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 13107 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 13108 } 13109