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 "Interp/Context.h" 36 #include "Interp/Frame.h" 37 #include "Interp/State.h" 38 #include "clang/AST/APValue.h" 39 #include "clang/AST/ASTContext.h" 40 #include "clang/AST/ASTDiagnostic.h" 41 #include "clang/AST/ASTLambda.h" 42 #include "clang/AST/Attr.h" 43 #include "clang/AST/CXXInheritance.h" 44 #include "clang/AST/CharUnits.h" 45 #include "clang/AST/CurrentSourceLocExprScope.h" 46 #include "clang/AST/Expr.h" 47 #include "clang/AST/OSLog.h" 48 #include "clang/AST/OptionalDiagnostic.h" 49 #include "clang/AST/RecordLayout.h" 50 #include "clang/AST/StmtVisitor.h" 51 #include "clang/AST/TypeLoc.h" 52 #include "clang/Basic/Builtins.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "llvm/ADT/APFixedPoint.h" 55 #include "llvm/ADT/Optional.h" 56 #include "llvm/ADT/SmallBitVector.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/SaveAndRestore.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include <cstring> 61 #include <functional> 62 63 #define DEBUG_TYPE "exprconstant" 64 65 using namespace clang; 66 using llvm::APFixedPoint; 67 using llvm::APInt; 68 using llvm::APSInt; 69 using llvm::APFloat; 70 using llvm::FixedPointSemantics; 71 using llvm::Optional; 72 73 namespace { 74 struct LValue; 75 class CallStackFrame; 76 class EvalInfo; 77 78 using SourceLocExprScopeGuard = 79 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 80 81 static QualType getType(APValue::LValueBase B) { 82 if (!B) return QualType(); 83 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 84 // FIXME: It's unclear where we're supposed to take the type from, and 85 // this actually matters for arrays of unknown bound. Eg: 86 // 87 // extern int arr[]; void f() { extern int arr[3]; }; 88 // constexpr int *p = &arr[1]; // valid? 89 // 90 // For now, we take the array bound from the most recent declaration. 91 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 92 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 93 QualType T = Redecl->getType(); 94 if (!T->isIncompleteArrayType()) 95 return T; 96 } 97 return D->getType(); 98 } 99 100 if (B.is<TypeInfoLValue>()) 101 return B.getTypeInfoType(); 102 103 if (B.is<DynamicAllocLValue>()) 104 return B.getDynamicAllocType(); 105 106 const Expr *Base = B.get<const Expr*>(); 107 108 // For a materialized temporary, the type of the temporary we materialized 109 // may not be the type of the expression. 110 if (const MaterializeTemporaryExpr *MTE = 111 dyn_cast<MaterializeTemporaryExpr>(Base)) { 112 SmallVector<const Expr *, 2> CommaLHSs; 113 SmallVector<SubobjectAdjustment, 2> Adjustments; 114 const Expr *Temp = MTE->getSubExpr(); 115 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 116 Adjustments); 117 // Keep any cv-qualifiers from the reference if we generated a temporary 118 // for it directly. Otherwise use the type after adjustment. 119 if (!Adjustments.empty()) 120 return Inner->getType(); 121 } 122 123 return Base->getType(); 124 } 125 126 /// Get an LValue path entry, which is known to not be an array index, as a 127 /// field declaration. 128 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 129 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 130 } 131 /// Get an LValue path entry, which is known to not be an array index, as a 132 /// base class declaration. 133 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 134 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 135 } 136 /// Determine whether this LValue path entry for a base class names a virtual 137 /// base class. 138 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 139 return E.getAsBaseOrMember().getInt(); 140 } 141 142 /// Given an expression, determine the type used to store the result of 143 /// evaluating that expression. 144 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 145 if (E->isRValue()) 146 return E->getType(); 147 return Ctx.getLValueReferenceType(E->getType()); 148 } 149 150 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 151 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 152 const FunctionDecl *Callee = CE->getDirectCallee(); 153 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 154 } 155 156 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 157 /// This will look through a single cast. 158 /// 159 /// Returns null if we couldn't unwrap a function with alloc_size. 160 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 161 if (!E->getType()->isPointerType()) 162 return nullptr; 163 164 E = E->IgnoreParens(); 165 // If we're doing a variable assignment from e.g. malloc(N), there will 166 // probably be a cast of some kind. In exotic cases, we might also see a 167 // top-level ExprWithCleanups. Ignore them either way. 168 if (const auto *FE = dyn_cast<FullExpr>(E)) 169 E = FE->getSubExpr()->IgnoreParens(); 170 171 if (const auto *Cast = dyn_cast<CastExpr>(E)) 172 E = Cast->getSubExpr()->IgnoreParens(); 173 174 if (const auto *CE = dyn_cast<CallExpr>(E)) 175 return getAllocSizeAttr(CE) ? CE : nullptr; 176 return nullptr; 177 } 178 179 /// Determines whether or not the given Base contains a call to a function 180 /// with the alloc_size attribute. 181 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 182 const auto *E = Base.dyn_cast<const Expr *>(); 183 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 184 } 185 186 /// The bound to claim that an array of unknown bound has. 187 /// The value in MostDerivedArraySize is undefined in this case. So, set it 188 /// to an arbitrary value that's likely to loudly break things if it's used. 189 static const uint64_t AssumedSizeForUnsizedArray = 190 std::numeric_limits<uint64_t>::max() / 2; 191 192 /// Determines if an LValue with the given LValueBase will have an unsized 193 /// array in its designator. 194 /// Find the path length and type of the most-derived subobject in the given 195 /// path, and find the size of the containing array, if any. 196 static unsigned 197 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 198 ArrayRef<APValue::LValuePathEntry> Path, 199 uint64_t &ArraySize, QualType &Type, bool &IsArray, 200 bool &FirstEntryIsUnsizedArray) { 201 // This only accepts LValueBases from APValues, and APValues don't support 202 // arrays that lack size info. 203 assert(!isBaseAnAllocSizeCall(Base) && 204 "Unsized arrays shouldn't appear here"); 205 unsigned MostDerivedLength = 0; 206 Type = getType(Base); 207 208 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 209 if (Type->isArrayType()) { 210 const ArrayType *AT = Ctx.getAsArrayType(Type); 211 Type = AT->getElementType(); 212 MostDerivedLength = I + 1; 213 IsArray = true; 214 215 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 216 ArraySize = CAT->getSize().getZExtValue(); 217 } else { 218 assert(I == 0 && "unexpected unsized array designator"); 219 FirstEntryIsUnsizedArray = true; 220 ArraySize = AssumedSizeForUnsizedArray; 221 } 222 } else if (Type->isAnyComplexType()) { 223 const ComplexType *CT = Type->castAs<ComplexType>(); 224 Type = CT->getElementType(); 225 ArraySize = 2; 226 MostDerivedLength = I + 1; 227 IsArray = true; 228 } else if (const FieldDecl *FD = getAsField(Path[I])) { 229 Type = FD->getType(); 230 ArraySize = 0; 231 MostDerivedLength = I + 1; 232 IsArray = false; 233 } else { 234 // Path[I] describes a base class. 235 ArraySize = 0; 236 IsArray = false; 237 } 238 } 239 return MostDerivedLength; 240 } 241 242 /// A path from a glvalue to a subobject of that glvalue. 243 struct SubobjectDesignator { 244 /// True if the subobject was named in a manner not supported by C++11. Such 245 /// lvalues can still be folded, but they are not core constant expressions 246 /// and we cannot perform lvalue-to-rvalue conversions on them. 247 unsigned Invalid : 1; 248 249 /// Is this a pointer one past the end of an object? 250 unsigned IsOnePastTheEnd : 1; 251 252 /// Indicator of whether the first entry is an unsized array. 253 unsigned FirstEntryIsAnUnsizedArray : 1; 254 255 /// Indicator of whether the most-derived object is an array element. 256 unsigned MostDerivedIsArrayElement : 1; 257 258 /// The length of the path to the most-derived object of which this is a 259 /// subobject. 260 unsigned MostDerivedPathLength : 28; 261 262 /// The size of the array of which the most-derived object is an element. 263 /// This will always be 0 if the most-derived object is not an array 264 /// element. 0 is not an indicator of whether or not the most-derived object 265 /// is an array, however, because 0-length arrays are allowed. 266 /// 267 /// If the current array is an unsized array, the value of this is 268 /// undefined. 269 uint64_t MostDerivedArraySize; 270 271 /// The type of the most derived object referred to by this address. 272 QualType MostDerivedType; 273 274 typedef APValue::LValuePathEntry PathEntry; 275 276 /// The entries on the path from the glvalue to the designated subobject. 277 SmallVector<PathEntry, 8> Entries; 278 279 SubobjectDesignator() : Invalid(true) {} 280 281 explicit SubobjectDesignator(QualType T) 282 : Invalid(false), IsOnePastTheEnd(false), 283 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 284 MostDerivedPathLength(0), MostDerivedArraySize(0), 285 MostDerivedType(T) {} 286 287 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 288 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 289 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 290 MostDerivedPathLength(0), MostDerivedArraySize(0) { 291 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 292 if (!Invalid) { 293 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 294 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 295 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 296 if (V.getLValueBase()) { 297 bool IsArray = false; 298 bool FirstIsUnsizedArray = false; 299 MostDerivedPathLength = findMostDerivedSubobject( 300 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 301 MostDerivedType, IsArray, FirstIsUnsizedArray); 302 MostDerivedIsArrayElement = IsArray; 303 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 304 } 305 } 306 } 307 308 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 309 unsigned NewLength) { 310 if (Invalid) 311 return; 312 313 assert(Base && "cannot truncate path for null pointer"); 314 assert(NewLength <= Entries.size() && "not a truncation"); 315 316 if (NewLength == Entries.size()) 317 return; 318 Entries.resize(NewLength); 319 320 bool IsArray = false; 321 bool FirstIsUnsizedArray = false; 322 MostDerivedPathLength = findMostDerivedSubobject( 323 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 324 FirstIsUnsizedArray); 325 MostDerivedIsArrayElement = IsArray; 326 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 327 } 328 329 void setInvalid() { 330 Invalid = true; 331 Entries.clear(); 332 } 333 334 /// Determine whether the most derived subobject is an array without a 335 /// known bound. 336 bool isMostDerivedAnUnsizedArray() const { 337 assert(!Invalid && "Calling this makes no sense on invalid designators"); 338 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 339 } 340 341 /// Determine what the most derived array's size is. Results in an assertion 342 /// failure if the most derived array lacks a size. 343 uint64_t getMostDerivedArraySize() const { 344 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 345 return MostDerivedArraySize; 346 } 347 348 /// Determine whether this is a one-past-the-end pointer. 349 bool isOnePastTheEnd() const { 350 assert(!Invalid); 351 if (IsOnePastTheEnd) 352 return true; 353 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 354 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 355 MostDerivedArraySize) 356 return true; 357 return false; 358 } 359 360 /// Get the range of valid index adjustments in the form 361 /// {maximum value that can be subtracted from this pointer, 362 /// maximum value that can be added to this pointer} 363 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 364 if (Invalid || isMostDerivedAnUnsizedArray()) 365 return {0, 0}; 366 367 // [expr.add]p4: For the purposes of these operators, a pointer to a 368 // nonarray object behaves the same as a pointer to the first element of 369 // an array of length one with the type of the object as its element type. 370 bool IsArray = MostDerivedPathLength == Entries.size() && 371 MostDerivedIsArrayElement; 372 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 373 : (uint64_t)IsOnePastTheEnd; 374 uint64_t ArraySize = 375 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 376 return {ArrayIndex, ArraySize - ArrayIndex}; 377 } 378 379 /// Check that this refers to a valid subobject. 380 bool isValidSubobject() const { 381 if (Invalid) 382 return false; 383 return !isOnePastTheEnd(); 384 } 385 /// Check that this refers to a valid subobject, and if not, produce a 386 /// relevant diagnostic and set the designator as invalid. 387 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 388 389 /// Get the type of the designated object. 390 QualType getType(ASTContext &Ctx) const { 391 assert(!Invalid && "invalid designator has no subobject type"); 392 return MostDerivedPathLength == Entries.size() 393 ? MostDerivedType 394 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 395 } 396 397 /// Update this designator to refer to the first element within this array. 398 void addArrayUnchecked(const ConstantArrayType *CAT) { 399 Entries.push_back(PathEntry::ArrayIndex(0)); 400 401 // This is a most-derived object. 402 MostDerivedType = CAT->getElementType(); 403 MostDerivedIsArrayElement = true; 404 MostDerivedArraySize = CAT->getSize().getZExtValue(); 405 MostDerivedPathLength = Entries.size(); 406 } 407 /// Update this designator to refer to the first element within the array of 408 /// elements of type T. This is an array of unknown size. 409 void addUnsizedArrayUnchecked(QualType ElemTy) { 410 Entries.push_back(PathEntry::ArrayIndex(0)); 411 412 MostDerivedType = ElemTy; 413 MostDerivedIsArrayElement = true; 414 // The value in MostDerivedArraySize is undefined in this case. So, set it 415 // to an arbitrary value that's likely to loudly break things if it's 416 // used. 417 MostDerivedArraySize = AssumedSizeForUnsizedArray; 418 MostDerivedPathLength = Entries.size(); 419 } 420 /// Update this designator to refer to the given base or member of this 421 /// object. 422 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 423 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 424 425 // If this isn't a base class, it's a new most-derived object. 426 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 427 MostDerivedType = FD->getType(); 428 MostDerivedIsArrayElement = false; 429 MostDerivedArraySize = 0; 430 MostDerivedPathLength = Entries.size(); 431 } 432 } 433 /// Update this designator to refer to the given complex component. 434 void addComplexUnchecked(QualType EltTy, bool Imag) { 435 Entries.push_back(PathEntry::ArrayIndex(Imag)); 436 437 // This is technically a most-derived object, though in practice this 438 // is unlikely to matter. 439 MostDerivedType = EltTy; 440 MostDerivedIsArrayElement = true; 441 MostDerivedArraySize = 2; 442 MostDerivedPathLength = Entries.size(); 443 } 444 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 445 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 446 const APSInt &N); 447 /// Add N to the address of this subobject. 448 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 449 if (Invalid || !N) return; 450 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 451 if (isMostDerivedAnUnsizedArray()) { 452 diagnoseUnsizedArrayPointerArithmetic(Info, E); 453 // Can't verify -- trust that the user is doing the right thing (or if 454 // not, trust that the caller will catch the bad behavior). 455 // FIXME: Should we reject if this overflows, at least? 456 Entries.back() = PathEntry::ArrayIndex( 457 Entries.back().getAsArrayIndex() + TruncatedN); 458 return; 459 } 460 461 // [expr.add]p4: For the purposes of these operators, a pointer to a 462 // nonarray object behaves the same as a pointer to the first element of 463 // an array of length one with the type of the object as its element type. 464 bool IsArray = MostDerivedPathLength == Entries.size() && 465 MostDerivedIsArrayElement; 466 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 467 : (uint64_t)IsOnePastTheEnd; 468 uint64_t ArraySize = 469 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 470 471 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 472 // Calculate the actual index in a wide enough type, so we can include 473 // it in the note. 474 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 475 (llvm::APInt&)N += ArrayIndex; 476 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 477 diagnosePointerArithmetic(Info, E, N); 478 setInvalid(); 479 return; 480 } 481 482 ArrayIndex += TruncatedN; 483 assert(ArrayIndex <= ArraySize && 484 "bounds check succeeded for out-of-bounds index"); 485 486 if (IsArray) 487 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 488 else 489 IsOnePastTheEnd = (ArrayIndex != 0); 490 } 491 }; 492 493 /// A stack frame in the constexpr call stack. 494 class CallStackFrame : public interp::Frame { 495 public: 496 EvalInfo &Info; 497 498 /// Parent - The caller of this stack frame. 499 CallStackFrame *Caller; 500 501 /// Callee - The function which was called. 502 const FunctionDecl *Callee; 503 504 /// This - The binding for the this pointer in this call, if any. 505 const LValue *This; 506 507 /// Arguments - Parameter bindings for this function call, indexed by 508 /// parameters' function scope indices. 509 APValue *Arguments; 510 511 /// Source location information about the default argument or default 512 /// initializer expression we're evaluating, if any. 513 CurrentSourceLocExprScope CurSourceLocExprScope; 514 515 // Note that we intentionally use std::map here so that references to 516 // values are stable. 517 typedef std::pair<const void *, unsigned> MapKeyTy; 518 typedef std::map<MapKeyTy, APValue> MapTy; 519 /// Temporaries - Temporary lvalues materialized within this stack frame. 520 MapTy Temporaries; 521 522 /// CallLoc - The location of the call expression for this call. 523 SourceLocation CallLoc; 524 525 /// Index - The call index of this call. 526 unsigned Index; 527 528 /// The stack of integers for tracking version numbers for temporaries. 529 SmallVector<unsigned, 2> TempVersionStack = {1}; 530 unsigned CurTempVersion = TempVersionStack.back(); 531 532 unsigned getTempVersion() const { return TempVersionStack.back(); } 533 534 void pushTempVersion() { 535 TempVersionStack.push_back(++CurTempVersion); 536 } 537 538 void popTempVersion() { 539 TempVersionStack.pop_back(); 540 } 541 542 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 543 // on the overall stack usage of deeply-recursing constexpr evaluations. 544 // (We should cache this map rather than recomputing it repeatedly.) 545 // But let's try this and see how it goes; we can look into caching the map 546 // as a later change. 547 548 /// LambdaCaptureFields - Mapping from captured variables/this to 549 /// corresponding data members in the closure class. 550 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 551 FieldDecl *LambdaThisCaptureField; 552 553 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 554 const FunctionDecl *Callee, const LValue *This, 555 APValue *Arguments); 556 ~CallStackFrame(); 557 558 // Return the temporary for Key whose version number is Version. 559 APValue *getTemporary(const void *Key, unsigned Version) { 560 MapKeyTy KV(Key, Version); 561 auto LB = Temporaries.lower_bound(KV); 562 if (LB != Temporaries.end() && LB->first == KV) 563 return &LB->second; 564 // Pair (Key,Version) wasn't found in the map. Check that no elements 565 // in the map have 'Key' as their key. 566 assert((LB == Temporaries.end() || LB->first.first != Key) && 567 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 568 "Element with key 'Key' found in map"); 569 return nullptr; 570 } 571 572 // Return the current temporary for Key in the map. 573 APValue *getCurrentTemporary(const void *Key) { 574 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 575 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 576 return &std::prev(UB)->second; 577 return nullptr; 578 } 579 580 // Return the version number of the current temporary for Key. 581 unsigned getCurrentTemporaryVersion(const void *Key) const { 582 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 583 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 584 return std::prev(UB)->first.second; 585 return 0; 586 } 587 588 /// Allocate storage for an object of type T in this stack frame. 589 /// Populates LV with a handle to the created object. Key identifies 590 /// the temporary within the stack frame, and must not be reused without 591 /// bumping the temporary version number. 592 template<typename KeyT> 593 APValue &createTemporary(const KeyT *Key, QualType T, 594 bool IsLifetimeExtended, LValue &LV); 595 596 void describe(llvm::raw_ostream &OS) override; 597 598 Frame *getCaller() const override { return Caller; } 599 SourceLocation getCallLocation() const override { return CallLoc; } 600 const FunctionDecl *getCallee() const override { return Callee; } 601 602 bool isStdFunction() const { 603 for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 604 if (DC->isStdNamespace()) 605 return true; 606 return false; 607 } 608 }; 609 610 /// Temporarily override 'this'. 611 class ThisOverrideRAII { 612 public: 613 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 614 : Frame(Frame), OldThis(Frame.This) { 615 if (Enable) 616 Frame.This = NewThis; 617 } 618 ~ThisOverrideRAII() { 619 Frame.This = OldThis; 620 } 621 private: 622 CallStackFrame &Frame; 623 const LValue *OldThis; 624 }; 625 } 626 627 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 628 const LValue &This, QualType ThisType); 629 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 630 APValue::LValueBase LVBase, APValue &Value, 631 QualType T); 632 633 namespace { 634 /// A cleanup, and a flag indicating whether it is lifetime-extended. 635 class Cleanup { 636 llvm::PointerIntPair<APValue*, 1, bool> Value; 637 APValue::LValueBase Base; 638 QualType T; 639 640 public: 641 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 642 bool IsLifetimeExtended) 643 : Value(Val, IsLifetimeExtended), Base(Base), T(T) {} 644 645 bool isLifetimeExtended() const { return Value.getInt(); } 646 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 647 if (RunDestructors) { 648 SourceLocation Loc; 649 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 650 Loc = VD->getLocation(); 651 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 652 Loc = E->getExprLoc(); 653 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 654 } 655 *Value.getPointer() = APValue(); 656 return true; 657 } 658 659 bool hasSideEffect() { 660 return T.isDestructedType(); 661 } 662 }; 663 664 /// A reference to an object whose construction we are currently evaluating. 665 struct ObjectUnderConstruction { 666 APValue::LValueBase Base; 667 ArrayRef<APValue::LValuePathEntry> Path; 668 friend bool operator==(const ObjectUnderConstruction &LHS, 669 const ObjectUnderConstruction &RHS) { 670 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 671 } 672 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 673 return llvm::hash_combine(Obj.Base, Obj.Path); 674 } 675 }; 676 enum class ConstructionPhase { 677 None, 678 Bases, 679 AfterBases, 680 AfterFields, 681 Destroying, 682 DestroyingBases 683 }; 684 } 685 686 namespace llvm { 687 template<> struct DenseMapInfo<ObjectUnderConstruction> { 688 using Base = DenseMapInfo<APValue::LValueBase>; 689 static ObjectUnderConstruction getEmptyKey() { 690 return {Base::getEmptyKey(), {}}; } 691 static ObjectUnderConstruction getTombstoneKey() { 692 return {Base::getTombstoneKey(), {}}; 693 } 694 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 695 return hash_value(Object); 696 } 697 static bool isEqual(const ObjectUnderConstruction &LHS, 698 const ObjectUnderConstruction &RHS) { 699 return LHS == RHS; 700 } 701 }; 702 } 703 704 namespace { 705 /// A dynamically-allocated heap object. 706 struct DynAlloc { 707 /// The value of this heap-allocated object. 708 APValue Value; 709 /// The allocating expression; used for diagnostics. Either a CXXNewExpr 710 /// or a CallExpr (the latter is for direct calls to operator new inside 711 /// std::allocator<T>::allocate). 712 const Expr *AllocExpr = nullptr; 713 714 enum Kind { 715 New, 716 ArrayNew, 717 StdAllocator 718 }; 719 720 /// Get the kind of the allocation. This must match between allocation 721 /// and deallocation. 722 Kind getKind() const { 723 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 724 return NE->isArray() ? ArrayNew : New; 725 assert(isa<CallExpr>(AllocExpr)); 726 return StdAllocator; 727 } 728 }; 729 730 struct DynAllocOrder { 731 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 732 return L.getIndex() < R.getIndex(); 733 } 734 }; 735 736 /// EvalInfo - This is a private struct used by the evaluator to capture 737 /// information about a subexpression as it is folded. It retains information 738 /// about the AST context, but also maintains information about the folded 739 /// expression. 740 /// 741 /// If an expression could be evaluated, it is still possible it is not a C 742 /// "integer constant expression" or constant expression. If not, this struct 743 /// captures information about how and why not. 744 /// 745 /// One bit of information passed *into* the request for constant folding 746 /// indicates whether the subexpression is "evaluated" or not according to C 747 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 748 /// evaluate the expression regardless of what the RHS is, but C only allows 749 /// certain things in certain situations. 750 class EvalInfo : public interp::State { 751 public: 752 ASTContext &Ctx; 753 754 /// EvalStatus - Contains information about the evaluation. 755 Expr::EvalStatus &EvalStatus; 756 757 /// CurrentCall - The top of the constexpr call stack. 758 CallStackFrame *CurrentCall; 759 760 /// CallStackDepth - The number of calls in the call stack right now. 761 unsigned CallStackDepth; 762 763 /// NextCallIndex - The next call index to assign. 764 unsigned NextCallIndex; 765 766 /// StepsLeft - The remaining number of evaluation steps we're permitted 767 /// to perform. This is essentially a limit for the number of statements 768 /// we will evaluate. 769 unsigned StepsLeft; 770 771 /// Enable the experimental new constant interpreter. If an expression is 772 /// not supported by the interpreter, an error is triggered. 773 bool EnableNewConstInterp; 774 775 /// BottomFrame - The frame in which evaluation started. This must be 776 /// initialized after CurrentCall and CallStackDepth. 777 CallStackFrame BottomFrame; 778 779 /// A stack of values whose lifetimes end at the end of some surrounding 780 /// evaluation frame. 781 llvm::SmallVector<Cleanup, 16> CleanupStack; 782 783 /// EvaluatingDecl - This is the declaration whose initializer is being 784 /// evaluated, if any. 785 APValue::LValueBase EvaluatingDecl; 786 787 enum class EvaluatingDeclKind { 788 None, 789 /// We're evaluating the construction of EvaluatingDecl. 790 Ctor, 791 /// We're evaluating the destruction of EvaluatingDecl. 792 Dtor, 793 }; 794 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 795 796 /// EvaluatingDeclValue - This is the value being constructed for the 797 /// declaration whose initializer is being evaluated, if any. 798 APValue *EvaluatingDeclValue; 799 800 /// Set of objects that are currently being constructed. 801 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 802 ObjectsUnderConstruction; 803 804 /// Current heap allocations, along with the location where each was 805 /// allocated. We use std::map here because we need stable addresses 806 /// for the stored APValues. 807 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 808 809 /// The number of heap allocations performed so far in this evaluation. 810 unsigned NumHeapAllocs = 0; 811 812 struct EvaluatingConstructorRAII { 813 EvalInfo &EI; 814 ObjectUnderConstruction Object; 815 bool DidInsert; 816 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 817 bool HasBases) 818 : EI(EI), Object(Object) { 819 DidInsert = 820 EI.ObjectsUnderConstruction 821 .insert({Object, HasBases ? ConstructionPhase::Bases 822 : ConstructionPhase::AfterBases}) 823 .second; 824 } 825 void finishedConstructingBases() { 826 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 827 } 828 void finishedConstructingFields() { 829 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 830 } 831 ~EvaluatingConstructorRAII() { 832 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 833 } 834 }; 835 836 struct EvaluatingDestructorRAII { 837 EvalInfo &EI; 838 ObjectUnderConstruction Object; 839 bool DidInsert; 840 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 841 : EI(EI), Object(Object) { 842 DidInsert = EI.ObjectsUnderConstruction 843 .insert({Object, ConstructionPhase::Destroying}) 844 .second; 845 } 846 void startedDestroyingBases() { 847 EI.ObjectsUnderConstruction[Object] = 848 ConstructionPhase::DestroyingBases; 849 } 850 ~EvaluatingDestructorRAII() { 851 if (DidInsert) 852 EI.ObjectsUnderConstruction.erase(Object); 853 } 854 }; 855 856 ConstructionPhase 857 isEvaluatingCtorDtor(APValue::LValueBase Base, 858 ArrayRef<APValue::LValuePathEntry> Path) { 859 return ObjectsUnderConstruction.lookup({Base, Path}); 860 } 861 862 /// If we're currently speculatively evaluating, the outermost call stack 863 /// depth at which we can mutate state, otherwise 0. 864 unsigned SpeculativeEvaluationDepth = 0; 865 866 /// The current array initialization index, if we're performing array 867 /// initialization. 868 uint64_t ArrayInitIndex = -1; 869 870 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 871 /// notes attached to it will also be stored, otherwise they will not be. 872 bool HasActiveDiagnostic; 873 874 /// Have we emitted a diagnostic explaining why we couldn't constant 875 /// fold (not just why it's not strictly a constant expression)? 876 bool HasFoldFailureDiagnostic; 877 878 /// Whether or not we're in a context where the front end requires a 879 /// constant value. 880 bool InConstantContext; 881 882 /// Whether we're checking that an expression is a potential constant 883 /// expression. If so, do not fail on constructs that could become constant 884 /// later on (such as a use of an undefined global). 885 bool CheckingPotentialConstantExpression = false; 886 887 /// Whether we're checking for an expression that has undefined behavior. 888 /// If so, we will produce warnings if we encounter an operation that is 889 /// always undefined. 890 bool CheckingForUndefinedBehavior = false; 891 892 enum EvaluationMode { 893 /// Evaluate as a constant expression. Stop if we find that the expression 894 /// is not a constant expression. 895 EM_ConstantExpression, 896 897 /// Evaluate as a constant expression. Stop if we find that the expression 898 /// is not a constant expression. Some expressions can be retried in the 899 /// optimizer if we don't constant fold them here, but in an unevaluated 900 /// context we try to fold them immediately since the optimizer never 901 /// gets a chance to look at it. 902 EM_ConstantExpressionUnevaluated, 903 904 /// Fold the expression to a constant. Stop if we hit a side-effect that 905 /// we can't model. 906 EM_ConstantFold, 907 908 /// Evaluate in any way we know how. Don't worry about side-effects that 909 /// can't be modeled. 910 EM_IgnoreSideEffects, 911 } EvalMode; 912 913 /// Are we checking whether the expression is a potential constant 914 /// expression? 915 bool checkingPotentialConstantExpression() const override { 916 return CheckingPotentialConstantExpression; 917 } 918 919 /// Are we checking an expression for overflow? 920 // FIXME: We should check for any kind of undefined or suspicious behavior 921 // in such constructs, not just overflow. 922 bool checkingForUndefinedBehavior() const override { 923 return CheckingForUndefinedBehavior; 924 } 925 926 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 927 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 928 CallStackDepth(0), NextCallIndex(1), 929 StepsLeft(C.getLangOpts().ConstexprStepLimit), 930 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 931 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 932 EvaluatingDecl((const ValueDecl *)nullptr), 933 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 934 HasFoldFailureDiagnostic(false), InConstantContext(false), 935 EvalMode(Mode) {} 936 937 ~EvalInfo() { 938 discardCleanups(); 939 } 940 941 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 942 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 943 EvaluatingDecl = Base; 944 IsEvaluatingDecl = EDK; 945 EvaluatingDeclValue = &Value; 946 } 947 948 bool CheckCallLimit(SourceLocation Loc) { 949 // Don't perform any constexpr calls (other than the call we're checking) 950 // when checking a potential constant expression. 951 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 952 return false; 953 if (NextCallIndex == 0) { 954 // NextCallIndex has wrapped around. 955 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 956 return false; 957 } 958 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 959 return true; 960 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 961 << getLangOpts().ConstexprCallDepth; 962 return false; 963 } 964 965 std::pair<CallStackFrame *, unsigned> 966 getCallFrameAndDepth(unsigned CallIndex) { 967 assert(CallIndex && "no call index in getCallFrameAndDepth"); 968 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 969 // be null in this loop. 970 unsigned Depth = CallStackDepth; 971 CallStackFrame *Frame = CurrentCall; 972 while (Frame->Index > CallIndex) { 973 Frame = Frame->Caller; 974 --Depth; 975 } 976 if (Frame->Index == CallIndex) 977 return {Frame, Depth}; 978 return {nullptr, 0}; 979 } 980 981 bool nextStep(const Stmt *S) { 982 if (!StepsLeft) { 983 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 984 return false; 985 } 986 --StepsLeft; 987 return true; 988 } 989 990 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 991 992 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 993 Optional<DynAlloc*> Result; 994 auto It = HeapAllocs.find(DA); 995 if (It != HeapAllocs.end()) 996 Result = &It->second; 997 return Result; 998 } 999 1000 /// Information about a stack frame for std::allocator<T>::[de]allocate. 1001 struct StdAllocatorCaller { 1002 unsigned FrameIndex; 1003 QualType ElemType; 1004 explicit operator bool() const { return FrameIndex != 0; }; 1005 }; 1006 1007 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1008 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1009 Call = Call->Caller) { 1010 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1011 if (!MD) 1012 continue; 1013 const IdentifierInfo *FnII = MD->getIdentifier(); 1014 if (!FnII || !FnII->isStr(FnName)) 1015 continue; 1016 1017 const auto *CTSD = 1018 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1019 if (!CTSD) 1020 continue; 1021 1022 const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1023 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1024 if (CTSD->isInStdNamespace() && ClassII && 1025 ClassII->isStr("allocator") && TAL.size() >= 1 && 1026 TAL[0].getKind() == TemplateArgument::Type) 1027 return {Call->Index, TAL[0].getAsType()}; 1028 } 1029 1030 return {}; 1031 } 1032 1033 void performLifetimeExtension() { 1034 // Disable the cleanups for lifetime-extended temporaries. 1035 CleanupStack.erase( 1036 std::remove_if(CleanupStack.begin(), CleanupStack.end(), 1037 [](Cleanup &C) { return C.isLifetimeExtended(); }), 1038 CleanupStack.end()); 1039 } 1040 1041 /// Throw away any remaining cleanups at the end of evaluation. If any 1042 /// cleanups would have had a side-effect, note that as an unmodeled 1043 /// side-effect and return false. Otherwise, return true. 1044 bool discardCleanups() { 1045 for (Cleanup &C : CleanupStack) { 1046 if (C.hasSideEffect() && !noteSideEffect()) { 1047 CleanupStack.clear(); 1048 return false; 1049 } 1050 } 1051 CleanupStack.clear(); 1052 return true; 1053 } 1054 1055 private: 1056 interp::Frame *getCurrentFrame() override { return CurrentCall; } 1057 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1058 1059 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1060 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1061 1062 void setFoldFailureDiagnostic(bool Flag) override { 1063 HasFoldFailureDiagnostic = Flag; 1064 } 1065 1066 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1067 1068 ASTContext &getCtx() const override { return Ctx; } 1069 1070 // If we have a prior diagnostic, it will be noting that the expression 1071 // isn't a constant expression. This diagnostic is more important, 1072 // unless we require this evaluation to produce a constant expression. 1073 // 1074 // FIXME: We might want to show both diagnostics to the user in 1075 // EM_ConstantFold mode. 1076 bool hasPriorDiagnostic() override { 1077 if (!EvalStatus.Diag->empty()) { 1078 switch (EvalMode) { 1079 case EM_ConstantFold: 1080 case EM_IgnoreSideEffects: 1081 if (!HasFoldFailureDiagnostic) 1082 break; 1083 // We've already failed to fold something. Keep that diagnostic. 1084 LLVM_FALLTHROUGH; 1085 case EM_ConstantExpression: 1086 case EM_ConstantExpressionUnevaluated: 1087 setActiveDiagnostic(false); 1088 return true; 1089 } 1090 } 1091 return false; 1092 } 1093 1094 unsigned getCallStackDepth() override { return CallStackDepth; } 1095 1096 public: 1097 /// Should we continue evaluation after encountering a side-effect that we 1098 /// couldn't model? 1099 bool keepEvaluatingAfterSideEffect() { 1100 switch (EvalMode) { 1101 case EM_IgnoreSideEffects: 1102 return true; 1103 1104 case EM_ConstantExpression: 1105 case EM_ConstantExpressionUnevaluated: 1106 case EM_ConstantFold: 1107 // By default, assume any side effect might be valid in some other 1108 // evaluation of this expression from a different context. 1109 return checkingPotentialConstantExpression() || 1110 checkingForUndefinedBehavior(); 1111 } 1112 llvm_unreachable("Missed EvalMode case"); 1113 } 1114 1115 /// Note that we have had a side-effect, and determine whether we should 1116 /// keep evaluating. 1117 bool noteSideEffect() { 1118 EvalStatus.HasSideEffects = true; 1119 return keepEvaluatingAfterSideEffect(); 1120 } 1121 1122 /// Should we continue evaluation after encountering undefined behavior? 1123 bool keepEvaluatingAfterUndefinedBehavior() { 1124 switch (EvalMode) { 1125 case EM_IgnoreSideEffects: 1126 case EM_ConstantFold: 1127 return true; 1128 1129 case EM_ConstantExpression: 1130 case EM_ConstantExpressionUnevaluated: 1131 return checkingForUndefinedBehavior(); 1132 } 1133 llvm_unreachable("Missed EvalMode case"); 1134 } 1135 1136 /// Note that we hit something that was technically undefined behavior, but 1137 /// that we can evaluate past it (such as signed overflow or floating-point 1138 /// division by zero.) 1139 bool noteUndefinedBehavior() override { 1140 EvalStatus.HasUndefinedBehavior = true; 1141 return keepEvaluatingAfterUndefinedBehavior(); 1142 } 1143 1144 /// Should we continue evaluation as much as possible after encountering a 1145 /// construct which can't be reduced to a value? 1146 bool keepEvaluatingAfterFailure() const override { 1147 if (!StepsLeft) 1148 return false; 1149 1150 switch (EvalMode) { 1151 case EM_ConstantExpression: 1152 case EM_ConstantExpressionUnevaluated: 1153 case EM_ConstantFold: 1154 case EM_IgnoreSideEffects: 1155 return checkingPotentialConstantExpression() || 1156 checkingForUndefinedBehavior(); 1157 } 1158 llvm_unreachable("Missed EvalMode case"); 1159 } 1160 1161 /// Notes that we failed to evaluate an expression that other expressions 1162 /// directly depend on, and determine if we should keep evaluating. This 1163 /// should only be called if we actually intend to keep evaluating. 1164 /// 1165 /// Call noteSideEffect() instead if we may be able to ignore the value that 1166 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1167 /// 1168 /// (Foo(), 1) // use noteSideEffect 1169 /// (Foo() || true) // use noteSideEffect 1170 /// Foo() + 1 // use noteFailure 1171 LLVM_NODISCARD bool noteFailure() { 1172 // Failure when evaluating some expression often means there is some 1173 // subexpression whose evaluation was skipped. Therefore, (because we 1174 // don't track whether we skipped an expression when unwinding after an 1175 // evaluation failure) every evaluation failure that bubbles up from a 1176 // subexpression implies that a side-effect has potentially happened. We 1177 // skip setting the HasSideEffects flag to true until we decide to 1178 // continue evaluating after that point, which happens here. 1179 bool KeepGoing = keepEvaluatingAfterFailure(); 1180 EvalStatus.HasSideEffects |= KeepGoing; 1181 return KeepGoing; 1182 } 1183 1184 class ArrayInitLoopIndex { 1185 EvalInfo &Info; 1186 uint64_t OuterIndex; 1187 1188 public: 1189 ArrayInitLoopIndex(EvalInfo &Info) 1190 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1191 Info.ArrayInitIndex = 0; 1192 } 1193 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1194 1195 operator uint64_t&() { return Info.ArrayInitIndex; } 1196 }; 1197 }; 1198 1199 /// Object used to treat all foldable expressions as constant expressions. 1200 struct FoldConstant { 1201 EvalInfo &Info; 1202 bool Enabled; 1203 bool HadNoPriorDiags; 1204 EvalInfo::EvaluationMode OldMode; 1205 1206 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1207 : Info(Info), 1208 Enabled(Enabled), 1209 HadNoPriorDiags(Info.EvalStatus.Diag && 1210 Info.EvalStatus.Diag->empty() && 1211 !Info.EvalStatus.HasSideEffects), 1212 OldMode(Info.EvalMode) { 1213 if (Enabled) 1214 Info.EvalMode = EvalInfo::EM_ConstantFold; 1215 } 1216 void keepDiagnostics() { Enabled = false; } 1217 ~FoldConstant() { 1218 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1219 !Info.EvalStatus.HasSideEffects) 1220 Info.EvalStatus.Diag->clear(); 1221 Info.EvalMode = OldMode; 1222 } 1223 }; 1224 1225 /// RAII object used to set the current evaluation mode to ignore 1226 /// side-effects. 1227 struct IgnoreSideEffectsRAII { 1228 EvalInfo &Info; 1229 EvalInfo::EvaluationMode OldMode; 1230 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1231 : Info(Info), OldMode(Info.EvalMode) { 1232 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1233 } 1234 1235 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1236 }; 1237 1238 /// RAII object used to optionally suppress diagnostics and side-effects from 1239 /// a speculative evaluation. 1240 class SpeculativeEvaluationRAII { 1241 EvalInfo *Info = nullptr; 1242 Expr::EvalStatus OldStatus; 1243 unsigned OldSpeculativeEvaluationDepth; 1244 1245 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1246 Info = Other.Info; 1247 OldStatus = Other.OldStatus; 1248 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1249 Other.Info = nullptr; 1250 } 1251 1252 void maybeRestoreState() { 1253 if (!Info) 1254 return; 1255 1256 Info->EvalStatus = OldStatus; 1257 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1258 } 1259 1260 public: 1261 SpeculativeEvaluationRAII() = default; 1262 1263 SpeculativeEvaluationRAII( 1264 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1265 : Info(&Info), OldStatus(Info.EvalStatus), 1266 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1267 Info.EvalStatus.Diag = NewDiag; 1268 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1269 } 1270 1271 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1272 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1273 moveFromAndCancel(std::move(Other)); 1274 } 1275 1276 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1277 maybeRestoreState(); 1278 moveFromAndCancel(std::move(Other)); 1279 return *this; 1280 } 1281 1282 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1283 }; 1284 1285 /// RAII object wrapping a full-expression or block scope, and handling 1286 /// the ending of the lifetime of temporaries created within it. 1287 template<bool IsFullExpression> 1288 class ScopeRAII { 1289 EvalInfo &Info; 1290 unsigned OldStackSize; 1291 public: 1292 ScopeRAII(EvalInfo &Info) 1293 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1294 // Push a new temporary version. This is needed to distinguish between 1295 // temporaries created in different iterations of a loop. 1296 Info.CurrentCall->pushTempVersion(); 1297 } 1298 bool destroy(bool RunDestructors = true) { 1299 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1300 OldStackSize = -1U; 1301 return OK; 1302 } 1303 ~ScopeRAII() { 1304 if (OldStackSize != -1U) 1305 destroy(false); 1306 // Body moved to a static method to encourage the compiler to inline away 1307 // instances of this class. 1308 Info.CurrentCall->popTempVersion(); 1309 } 1310 private: 1311 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1312 unsigned OldStackSize) { 1313 assert(OldStackSize <= Info.CleanupStack.size() && 1314 "running cleanups out of order?"); 1315 1316 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1317 // for a full-expression scope. 1318 bool Success = true; 1319 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1320 if (!(IsFullExpression && 1321 Info.CleanupStack[I - 1].isLifetimeExtended())) { 1322 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1323 Success = false; 1324 break; 1325 } 1326 } 1327 } 1328 1329 // Compact lifetime-extended cleanups. 1330 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1331 if (IsFullExpression) 1332 NewEnd = 1333 std::remove_if(NewEnd, Info.CleanupStack.end(), 1334 [](Cleanup &C) { return !C.isLifetimeExtended(); }); 1335 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1336 return Success; 1337 } 1338 }; 1339 typedef ScopeRAII<false> BlockScopeRAII; 1340 typedef ScopeRAII<true> FullExpressionRAII; 1341 } 1342 1343 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1344 CheckSubobjectKind CSK) { 1345 if (Invalid) 1346 return false; 1347 if (isOnePastTheEnd()) { 1348 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1349 << CSK; 1350 setInvalid(); 1351 return false; 1352 } 1353 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1354 // must actually be at least one array element; even a VLA cannot have a 1355 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1356 return true; 1357 } 1358 1359 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1360 const Expr *E) { 1361 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1362 // Do not set the designator as invalid: we can represent this situation, 1363 // and correct handling of __builtin_object_size requires us to do so. 1364 } 1365 1366 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1367 const Expr *E, 1368 const APSInt &N) { 1369 // If we're complaining, we must be able to statically determine the size of 1370 // the most derived array. 1371 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1372 Info.CCEDiag(E, diag::note_constexpr_array_index) 1373 << N << /*array*/ 0 1374 << static_cast<unsigned>(getMostDerivedArraySize()); 1375 else 1376 Info.CCEDiag(E, diag::note_constexpr_array_index) 1377 << N << /*non-array*/ 1; 1378 setInvalid(); 1379 } 1380 1381 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1382 const FunctionDecl *Callee, const LValue *This, 1383 APValue *Arguments) 1384 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1385 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1386 Info.CurrentCall = this; 1387 ++Info.CallStackDepth; 1388 } 1389 1390 CallStackFrame::~CallStackFrame() { 1391 assert(Info.CurrentCall == this && "calls retired out of order"); 1392 --Info.CallStackDepth; 1393 Info.CurrentCall = Caller; 1394 } 1395 1396 static bool isRead(AccessKinds AK) { 1397 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1398 } 1399 1400 static bool isModification(AccessKinds AK) { 1401 switch (AK) { 1402 case AK_Read: 1403 case AK_ReadObjectRepresentation: 1404 case AK_MemberCall: 1405 case AK_DynamicCast: 1406 case AK_TypeId: 1407 return false; 1408 case AK_Assign: 1409 case AK_Increment: 1410 case AK_Decrement: 1411 case AK_Construct: 1412 case AK_Destroy: 1413 return true; 1414 } 1415 llvm_unreachable("unknown access kind"); 1416 } 1417 1418 static bool isAnyAccess(AccessKinds AK) { 1419 return isRead(AK) || isModification(AK); 1420 } 1421 1422 /// Is this an access per the C++ definition? 1423 static bool isFormalAccess(AccessKinds AK) { 1424 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1425 } 1426 1427 /// Is this kind of axcess valid on an indeterminate object value? 1428 static bool isValidIndeterminateAccess(AccessKinds AK) { 1429 switch (AK) { 1430 case AK_Read: 1431 case AK_Increment: 1432 case AK_Decrement: 1433 // These need the object's value. 1434 return false; 1435 1436 case AK_ReadObjectRepresentation: 1437 case AK_Assign: 1438 case AK_Construct: 1439 case AK_Destroy: 1440 // Construction and destruction don't need the value. 1441 return true; 1442 1443 case AK_MemberCall: 1444 case AK_DynamicCast: 1445 case AK_TypeId: 1446 // These aren't really meaningful on scalars. 1447 return true; 1448 } 1449 llvm_unreachable("unknown access kind"); 1450 } 1451 1452 namespace { 1453 struct ComplexValue { 1454 private: 1455 bool IsInt; 1456 1457 public: 1458 APSInt IntReal, IntImag; 1459 APFloat FloatReal, FloatImag; 1460 1461 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1462 1463 void makeComplexFloat() { IsInt = false; } 1464 bool isComplexFloat() const { return !IsInt; } 1465 APFloat &getComplexFloatReal() { return FloatReal; } 1466 APFloat &getComplexFloatImag() { return FloatImag; } 1467 1468 void makeComplexInt() { IsInt = true; } 1469 bool isComplexInt() const { return IsInt; } 1470 APSInt &getComplexIntReal() { return IntReal; } 1471 APSInt &getComplexIntImag() { return IntImag; } 1472 1473 void moveInto(APValue &v) const { 1474 if (isComplexFloat()) 1475 v = APValue(FloatReal, FloatImag); 1476 else 1477 v = APValue(IntReal, IntImag); 1478 } 1479 void setFrom(const APValue &v) { 1480 assert(v.isComplexFloat() || v.isComplexInt()); 1481 if (v.isComplexFloat()) { 1482 makeComplexFloat(); 1483 FloatReal = v.getComplexFloatReal(); 1484 FloatImag = v.getComplexFloatImag(); 1485 } else { 1486 makeComplexInt(); 1487 IntReal = v.getComplexIntReal(); 1488 IntImag = v.getComplexIntImag(); 1489 } 1490 } 1491 }; 1492 1493 struct LValue { 1494 APValue::LValueBase Base; 1495 CharUnits Offset; 1496 SubobjectDesignator Designator; 1497 bool IsNullPtr : 1; 1498 bool InvalidBase : 1; 1499 1500 const APValue::LValueBase getLValueBase() const { return Base; } 1501 CharUnits &getLValueOffset() { return Offset; } 1502 const CharUnits &getLValueOffset() const { return Offset; } 1503 SubobjectDesignator &getLValueDesignator() { return Designator; } 1504 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1505 bool isNullPointer() const { return IsNullPtr;} 1506 1507 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1508 unsigned getLValueVersion() const { return Base.getVersion(); } 1509 1510 void moveInto(APValue &V) const { 1511 if (Designator.Invalid) 1512 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1513 else { 1514 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1515 V = APValue(Base, Offset, Designator.Entries, 1516 Designator.IsOnePastTheEnd, IsNullPtr); 1517 } 1518 } 1519 void setFrom(ASTContext &Ctx, const APValue &V) { 1520 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1521 Base = V.getLValueBase(); 1522 Offset = V.getLValueOffset(); 1523 InvalidBase = false; 1524 Designator = SubobjectDesignator(Ctx, V); 1525 IsNullPtr = V.isNullPointer(); 1526 } 1527 1528 void set(APValue::LValueBase B, bool BInvalid = false) { 1529 #ifndef NDEBUG 1530 // We only allow a few types of invalid bases. Enforce that here. 1531 if (BInvalid) { 1532 const auto *E = B.get<const Expr *>(); 1533 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1534 "Unexpected type of invalid base"); 1535 } 1536 #endif 1537 1538 Base = B; 1539 Offset = CharUnits::fromQuantity(0); 1540 InvalidBase = BInvalid; 1541 Designator = SubobjectDesignator(getType(B)); 1542 IsNullPtr = false; 1543 } 1544 1545 void setNull(ASTContext &Ctx, QualType PointerTy) { 1546 Base = (Expr *)nullptr; 1547 Offset = 1548 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1549 InvalidBase = false; 1550 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1551 IsNullPtr = true; 1552 } 1553 1554 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1555 set(B, true); 1556 } 1557 1558 std::string toString(ASTContext &Ctx, QualType T) const { 1559 APValue Printable; 1560 moveInto(Printable); 1561 return Printable.getAsString(Ctx, T); 1562 } 1563 1564 private: 1565 // Check that this LValue is not based on a null pointer. If it is, produce 1566 // a diagnostic and mark the designator as invalid. 1567 template <typename GenDiagType> 1568 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1569 if (Designator.Invalid) 1570 return false; 1571 if (IsNullPtr) { 1572 GenDiag(); 1573 Designator.setInvalid(); 1574 return false; 1575 } 1576 return true; 1577 } 1578 1579 public: 1580 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1581 CheckSubobjectKind CSK) { 1582 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1583 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1584 }); 1585 } 1586 1587 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1588 AccessKinds AK) { 1589 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1590 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1591 }); 1592 } 1593 1594 // Check this LValue refers to an object. If not, set the designator to be 1595 // invalid and emit a diagnostic. 1596 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1597 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1598 Designator.checkSubobject(Info, E, CSK); 1599 } 1600 1601 void addDecl(EvalInfo &Info, const Expr *E, 1602 const Decl *D, bool Virtual = false) { 1603 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1604 Designator.addDeclUnchecked(D, Virtual); 1605 } 1606 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1607 if (!Designator.Entries.empty()) { 1608 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1609 Designator.setInvalid(); 1610 return; 1611 } 1612 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1613 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1614 Designator.FirstEntryIsAnUnsizedArray = true; 1615 Designator.addUnsizedArrayUnchecked(ElemTy); 1616 } 1617 } 1618 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1619 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1620 Designator.addArrayUnchecked(CAT); 1621 } 1622 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1623 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1624 Designator.addComplexUnchecked(EltTy, Imag); 1625 } 1626 void clearIsNullPointer() { 1627 IsNullPtr = false; 1628 } 1629 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1630 const APSInt &Index, CharUnits ElementSize) { 1631 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1632 // but we're not required to diagnose it and it's valid in C++.) 1633 if (!Index) 1634 return; 1635 1636 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1637 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1638 // offsets. 1639 uint64_t Offset64 = Offset.getQuantity(); 1640 uint64_t ElemSize64 = ElementSize.getQuantity(); 1641 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1642 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1643 1644 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1645 Designator.adjustIndex(Info, E, Index); 1646 clearIsNullPointer(); 1647 } 1648 void adjustOffset(CharUnits N) { 1649 Offset += N; 1650 if (N.getQuantity()) 1651 clearIsNullPointer(); 1652 } 1653 }; 1654 1655 struct MemberPtr { 1656 MemberPtr() {} 1657 explicit MemberPtr(const ValueDecl *Decl) : 1658 DeclAndIsDerivedMember(Decl, false), Path() {} 1659 1660 /// The member or (direct or indirect) field referred to by this member 1661 /// pointer, or 0 if this is a null member pointer. 1662 const ValueDecl *getDecl() const { 1663 return DeclAndIsDerivedMember.getPointer(); 1664 } 1665 /// Is this actually a member of some type derived from the relevant class? 1666 bool isDerivedMember() const { 1667 return DeclAndIsDerivedMember.getInt(); 1668 } 1669 /// Get the class which the declaration actually lives in. 1670 const CXXRecordDecl *getContainingRecord() const { 1671 return cast<CXXRecordDecl>( 1672 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1673 } 1674 1675 void moveInto(APValue &V) const { 1676 V = APValue(getDecl(), isDerivedMember(), Path); 1677 } 1678 void setFrom(const APValue &V) { 1679 assert(V.isMemberPointer()); 1680 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1681 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1682 Path.clear(); 1683 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1684 Path.insert(Path.end(), P.begin(), P.end()); 1685 } 1686 1687 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1688 /// whether the member is a member of some class derived from the class type 1689 /// of the member pointer. 1690 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1691 /// Path - The path of base/derived classes from the member declaration's 1692 /// class (exclusive) to the class type of the member pointer (inclusive). 1693 SmallVector<const CXXRecordDecl*, 4> Path; 1694 1695 /// Perform a cast towards the class of the Decl (either up or down the 1696 /// hierarchy). 1697 bool castBack(const CXXRecordDecl *Class) { 1698 assert(!Path.empty()); 1699 const CXXRecordDecl *Expected; 1700 if (Path.size() >= 2) 1701 Expected = Path[Path.size() - 2]; 1702 else 1703 Expected = getContainingRecord(); 1704 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1705 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1706 // if B does not contain the original member and is not a base or 1707 // derived class of the class containing the original member, the result 1708 // of the cast is undefined. 1709 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1710 // (D::*). We consider that to be a language defect. 1711 return false; 1712 } 1713 Path.pop_back(); 1714 return true; 1715 } 1716 /// Perform a base-to-derived member pointer cast. 1717 bool castToDerived(const CXXRecordDecl *Derived) { 1718 if (!getDecl()) 1719 return true; 1720 if (!isDerivedMember()) { 1721 Path.push_back(Derived); 1722 return true; 1723 } 1724 if (!castBack(Derived)) 1725 return false; 1726 if (Path.empty()) 1727 DeclAndIsDerivedMember.setInt(false); 1728 return true; 1729 } 1730 /// Perform a derived-to-base member pointer cast. 1731 bool castToBase(const CXXRecordDecl *Base) { 1732 if (!getDecl()) 1733 return true; 1734 if (Path.empty()) 1735 DeclAndIsDerivedMember.setInt(true); 1736 if (isDerivedMember()) { 1737 Path.push_back(Base); 1738 return true; 1739 } 1740 return castBack(Base); 1741 } 1742 }; 1743 1744 /// Compare two member pointers, which are assumed to be of the same type. 1745 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1746 if (!LHS.getDecl() || !RHS.getDecl()) 1747 return !LHS.getDecl() && !RHS.getDecl(); 1748 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1749 return false; 1750 return LHS.Path == RHS.Path; 1751 } 1752 } 1753 1754 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1755 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1756 const LValue &This, const Expr *E, 1757 bool AllowNonLiteralTypes = false); 1758 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1759 bool InvalidBaseOK = false); 1760 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1761 bool InvalidBaseOK = false); 1762 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1763 EvalInfo &Info); 1764 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1765 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1766 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1767 EvalInfo &Info); 1768 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1769 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1770 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1771 EvalInfo &Info); 1772 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1773 1774 /// Evaluate an integer or fixed point expression into an APResult. 1775 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1776 EvalInfo &Info); 1777 1778 /// Evaluate only a fixed point expression into an APResult. 1779 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1780 EvalInfo &Info); 1781 1782 //===----------------------------------------------------------------------===// 1783 // Misc utilities 1784 //===----------------------------------------------------------------------===// 1785 1786 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1787 /// preserving its value (by extending by up to one bit as needed). 1788 static void negateAsSigned(APSInt &Int) { 1789 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1790 Int = Int.extend(Int.getBitWidth() + 1); 1791 Int.setIsSigned(true); 1792 } 1793 Int = -Int; 1794 } 1795 1796 template<typename KeyT> 1797 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1798 bool IsLifetimeExtended, LValue &LV) { 1799 unsigned Version = getTempVersion(); 1800 APValue::LValueBase Base(Key, Index, Version); 1801 LV.set(Base); 1802 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1803 assert(Result.isAbsent() && "temporary created multiple times"); 1804 1805 // If we're creating a temporary immediately in the operand of a speculative 1806 // evaluation, don't register a cleanup to be run outside the speculative 1807 // evaluation context, since we won't actually be able to initialize this 1808 // object. 1809 if (Index <= Info.SpeculativeEvaluationDepth) { 1810 if (T.isDestructedType()) 1811 Info.noteSideEffect(); 1812 } else { 1813 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended)); 1814 } 1815 return Result; 1816 } 1817 1818 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1819 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1820 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1821 return nullptr; 1822 } 1823 1824 DynamicAllocLValue DA(NumHeapAllocs++); 1825 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1826 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1827 std::forward_as_tuple(DA), std::tuple<>()); 1828 assert(Result.second && "reused a heap alloc index?"); 1829 Result.first->second.AllocExpr = E; 1830 return &Result.first->second.Value; 1831 } 1832 1833 /// Produce a string describing the given constexpr call. 1834 void CallStackFrame::describe(raw_ostream &Out) { 1835 unsigned ArgIndex = 0; 1836 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1837 !isa<CXXConstructorDecl>(Callee) && 1838 cast<CXXMethodDecl>(Callee)->isInstance(); 1839 1840 if (!IsMemberCall) 1841 Out << *Callee << '('; 1842 1843 if (This && IsMemberCall) { 1844 APValue Val; 1845 This->moveInto(Val); 1846 Val.printPretty(Out, Info.Ctx, 1847 This->Designator.MostDerivedType); 1848 // FIXME: Add parens around Val if needed. 1849 Out << "->" << *Callee << '('; 1850 IsMemberCall = false; 1851 } 1852 1853 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1854 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1855 if (ArgIndex > (unsigned)IsMemberCall) 1856 Out << ", "; 1857 1858 const ParmVarDecl *Param = *I; 1859 const APValue &Arg = Arguments[ArgIndex]; 1860 Arg.printPretty(Out, Info.Ctx, Param->getType()); 1861 1862 if (ArgIndex == 0 && IsMemberCall) 1863 Out << "->" << *Callee << '('; 1864 } 1865 1866 Out << ')'; 1867 } 1868 1869 /// Evaluate an expression to see if it had side-effects, and discard its 1870 /// result. 1871 /// \return \c true if the caller should keep evaluating. 1872 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1873 APValue Scratch; 1874 if (!Evaluate(Scratch, Info, E)) 1875 // We don't need the value, but we might have skipped a side effect here. 1876 return Info.noteSideEffect(); 1877 return true; 1878 } 1879 1880 /// Should this call expression be treated as a string literal? 1881 static bool IsStringLiteralCall(const CallExpr *E) { 1882 unsigned Builtin = E->getBuiltinCallee(); 1883 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1884 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1885 } 1886 1887 static bool IsGlobalLValue(APValue::LValueBase B) { 1888 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1889 // constant expression of pointer type that evaluates to... 1890 1891 // ... a null pointer value, or a prvalue core constant expression of type 1892 // std::nullptr_t. 1893 if (!B) return true; 1894 1895 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1896 // ... the address of an object with static storage duration, 1897 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1898 return VD->hasGlobalStorage(); 1899 // ... the address of a function, 1900 // ... the address of a GUID [MS extension], 1901 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1902 } 1903 1904 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1905 return true; 1906 1907 const Expr *E = B.get<const Expr*>(); 1908 switch (E->getStmtClass()) { 1909 default: 1910 return false; 1911 case Expr::CompoundLiteralExprClass: { 1912 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1913 return CLE->isFileScope() && CLE->isLValue(); 1914 } 1915 case Expr::MaterializeTemporaryExprClass: 1916 // A materialized temporary might have been lifetime-extended to static 1917 // storage duration. 1918 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1919 // A string literal has static storage duration. 1920 case Expr::StringLiteralClass: 1921 case Expr::PredefinedExprClass: 1922 case Expr::ObjCStringLiteralClass: 1923 case Expr::ObjCEncodeExprClass: 1924 return true; 1925 case Expr::ObjCBoxedExprClass: 1926 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 1927 case Expr::CallExprClass: 1928 return IsStringLiteralCall(cast<CallExpr>(E)); 1929 // For GCC compatibility, &&label has static storage duration. 1930 case Expr::AddrLabelExprClass: 1931 return true; 1932 // A Block literal expression may be used as the initialization value for 1933 // Block variables at global or local static scope. 1934 case Expr::BlockExprClass: 1935 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1936 case Expr::ImplicitValueInitExprClass: 1937 // FIXME: 1938 // We can never form an lvalue with an implicit value initialization as its 1939 // base through expression evaluation, so these only appear in one case: the 1940 // implicit variable declaration we invent when checking whether a constexpr 1941 // constructor can produce a constant expression. We must assume that such 1942 // an expression might be a global lvalue. 1943 return true; 1944 } 1945 } 1946 1947 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1948 return LVal.Base.dyn_cast<const ValueDecl*>(); 1949 } 1950 1951 static bool IsLiteralLValue(const LValue &Value) { 1952 if (Value.getLValueCallIndex()) 1953 return false; 1954 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1955 return E && !isa<MaterializeTemporaryExpr>(E); 1956 } 1957 1958 static bool IsWeakLValue(const LValue &Value) { 1959 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1960 return Decl && Decl->isWeak(); 1961 } 1962 1963 static bool isZeroSized(const LValue &Value) { 1964 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1965 if (Decl && isa<VarDecl>(Decl)) { 1966 QualType Ty = Decl->getType(); 1967 if (Ty->isArrayType()) 1968 return Ty->isIncompleteType() || 1969 Decl->getASTContext().getTypeSize(Ty) == 0; 1970 } 1971 return false; 1972 } 1973 1974 static bool HasSameBase(const LValue &A, const LValue &B) { 1975 if (!A.getLValueBase()) 1976 return !B.getLValueBase(); 1977 if (!B.getLValueBase()) 1978 return false; 1979 1980 if (A.getLValueBase().getOpaqueValue() != 1981 B.getLValueBase().getOpaqueValue()) { 1982 const Decl *ADecl = GetLValueBaseDecl(A); 1983 if (!ADecl) 1984 return false; 1985 const Decl *BDecl = GetLValueBaseDecl(B); 1986 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 1987 return false; 1988 } 1989 1990 return IsGlobalLValue(A.getLValueBase()) || 1991 (A.getLValueCallIndex() == B.getLValueCallIndex() && 1992 A.getLValueVersion() == B.getLValueVersion()); 1993 } 1994 1995 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1996 assert(Base && "no location for a null lvalue"); 1997 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1998 if (VD) 1999 Info.Note(VD->getLocation(), diag::note_declared_at); 2000 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2001 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2002 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2003 // FIXME: Produce a note for dangling pointers too. 2004 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2005 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2006 diag::note_constexpr_dynamic_alloc_here); 2007 } 2008 // We have no information to show for a typeid(T) object. 2009 } 2010 2011 enum class CheckEvaluationResultKind { 2012 ConstantExpression, 2013 FullyInitialized, 2014 }; 2015 2016 /// Materialized temporaries that we've already checked to determine if they're 2017 /// initializsed by a constant expression. 2018 using CheckedTemporaries = 2019 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2020 2021 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2022 EvalInfo &Info, SourceLocation DiagLoc, 2023 QualType Type, const APValue &Value, 2024 Expr::ConstExprUsage Usage, 2025 SourceLocation SubobjectLoc, 2026 CheckedTemporaries &CheckedTemps); 2027 2028 /// Check that this reference or pointer core constant expression is a valid 2029 /// value for an address or reference constant expression. Return true if we 2030 /// can fold this expression, whether or not it's a constant expression. 2031 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2032 QualType Type, const LValue &LVal, 2033 Expr::ConstExprUsage Usage, 2034 CheckedTemporaries &CheckedTemps) { 2035 bool IsReferenceType = Type->isReferenceType(); 2036 2037 APValue::LValueBase Base = LVal.getLValueBase(); 2038 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2039 2040 if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) { 2041 if (auto *FD = dyn_cast<FunctionDecl>(VD)) { 2042 if (FD->isConsteval()) { 2043 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2044 << !Type->isAnyPointerType(); 2045 Info.Note(FD->getLocation(), diag::note_declared_at); 2046 return false; 2047 } 2048 } 2049 } 2050 2051 // Check that the object is a global. Note that the fake 'this' object we 2052 // manufacture when checking potential constant expressions is conservatively 2053 // assumed to be global here. 2054 if (!IsGlobalLValue(Base)) { 2055 if (Info.getLangOpts().CPlusPlus11) { 2056 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2057 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2058 << IsReferenceType << !Designator.Entries.empty() 2059 << !!VD << VD; 2060 2061 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2062 if (VarD && VarD->isConstexpr()) { 2063 // Non-static local constexpr variables have unintuitive semantics: 2064 // constexpr int a = 1; 2065 // constexpr const int *p = &a; 2066 // ... is invalid because the address of 'a' is not constant. Suggest 2067 // adding a 'static' in this case. 2068 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2069 << VarD 2070 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2071 } else { 2072 NoteLValueLocation(Info, Base); 2073 } 2074 } else { 2075 Info.FFDiag(Loc); 2076 } 2077 // Don't allow references to temporaries to escape. 2078 return false; 2079 } 2080 assert((Info.checkingPotentialConstantExpression() || 2081 LVal.getLValueCallIndex() == 0) && 2082 "have call index for global lvalue"); 2083 2084 if (Base.is<DynamicAllocLValue>()) { 2085 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2086 << IsReferenceType << !Designator.Entries.empty(); 2087 NoteLValueLocation(Info, Base); 2088 return false; 2089 } 2090 2091 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 2092 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 2093 // Check if this is a thread-local variable. 2094 if (Var->getTLSKind()) 2095 // FIXME: Diagnostic! 2096 return false; 2097 2098 // A dllimport variable never acts like a constant. 2099 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 2100 // FIXME: Diagnostic! 2101 return false; 2102 } 2103 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 2104 // __declspec(dllimport) must be handled very carefully: 2105 // We must never initialize an expression with the thunk in C++. 2106 // Doing otherwise would allow the same id-expression to yield 2107 // different addresses for the same function in different translation 2108 // units. However, this means that we must dynamically initialize the 2109 // expression with the contents of the import address table at runtime. 2110 // 2111 // The C language has no notion of ODR; furthermore, it has no notion of 2112 // dynamic initialization. This means that we are permitted to 2113 // perform initialization with the address of the thunk. 2114 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 2115 FD->hasAttr<DLLImportAttr>()) 2116 // FIXME: Diagnostic! 2117 return false; 2118 } 2119 } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>( 2120 Base.dyn_cast<const Expr *>())) { 2121 if (CheckedTemps.insert(MTE).second) { 2122 QualType TempType = getType(Base); 2123 if (TempType.isDestructedType()) { 2124 Info.FFDiag(MTE->getExprLoc(), 2125 diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor) 2126 << TempType; 2127 return false; 2128 } 2129 2130 APValue *V = MTE->getOrCreateValue(false); 2131 assert(V && "evasluation result refers to uninitialised temporary"); 2132 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2133 Info, MTE->getExprLoc(), TempType, *V, 2134 Usage, SourceLocation(), CheckedTemps)) 2135 return false; 2136 } 2137 } 2138 2139 // Allow address constant expressions to be past-the-end pointers. This is 2140 // an extension: the standard requires them to point to an object. 2141 if (!IsReferenceType) 2142 return true; 2143 2144 // A reference constant expression must refer to an object. 2145 if (!Base) { 2146 // FIXME: diagnostic 2147 Info.CCEDiag(Loc); 2148 return true; 2149 } 2150 2151 // Does this refer one past the end of some object? 2152 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2153 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2154 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2155 << !Designator.Entries.empty() << !!VD << VD; 2156 NoteLValueLocation(Info, Base); 2157 } 2158 2159 return true; 2160 } 2161 2162 /// Member pointers are constant expressions unless they point to a 2163 /// non-virtual dllimport member function. 2164 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2165 SourceLocation Loc, 2166 QualType Type, 2167 const APValue &Value, 2168 Expr::ConstExprUsage Usage) { 2169 const ValueDecl *Member = Value.getMemberPointerDecl(); 2170 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2171 if (!FD) 2172 return true; 2173 if (FD->isConsteval()) { 2174 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2175 Info.Note(FD->getLocation(), diag::note_declared_at); 2176 return false; 2177 } 2178 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 2179 !FD->hasAttr<DLLImportAttr>(); 2180 } 2181 2182 /// Check that this core constant expression is of literal type, and if not, 2183 /// produce an appropriate diagnostic. 2184 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2185 const LValue *This = nullptr) { 2186 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2187 return true; 2188 2189 // C++1y: A constant initializer for an object o [...] may also invoke 2190 // constexpr constructors for o and its subobjects even if those objects 2191 // are of non-literal class types. 2192 // 2193 // C++11 missed this detail for aggregates, so classes like this: 2194 // struct foo_t { union { int i; volatile int j; } u; }; 2195 // are not (obviously) initializable like so: 2196 // __attribute__((__require_constant_initialization__)) 2197 // static const foo_t x = {{0}}; 2198 // because "i" is a subobject with non-literal initialization (due to the 2199 // volatile member of the union). See: 2200 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2201 // Therefore, we use the C++1y behavior. 2202 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2203 return true; 2204 2205 // Prvalue constant expressions must be of literal types. 2206 if (Info.getLangOpts().CPlusPlus11) 2207 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2208 << E->getType(); 2209 else 2210 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2211 return false; 2212 } 2213 2214 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2215 EvalInfo &Info, SourceLocation DiagLoc, 2216 QualType Type, const APValue &Value, 2217 Expr::ConstExprUsage Usage, 2218 SourceLocation SubobjectLoc, 2219 CheckedTemporaries &CheckedTemps) { 2220 if (!Value.hasValue()) { 2221 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2222 << true << Type; 2223 if (SubobjectLoc.isValid()) 2224 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2225 return false; 2226 } 2227 2228 // We allow _Atomic(T) to be initialized from anything that T can be 2229 // initialized from. 2230 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2231 Type = AT->getValueType(); 2232 2233 // Core issue 1454: For a literal constant expression of array or class type, 2234 // each subobject of its value shall have been initialized by a constant 2235 // expression. 2236 if (Value.isArray()) { 2237 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2238 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2239 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2240 Value.getArrayInitializedElt(I), Usage, 2241 SubobjectLoc, CheckedTemps)) 2242 return false; 2243 } 2244 if (!Value.hasArrayFiller()) 2245 return true; 2246 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2247 Value.getArrayFiller(), Usage, SubobjectLoc, 2248 CheckedTemps); 2249 } 2250 if (Value.isUnion() && Value.getUnionField()) { 2251 return CheckEvaluationResult( 2252 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2253 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(), 2254 CheckedTemps); 2255 } 2256 if (Value.isStruct()) { 2257 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2258 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2259 unsigned BaseIndex = 0; 2260 for (const CXXBaseSpecifier &BS : CD->bases()) { 2261 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2262 Value.getStructBase(BaseIndex), Usage, 2263 BS.getBeginLoc(), CheckedTemps)) 2264 return false; 2265 ++BaseIndex; 2266 } 2267 } 2268 for (const auto *I : RD->fields()) { 2269 if (I->isUnnamedBitfield()) 2270 continue; 2271 2272 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2273 Value.getStructField(I->getFieldIndex()), 2274 Usage, I->getLocation(), CheckedTemps)) 2275 return false; 2276 } 2277 } 2278 2279 if (Value.isLValue() && 2280 CERK == CheckEvaluationResultKind::ConstantExpression) { 2281 LValue LVal; 2282 LVal.setFrom(Info.Ctx, Value); 2283 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage, 2284 CheckedTemps); 2285 } 2286 2287 if (Value.isMemberPointer() && 2288 CERK == CheckEvaluationResultKind::ConstantExpression) 2289 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 2290 2291 // Everything else is fine. 2292 return true; 2293 } 2294 2295 /// Check that this core constant expression value is a valid value for a 2296 /// constant expression. If not, report an appropriate diagnostic. Does not 2297 /// check that the expression is of literal type. 2298 static bool 2299 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 2300 const APValue &Value, 2301 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) { 2302 // Nothing to check for a constant expression of type 'cv void'. 2303 if (Type->isVoidType()) 2304 return true; 2305 2306 CheckedTemporaries CheckedTemps; 2307 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2308 Info, DiagLoc, Type, Value, Usage, 2309 SourceLocation(), CheckedTemps); 2310 } 2311 2312 /// Check that this evaluated value is fully-initialized and can be loaded by 2313 /// an lvalue-to-rvalue conversion. 2314 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2315 QualType Type, const APValue &Value) { 2316 CheckedTemporaries CheckedTemps; 2317 return CheckEvaluationResult( 2318 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2319 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps); 2320 } 2321 2322 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2323 /// "the allocated storage is deallocated within the evaluation". 2324 static bool CheckMemoryLeaks(EvalInfo &Info) { 2325 if (!Info.HeapAllocs.empty()) { 2326 // We can still fold to a constant despite a compile-time memory leak, 2327 // so long as the heap allocation isn't referenced in the result (we check 2328 // that in CheckConstantExpression). 2329 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2330 diag::note_constexpr_memory_leak) 2331 << unsigned(Info.HeapAllocs.size() - 1); 2332 } 2333 return true; 2334 } 2335 2336 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2337 // A null base expression indicates a null pointer. These are always 2338 // evaluatable, and they are false unless the offset is zero. 2339 if (!Value.getLValueBase()) { 2340 Result = !Value.getLValueOffset().isZero(); 2341 return true; 2342 } 2343 2344 // We have a non-null base. These are generally known to be true, but if it's 2345 // a weak declaration it can be null at runtime. 2346 Result = true; 2347 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2348 return !Decl || !Decl->isWeak(); 2349 } 2350 2351 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2352 switch (Val.getKind()) { 2353 case APValue::None: 2354 case APValue::Indeterminate: 2355 return false; 2356 case APValue::Int: 2357 Result = Val.getInt().getBoolValue(); 2358 return true; 2359 case APValue::FixedPoint: 2360 Result = Val.getFixedPoint().getBoolValue(); 2361 return true; 2362 case APValue::Float: 2363 Result = !Val.getFloat().isZero(); 2364 return true; 2365 case APValue::ComplexInt: 2366 Result = Val.getComplexIntReal().getBoolValue() || 2367 Val.getComplexIntImag().getBoolValue(); 2368 return true; 2369 case APValue::ComplexFloat: 2370 Result = !Val.getComplexFloatReal().isZero() || 2371 !Val.getComplexFloatImag().isZero(); 2372 return true; 2373 case APValue::LValue: 2374 return EvalPointerValueAsBool(Val, Result); 2375 case APValue::MemberPointer: 2376 Result = Val.getMemberPointerDecl(); 2377 return true; 2378 case APValue::Vector: 2379 case APValue::Array: 2380 case APValue::Struct: 2381 case APValue::Union: 2382 case APValue::AddrLabelDiff: 2383 return false; 2384 } 2385 2386 llvm_unreachable("unknown APValue kind"); 2387 } 2388 2389 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2390 EvalInfo &Info) { 2391 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2392 APValue Val; 2393 if (!Evaluate(Val, Info, E)) 2394 return false; 2395 return HandleConversionToBool(Val, Result); 2396 } 2397 2398 template<typename T> 2399 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2400 const T &SrcValue, QualType DestType) { 2401 Info.CCEDiag(E, diag::note_constexpr_overflow) 2402 << SrcValue << DestType; 2403 return Info.noteUndefinedBehavior(); 2404 } 2405 2406 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2407 QualType SrcType, const APFloat &Value, 2408 QualType DestType, APSInt &Result) { 2409 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2410 // Determine whether we are converting to unsigned or signed. 2411 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2412 2413 Result = APSInt(DestWidth, !DestSigned); 2414 bool ignored; 2415 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2416 & APFloat::opInvalidOp) 2417 return HandleOverflow(Info, E, Value, DestType); 2418 return true; 2419 } 2420 2421 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2422 QualType SrcType, QualType DestType, 2423 APFloat &Result) { 2424 APFloat Value = Result; 2425 bool ignored; 2426 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 2427 APFloat::rmNearestTiesToEven, &ignored); 2428 return true; 2429 } 2430 2431 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2432 QualType DestType, QualType SrcType, 2433 const APSInt &Value) { 2434 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2435 // Figure out if this is a truncate, extend or noop cast. 2436 // If the input is signed, do a sign extend, noop, or truncate. 2437 APSInt Result = Value.extOrTrunc(DestWidth); 2438 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2439 if (DestType->isBooleanType()) 2440 Result = Value.getBoolValue(); 2441 return Result; 2442 } 2443 2444 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2445 QualType SrcType, const APSInt &Value, 2446 QualType DestType, APFloat &Result) { 2447 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2448 Result.convertFromAPInt(Value, Value.isSigned(), 2449 APFloat::rmNearestTiesToEven); 2450 return true; 2451 } 2452 2453 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2454 APValue &Value, const FieldDecl *FD) { 2455 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2456 2457 if (!Value.isInt()) { 2458 // Trying to store a pointer-cast-to-integer into a bitfield. 2459 // FIXME: In this case, we should provide the diagnostic for casting 2460 // a pointer to an integer. 2461 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2462 Info.FFDiag(E); 2463 return false; 2464 } 2465 2466 APSInt &Int = Value.getInt(); 2467 unsigned OldBitWidth = Int.getBitWidth(); 2468 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2469 if (NewBitWidth < OldBitWidth) 2470 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2471 return true; 2472 } 2473 2474 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2475 llvm::APInt &Res) { 2476 APValue SVal; 2477 if (!Evaluate(SVal, Info, E)) 2478 return false; 2479 if (SVal.isInt()) { 2480 Res = SVal.getInt(); 2481 return true; 2482 } 2483 if (SVal.isFloat()) { 2484 Res = SVal.getFloat().bitcastToAPInt(); 2485 return true; 2486 } 2487 if (SVal.isVector()) { 2488 QualType VecTy = E->getType(); 2489 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2490 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2491 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2492 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2493 Res = llvm::APInt::getNullValue(VecSize); 2494 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2495 APValue &Elt = SVal.getVectorElt(i); 2496 llvm::APInt EltAsInt; 2497 if (Elt.isInt()) { 2498 EltAsInt = Elt.getInt(); 2499 } else if (Elt.isFloat()) { 2500 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2501 } else { 2502 // Don't try to handle vectors of anything other than int or float 2503 // (not sure if it's possible to hit this case). 2504 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2505 return false; 2506 } 2507 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2508 if (BigEndian) 2509 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2510 else 2511 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2512 } 2513 return true; 2514 } 2515 // Give up if the input isn't an int, float, or vector. For example, we 2516 // reject "(v4i16)(intptr_t)&a". 2517 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2518 return false; 2519 } 2520 2521 /// Perform the given integer operation, which is known to need at most BitWidth 2522 /// bits, and check for overflow in the original type (if that type was not an 2523 /// unsigned type). 2524 template<typename Operation> 2525 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2526 const APSInt &LHS, const APSInt &RHS, 2527 unsigned BitWidth, Operation Op, 2528 APSInt &Result) { 2529 if (LHS.isUnsigned()) { 2530 Result = Op(LHS, RHS); 2531 return true; 2532 } 2533 2534 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2535 Result = Value.trunc(LHS.getBitWidth()); 2536 if (Result.extend(BitWidth) != Value) { 2537 if (Info.checkingForUndefinedBehavior()) 2538 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2539 diag::warn_integer_constant_overflow) 2540 << Result.toString(10) << E->getType(); 2541 else 2542 return HandleOverflow(Info, E, Value, E->getType()); 2543 } 2544 return true; 2545 } 2546 2547 /// Perform the given binary integer operation. 2548 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2549 BinaryOperatorKind Opcode, APSInt RHS, 2550 APSInt &Result) { 2551 switch (Opcode) { 2552 default: 2553 Info.FFDiag(E); 2554 return false; 2555 case BO_Mul: 2556 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2557 std::multiplies<APSInt>(), Result); 2558 case BO_Add: 2559 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2560 std::plus<APSInt>(), Result); 2561 case BO_Sub: 2562 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2563 std::minus<APSInt>(), Result); 2564 case BO_And: Result = LHS & RHS; return true; 2565 case BO_Xor: Result = LHS ^ RHS; return true; 2566 case BO_Or: Result = LHS | RHS; return true; 2567 case BO_Div: 2568 case BO_Rem: 2569 if (RHS == 0) { 2570 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2571 return false; 2572 } 2573 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2574 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2575 // this operation and gives the two's complement result. 2576 if (RHS.isNegative() && RHS.isAllOnesValue() && 2577 LHS.isSigned() && LHS.isMinSignedValue()) 2578 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2579 E->getType()); 2580 return true; 2581 case BO_Shl: { 2582 if (Info.getLangOpts().OpenCL) 2583 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2584 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2585 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2586 RHS.isUnsigned()); 2587 else if (RHS.isSigned() && RHS.isNegative()) { 2588 // During constant-folding, a negative shift is an opposite shift. Such 2589 // a shift is not a constant expression. 2590 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2591 RHS = -RHS; 2592 goto shift_right; 2593 } 2594 shift_left: 2595 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2596 // the shifted type. 2597 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2598 if (SA != RHS) { 2599 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2600 << RHS << E->getType() << LHS.getBitWidth(); 2601 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2602 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2603 // operand, and must not overflow the corresponding unsigned type. 2604 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2605 // E1 x 2^E2 module 2^N. 2606 if (LHS.isNegative()) 2607 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2608 else if (LHS.countLeadingZeros() < SA) 2609 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2610 } 2611 Result = LHS << SA; 2612 return true; 2613 } 2614 case BO_Shr: { 2615 if (Info.getLangOpts().OpenCL) 2616 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2617 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2618 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2619 RHS.isUnsigned()); 2620 else if (RHS.isSigned() && RHS.isNegative()) { 2621 // During constant-folding, a negative shift is an opposite shift. Such a 2622 // shift is not a constant expression. 2623 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2624 RHS = -RHS; 2625 goto shift_left; 2626 } 2627 shift_right: 2628 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2629 // shifted type. 2630 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2631 if (SA != RHS) 2632 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2633 << RHS << E->getType() << LHS.getBitWidth(); 2634 Result = LHS >> SA; 2635 return true; 2636 } 2637 2638 case BO_LT: Result = LHS < RHS; return true; 2639 case BO_GT: Result = LHS > RHS; return true; 2640 case BO_LE: Result = LHS <= RHS; return true; 2641 case BO_GE: Result = LHS >= RHS; return true; 2642 case BO_EQ: Result = LHS == RHS; return true; 2643 case BO_NE: Result = LHS != RHS; return true; 2644 case BO_Cmp: 2645 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2646 } 2647 } 2648 2649 /// Perform the given binary floating-point operation, in-place, on LHS. 2650 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2651 APFloat &LHS, BinaryOperatorKind Opcode, 2652 const APFloat &RHS) { 2653 switch (Opcode) { 2654 default: 2655 Info.FFDiag(E); 2656 return false; 2657 case BO_Mul: 2658 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2659 break; 2660 case BO_Add: 2661 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2662 break; 2663 case BO_Sub: 2664 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2665 break; 2666 case BO_Div: 2667 // [expr.mul]p4: 2668 // If the second operand of / or % is zero the behavior is undefined. 2669 if (RHS.isZero()) 2670 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2671 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2672 break; 2673 } 2674 2675 // [expr.pre]p4: 2676 // If during the evaluation of an expression, the result is not 2677 // mathematically defined [...], the behavior is undefined. 2678 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2679 if (LHS.isNaN()) { 2680 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2681 return Info.noteUndefinedBehavior(); 2682 } 2683 return true; 2684 } 2685 2686 static bool handleLogicalOpForVector(const APInt &LHSValue, 2687 BinaryOperatorKind Opcode, 2688 const APInt &RHSValue, APInt &Result) { 2689 bool LHS = (LHSValue != 0); 2690 bool RHS = (RHSValue != 0); 2691 2692 if (Opcode == BO_LAnd) 2693 Result = LHS && RHS; 2694 else 2695 Result = LHS || RHS; 2696 return true; 2697 } 2698 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2699 BinaryOperatorKind Opcode, 2700 const APFloat &RHSValue, APInt &Result) { 2701 bool LHS = !LHSValue.isZero(); 2702 bool RHS = !RHSValue.isZero(); 2703 2704 if (Opcode == BO_LAnd) 2705 Result = LHS && RHS; 2706 else 2707 Result = LHS || RHS; 2708 return true; 2709 } 2710 2711 static bool handleLogicalOpForVector(const APValue &LHSValue, 2712 BinaryOperatorKind Opcode, 2713 const APValue &RHSValue, APInt &Result) { 2714 // The result is always an int type, however operands match the first. 2715 if (LHSValue.getKind() == APValue::Int) 2716 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2717 RHSValue.getInt(), Result); 2718 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2719 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2720 RHSValue.getFloat(), Result); 2721 } 2722 2723 template <typename APTy> 2724 static bool 2725 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2726 const APTy &RHSValue, APInt &Result) { 2727 switch (Opcode) { 2728 default: 2729 llvm_unreachable("unsupported binary operator"); 2730 case BO_EQ: 2731 Result = (LHSValue == RHSValue); 2732 break; 2733 case BO_NE: 2734 Result = (LHSValue != RHSValue); 2735 break; 2736 case BO_LT: 2737 Result = (LHSValue < RHSValue); 2738 break; 2739 case BO_GT: 2740 Result = (LHSValue > RHSValue); 2741 break; 2742 case BO_LE: 2743 Result = (LHSValue <= RHSValue); 2744 break; 2745 case BO_GE: 2746 Result = (LHSValue >= RHSValue); 2747 break; 2748 } 2749 2750 return true; 2751 } 2752 2753 static bool handleCompareOpForVector(const APValue &LHSValue, 2754 BinaryOperatorKind Opcode, 2755 const APValue &RHSValue, APInt &Result) { 2756 // The result is always an int type, however operands match the first. 2757 if (LHSValue.getKind() == APValue::Int) 2758 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2759 RHSValue.getInt(), Result); 2760 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2761 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2762 RHSValue.getFloat(), Result); 2763 } 2764 2765 // Perform binary operations for vector types, in place on the LHS. 2766 static bool handleVectorVectorBinOp(EvalInfo &Info, const Expr *E, 2767 BinaryOperatorKind Opcode, 2768 APValue &LHSValue, 2769 const APValue &RHSValue) { 2770 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2771 "Operation not supported on vector types"); 2772 2773 const auto *VT = E->getType()->castAs<VectorType>(); 2774 unsigned NumElements = VT->getNumElements(); 2775 QualType EltTy = VT->getElementType(); 2776 2777 // In the cases (typically C as I've observed) where we aren't evaluating 2778 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2779 // just give up. 2780 if (!LHSValue.isVector()) { 2781 assert(LHSValue.isLValue() && 2782 "A vector result that isn't a vector OR uncalculated LValue"); 2783 Info.FFDiag(E); 2784 return false; 2785 } 2786 2787 assert(LHSValue.getVectorLength() == NumElements && 2788 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2789 2790 SmallVector<APValue, 4> ResultElements; 2791 2792 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2793 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2794 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2795 2796 if (EltTy->isIntegerType()) { 2797 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2798 EltTy->isUnsignedIntegerType()}; 2799 bool Success = true; 2800 2801 if (BinaryOperator::isLogicalOp(Opcode)) 2802 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2803 else if (BinaryOperator::isComparisonOp(Opcode)) 2804 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2805 else 2806 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2807 RHSElt.getInt(), EltResult); 2808 2809 if (!Success) { 2810 Info.FFDiag(E); 2811 return false; 2812 } 2813 ResultElements.emplace_back(EltResult); 2814 2815 } else if (EltTy->isFloatingType()) { 2816 assert(LHSElt.getKind() == APValue::Float && 2817 RHSElt.getKind() == APValue::Float && 2818 "Mismatched LHS/RHS/Result Type"); 2819 APFloat LHSFloat = LHSElt.getFloat(); 2820 2821 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 2822 RHSElt.getFloat())) { 2823 Info.FFDiag(E); 2824 return false; 2825 } 2826 2827 ResultElements.emplace_back(LHSFloat); 2828 } 2829 } 2830 2831 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 2832 return true; 2833 } 2834 2835 /// Cast an lvalue referring to a base subobject to a derived class, by 2836 /// truncating the lvalue's path to the given length. 2837 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2838 const RecordDecl *TruncatedType, 2839 unsigned TruncatedElements) { 2840 SubobjectDesignator &D = Result.Designator; 2841 2842 // Check we actually point to a derived class object. 2843 if (TruncatedElements == D.Entries.size()) 2844 return true; 2845 assert(TruncatedElements >= D.MostDerivedPathLength && 2846 "not casting to a derived class"); 2847 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2848 return false; 2849 2850 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2851 const RecordDecl *RD = TruncatedType; 2852 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2853 if (RD->isInvalidDecl()) return false; 2854 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2855 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2856 if (isVirtualBaseClass(D.Entries[I])) 2857 Result.Offset -= Layout.getVBaseClassOffset(Base); 2858 else 2859 Result.Offset -= Layout.getBaseClassOffset(Base); 2860 RD = Base; 2861 } 2862 D.Entries.resize(TruncatedElements); 2863 return true; 2864 } 2865 2866 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2867 const CXXRecordDecl *Derived, 2868 const CXXRecordDecl *Base, 2869 const ASTRecordLayout *RL = nullptr) { 2870 if (!RL) { 2871 if (Derived->isInvalidDecl()) return false; 2872 RL = &Info.Ctx.getASTRecordLayout(Derived); 2873 } 2874 2875 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2876 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2877 return true; 2878 } 2879 2880 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2881 const CXXRecordDecl *DerivedDecl, 2882 const CXXBaseSpecifier *Base) { 2883 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2884 2885 if (!Base->isVirtual()) 2886 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2887 2888 SubobjectDesignator &D = Obj.Designator; 2889 if (D.Invalid) 2890 return false; 2891 2892 // Extract most-derived object and corresponding type. 2893 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2894 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2895 return false; 2896 2897 // Find the virtual base class. 2898 if (DerivedDecl->isInvalidDecl()) return false; 2899 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2900 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2901 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2902 return true; 2903 } 2904 2905 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2906 QualType Type, LValue &Result) { 2907 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2908 PathE = E->path_end(); 2909 PathI != PathE; ++PathI) { 2910 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2911 *PathI)) 2912 return false; 2913 Type = (*PathI)->getType(); 2914 } 2915 return true; 2916 } 2917 2918 /// Cast an lvalue referring to a derived class to a known base subobject. 2919 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 2920 const CXXRecordDecl *DerivedRD, 2921 const CXXRecordDecl *BaseRD) { 2922 CXXBasePaths Paths(/*FindAmbiguities=*/false, 2923 /*RecordPaths=*/true, /*DetectVirtual=*/false); 2924 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 2925 llvm_unreachable("Class must be derived from the passed in base class!"); 2926 2927 for (CXXBasePathElement &Elem : Paths.front()) 2928 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 2929 return false; 2930 return true; 2931 } 2932 2933 /// Update LVal to refer to the given field, which must be a member of the type 2934 /// currently described by LVal. 2935 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2936 const FieldDecl *FD, 2937 const ASTRecordLayout *RL = nullptr) { 2938 if (!RL) { 2939 if (FD->getParent()->isInvalidDecl()) return false; 2940 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2941 } 2942 2943 unsigned I = FD->getFieldIndex(); 2944 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2945 LVal.addDecl(Info, E, FD); 2946 return true; 2947 } 2948 2949 /// Update LVal to refer to the given indirect field. 2950 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2951 LValue &LVal, 2952 const IndirectFieldDecl *IFD) { 2953 for (const auto *C : IFD->chain()) 2954 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2955 return false; 2956 return true; 2957 } 2958 2959 /// Get the size of the given type in char units. 2960 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2961 QualType Type, CharUnits &Size) { 2962 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2963 // extension. 2964 if (Type->isVoidType() || Type->isFunctionType()) { 2965 Size = CharUnits::One(); 2966 return true; 2967 } 2968 2969 if (Type->isDependentType()) { 2970 Info.FFDiag(Loc); 2971 return false; 2972 } 2973 2974 if (!Type->isConstantSizeType()) { 2975 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2976 // FIXME: Better diagnostic. 2977 Info.FFDiag(Loc); 2978 return false; 2979 } 2980 2981 Size = Info.Ctx.getTypeSizeInChars(Type); 2982 return true; 2983 } 2984 2985 /// Update a pointer value to model pointer arithmetic. 2986 /// \param Info - Information about the ongoing evaluation. 2987 /// \param E - The expression being evaluated, for diagnostic purposes. 2988 /// \param LVal - The pointer value to be updated. 2989 /// \param EltTy - The pointee type represented by LVal. 2990 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2991 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2992 LValue &LVal, QualType EltTy, 2993 APSInt Adjustment) { 2994 CharUnits SizeOfPointee; 2995 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2996 return false; 2997 2998 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2999 return true; 3000 } 3001 3002 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3003 LValue &LVal, QualType EltTy, 3004 int64_t Adjustment) { 3005 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3006 APSInt::get(Adjustment)); 3007 } 3008 3009 /// Update an lvalue to refer to a component of a complex number. 3010 /// \param Info - Information about the ongoing evaluation. 3011 /// \param LVal - The lvalue to be updated. 3012 /// \param EltTy - The complex number's component type. 3013 /// \param Imag - False for the real component, true for the imaginary. 3014 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3015 LValue &LVal, QualType EltTy, 3016 bool Imag) { 3017 if (Imag) { 3018 CharUnits SizeOfComponent; 3019 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3020 return false; 3021 LVal.Offset += SizeOfComponent; 3022 } 3023 LVal.addComplex(Info, E, EltTy, Imag); 3024 return true; 3025 } 3026 3027 /// Try to evaluate the initializer for a variable declaration. 3028 /// 3029 /// \param Info Information about the ongoing evaluation. 3030 /// \param E An expression to be used when printing diagnostics. 3031 /// \param VD The variable whose initializer should be obtained. 3032 /// \param Frame The frame in which the variable was created. Must be null 3033 /// if this variable is not local to the evaluation. 3034 /// \param Result Filled in with a pointer to the value of the variable. 3035 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3036 const VarDecl *VD, CallStackFrame *Frame, 3037 APValue *&Result, const LValue *LVal) { 3038 3039 // If this is a parameter to an active constexpr function call, perform 3040 // argument substitution. 3041 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 3042 // Assume arguments of a potential constant expression are unknown 3043 // constant expressions. 3044 if (Info.checkingPotentialConstantExpression()) 3045 return false; 3046 if (!Frame || !Frame->Arguments) { 3047 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) << VD; 3048 return false; 3049 } 3050 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 3051 return true; 3052 } 3053 3054 // If this is a local variable, dig out its value. 3055 if (Frame) { 3056 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 3057 : Frame->getCurrentTemporary(VD); 3058 if (!Result) { 3059 // Assume variables referenced within a lambda's call operator that were 3060 // not declared within the call operator are captures and during checking 3061 // of a potential constant expression, assume they are unknown constant 3062 // expressions. 3063 assert(isLambdaCallOperator(Frame->Callee) && 3064 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3065 "missing value for local variable"); 3066 if (Info.checkingPotentialConstantExpression()) 3067 return false; 3068 // FIXME: implement capture evaluation during constant expr evaluation. 3069 Info.FFDiag(E->getBeginLoc(), 3070 diag::note_unimplemented_constexpr_lambda_feature_ast) 3071 << "captures not currently allowed"; 3072 return false; 3073 } 3074 return true; 3075 } 3076 3077 // Dig out the initializer, and use the declaration which it's attached to. 3078 // FIXME: We should eventually check whether the variable has a reachable 3079 // initializing declaration. 3080 const Expr *Init = VD->getAnyInitializer(VD); 3081 if (!Init) { 3082 // Don't diagnose during potential constant expression checking; an 3083 // initializer might be added later. 3084 if (!Info.checkingPotentialConstantExpression()) { 3085 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3086 << VD; 3087 Info.Note(VD->getLocation(), diag::note_declared_at); 3088 } 3089 return false; 3090 } 3091 3092 if (Init->isValueDependent()) { 3093 // The DeclRefExpr is not value-dependent, but the variable it refers to 3094 // has a value-dependent initializer. This should only happen in 3095 // constant-folding cases, where the variable is not actually of a suitable 3096 // type for use in a constant expression (otherwise the DeclRefExpr would 3097 // have been value-dependent too), so diagnose that. 3098 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3099 if (!Info.checkingPotentialConstantExpression()) { 3100 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3101 ? diag::note_constexpr_ltor_non_constexpr 3102 : diag::note_constexpr_ltor_non_integral, 1) 3103 << VD << VD->getType(); 3104 Info.Note(VD->getLocation(), diag::note_declared_at); 3105 } 3106 return false; 3107 } 3108 3109 // If we're currently evaluating the initializer of this declaration, use that 3110 // in-flight value. 3111 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 3112 Result = Info.EvaluatingDeclValue; 3113 return true; 3114 } 3115 3116 // Check that we can fold the initializer. In C++, we will have already done 3117 // this in the cases where it matters for conformance. 3118 SmallVector<PartialDiagnosticAt, 8> Notes; 3119 if (!VD->evaluateValue(Notes)) { 3120 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 3121 Notes.size() + 1) << VD; 3122 Info.Note(VD->getLocation(), diag::note_declared_at); 3123 Info.addNotes(Notes); 3124 return false; 3125 } 3126 3127 // Check that the variable is actually usable in constant expressions. 3128 if (!VD->checkInitIsICE()) { 3129 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 3130 Notes.size() + 1) << VD; 3131 Info.Note(VD->getLocation(), diag::note_declared_at); 3132 Info.addNotes(Notes); 3133 } 3134 3135 // Never use the initializer of a weak variable, not even for constant 3136 // folding. We can't be sure that this is the definition that will be used. 3137 if (VD->isWeak()) { 3138 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3139 Info.Note(VD->getLocation(), diag::note_declared_at); 3140 return false; 3141 } 3142 3143 Result = VD->getEvaluatedValue(); 3144 return true; 3145 } 3146 3147 static bool IsConstNonVolatile(QualType T) { 3148 Qualifiers Quals = T.getQualifiers(); 3149 return Quals.hasConst() && !Quals.hasVolatile(); 3150 } 3151 3152 /// Get the base index of the given base class within an APValue representing 3153 /// the given derived class. 3154 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3155 const CXXRecordDecl *Base) { 3156 Base = Base->getCanonicalDecl(); 3157 unsigned Index = 0; 3158 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3159 E = Derived->bases_end(); I != E; ++I, ++Index) { 3160 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3161 return Index; 3162 } 3163 3164 llvm_unreachable("base class missing from derived class's bases list"); 3165 } 3166 3167 /// Extract the value of a character from a string literal. 3168 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3169 uint64_t Index) { 3170 assert(!isa<SourceLocExpr>(Lit) && 3171 "SourceLocExpr should have already been converted to a StringLiteral"); 3172 3173 // FIXME: Support MakeStringConstant 3174 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3175 std::string Str; 3176 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3177 assert(Index <= Str.size() && "Index too large"); 3178 return APSInt::getUnsigned(Str.c_str()[Index]); 3179 } 3180 3181 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3182 Lit = PE->getFunctionName(); 3183 const StringLiteral *S = cast<StringLiteral>(Lit); 3184 const ConstantArrayType *CAT = 3185 Info.Ctx.getAsConstantArrayType(S->getType()); 3186 assert(CAT && "string literal isn't an array"); 3187 QualType CharType = CAT->getElementType(); 3188 assert(CharType->isIntegerType() && "unexpected character type"); 3189 3190 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3191 CharType->isUnsignedIntegerType()); 3192 if (Index < S->getLength()) 3193 Value = S->getCodeUnit(Index); 3194 return Value; 3195 } 3196 3197 // Expand a string literal into an array of characters. 3198 // 3199 // FIXME: This is inefficient; we should probably introduce something similar 3200 // to the LLVM ConstantDataArray to make this cheaper. 3201 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3202 APValue &Result, 3203 QualType AllocType = QualType()) { 3204 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3205 AllocType.isNull() ? S->getType() : AllocType); 3206 assert(CAT && "string literal isn't an array"); 3207 QualType CharType = CAT->getElementType(); 3208 assert(CharType->isIntegerType() && "unexpected character type"); 3209 3210 unsigned Elts = CAT->getSize().getZExtValue(); 3211 Result = APValue(APValue::UninitArray(), 3212 std::min(S->getLength(), Elts), Elts); 3213 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3214 CharType->isUnsignedIntegerType()); 3215 if (Result.hasArrayFiller()) 3216 Result.getArrayFiller() = APValue(Value); 3217 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3218 Value = S->getCodeUnit(I); 3219 Result.getArrayInitializedElt(I) = APValue(Value); 3220 } 3221 } 3222 3223 // Expand an array so that it has more than Index filled elements. 3224 static void expandArray(APValue &Array, unsigned Index) { 3225 unsigned Size = Array.getArraySize(); 3226 assert(Index < Size); 3227 3228 // Always at least double the number of elements for which we store a value. 3229 unsigned OldElts = Array.getArrayInitializedElts(); 3230 unsigned NewElts = std::max(Index+1, OldElts * 2); 3231 NewElts = std::min(Size, std::max(NewElts, 8u)); 3232 3233 // Copy the data across. 3234 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3235 for (unsigned I = 0; I != OldElts; ++I) 3236 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3237 for (unsigned I = OldElts; I != NewElts; ++I) 3238 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3239 if (NewValue.hasArrayFiller()) 3240 NewValue.getArrayFiller() = Array.getArrayFiller(); 3241 Array.swap(NewValue); 3242 } 3243 3244 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3245 /// conversion. If it's of class type, we may assume that the copy operation 3246 /// is trivial. Note that this is never true for a union type with fields 3247 /// (because the copy always "reads" the active member) and always true for 3248 /// a non-class type. 3249 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3250 static bool isReadByLvalueToRvalueConversion(QualType T) { 3251 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3252 return !RD || isReadByLvalueToRvalueConversion(RD); 3253 } 3254 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3255 // FIXME: A trivial copy of a union copies the object representation, even if 3256 // the union is empty. 3257 if (RD->isUnion()) 3258 return !RD->field_empty(); 3259 if (RD->isEmpty()) 3260 return false; 3261 3262 for (auto *Field : RD->fields()) 3263 if (!Field->isUnnamedBitfield() && 3264 isReadByLvalueToRvalueConversion(Field->getType())) 3265 return true; 3266 3267 for (auto &BaseSpec : RD->bases()) 3268 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3269 return true; 3270 3271 return false; 3272 } 3273 3274 /// Diagnose an attempt to read from any unreadable field within the specified 3275 /// type, which might be a class type. 3276 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3277 QualType T) { 3278 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3279 if (!RD) 3280 return false; 3281 3282 if (!RD->hasMutableFields()) 3283 return false; 3284 3285 for (auto *Field : RD->fields()) { 3286 // If we're actually going to read this field in some way, then it can't 3287 // be mutable. If we're in a union, then assigning to a mutable field 3288 // (even an empty one) can change the active member, so that's not OK. 3289 // FIXME: Add core issue number for the union case. 3290 if (Field->isMutable() && 3291 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3292 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3293 Info.Note(Field->getLocation(), diag::note_declared_at); 3294 return true; 3295 } 3296 3297 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3298 return true; 3299 } 3300 3301 for (auto &BaseSpec : RD->bases()) 3302 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3303 return true; 3304 3305 // All mutable fields were empty, and thus not actually read. 3306 return false; 3307 } 3308 3309 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3310 APValue::LValueBase Base, 3311 bool MutableSubobject = false) { 3312 // A temporary we created. 3313 if (Base.getCallIndex()) 3314 return true; 3315 3316 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3317 if (!Evaluating) 3318 return false; 3319 3320 auto *BaseD = Base.dyn_cast<const ValueDecl*>(); 3321 3322 switch (Info.IsEvaluatingDecl) { 3323 case EvalInfo::EvaluatingDeclKind::None: 3324 return false; 3325 3326 case EvalInfo::EvaluatingDeclKind::Ctor: 3327 // The variable whose initializer we're evaluating. 3328 if (BaseD) 3329 return declaresSameEntity(Evaluating, BaseD); 3330 3331 // A temporary lifetime-extended by the variable whose initializer we're 3332 // evaluating. 3333 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3334 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3335 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating); 3336 return false; 3337 3338 case EvalInfo::EvaluatingDeclKind::Dtor: 3339 // C++2a [expr.const]p6: 3340 // [during constant destruction] the lifetime of a and its non-mutable 3341 // subobjects (but not its mutable subobjects) [are] considered to start 3342 // within e. 3343 // 3344 // FIXME: We can meaningfully extend this to cover non-const objects, but 3345 // we will need special handling: we should be able to access only 3346 // subobjects of such objects that are themselves declared const. 3347 if (!BaseD || 3348 !(BaseD->getType().isConstQualified() || 3349 BaseD->getType()->isReferenceType()) || 3350 MutableSubobject) 3351 return false; 3352 return declaresSameEntity(Evaluating, BaseD); 3353 } 3354 3355 llvm_unreachable("unknown evaluating decl kind"); 3356 } 3357 3358 namespace { 3359 /// A handle to a complete object (an object that is not a subobject of 3360 /// another object). 3361 struct CompleteObject { 3362 /// The identity of the object. 3363 APValue::LValueBase Base; 3364 /// The value of the complete object. 3365 APValue *Value; 3366 /// The type of the complete object. 3367 QualType Type; 3368 3369 CompleteObject() : Value(nullptr) {} 3370 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3371 : Base(Base), Value(Value), Type(Type) {} 3372 3373 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3374 // If this isn't a "real" access (eg, if it's just accessing the type 3375 // info), allow it. We assume the type doesn't change dynamically for 3376 // subobjects of constexpr objects (even though we'd hit UB here if it 3377 // did). FIXME: Is this right? 3378 if (!isAnyAccess(AK)) 3379 return true; 3380 3381 // In C++14 onwards, it is permitted to read a mutable member whose 3382 // lifetime began within the evaluation. 3383 // FIXME: Should we also allow this in C++11? 3384 if (!Info.getLangOpts().CPlusPlus14) 3385 return false; 3386 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3387 } 3388 3389 explicit operator bool() const { return !Type.isNull(); } 3390 }; 3391 } // end anonymous namespace 3392 3393 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3394 bool IsMutable = false) { 3395 // C++ [basic.type.qualifier]p1: 3396 // - A const object is an object of type const T or a non-mutable subobject 3397 // of a const object. 3398 if (ObjType.isConstQualified() && !IsMutable) 3399 SubobjType.addConst(); 3400 // - A volatile object is an object of type const T or a subobject of a 3401 // volatile object. 3402 if (ObjType.isVolatileQualified()) 3403 SubobjType.addVolatile(); 3404 return SubobjType; 3405 } 3406 3407 /// Find the designated sub-object of an rvalue. 3408 template<typename SubobjectHandler> 3409 typename SubobjectHandler::result_type 3410 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3411 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3412 if (Sub.Invalid) 3413 // A diagnostic will have already been produced. 3414 return handler.failed(); 3415 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3416 if (Info.getLangOpts().CPlusPlus11) 3417 Info.FFDiag(E, Sub.isOnePastTheEnd() 3418 ? diag::note_constexpr_access_past_end 3419 : diag::note_constexpr_access_unsized_array) 3420 << handler.AccessKind; 3421 else 3422 Info.FFDiag(E); 3423 return handler.failed(); 3424 } 3425 3426 APValue *O = Obj.Value; 3427 QualType ObjType = Obj.Type; 3428 const FieldDecl *LastField = nullptr; 3429 const FieldDecl *VolatileField = nullptr; 3430 3431 // Walk the designator's path to find the subobject. 3432 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3433 // Reading an indeterminate value is undefined, but assigning over one is OK. 3434 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3435 (O->isIndeterminate() && 3436 !isValidIndeterminateAccess(handler.AccessKind))) { 3437 if (!Info.checkingPotentialConstantExpression()) 3438 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3439 << handler.AccessKind << O->isIndeterminate(); 3440 return handler.failed(); 3441 } 3442 3443 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3444 // const and volatile semantics are not applied on an object under 3445 // {con,de}struction. 3446 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3447 ObjType->isRecordType() && 3448 Info.isEvaluatingCtorDtor( 3449 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3450 Sub.Entries.begin() + I)) != 3451 ConstructionPhase::None) { 3452 ObjType = Info.Ctx.getCanonicalType(ObjType); 3453 ObjType.removeLocalConst(); 3454 ObjType.removeLocalVolatile(); 3455 } 3456 3457 // If this is our last pass, check that the final object type is OK. 3458 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3459 // Accesses to volatile objects are prohibited. 3460 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3461 if (Info.getLangOpts().CPlusPlus) { 3462 int DiagKind; 3463 SourceLocation Loc; 3464 const NamedDecl *Decl = nullptr; 3465 if (VolatileField) { 3466 DiagKind = 2; 3467 Loc = VolatileField->getLocation(); 3468 Decl = VolatileField; 3469 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3470 DiagKind = 1; 3471 Loc = VD->getLocation(); 3472 Decl = VD; 3473 } else { 3474 DiagKind = 0; 3475 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3476 Loc = E->getExprLoc(); 3477 } 3478 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3479 << handler.AccessKind << DiagKind << Decl; 3480 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3481 } else { 3482 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3483 } 3484 return handler.failed(); 3485 } 3486 3487 // If we are reading an object of class type, there may still be more 3488 // things we need to check: if there are any mutable subobjects, we 3489 // cannot perform this read. (This only happens when performing a trivial 3490 // copy or assignment.) 3491 if (ObjType->isRecordType() && 3492 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3493 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3494 return handler.failed(); 3495 } 3496 3497 if (I == N) { 3498 if (!handler.found(*O, ObjType)) 3499 return false; 3500 3501 // If we modified a bit-field, truncate it to the right width. 3502 if (isModification(handler.AccessKind) && 3503 LastField && LastField->isBitField() && 3504 !truncateBitfieldValue(Info, E, *O, LastField)) 3505 return false; 3506 3507 return true; 3508 } 3509 3510 LastField = nullptr; 3511 if (ObjType->isArrayType()) { 3512 // Next subobject is an array element. 3513 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3514 assert(CAT && "vla in literal type?"); 3515 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3516 if (CAT->getSize().ule(Index)) { 3517 // Note, it should not be possible to form a pointer with a valid 3518 // designator which points more than one past the end of the array. 3519 if (Info.getLangOpts().CPlusPlus11) 3520 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3521 << handler.AccessKind; 3522 else 3523 Info.FFDiag(E); 3524 return handler.failed(); 3525 } 3526 3527 ObjType = CAT->getElementType(); 3528 3529 if (O->getArrayInitializedElts() > Index) 3530 O = &O->getArrayInitializedElt(Index); 3531 else if (!isRead(handler.AccessKind)) { 3532 expandArray(*O, Index); 3533 O = &O->getArrayInitializedElt(Index); 3534 } else 3535 O = &O->getArrayFiller(); 3536 } else if (ObjType->isAnyComplexType()) { 3537 // Next subobject is a complex number. 3538 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3539 if (Index > 1) { 3540 if (Info.getLangOpts().CPlusPlus11) 3541 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3542 << handler.AccessKind; 3543 else 3544 Info.FFDiag(E); 3545 return handler.failed(); 3546 } 3547 3548 ObjType = getSubobjectType( 3549 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3550 3551 assert(I == N - 1 && "extracting subobject of scalar?"); 3552 if (O->isComplexInt()) { 3553 return handler.found(Index ? O->getComplexIntImag() 3554 : O->getComplexIntReal(), ObjType); 3555 } else { 3556 assert(O->isComplexFloat()); 3557 return handler.found(Index ? O->getComplexFloatImag() 3558 : O->getComplexFloatReal(), ObjType); 3559 } 3560 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3561 if (Field->isMutable() && 3562 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3563 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3564 << handler.AccessKind << Field; 3565 Info.Note(Field->getLocation(), diag::note_declared_at); 3566 return handler.failed(); 3567 } 3568 3569 // Next subobject is a class, struct or union field. 3570 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3571 if (RD->isUnion()) { 3572 const FieldDecl *UnionField = O->getUnionField(); 3573 if (!UnionField || 3574 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3575 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3576 // Placement new onto an inactive union member makes it active. 3577 O->setUnion(Field, APValue()); 3578 } else { 3579 // FIXME: If O->getUnionValue() is absent, report that there's no 3580 // active union member rather than reporting the prior active union 3581 // member. We'll need to fix nullptr_t to not use APValue() as its 3582 // representation first. 3583 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3584 << handler.AccessKind << Field << !UnionField << UnionField; 3585 return handler.failed(); 3586 } 3587 } 3588 O = &O->getUnionValue(); 3589 } else 3590 O = &O->getStructField(Field->getFieldIndex()); 3591 3592 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3593 LastField = Field; 3594 if (Field->getType().isVolatileQualified()) 3595 VolatileField = Field; 3596 } else { 3597 // Next subobject is a base class. 3598 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3599 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3600 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3601 3602 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3603 } 3604 } 3605 } 3606 3607 namespace { 3608 struct ExtractSubobjectHandler { 3609 EvalInfo &Info; 3610 const Expr *E; 3611 APValue &Result; 3612 const AccessKinds AccessKind; 3613 3614 typedef bool result_type; 3615 bool failed() { return false; } 3616 bool found(APValue &Subobj, QualType SubobjType) { 3617 Result = Subobj; 3618 if (AccessKind == AK_ReadObjectRepresentation) 3619 return true; 3620 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3621 } 3622 bool found(APSInt &Value, QualType SubobjType) { 3623 Result = APValue(Value); 3624 return true; 3625 } 3626 bool found(APFloat &Value, QualType SubobjType) { 3627 Result = APValue(Value); 3628 return true; 3629 } 3630 }; 3631 } // end anonymous namespace 3632 3633 /// Extract the designated sub-object of an rvalue. 3634 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3635 const CompleteObject &Obj, 3636 const SubobjectDesignator &Sub, APValue &Result, 3637 AccessKinds AK = AK_Read) { 3638 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3639 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3640 return findSubobject(Info, E, Obj, Sub, Handler); 3641 } 3642 3643 namespace { 3644 struct ModifySubobjectHandler { 3645 EvalInfo &Info; 3646 APValue &NewVal; 3647 const Expr *E; 3648 3649 typedef bool result_type; 3650 static const AccessKinds AccessKind = AK_Assign; 3651 3652 bool checkConst(QualType QT) { 3653 // Assigning to a const object has undefined behavior. 3654 if (QT.isConstQualified()) { 3655 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3656 return false; 3657 } 3658 return true; 3659 } 3660 3661 bool failed() { return false; } 3662 bool found(APValue &Subobj, QualType SubobjType) { 3663 if (!checkConst(SubobjType)) 3664 return false; 3665 // We've been given ownership of NewVal, so just swap it in. 3666 Subobj.swap(NewVal); 3667 return true; 3668 } 3669 bool found(APSInt &Value, QualType SubobjType) { 3670 if (!checkConst(SubobjType)) 3671 return false; 3672 if (!NewVal.isInt()) { 3673 // Maybe trying to write a cast pointer value into a complex? 3674 Info.FFDiag(E); 3675 return false; 3676 } 3677 Value = NewVal.getInt(); 3678 return true; 3679 } 3680 bool found(APFloat &Value, QualType SubobjType) { 3681 if (!checkConst(SubobjType)) 3682 return false; 3683 Value = NewVal.getFloat(); 3684 return true; 3685 } 3686 }; 3687 } // end anonymous namespace 3688 3689 const AccessKinds ModifySubobjectHandler::AccessKind; 3690 3691 /// Update the designated sub-object of an rvalue to the given value. 3692 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3693 const CompleteObject &Obj, 3694 const SubobjectDesignator &Sub, 3695 APValue &NewVal) { 3696 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3697 return findSubobject(Info, E, Obj, Sub, Handler); 3698 } 3699 3700 /// Find the position where two subobject designators diverge, or equivalently 3701 /// the length of the common initial subsequence. 3702 static unsigned FindDesignatorMismatch(QualType ObjType, 3703 const SubobjectDesignator &A, 3704 const SubobjectDesignator &B, 3705 bool &WasArrayIndex) { 3706 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3707 for (/**/; I != N; ++I) { 3708 if (!ObjType.isNull() && 3709 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3710 // Next subobject is an array element. 3711 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3712 WasArrayIndex = true; 3713 return I; 3714 } 3715 if (ObjType->isAnyComplexType()) 3716 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3717 else 3718 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3719 } else { 3720 if (A.Entries[I].getAsBaseOrMember() != 3721 B.Entries[I].getAsBaseOrMember()) { 3722 WasArrayIndex = false; 3723 return I; 3724 } 3725 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3726 // Next subobject is a field. 3727 ObjType = FD->getType(); 3728 else 3729 // Next subobject is a base class. 3730 ObjType = QualType(); 3731 } 3732 } 3733 WasArrayIndex = false; 3734 return I; 3735 } 3736 3737 /// Determine whether the given subobject designators refer to elements of the 3738 /// same array object. 3739 static bool AreElementsOfSameArray(QualType ObjType, 3740 const SubobjectDesignator &A, 3741 const SubobjectDesignator &B) { 3742 if (A.Entries.size() != B.Entries.size()) 3743 return false; 3744 3745 bool IsArray = A.MostDerivedIsArrayElement; 3746 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3747 // A is a subobject of the array element. 3748 return false; 3749 3750 // If A (and B) designates an array element, the last entry will be the array 3751 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3752 // of length 1' case, and the entire path must match. 3753 bool WasArrayIndex; 3754 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3755 return CommonLength >= A.Entries.size() - IsArray; 3756 } 3757 3758 /// Find the complete object to which an LValue refers. 3759 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3760 AccessKinds AK, const LValue &LVal, 3761 QualType LValType) { 3762 if (LVal.InvalidBase) { 3763 Info.FFDiag(E); 3764 return CompleteObject(); 3765 } 3766 3767 if (!LVal.Base) { 3768 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3769 return CompleteObject(); 3770 } 3771 3772 CallStackFrame *Frame = nullptr; 3773 unsigned Depth = 0; 3774 if (LVal.getLValueCallIndex()) { 3775 std::tie(Frame, Depth) = 3776 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3777 if (!Frame) { 3778 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3779 << AK << LVal.Base.is<const ValueDecl*>(); 3780 NoteLValueLocation(Info, LVal.Base); 3781 return CompleteObject(); 3782 } 3783 } 3784 3785 bool IsAccess = isAnyAccess(AK); 3786 3787 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3788 // is not a constant expression (even if the object is non-volatile). We also 3789 // apply this rule to C++98, in order to conform to the expected 'volatile' 3790 // semantics. 3791 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3792 if (Info.getLangOpts().CPlusPlus) 3793 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3794 << AK << LValType; 3795 else 3796 Info.FFDiag(E); 3797 return CompleteObject(); 3798 } 3799 3800 // Compute value storage location and type of base object. 3801 APValue *BaseVal = nullptr; 3802 QualType BaseType = getType(LVal.Base); 3803 3804 if (const ConstantExpr *CE = 3805 dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) { 3806 /// Nested immediate invocation have been previously removed so if we found 3807 /// a ConstantExpr it can only be the EvaluatingDecl. 3808 assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl); 3809 (void)CE; 3810 BaseVal = Info.EvaluatingDeclValue; 3811 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3812 // Allow reading from a GUID declaration. 3813 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 3814 if (isModification(AK)) { 3815 // All the remaining cases do not permit modification of the object. 3816 Info.FFDiag(E, diag::note_constexpr_modify_global); 3817 return CompleteObject(); 3818 } 3819 APValue &V = GD->getAsAPValue(); 3820 if (V.isAbsent()) { 3821 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 3822 << GD->getType(); 3823 return CompleteObject(); 3824 } 3825 return CompleteObject(LVal.Base, &V, GD->getType()); 3826 } 3827 3828 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3829 // In C++11, constexpr, non-volatile variables initialized with constant 3830 // expressions are constant expressions too. Inside constexpr functions, 3831 // parameters are constant expressions even if they're non-const. 3832 // In C++1y, objects local to a constant expression (those with a Frame) are 3833 // both readable and writable inside constant expressions. 3834 // In C, such things can also be folded, although they are not ICEs. 3835 const VarDecl *VD = dyn_cast<VarDecl>(D); 3836 if (VD) { 3837 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3838 VD = VDef; 3839 } 3840 if (!VD || VD->isInvalidDecl()) { 3841 Info.FFDiag(E); 3842 return CompleteObject(); 3843 } 3844 3845 // In OpenCL if a variable is in constant address space it is a const value. 3846 bool IsConstant = BaseType.isConstQualified() || 3847 (Info.getLangOpts().OpenCL && 3848 BaseType.getAddressSpace() == LangAS::opencl_constant); 3849 3850 // Unless we're looking at a local variable or argument in a constexpr call, 3851 // the variable we're reading must be const. 3852 if (!Frame) { 3853 if (Info.getLangOpts().CPlusPlus14 && 3854 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3855 // OK, we can read and modify an object if we're in the process of 3856 // evaluating its initializer, because its lifetime began in this 3857 // evaluation. 3858 } else if (isModification(AK)) { 3859 // All the remaining cases do not permit modification of the object. 3860 Info.FFDiag(E, diag::note_constexpr_modify_global); 3861 return CompleteObject(); 3862 } else if (VD->isConstexpr()) { 3863 // OK, we can read this variable. 3864 } else if (BaseType->isIntegralOrEnumerationType()) { 3865 // In OpenCL if a variable is in constant address space it is a const 3866 // value. 3867 if (!IsConstant) { 3868 if (!IsAccess) 3869 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3870 if (Info.getLangOpts().CPlusPlus) { 3871 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3872 Info.Note(VD->getLocation(), diag::note_declared_at); 3873 } else { 3874 Info.FFDiag(E); 3875 } 3876 return CompleteObject(); 3877 } 3878 } else if (!IsAccess) { 3879 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3880 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 3881 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 3882 // This variable might end up being constexpr. Don't diagnose it yet. 3883 } else if (IsConstant) { 3884 // Keep evaluating to see what we can do. In particular, we support 3885 // folding of const floating-point types, in order to make static const 3886 // data members of such types (supported as an extension) more useful. 3887 if (Info.getLangOpts().CPlusPlus) { 3888 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 3889 ? diag::note_constexpr_ltor_non_constexpr 3890 : diag::note_constexpr_ltor_non_integral, 1) 3891 << VD << BaseType; 3892 Info.Note(VD->getLocation(), diag::note_declared_at); 3893 } else { 3894 Info.CCEDiag(E); 3895 } 3896 } else { 3897 // Never allow reading a non-const value. 3898 if (Info.getLangOpts().CPlusPlus) { 3899 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3900 ? diag::note_constexpr_ltor_non_constexpr 3901 : diag::note_constexpr_ltor_non_integral, 1) 3902 << VD << BaseType; 3903 Info.Note(VD->getLocation(), diag::note_declared_at); 3904 } else { 3905 Info.FFDiag(E); 3906 } 3907 return CompleteObject(); 3908 } 3909 } 3910 3911 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3912 return CompleteObject(); 3913 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 3914 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 3915 if (!Alloc) { 3916 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 3917 return CompleteObject(); 3918 } 3919 return CompleteObject(LVal.Base, &(*Alloc)->Value, 3920 LVal.Base.getDynamicAllocType()); 3921 } else { 3922 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3923 3924 if (!Frame) { 3925 if (const MaterializeTemporaryExpr *MTE = 3926 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 3927 assert(MTE->getStorageDuration() == SD_Static && 3928 "should have a frame for a non-global materialized temporary"); 3929 3930 // Per C++1y [expr.const]p2: 3931 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3932 // - a [...] glvalue of integral or enumeration type that refers to 3933 // a non-volatile const object [...] 3934 // [...] 3935 // - a [...] glvalue of literal type that refers to a non-volatile 3936 // object whose lifetime began within the evaluation of e. 3937 // 3938 // C++11 misses the 'began within the evaluation of e' check and 3939 // instead allows all temporaries, including things like: 3940 // int &&r = 1; 3941 // int x = ++r; 3942 // constexpr int k = r; 3943 // Therefore we use the C++14 rules in C++11 too. 3944 // 3945 // Note that temporaries whose lifetimes began while evaluating a 3946 // variable's constructor are not usable while evaluating the 3947 // corresponding destructor, not even if they're of const-qualified 3948 // types. 3949 if (!(BaseType.isConstQualified() && 3950 BaseType->isIntegralOrEnumerationType()) && 3951 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 3952 if (!IsAccess) 3953 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3954 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3955 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3956 return CompleteObject(); 3957 } 3958 3959 BaseVal = MTE->getOrCreateValue(false); 3960 assert(BaseVal && "got reference to unevaluated temporary"); 3961 } else { 3962 if (!IsAccess) 3963 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3964 APValue Val; 3965 LVal.moveInto(Val); 3966 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 3967 << AK 3968 << Val.getAsString(Info.Ctx, 3969 Info.Ctx.getLValueReferenceType(LValType)); 3970 NoteLValueLocation(Info, LVal.Base); 3971 return CompleteObject(); 3972 } 3973 } else { 3974 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 3975 assert(BaseVal && "missing value for temporary"); 3976 } 3977 } 3978 3979 // In C++14, we can't safely access any mutable state when we might be 3980 // evaluating after an unmodeled side effect. 3981 // 3982 // FIXME: Not all local state is mutable. Allow local constant subobjects 3983 // to be read here (but take care with 'mutable' fields). 3984 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3985 Info.EvalStatus.HasSideEffects) || 3986 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth)) 3987 return CompleteObject(); 3988 3989 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 3990 } 3991 3992 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 3993 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3994 /// glvalue referred to by an entity of reference type. 3995 /// 3996 /// \param Info - Information about the ongoing evaluation. 3997 /// \param Conv - The expression for which we are performing the conversion. 3998 /// Used for diagnostics. 3999 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4000 /// case of a non-class type). 4001 /// \param LVal - The glvalue on which we are attempting to perform this action. 4002 /// \param RVal - The produced value will be placed here. 4003 /// \param WantObjectRepresentation - If true, we're looking for the object 4004 /// representation rather than the value, and in particular, 4005 /// there is no requirement that the result be fully initialized. 4006 static bool 4007 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4008 const LValue &LVal, APValue &RVal, 4009 bool WantObjectRepresentation = false) { 4010 if (LVal.Designator.Invalid) 4011 return false; 4012 4013 // Check for special cases where there is no existing APValue to look at. 4014 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4015 4016 AccessKinds AK = 4017 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4018 4019 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4020 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4021 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4022 // initializer until now for such expressions. Such an expression can't be 4023 // an ICE in C, so this only matters for fold. 4024 if (Type.isVolatileQualified()) { 4025 Info.FFDiag(Conv); 4026 return false; 4027 } 4028 APValue Lit; 4029 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4030 return false; 4031 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4032 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4033 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4034 // Special-case character extraction so we don't have to construct an 4035 // APValue for the whole string. 4036 assert(LVal.Designator.Entries.size() <= 1 && 4037 "Can only read characters from string literals"); 4038 if (LVal.Designator.Entries.empty()) { 4039 // Fail for now for LValue to RValue conversion of an array. 4040 // (This shouldn't show up in C/C++, but it could be triggered by a 4041 // weird EvaluateAsRValue call from a tool.) 4042 Info.FFDiag(Conv); 4043 return false; 4044 } 4045 if (LVal.Designator.isOnePastTheEnd()) { 4046 if (Info.getLangOpts().CPlusPlus11) 4047 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4048 else 4049 Info.FFDiag(Conv); 4050 return false; 4051 } 4052 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4053 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4054 return true; 4055 } 4056 } 4057 4058 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4059 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4060 } 4061 4062 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4063 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4064 QualType LValType, APValue &Val) { 4065 if (LVal.Designator.Invalid) 4066 return false; 4067 4068 if (!Info.getLangOpts().CPlusPlus14) { 4069 Info.FFDiag(E); 4070 return false; 4071 } 4072 4073 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4074 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4075 } 4076 4077 namespace { 4078 struct CompoundAssignSubobjectHandler { 4079 EvalInfo &Info; 4080 const Expr *E; 4081 QualType PromotedLHSType; 4082 BinaryOperatorKind Opcode; 4083 const APValue &RHS; 4084 4085 static const AccessKinds AccessKind = AK_Assign; 4086 4087 typedef bool result_type; 4088 4089 bool checkConst(QualType QT) { 4090 // Assigning to a const object has undefined behavior. 4091 if (QT.isConstQualified()) { 4092 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4093 return false; 4094 } 4095 return true; 4096 } 4097 4098 bool failed() { return false; } 4099 bool found(APValue &Subobj, QualType SubobjType) { 4100 switch (Subobj.getKind()) { 4101 case APValue::Int: 4102 return found(Subobj.getInt(), SubobjType); 4103 case APValue::Float: 4104 return found(Subobj.getFloat(), SubobjType); 4105 case APValue::ComplexInt: 4106 case APValue::ComplexFloat: 4107 // FIXME: Implement complex compound assignment. 4108 Info.FFDiag(E); 4109 return false; 4110 case APValue::LValue: 4111 return foundPointer(Subobj, SubobjType); 4112 case APValue::Vector: 4113 return foundVector(Subobj, SubobjType); 4114 default: 4115 // FIXME: can this happen? 4116 Info.FFDiag(E); 4117 return false; 4118 } 4119 } 4120 4121 bool foundVector(APValue &Value, QualType SubobjType) { 4122 if (!checkConst(SubobjType)) 4123 return false; 4124 4125 if (!SubobjType->isVectorType()) { 4126 Info.FFDiag(E); 4127 return false; 4128 } 4129 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4130 } 4131 4132 bool found(APSInt &Value, QualType SubobjType) { 4133 if (!checkConst(SubobjType)) 4134 return false; 4135 4136 if (!SubobjType->isIntegerType()) { 4137 // We don't support compound assignment on integer-cast-to-pointer 4138 // values. 4139 Info.FFDiag(E); 4140 return false; 4141 } 4142 4143 if (RHS.isInt()) { 4144 APSInt LHS = 4145 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4146 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4147 return false; 4148 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4149 return true; 4150 } else if (RHS.isFloat()) { 4151 APFloat FValue(0.0); 4152 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, 4153 FValue) && 4154 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4155 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4156 Value); 4157 } 4158 4159 Info.FFDiag(E); 4160 return false; 4161 } 4162 bool found(APFloat &Value, QualType SubobjType) { 4163 return checkConst(SubobjType) && 4164 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4165 Value) && 4166 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4167 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4168 } 4169 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4170 if (!checkConst(SubobjType)) 4171 return false; 4172 4173 QualType PointeeType; 4174 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4175 PointeeType = PT->getPointeeType(); 4176 4177 if (PointeeType.isNull() || !RHS.isInt() || 4178 (Opcode != BO_Add && Opcode != BO_Sub)) { 4179 Info.FFDiag(E); 4180 return false; 4181 } 4182 4183 APSInt Offset = RHS.getInt(); 4184 if (Opcode == BO_Sub) 4185 negateAsSigned(Offset); 4186 4187 LValue LVal; 4188 LVal.setFrom(Info.Ctx, Subobj); 4189 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4190 return false; 4191 LVal.moveInto(Subobj); 4192 return true; 4193 } 4194 }; 4195 } // end anonymous namespace 4196 4197 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4198 4199 /// Perform a compound assignment of LVal <op>= RVal. 4200 static bool handleCompoundAssignment( 4201 EvalInfo &Info, const Expr *E, 4202 const LValue &LVal, QualType LValType, QualType PromotedLValType, 4203 BinaryOperatorKind Opcode, const APValue &RVal) { 4204 if (LVal.Designator.Invalid) 4205 return false; 4206 4207 if (!Info.getLangOpts().CPlusPlus14) { 4208 Info.FFDiag(E); 4209 return false; 4210 } 4211 4212 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4213 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4214 RVal }; 4215 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4216 } 4217 4218 namespace { 4219 struct IncDecSubobjectHandler { 4220 EvalInfo &Info; 4221 const UnaryOperator *E; 4222 AccessKinds AccessKind; 4223 APValue *Old; 4224 4225 typedef bool result_type; 4226 4227 bool checkConst(QualType QT) { 4228 // Assigning to a const object has undefined behavior. 4229 if (QT.isConstQualified()) { 4230 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4231 return false; 4232 } 4233 return true; 4234 } 4235 4236 bool failed() { return false; } 4237 bool found(APValue &Subobj, QualType SubobjType) { 4238 // Stash the old value. Also clear Old, so we don't clobber it later 4239 // if we're post-incrementing a complex. 4240 if (Old) { 4241 *Old = Subobj; 4242 Old = nullptr; 4243 } 4244 4245 switch (Subobj.getKind()) { 4246 case APValue::Int: 4247 return found(Subobj.getInt(), SubobjType); 4248 case APValue::Float: 4249 return found(Subobj.getFloat(), SubobjType); 4250 case APValue::ComplexInt: 4251 return found(Subobj.getComplexIntReal(), 4252 SubobjType->castAs<ComplexType>()->getElementType() 4253 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4254 case APValue::ComplexFloat: 4255 return found(Subobj.getComplexFloatReal(), 4256 SubobjType->castAs<ComplexType>()->getElementType() 4257 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4258 case APValue::LValue: 4259 return foundPointer(Subobj, SubobjType); 4260 default: 4261 // FIXME: can this happen? 4262 Info.FFDiag(E); 4263 return false; 4264 } 4265 } 4266 bool found(APSInt &Value, QualType SubobjType) { 4267 if (!checkConst(SubobjType)) 4268 return false; 4269 4270 if (!SubobjType->isIntegerType()) { 4271 // We don't support increment / decrement on integer-cast-to-pointer 4272 // values. 4273 Info.FFDiag(E); 4274 return false; 4275 } 4276 4277 if (Old) *Old = APValue(Value); 4278 4279 // bool arithmetic promotes to int, and the conversion back to bool 4280 // doesn't reduce mod 2^n, so special-case it. 4281 if (SubobjType->isBooleanType()) { 4282 if (AccessKind == AK_Increment) 4283 Value = 1; 4284 else 4285 Value = !Value; 4286 return true; 4287 } 4288 4289 bool WasNegative = Value.isNegative(); 4290 if (AccessKind == AK_Increment) { 4291 ++Value; 4292 4293 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4294 APSInt ActualValue(Value, /*IsUnsigned*/true); 4295 return HandleOverflow(Info, E, ActualValue, SubobjType); 4296 } 4297 } else { 4298 --Value; 4299 4300 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4301 unsigned BitWidth = Value.getBitWidth(); 4302 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4303 ActualValue.setBit(BitWidth); 4304 return HandleOverflow(Info, E, ActualValue, SubobjType); 4305 } 4306 } 4307 return true; 4308 } 4309 bool found(APFloat &Value, QualType SubobjType) { 4310 if (!checkConst(SubobjType)) 4311 return false; 4312 4313 if (Old) *Old = APValue(Value); 4314 4315 APFloat One(Value.getSemantics(), 1); 4316 if (AccessKind == AK_Increment) 4317 Value.add(One, APFloat::rmNearestTiesToEven); 4318 else 4319 Value.subtract(One, APFloat::rmNearestTiesToEven); 4320 return true; 4321 } 4322 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4323 if (!checkConst(SubobjType)) 4324 return false; 4325 4326 QualType PointeeType; 4327 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4328 PointeeType = PT->getPointeeType(); 4329 else { 4330 Info.FFDiag(E); 4331 return false; 4332 } 4333 4334 LValue LVal; 4335 LVal.setFrom(Info.Ctx, Subobj); 4336 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4337 AccessKind == AK_Increment ? 1 : -1)) 4338 return false; 4339 LVal.moveInto(Subobj); 4340 return true; 4341 } 4342 }; 4343 } // end anonymous namespace 4344 4345 /// Perform an increment or decrement on LVal. 4346 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4347 QualType LValType, bool IsIncrement, APValue *Old) { 4348 if (LVal.Designator.Invalid) 4349 return false; 4350 4351 if (!Info.getLangOpts().CPlusPlus14) { 4352 Info.FFDiag(E); 4353 return false; 4354 } 4355 4356 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4357 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4358 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4359 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4360 } 4361 4362 /// Build an lvalue for the object argument of a member function call. 4363 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4364 LValue &This) { 4365 if (Object->getType()->isPointerType() && Object->isRValue()) 4366 return EvaluatePointer(Object, This, Info); 4367 4368 if (Object->isGLValue()) 4369 return EvaluateLValue(Object, This, Info); 4370 4371 if (Object->getType()->isLiteralType(Info.Ctx)) 4372 return EvaluateTemporary(Object, This, Info); 4373 4374 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4375 return false; 4376 } 4377 4378 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4379 /// lvalue referring to the result. 4380 /// 4381 /// \param Info - Information about the ongoing evaluation. 4382 /// \param LV - An lvalue referring to the base of the member pointer. 4383 /// \param RHS - The member pointer expression. 4384 /// \param IncludeMember - Specifies whether the member itself is included in 4385 /// the resulting LValue subobject designator. This is not possible when 4386 /// creating a bound member function. 4387 /// \return The field or method declaration to which the member pointer refers, 4388 /// or 0 if evaluation fails. 4389 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4390 QualType LVType, 4391 LValue &LV, 4392 const Expr *RHS, 4393 bool IncludeMember = true) { 4394 MemberPtr MemPtr; 4395 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4396 return nullptr; 4397 4398 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4399 // member value, the behavior is undefined. 4400 if (!MemPtr.getDecl()) { 4401 // FIXME: Specific diagnostic. 4402 Info.FFDiag(RHS); 4403 return nullptr; 4404 } 4405 4406 if (MemPtr.isDerivedMember()) { 4407 // This is a member of some derived class. Truncate LV appropriately. 4408 // The end of the derived-to-base path for the base object must match the 4409 // derived-to-base path for the member pointer. 4410 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4411 LV.Designator.Entries.size()) { 4412 Info.FFDiag(RHS); 4413 return nullptr; 4414 } 4415 unsigned PathLengthToMember = 4416 LV.Designator.Entries.size() - MemPtr.Path.size(); 4417 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4418 const CXXRecordDecl *LVDecl = getAsBaseClass( 4419 LV.Designator.Entries[PathLengthToMember + I]); 4420 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4421 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4422 Info.FFDiag(RHS); 4423 return nullptr; 4424 } 4425 } 4426 4427 // Truncate the lvalue to the appropriate derived class. 4428 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4429 PathLengthToMember)) 4430 return nullptr; 4431 } else if (!MemPtr.Path.empty()) { 4432 // Extend the LValue path with the member pointer's path. 4433 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4434 MemPtr.Path.size() + IncludeMember); 4435 4436 // Walk down to the appropriate base class. 4437 if (const PointerType *PT = LVType->getAs<PointerType>()) 4438 LVType = PT->getPointeeType(); 4439 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4440 assert(RD && "member pointer access on non-class-type expression"); 4441 // The first class in the path is that of the lvalue. 4442 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4443 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4444 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4445 return nullptr; 4446 RD = Base; 4447 } 4448 // Finally cast to the class containing the member. 4449 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4450 MemPtr.getContainingRecord())) 4451 return nullptr; 4452 } 4453 4454 // Add the member. Note that we cannot build bound member functions here. 4455 if (IncludeMember) { 4456 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4457 if (!HandleLValueMember(Info, RHS, LV, FD)) 4458 return nullptr; 4459 } else if (const IndirectFieldDecl *IFD = 4460 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4461 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4462 return nullptr; 4463 } else { 4464 llvm_unreachable("can't construct reference to bound member function"); 4465 } 4466 } 4467 4468 return MemPtr.getDecl(); 4469 } 4470 4471 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4472 const BinaryOperator *BO, 4473 LValue &LV, 4474 bool IncludeMember = true) { 4475 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4476 4477 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4478 if (Info.noteFailure()) { 4479 MemberPtr MemPtr; 4480 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4481 } 4482 return nullptr; 4483 } 4484 4485 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4486 BO->getRHS(), IncludeMember); 4487 } 4488 4489 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4490 /// the provided lvalue, which currently refers to the base object. 4491 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4492 LValue &Result) { 4493 SubobjectDesignator &D = Result.Designator; 4494 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4495 return false; 4496 4497 QualType TargetQT = E->getType(); 4498 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4499 TargetQT = PT->getPointeeType(); 4500 4501 // Check this cast lands within the final derived-to-base subobject path. 4502 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4503 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4504 << D.MostDerivedType << TargetQT; 4505 return false; 4506 } 4507 4508 // Check the type of the final cast. We don't need to check the path, 4509 // since a cast can only be formed if the path is unique. 4510 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4511 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4512 const CXXRecordDecl *FinalType; 4513 if (NewEntriesSize == D.MostDerivedPathLength) 4514 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4515 else 4516 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4517 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4518 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4519 << D.MostDerivedType << TargetQT; 4520 return false; 4521 } 4522 4523 // Truncate the lvalue to the appropriate derived class. 4524 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4525 } 4526 4527 /// Get the value to use for a default-initialized object of type T. 4528 /// Return false if it encounters something invalid. 4529 static bool getDefaultInitValue(QualType T, APValue &Result) { 4530 bool Success = true; 4531 if (auto *RD = T->getAsCXXRecordDecl()) { 4532 if (RD->isInvalidDecl()) { 4533 Result = APValue(); 4534 return false; 4535 } 4536 if (RD->isUnion()) { 4537 Result = APValue((const FieldDecl *)nullptr); 4538 return true; 4539 } 4540 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4541 std::distance(RD->field_begin(), RD->field_end())); 4542 4543 unsigned Index = 0; 4544 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4545 End = RD->bases_end(); 4546 I != End; ++I, ++Index) 4547 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4548 4549 for (const auto *I : RD->fields()) { 4550 if (I->isUnnamedBitfield()) 4551 continue; 4552 Success &= getDefaultInitValue(I->getType(), 4553 Result.getStructField(I->getFieldIndex())); 4554 } 4555 return Success; 4556 } 4557 4558 if (auto *AT = 4559 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4560 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4561 if (Result.hasArrayFiller()) 4562 Success &= 4563 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4564 4565 return Success; 4566 } 4567 4568 Result = APValue::IndeterminateValue(); 4569 return true; 4570 } 4571 4572 namespace { 4573 enum EvalStmtResult { 4574 /// Evaluation failed. 4575 ESR_Failed, 4576 /// Hit a 'return' statement. 4577 ESR_Returned, 4578 /// Evaluation succeeded. 4579 ESR_Succeeded, 4580 /// Hit a 'continue' statement. 4581 ESR_Continue, 4582 /// Hit a 'break' statement. 4583 ESR_Break, 4584 /// Still scanning for 'case' or 'default' statement. 4585 ESR_CaseNotFound 4586 }; 4587 } 4588 4589 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4590 // We don't need to evaluate the initializer for a static local. 4591 if (!VD->hasLocalStorage()) 4592 return true; 4593 4594 LValue Result; 4595 APValue &Val = 4596 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result); 4597 4598 const Expr *InitE = VD->getInit(); 4599 if (!InitE) 4600 return getDefaultInitValue(VD->getType(), Val); 4601 4602 if (InitE->isValueDependent()) 4603 return false; 4604 4605 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4606 // Wipe out any partially-computed value, to allow tracking that this 4607 // evaluation failed. 4608 Val = APValue(); 4609 return false; 4610 } 4611 4612 return true; 4613 } 4614 4615 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4616 bool OK = true; 4617 4618 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4619 OK &= EvaluateVarDecl(Info, VD); 4620 4621 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4622 for (auto *BD : DD->bindings()) 4623 if (auto *VD = BD->getHoldingVar()) 4624 OK &= EvaluateDecl(Info, VD); 4625 4626 return OK; 4627 } 4628 4629 4630 /// Evaluate a condition (either a variable declaration or an expression). 4631 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4632 const Expr *Cond, bool &Result) { 4633 FullExpressionRAII Scope(Info); 4634 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4635 return false; 4636 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4637 return false; 4638 return Scope.destroy(); 4639 } 4640 4641 namespace { 4642 /// A location where the result (returned value) of evaluating a 4643 /// statement should be stored. 4644 struct StmtResult { 4645 /// The APValue that should be filled in with the returned value. 4646 APValue &Value; 4647 /// The location containing the result, if any (used to support RVO). 4648 const LValue *Slot; 4649 }; 4650 4651 struct TempVersionRAII { 4652 CallStackFrame &Frame; 4653 4654 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4655 Frame.pushTempVersion(); 4656 } 4657 4658 ~TempVersionRAII() { 4659 Frame.popTempVersion(); 4660 } 4661 }; 4662 4663 } 4664 4665 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4666 const Stmt *S, 4667 const SwitchCase *SC = nullptr); 4668 4669 /// Evaluate the body of a loop, and translate the result as appropriate. 4670 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4671 const Stmt *Body, 4672 const SwitchCase *Case = nullptr) { 4673 BlockScopeRAII Scope(Info); 4674 4675 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4676 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4677 ESR = ESR_Failed; 4678 4679 switch (ESR) { 4680 case ESR_Break: 4681 return ESR_Succeeded; 4682 case ESR_Succeeded: 4683 case ESR_Continue: 4684 return ESR_Continue; 4685 case ESR_Failed: 4686 case ESR_Returned: 4687 case ESR_CaseNotFound: 4688 return ESR; 4689 } 4690 llvm_unreachable("Invalid EvalStmtResult!"); 4691 } 4692 4693 /// Evaluate a switch statement. 4694 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4695 const SwitchStmt *SS) { 4696 BlockScopeRAII Scope(Info); 4697 4698 // Evaluate the switch condition. 4699 APSInt Value; 4700 { 4701 if (const Stmt *Init = SS->getInit()) { 4702 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4703 if (ESR != ESR_Succeeded) { 4704 if (ESR != ESR_Failed && !Scope.destroy()) 4705 ESR = ESR_Failed; 4706 return ESR; 4707 } 4708 } 4709 4710 FullExpressionRAII CondScope(Info); 4711 if (SS->getConditionVariable() && 4712 !EvaluateDecl(Info, SS->getConditionVariable())) 4713 return ESR_Failed; 4714 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4715 return ESR_Failed; 4716 if (!CondScope.destroy()) 4717 return ESR_Failed; 4718 } 4719 4720 // Find the switch case corresponding to the value of the condition. 4721 // FIXME: Cache this lookup. 4722 const SwitchCase *Found = nullptr; 4723 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4724 SC = SC->getNextSwitchCase()) { 4725 if (isa<DefaultStmt>(SC)) { 4726 Found = SC; 4727 continue; 4728 } 4729 4730 const CaseStmt *CS = cast<CaseStmt>(SC); 4731 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4732 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4733 : LHS; 4734 if (LHS <= Value && Value <= RHS) { 4735 Found = SC; 4736 break; 4737 } 4738 } 4739 4740 if (!Found) 4741 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4742 4743 // Search the switch body for the switch case and evaluate it from there. 4744 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4745 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4746 return ESR_Failed; 4747 4748 switch (ESR) { 4749 case ESR_Break: 4750 return ESR_Succeeded; 4751 case ESR_Succeeded: 4752 case ESR_Continue: 4753 case ESR_Failed: 4754 case ESR_Returned: 4755 return ESR; 4756 case ESR_CaseNotFound: 4757 // This can only happen if the switch case is nested within a statement 4758 // expression. We have no intention of supporting that. 4759 Info.FFDiag(Found->getBeginLoc(), 4760 diag::note_constexpr_stmt_expr_unsupported); 4761 return ESR_Failed; 4762 } 4763 llvm_unreachable("Invalid EvalStmtResult!"); 4764 } 4765 4766 // Evaluate a statement. 4767 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4768 const Stmt *S, const SwitchCase *Case) { 4769 if (!Info.nextStep(S)) 4770 return ESR_Failed; 4771 4772 // If we're hunting down a 'case' or 'default' label, recurse through 4773 // substatements until we hit the label. 4774 if (Case) { 4775 switch (S->getStmtClass()) { 4776 case Stmt::CompoundStmtClass: 4777 // FIXME: Precompute which substatement of a compound statement we 4778 // would jump to, and go straight there rather than performing a 4779 // linear scan each time. 4780 case Stmt::LabelStmtClass: 4781 case Stmt::AttributedStmtClass: 4782 case Stmt::DoStmtClass: 4783 break; 4784 4785 case Stmt::CaseStmtClass: 4786 case Stmt::DefaultStmtClass: 4787 if (Case == S) 4788 Case = nullptr; 4789 break; 4790 4791 case Stmt::IfStmtClass: { 4792 // FIXME: Precompute which side of an 'if' we would jump to, and go 4793 // straight there rather than scanning both sides. 4794 const IfStmt *IS = cast<IfStmt>(S); 4795 4796 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4797 // preceded by our switch label. 4798 BlockScopeRAII Scope(Info); 4799 4800 // Step into the init statement in case it brings an (uninitialized) 4801 // variable into scope. 4802 if (const Stmt *Init = IS->getInit()) { 4803 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4804 if (ESR != ESR_CaseNotFound) { 4805 assert(ESR != ESR_Succeeded); 4806 return ESR; 4807 } 4808 } 4809 4810 // Condition variable must be initialized if it exists. 4811 // FIXME: We can skip evaluating the body if there's a condition 4812 // variable, as there can't be any case labels within it. 4813 // (The same is true for 'for' statements.) 4814 4815 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4816 if (ESR == ESR_Failed) 4817 return ESR; 4818 if (ESR != ESR_CaseNotFound) 4819 return Scope.destroy() ? ESR : ESR_Failed; 4820 if (!IS->getElse()) 4821 return ESR_CaseNotFound; 4822 4823 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 4824 if (ESR == ESR_Failed) 4825 return ESR; 4826 if (ESR != ESR_CaseNotFound) 4827 return Scope.destroy() ? ESR : ESR_Failed; 4828 return ESR_CaseNotFound; 4829 } 4830 4831 case Stmt::WhileStmtClass: { 4832 EvalStmtResult ESR = 4833 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4834 if (ESR != ESR_Continue) 4835 return ESR; 4836 break; 4837 } 4838 4839 case Stmt::ForStmtClass: { 4840 const ForStmt *FS = cast<ForStmt>(S); 4841 BlockScopeRAII Scope(Info); 4842 4843 // Step into the init statement in case it brings an (uninitialized) 4844 // variable into scope. 4845 if (const Stmt *Init = FS->getInit()) { 4846 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4847 if (ESR != ESR_CaseNotFound) { 4848 assert(ESR != ESR_Succeeded); 4849 return ESR; 4850 } 4851 } 4852 4853 EvalStmtResult ESR = 4854 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4855 if (ESR != ESR_Continue) 4856 return ESR; 4857 if (FS->getInc()) { 4858 FullExpressionRAII IncScope(Info); 4859 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 4860 return ESR_Failed; 4861 } 4862 break; 4863 } 4864 4865 case Stmt::DeclStmtClass: { 4866 // Start the lifetime of any uninitialized variables we encounter. They 4867 // might be used by the selected branch of the switch. 4868 const DeclStmt *DS = cast<DeclStmt>(S); 4869 for (const auto *D : DS->decls()) { 4870 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4871 if (VD->hasLocalStorage() && !VD->getInit()) 4872 if (!EvaluateVarDecl(Info, VD)) 4873 return ESR_Failed; 4874 // FIXME: If the variable has initialization that can't be jumped 4875 // over, bail out of any immediately-surrounding compound-statement 4876 // too. There can't be any case labels here. 4877 } 4878 } 4879 return ESR_CaseNotFound; 4880 } 4881 4882 default: 4883 return ESR_CaseNotFound; 4884 } 4885 } 4886 4887 switch (S->getStmtClass()) { 4888 default: 4889 if (const Expr *E = dyn_cast<Expr>(S)) { 4890 // Don't bother evaluating beyond an expression-statement which couldn't 4891 // be evaluated. 4892 // FIXME: Do we need the FullExpressionRAII object here? 4893 // VisitExprWithCleanups should create one when necessary. 4894 FullExpressionRAII Scope(Info); 4895 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 4896 return ESR_Failed; 4897 return ESR_Succeeded; 4898 } 4899 4900 Info.FFDiag(S->getBeginLoc()); 4901 return ESR_Failed; 4902 4903 case Stmt::NullStmtClass: 4904 return ESR_Succeeded; 4905 4906 case Stmt::DeclStmtClass: { 4907 const DeclStmt *DS = cast<DeclStmt>(S); 4908 for (const auto *D : DS->decls()) { 4909 // Each declaration initialization is its own full-expression. 4910 FullExpressionRAII Scope(Info); 4911 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 4912 return ESR_Failed; 4913 if (!Scope.destroy()) 4914 return ESR_Failed; 4915 } 4916 return ESR_Succeeded; 4917 } 4918 4919 case Stmt::ReturnStmtClass: { 4920 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4921 FullExpressionRAII Scope(Info); 4922 if (RetExpr && 4923 !(Result.Slot 4924 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4925 : Evaluate(Result.Value, Info, RetExpr))) 4926 return ESR_Failed; 4927 return Scope.destroy() ? ESR_Returned : ESR_Failed; 4928 } 4929 4930 case Stmt::CompoundStmtClass: { 4931 BlockScopeRAII Scope(Info); 4932 4933 const CompoundStmt *CS = cast<CompoundStmt>(S); 4934 for (const auto *BI : CS->body()) { 4935 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4936 if (ESR == ESR_Succeeded) 4937 Case = nullptr; 4938 else if (ESR != ESR_CaseNotFound) { 4939 if (ESR != ESR_Failed && !Scope.destroy()) 4940 return ESR_Failed; 4941 return ESR; 4942 } 4943 } 4944 if (Case) 4945 return ESR_CaseNotFound; 4946 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4947 } 4948 4949 case Stmt::IfStmtClass: { 4950 const IfStmt *IS = cast<IfStmt>(S); 4951 4952 // Evaluate the condition, as either a var decl or as an expression. 4953 BlockScopeRAII Scope(Info); 4954 if (const Stmt *Init = IS->getInit()) { 4955 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4956 if (ESR != ESR_Succeeded) { 4957 if (ESR != ESR_Failed && !Scope.destroy()) 4958 return ESR_Failed; 4959 return ESR; 4960 } 4961 } 4962 bool Cond; 4963 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 4964 return ESR_Failed; 4965 4966 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 4967 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 4968 if (ESR != ESR_Succeeded) { 4969 if (ESR != ESR_Failed && !Scope.destroy()) 4970 return ESR_Failed; 4971 return ESR; 4972 } 4973 } 4974 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4975 } 4976 4977 case Stmt::WhileStmtClass: { 4978 const WhileStmt *WS = cast<WhileStmt>(S); 4979 while (true) { 4980 BlockScopeRAII Scope(Info); 4981 bool Continue; 4982 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 4983 Continue)) 4984 return ESR_Failed; 4985 if (!Continue) 4986 break; 4987 4988 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 4989 if (ESR != ESR_Continue) { 4990 if (ESR != ESR_Failed && !Scope.destroy()) 4991 return ESR_Failed; 4992 return ESR; 4993 } 4994 if (!Scope.destroy()) 4995 return ESR_Failed; 4996 } 4997 return ESR_Succeeded; 4998 } 4999 5000 case Stmt::DoStmtClass: { 5001 const DoStmt *DS = cast<DoStmt>(S); 5002 bool Continue; 5003 do { 5004 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5005 if (ESR != ESR_Continue) 5006 return ESR; 5007 Case = nullptr; 5008 5009 FullExpressionRAII CondScope(Info); 5010 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5011 !CondScope.destroy()) 5012 return ESR_Failed; 5013 } while (Continue); 5014 return ESR_Succeeded; 5015 } 5016 5017 case Stmt::ForStmtClass: { 5018 const ForStmt *FS = cast<ForStmt>(S); 5019 BlockScopeRAII ForScope(Info); 5020 if (FS->getInit()) { 5021 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5022 if (ESR != ESR_Succeeded) { 5023 if (ESR != ESR_Failed && !ForScope.destroy()) 5024 return ESR_Failed; 5025 return ESR; 5026 } 5027 } 5028 while (true) { 5029 BlockScopeRAII IterScope(Info); 5030 bool Continue = true; 5031 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5032 FS->getCond(), Continue)) 5033 return ESR_Failed; 5034 if (!Continue) 5035 break; 5036 5037 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5038 if (ESR != ESR_Continue) { 5039 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5040 return ESR_Failed; 5041 return ESR; 5042 } 5043 5044 if (FS->getInc()) { 5045 FullExpressionRAII IncScope(Info); 5046 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 5047 return ESR_Failed; 5048 } 5049 5050 if (!IterScope.destroy()) 5051 return ESR_Failed; 5052 } 5053 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5054 } 5055 5056 case Stmt::CXXForRangeStmtClass: { 5057 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5058 BlockScopeRAII Scope(Info); 5059 5060 // Evaluate the init-statement if present. 5061 if (FS->getInit()) { 5062 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5063 if (ESR != ESR_Succeeded) { 5064 if (ESR != ESR_Failed && !Scope.destroy()) 5065 return ESR_Failed; 5066 return ESR; 5067 } 5068 } 5069 5070 // Initialize the __range variable. 5071 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5072 if (ESR != ESR_Succeeded) { 5073 if (ESR != ESR_Failed && !Scope.destroy()) 5074 return ESR_Failed; 5075 return ESR; 5076 } 5077 5078 // Create the __begin and __end iterators. 5079 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5080 if (ESR != ESR_Succeeded) { 5081 if (ESR != ESR_Failed && !Scope.destroy()) 5082 return ESR_Failed; 5083 return ESR; 5084 } 5085 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5086 if (ESR != ESR_Succeeded) { 5087 if (ESR != ESR_Failed && !Scope.destroy()) 5088 return ESR_Failed; 5089 return ESR; 5090 } 5091 5092 while (true) { 5093 // Condition: __begin != __end. 5094 { 5095 bool Continue = true; 5096 FullExpressionRAII CondExpr(Info); 5097 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5098 return ESR_Failed; 5099 if (!Continue) 5100 break; 5101 } 5102 5103 // User's variable declaration, initialized by *__begin. 5104 BlockScopeRAII InnerScope(Info); 5105 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5106 if (ESR != ESR_Succeeded) { 5107 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5108 return ESR_Failed; 5109 return ESR; 5110 } 5111 5112 // Loop body. 5113 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5114 if (ESR != ESR_Continue) { 5115 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5116 return ESR_Failed; 5117 return ESR; 5118 } 5119 5120 // Increment: ++__begin 5121 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5122 return ESR_Failed; 5123 5124 if (!InnerScope.destroy()) 5125 return ESR_Failed; 5126 } 5127 5128 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5129 } 5130 5131 case Stmt::SwitchStmtClass: 5132 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5133 5134 case Stmt::ContinueStmtClass: 5135 return ESR_Continue; 5136 5137 case Stmt::BreakStmtClass: 5138 return ESR_Break; 5139 5140 case Stmt::LabelStmtClass: 5141 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5142 5143 case Stmt::AttributedStmtClass: 5144 // As a general principle, C++11 attributes can be ignored without 5145 // any semantic impact. 5146 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5147 Case); 5148 5149 case Stmt::CaseStmtClass: 5150 case Stmt::DefaultStmtClass: 5151 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5152 case Stmt::CXXTryStmtClass: 5153 // Evaluate try blocks by evaluating all sub statements. 5154 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5155 } 5156 } 5157 5158 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5159 /// default constructor. If so, we'll fold it whether or not it's marked as 5160 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5161 /// so we need special handling. 5162 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5163 const CXXConstructorDecl *CD, 5164 bool IsValueInitialization) { 5165 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5166 return false; 5167 5168 // Value-initialization does not call a trivial default constructor, so such a 5169 // call is a core constant expression whether or not the constructor is 5170 // constexpr. 5171 if (!CD->isConstexpr() && !IsValueInitialization) { 5172 if (Info.getLangOpts().CPlusPlus11) { 5173 // FIXME: If DiagDecl is an implicitly-declared special member function, 5174 // we should be much more explicit about why it's not constexpr. 5175 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5176 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5177 Info.Note(CD->getLocation(), diag::note_declared_at); 5178 } else { 5179 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5180 } 5181 } 5182 return true; 5183 } 5184 5185 /// CheckConstexprFunction - Check that a function can be called in a constant 5186 /// expression. 5187 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5188 const FunctionDecl *Declaration, 5189 const FunctionDecl *Definition, 5190 const Stmt *Body) { 5191 // Potential constant expressions can contain calls to declared, but not yet 5192 // defined, constexpr functions. 5193 if (Info.checkingPotentialConstantExpression() && !Definition && 5194 Declaration->isConstexpr()) 5195 return false; 5196 5197 // Bail out if the function declaration itself is invalid. We will 5198 // have produced a relevant diagnostic while parsing it, so just 5199 // note the problematic sub-expression. 5200 if (Declaration->isInvalidDecl()) { 5201 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5202 return false; 5203 } 5204 5205 // DR1872: An instantiated virtual constexpr function can't be called in a 5206 // constant expression (prior to C++20). We can still constant-fold such a 5207 // call. 5208 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5209 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5210 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5211 5212 if (Definition && Definition->isInvalidDecl()) { 5213 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5214 return false; 5215 } 5216 5217 if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) { 5218 for (const auto *InitExpr : CtorDecl->inits()) { 5219 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 5220 return false; 5221 } 5222 } 5223 5224 // Can we evaluate this function call? 5225 if (Definition && Definition->isConstexpr() && Body) 5226 return true; 5227 5228 if (Info.getLangOpts().CPlusPlus11) { 5229 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5230 5231 // If this function is not constexpr because it is an inherited 5232 // non-constexpr constructor, diagnose that directly. 5233 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5234 if (CD && CD->isInheritingConstructor()) { 5235 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5236 if (!Inherited->isConstexpr()) 5237 DiagDecl = CD = Inherited; 5238 } 5239 5240 // FIXME: If DiagDecl is an implicitly-declared special member function 5241 // or an inheriting constructor, we should be much more explicit about why 5242 // it's not constexpr. 5243 if (CD && CD->isInheritingConstructor()) 5244 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5245 << CD->getInheritedConstructor().getConstructor()->getParent(); 5246 else 5247 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5248 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5249 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5250 } else { 5251 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5252 } 5253 return false; 5254 } 5255 5256 namespace { 5257 struct CheckDynamicTypeHandler { 5258 AccessKinds AccessKind; 5259 typedef bool result_type; 5260 bool failed() { return false; } 5261 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5262 bool found(APSInt &Value, QualType SubobjType) { return true; } 5263 bool found(APFloat &Value, QualType SubobjType) { return true; } 5264 }; 5265 } // end anonymous namespace 5266 5267 /// Check that we can access the notional vptr of an object / determine its 5268 /// dynamic type. 5269 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5270 AccessKinds AK, bool Polymorphic) { 5271 if (This.Designator.Invalid) 5272 return false; 5273 5274 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5275 5276 if (!Obj) 5277 return false; 5278 5279 if (!Obj.Value) { 5280 // The object is not usable in constant expressions, so we can't inspect 5281 // its value to see if it's in-lifetime or what the active union members 5282 // are. We can still check for a one-past-the-end lvalue. 5283 if (This.Designator.isOnePastTheEnd() || 5284 This.Designator.isMostDerivedAnUnsizedArray()) { 5285 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5286 ? diag::note_constexpr_access_past_end 5287 : diag::note_constexpr_access_unsized_array) 5288 << AK; 5289 return false; 5290 } else if (Polymorphic) { 5291 // Conservatively refuse to perform a polymorphic operation if we would 5292 // not be able to read a notional 'vptr' value. 5293 APValue Val; 5294 This.moveInto(Val); 5295 QualType StarThisType = 5296 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5297 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5298 << AK << Val.getAsString(Info.Ctx, StarThisType); 5299 return false; 5300 } 5301 return true; 5302 } 5303 5304 CheckDynamicTypeHandler Handler{AK}; 5305 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5306 } 5307 5308 /// Check that the pointee of the 'this' pointer in a member function call is 5309 /// either within its lifetime or in its period of construction or destruction. 5310 static bool 5311 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5312 const LValue &This, 5313 const CXXMethodDecl *NamedMember) { 5314 return checkDynamicType( 5315 Info, E, This, 5316 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5317 } 5318 5319 struct DynamicType { 5320 /// The dynamic class type of the object. 5321 const CXXRecordDecl *Type; 5322 /// The corresponding path length in the lvalue. 5323 unsigned PathLength; 5324 }; 5325 5326 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5327 unsigned PathLength) { 5328 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5329 Designator.Entries.size() && "invalid path length"); 5330 return (PathLength == Designator.MostDerivedPathLength) 5331 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5332 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5333 } 5334 5335 /// Determine the dynamic type of an object. 5336 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5337 LValue &This, AccessKinds AK) { 5338 // If we don't have an lvalue denoting an object of class type, there is no 5339 // meaningful dynamic type. (We consider objects of non-class type to have no 5340 // dynamic type.) 5341 if (!checkDynamicType(Info, E, This, AK, true)) 5342 return None; 5343 5344 // Refuse to compute a dynamic type in the presence of virtual bases. This 5345 // shouldn't happen other than in constant-folding situations, since literal 5346 // types can't have virtual bases. 5347 // 5348 // Note that consumers of DynamicType assume that the type has no virtual 5349 // bases, and will need modifications if this restriction is relaxed. 5350 const CXXRecordDecl *Class = 5351 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5352 if (!Class || Class->getNumVBases()) { 5353 Info.FFDiag(E); 5354 return None; 5355 } 5356 5357 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5358 // binary search here instead. But the overwhelmingly common case is that 5359 // we're not in the middle of a constructor, so it probably doesn't matter 5360 // in practice. 5361 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5362 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5363 PathLength <= Path.size(); ++PathLength) { 5364 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5365 Path.slice(0, PathLength))) { 5366 case ConstructionPhase::Bases: 5367 case ConstructionPhase::DestroyingBases: 5368 // We're constructing or destroying a base class. This is not the dynamic 5369 // type. 5370 break; 5371 5372 case ConstructionPhase::None: 5373 case ConstructionPhase::AfterBases: 5374 case ConstructionPhase::AfterFields: 5375 case ConstructionPhase::Destroying: 5376 // We've finished constructing the base classes and not yet started 5377 // destroying them again, so this is the dynamic type. 5378 return DynamicType{getBaseClassType(This.Designator, PathLength), 5379 PathLength}; 5380 } 5381 } 5382 5383 // CWG issue 1517: we're constructing a base class of the object described by 5384 // 'This', so that object has not yet begun its period of construction and 5385 // any polymorphic operation on it results in undefined behavior. 5386 Info.FFDiag(E); 5387 return None; 5388 } 5389 5390 /// Perform virtual dispatch. 5391 static const CXXMethodDecl *HandleVirtualDispatch( 5392 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5393 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5394 Optional<DynamicType> DynType = ComputeDynamicType( 5395 Info, E, This, 5396 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5397 if (!DynType) 5398 return nullptr; 5399 5400 // Find the final overrider. It must be declared in one of the classes on the 5401 // path from the dynamic type to the static type. 5402 // FIXME: If we ever allow literal types to have virtual base classes, that 5403 // won't be true. 5404 const CXXMethodDecl *Callee = Found; 5405 unsigned PathLength = DynType->PathLength; 5406 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5407 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5408 const CXXMethodDecl *Overrider = 5409 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5410 if (Overrider) { 5411 Callee = Overrider; 5412 break; 5413 } 5414 } 5415 5416 // C++2a [class.abstract]p6: 5417 // the effect of making a virtual call to a pure virtual function [...] is 5418 // undefined 5419 if (Callee->isPure()) { 5420 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5421 Info.Note(Callee->getLocation(), diag::note_declared_at); 5422 return nullptr; 5423 } 5424 5425 // If necessary, walk the rest of the path to determine the sequence of 5426 // covariant adjustment steps to apply. 5427 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5428 Found->getReturnType())) { 5429 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5430 for (unsigned CovariantPathLength = PathLength + 1; 5431 CovariantPathLength != This.Designator.Entries.size(); 5432 ++CovariantPathLength) { 5433 const CXXRecordDecl *NextClass = 5434 getBaseClassType(This.Designator, CovariantPathLength); 5435 const CXXMethodDecl *Next = 5436 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5437 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5438 Next->getReturnType(), CovariantAdjustmentPath.back())) 5439 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5440 } 5441 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5442 CovariantAdjustmentPath.back())) 5443 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5444 } 5445 5446 // Perform 'this' adjustment. 5447 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5448 return nullptr; 5449 5450 return Callee; 5451 } 5452 5453 /// Perform the adjustment from a value returned by a virtual function to 5454 /// a value of the statically expected type, which may be a pointer or 5455 /// reference to a base class of the returned type. 5456 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5457 APValue &Result, 5458 ArrayRef<QualType> Path) { 5459 assert(Result.isLValue() && 5460 "unexpected kind of APValue for covariant return"); 5461 if (Result.isNullPointer()) 5462 return true; 5463 5464 LValue LVal; 5465 LVal.setFrom(Info.Ctx, Result); 5466 5467 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5468 for (unsigned I = 1; I != Path.size(); ++I) { 5469 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5470 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5471 if (OldClass != NewClass && 5472 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5473 return false; 5474 OldClass = NewClass; 5475 } 5476 5477 LVal.moveInto(Result); 5478 return true; 5479 } 5480 5481 /// Determine whether \p Base, which is known to be a direct base class of 5482 /// \p Derived, is a public base class. 5483 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5484 const CXXRecordDecl *Base) { 5485 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5486 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5487 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5488 return BaseSpec.getAccessSpecifier() == AS_public; 5489 } 5490 llvm_unreachable("Base is not a direct base of Derived"); 5491 } 5492 5493 /// Apply the given dynamic cast operation on the provided lvalue. 5494 /// 5495 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5496 /// to find a suitable target subobject. 5497 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5498 LValue &Ptr) { 5499 // We can't do anything with a non-symbolic pointer value. 5500 SubobjectDesignator &D = Ptr.Designator; 5501 if (D.Invalid) 5502 return false; 5503 5504 // C++ [expr.dynamic.cast]p6: 5505 // If v is a null pointer value, the result is a null pointer value. 5506 if (Ptr.isNullPointer() && !E->isGLValue()) 5507 return true; 5508 5509 // For all the other cases, we need the pointer to point to an object within 5510 // its lifetime / period of construction / destruction, and we need to know 5511 // its dynamic type. 5512 Optional<DynamicType> DynType = 5513 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5514 if (!DynType) 5515 return false; 5516 5517 // C++ [expr.dynamic.cast]p7: 5518 // If T is "pointer to cv void", then the result is a pointer to the most 5519 // derived object 5520 if (E->getType()->isVoidPointerType()) 5521 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5522 5523 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5524 assert(C && "dynamic_cast target is not void pointer nor class"); 5525 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5526 5527 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5528 // C++ [expr.dynamic.cast]p9: 5529 if (!E->isGLValue()) { 5530 // The value of a failed cast to pointer type is the null pointer value 5531 // of the required result type. 5532 Ptr.setNull(Info.Ctx, E->getType()); 5533 return true; 5534 } 5535 5536 // A failed cast to reference type throws [...] std::bad_cast. 5537 unsigned DiagKind; 5538 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5539 DynType->Type->isDerivedFrom(C))) 5540 DiagKind = 0; 5541 else if (!Paths || Paths->begin() == Paths->end()) 5542 DiagKind = 1; 5543 else if (Paths->isAmbiguous(CQT)) 5544 DiagKind = 2; 5545 else { 5546 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5547 DiagKind = 3; 5548 } 5549 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5550 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5551 << Info.Ctx.getRecordType(DynType->Type) 5552 << E->getType().getUnqualifiedType(); 5553 return false; 5554 }; 5555 5556 // Runtime check, phase 1: 5557 // Walk from the base subobject towards the derived object looking for the 5558 // target type. 5559 for (int PathLength = Ptr.Designator.Entries.size(); 5560 PathLength >= (int)DynType->PathLength; --PathLength) { 5561 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5562 if (declaresSameEntity(Class, C)) 5563 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5564 // We can only walk across public inheritance edges. 5565 if (PathLength > (int)DynType->PathLength && 5566 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5567 Class)) 5568 return RuntimeCheckFailed(nullptr); 5569 } 5570 5571 // Runtime check, phase 2: 5572 // Search the dynamic type for an unambiguous public base of type C. 5573 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5574 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5575 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5576 Paths.front().Access == AS_public) { 5577 // Downcast to the dynamic type... 5578 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5579 return false; 5580 // ... then upcast to the chosen base class subobject. 5581 for (CXXBasePathElement &Elem : Paths.front()) 5582 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5583 return false; 5584 return true; 5585 } 5586 5587 // Otherwise, the runtime check fails. 5588 return RuntimeCheckFailed(&Paths); 5589 } 5590 5591 namespace { 5592 struct StartLifetimeOfUnionMemberHandler { 5593 EvalInfo &Info; 5594 const Expr *LHSExpr; 5595 const FieldDecl *Field; 5596 bool DuringInit; 5597 bool Failed = false; 5598 static const AccessKinds AccessKind = AK_Assign; 5599 5600 typedef bool result_type; 5601 bool failed() { return Failed; } 5602 bool found(APValue &Subobj, QualType SubobjType) { 5603 // We are supposed to perform no initialization but begin the lifetime of 5604 // the object. We interpret that as meaning to do what default 5605 // initialization of the object would do if all constructors involved were 5606 // trivial: 5607 // * All base, non-variant member, and array element subobjects' lifetimes 5608 // begin 5609 // * No variant members' lifetimes begin 5610 // * All scalar subobjects whose lifetimes begin have indeterminate values 5611 assert(SubobjType->isUnionType()); 5612 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5613 // This union member is already active. If it's also in-lifetime, there's 5614 // nothing to do. 5615 if (Subobj.getUnionValue().hasValue()) 5616 return true; 5617 } else if (DuringInit) { 5618 // We're currently in the process of initializing a different union 5619 // member. If we carried on, that initialization would attempt to 5620 // store to an inactive union member, resulting in undefined behavior. 5621 Info.FFDiag(LHSExpr, 5622 diag::note_constexpr_union_member_change_during_init); 5623 return false; 5624 } 5625 APValue Result; 5626 Failed = !getDefaultInitValue(Field->getType(), Result); 5627 Subobj.setUnion(Field, Result); 5628 return true; 5629 } 5630 bool found(APSInt &Value, QualType SubobjType) { 5631 llvm_unreachable("wrong value kind for union object"); 5632 } 5633 bool found(APFloat &Value, QualType SubobjType) { 5634 llvm_unreachable("wrong value kind for union object"); 5635 } 5636 }; 5637 } // end anonymous namespace 5638 5639 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5640 5641 /// Handle a builtin simple-assignment or a call to a trivial assignment 5642 /// operator whose left-hand side might involve a union member access. If it 5643 /// does, implicitly start the lifetime of any accessed union elements per 5644 /// C++20 [class.union]5. 5645 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5646 const LValue &LHS) { 5647 if (LHS.InvalidBase || LHS.Designator.Invalid) 5648 return false; 5649 5650 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5651 // C++ [class.union]p5: 5652 // define the set S(E) of subexpressions of E as follows: 5653 unsigned PathLength = LHS.Designator.Entries.size(); 5654 for (const Expr *E = LHSExpr; E != nullptr;) { 5655 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5656 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5657 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5658 // Note that we can't implicitly start the lifetime of a reference, 5659 // so we don't need to proceed any further if we reach one. 5660 if (!FD || FD->getType()->isReferenceType()) 5661 break; 5662 5663 // ... and also contains A.B if B names a union member ... 5664 if (FD->getParent()->isUnion()) { 5665 // ... of a non-class, non-array type, or of a class type with a 5666 // trivial default constructor that is not deleted, or an array of 5667 // such types. 5668 auto *RD = 5669 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5670 if (!RD || RD->hasTrivialDefaultConstructor()) 5671 UnionPathLengths.push_back({PathLength - 1, FD}); 5672 } 5673 5674 E = ME->getBase(); 5675 --PathLength; 5676 assert(declaresSameEntity(FD, 5677 LHS.Designator.Entries[PathLength] 5678 .getAsBaseOrMember().getPointer())); 5679 5680 // -- If E is of the form A[B] and is interpreted as a built-in array 5681 // subscripting operator, S(E) is [S(the array operand, if any)]. 5682 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5683 // Step over an ArrayToPointerDecay implicit cast. 5684 auto *Base = ASE->getBase()->IgnoreImplicit(); 5685 if (!Base->getType()->isArrayType()) 5686 break; 5687 5688 E = Base; 5689 --PathLength; 5690 5691 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5692 // Step over a derived-to-base conversion. 5693 E = ICE->getSubExpr(); 5694 if (ICE->getCastKind() == CK_NoOp) 5695 continue; 5696 if (ICE->getCastKind() != CK_DerivedToBase && 5697 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5698 break; 5699 // Walk path backwards as we walk up from the base to the derived class. 5700 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5701 --PathLength; 5702 (void)Elt; 5703 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5704 LHS.Designator.Entries[PathLength] 5705 .getAsBaseOrMember().getPointer())); 5706 } 5707 5708 // -- Otherwise, S(E) is empty. 5709 } else { 5710 break; 5711 } 5712 } 5713 5714 // Common case: no unions' lifetimes are started. 5715 if (UnionPathLengths.empty()) 5716 return true; 5717 5718 // if modification of X [would access an inactive union member], an object 5719 // of the type of X is implicitly created 5720 CompleteObject Obj = 5721 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5722 if (!Obj) 5723 return false; 5724 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5725 llvm::reverse(UnionPathLengths)) { 5726 // Form a designator for the union object. 5727 SubobjectDesignator D = LHS.Designator; 5728 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5729 5730 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5731 ConstructionPhase::AfterBases; 5732 StartLifetimeOfUnionMemberHandler StartLifetime{ 5733 Info, LHSExpr, LengthAndField.second, DuringInit}; 5734 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5735 return false; 5736 } 5737 5738 return true; 5739 } 5740 5741 namespace { 5742 typedef SmallVector<APValue, 8> ArgVector; 5743 } 5744 5745 /// EvaluateArgs - Evaluate the arguments to a function call. 5746 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues, 5747 EvalInfo &Info, const FunctionDecl *Callee) { 5748 bool Success = true; 5749 llvm::SmallBitVector ForbiddenNullArgs; 5750 if (Callee->hasAttr<NonNullAttr>()) { 5751 ForbiddenNullArgs.resize(Args.size()); 5752 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 5753 if (!Attr->args_size()) { 5754 ForbiddenNullArgs.set(); 5755 break; 5756 } else 5757 for (auto Idx : Attr->args()) { 5758 unsigned ASTIdx = Idx.getASTIndex(); 5759 if (ASTIdx >= Args.size()) 5760 continue; 5761 ForbiddenNullArgs[ASTIdx] = 1; 5762 } 5763 } 5764 } 5765 // FIXME: This is the wrong evaluation order for an assignment operator 5766 // called via operator syntax. 5767 for (unsigned Idx = 0; Idx < Args.size(); Idx++) { 5768 if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) { 5769 // If we're checking for a potential constant expression, evaluate all 5770 // initializers even if some of them fail. 5771 if (!Info.noteFailure()) 5772 return false; 5773 Success = false; 5774 } else if (!ForbiddenNullArgs.empty() && 5775 ForbiddenNullArgs[Idx] && 5776 ArgValues[Idx].isLValue() && 5777 ArgValues[Idx].isNullPointer()) { 5778 Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed); 5779 if (!Info.noteFailure()) 5780 return false; 5781 Success = false; 5782 } 5783 } 5784 return Success; 5785 } 5786 5787 /// Evaluate a function call. 5788 static bool HandleFunctionCall(SourceLocation CallLoc, 5789 const FunctionDecl *Callee, const LValue *This, 5790 ArrayRef<const Expr*> Args, const Stmt *Body, 5791 EvalInfo &Info, APValue &Result, 5792 const LValue *ResultSlot) { 5793 ArgVector ArgValues(Args.size()); 5794 if (!EvaluateArgs(Args, ArgValues, Info, Callee)) 5795 return false; 5796 5797 if (!Info.CheckCallLimit(CallLoc)) 5798 return false; 5799 5800 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 5801 5802 // For a trivial copy or move assignment, perform an APValue copy. This is 5803 // essential for unions, where the operations performed by the assignment 5804 // operator cannot be represented as statements. 5805 // 5806 // Skip this for non-union classes with no fields; in that case, the defaulted 5807 // copy/move does not actually read the object. 5808 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 5809 if (MD && MD->isDefaulted() && 5810 (MD->getParent()->isUnion() || 5811 (MD->isTrivial() && 5812 isReadByLvalueToRvalueConversion(MD->getParent())))) { 5813 assert(This && 5814 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 5815 LValue RHS; 5816 RHS.setFrom(Info.Ctx, ArgValues[0]); 5817 APValue RHSValue; 5818 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS, 5819 RHSValue, MD->getParent()->isUnion())) 5820 return false; 5821 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 5822 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 5823 return false; 5824 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 5825 RHSValue)) 5826 return false; 5827 This->moveInto(Result); 5828 return true; 5829 } else if (MD && isLambdaCallOperator(MD)) { 5830 // We're in a lambda; determine the lambda capture field maps unless we're 5831 // just constexpr checking a lambda's call operator. constexpr checking is 5832 // done before the captures have been added to the closure object (unless 5833 // we're inferring constexpr-ness), so we don't have access to them in this 5834 // case. But since we don't need the captures to constexpr check, we can 5835 // just ignore them. 5836 if (!Info.checkingPotentialConstantExpression()) 5837 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 5838 Frame.LambdaThisCaptureField); 5839 } 5840 5841 StmtResult Ret = {Result, ResultSlot}; 5842 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 5843 if (ESR == ESR_Succeeded) { 5844 if (Callee->getReturnType()->isVoidType()) 5845 return true; 5846 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 5847 } 5848 return ESR == ESR_Returned; 5849 } 5850 5851 /// Evaluate a constructor call. 5852 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5853 APValue *ArgValues, 5854 const CXXConstructorDecl *Definition, 5855 EvalInfo &Info, APValue &Result) { 5856 SourceLocation CallLoc = E->getExprLoc(); 5857 if (!Info.CheckCallLimit(CallLoc)) 5858 return false; 5859 5860 const CXXRecordDecl *RD = Definition->getParent(); 5861 if (RD->getNumVBases()) { 5862 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 5863 return false; 5864 } 5865 5866 EvalInfo::EvaluatingConstructorRAII EvalObj( 5867 Info, 5868 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 5869 RD->getNumBases()); 5870 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 5871 5872 // FIXME: Creating an APValue just to hold a nonexistent return value is 5873 // wasteful. 5874 APValue RetVal; 5875 StmtResult Ret = {RetVal, nullptr}; 5876 5877 // If it's a delegating constructor, delegate. 5878 if (Definition->isDelegatingConstructor()) { 5879 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 5880 { 5881 FullExpressionRAII InitScope(Info); 5882 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 5883 !InitScope.destroy()) 5884 return false; 5885 } 5886 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5887 } 5888 5889 // For a trivial copy or move constructor, perform an APValue copy. This is 5890 // essential for unions (or classes with anonymous union members), where the 5891 // operations performed by the constructor cannot be represented by 5892 // ctor-initializers. 5893 // 5894 // Skip this for empty non-union classes; we should not perform an 5895 // lvalue-to-rvalue conversion on them because their copy constructor does not 5896 // actually read them. 5897 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 5898 (Definition->getParent()->isUnion() || 5899 (Definition->isTrivial() && 5900 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 5901 LValue RHS; 5902 RHS.setFrom(Info.Ctx, ArgValues[0]); 5903 return handleLValueToRValueConversion( 5904 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 5905 RHS, Result, Definition->getParent()->isUnion()); 5906 } 5907 5908 // Reserve space for the struct members. 5909 if (!Result.hasValue()) { 5910 if (!RD->isUnion()) 5911 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 5912 std::distance(RD->field_begin(), RD->field_end())); 5913 else 5914 // A union starts with no active member. 5915 Result = APValue((const FieldDecl*)nullptr); 5916 } 5917 5918 if (RD->isInvalidDecl()) return false; 5919 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5920 5921 // A scope for temporaries lifetime-extended by reference members. 5922 BlockScopeRAII LifetimeExtendedScope(Info); 5923 5924 bool Success = true; 5925 unsigned BasesSeen = 0; 5926 #ifndef NDEBUG 5927 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 5928 #endif 5929 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 5930 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 5931 // We might be initializing the same field again if this is an indirect 5932 // field initialization. 5933 if (FieldIt == RD->field_end() || 5934 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 5935 assert(Indirect && "fields out of order?"); 5936 return; 5937 } 5938 5939 // Default-initialize any fields with no explicit initializer. 5940 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 5941 assert(FieldIt != RD->field_end() && "missing field?"); 5942 if (!FieldIt->isUnnamedBitfield()) 5943 Success &= getDefaultInitValue( 5944 FieldIt->getType(), 5945 Result.getStructField(FieldIt->getFieldIndex())); 5946 } 5947 ++FieldIt; 5948 }; 5949 for (const auto *I : Definition->inits()) { 5950 LValue Subobject = This; 5951 LValue SubobjectParent = This; 5952 APValue *Value = &Result; 5953 5954 // Determine the subobject to initialize. 5955 FieldDecl *FD = nullptr; 5956 if (I->isBaseInitializer()) { 5957 QualType BaseType(I->getBaseClass(), 0); 5958 #ifndef NDEBUG 5959 // Non-virtual base classes are initialized in the order in the class 5960 // definition. We have already checked for virtual base classes. 5961 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 5962 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 5963 "base class initializers not in expected order"); 5964 ++BaseIt; 5965 #endif 5966 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 5967 BaseType->getAsCXXRecordDecl(), &Layout)) 5968 return false; 5969 Value = &Result.getStructBase(BasesSeen++); 5970 } else if ((FD = I->getMember())) { 5971 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 5972 return false; 5973 if (RD->isUnion()) { 5974 Result = APValue(FD); 5975 Value = &Result.getUnionValue(); 5976 } else { 5977 SkipToField(FD, false); 5978 Value = &Result.getStructField(FD->getFieldIndex()); 5979 } 5980 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 5981 // Walk the indirect field decl's chain to find the object to initialize, 5982 // and make sure we've initialized every step along it. 5983 auto IndirectFieldChain = IFD->chain(); 5984 for (auto *C : IndirectFieldChain) { 5985 FD = cast<FieldDecl>(C); 5986 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 5987 // Switch the union field if it differs. This happens if we had 5988 // preceding zero-initialization, and we're now initializing a union 5989 // subobject other than the first. 5990 // FIXME: In this case, the values of the other subobjects are 5991 // specified, since zero-initialization sets all padding bits to zero. 5992 if (!Value->hasValue() || 5993 (Value->isUnion() && Value->getUnionField() != FD)) { 5994 if (CD->isUnion()) 5995 *Value = APValue(FD); 5996 else 5997 // FIXME: This immediately starts the lifetime of all members of 5998 // an anonymous struct. It would be preferable to strictly start 5999 // member lifetime in initialization order. 6000 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6001 } 6002 // Store Subobject as its parent before updating it for the last element 6003 // in the chain. 6004 if (C == IndirectFieldChain.back()) 6005 SubobjectParent = Subobject; 6006 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6007 return false; 6008 if (CD->isUnion()) 6009 Value = &Value->getUnionValue(); 6010 else { 6011 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6012 SkipToField(FD, true); 6013 Value = &Value->getStructField(FD->getFieldIndex()); 6014 } 6015 } 6016 } else { 6017 llvm_unreachable("unknown base initializer kind"); 6018 } 6019 6020 // Need to override This for implicit field initializers as in this case 6021 // This refers to innermost anonymous struct/union containing initializer, 6022 // not to currently constructed class. 6023 const Expr *Init = I->getInit(); 6024 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6025 isa<CXXDefaultInitExpr>(Init)); 6026 FullExpressionRAII InitScope(Info); 6027 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6028 (FD && FD->isBitField() && 6029 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6030 // If we're checking for a potential constant expression, evaluate all 6031 // initializers even if some of them fail. 6032 if (!Info.noteFailure()) 6033 return false; 6034 Success = false; 6035 } 6036 6037 // This is the point at which the dynamic type of the object becomes this 6038 // class type. 6039 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6040 EvalObj.finishedConstructingBases(); 6041 } 6042 6043 // Default-initialize any remaining fields. 6044 if (!RD->isUnion()) { 6045 for (; FieldIt != RD->field_end(); ++FieldIt) { 6046 if (!FieldIt->isUnnamedBitfield()) 6047 Success &= getDefaultInitValue( 6048 FieldIt->getType(), 6049 Result.getStructField(FieldIt->getFieldIndex())); 6050 } 6051 } 6052 6053 EvalObj.finishedConstructingFields(); 6054 6055 return Success && 6056 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6057 LifetimeExtendedScope.destroy(); 6058 } 6059 6060 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6061 ArrayRef<const Expr*> Args, 6062 const CXXConstructorDecl *Definition, 6063 EvalInfo &Info, APValue &Result) { 6064 ArgVector ArgValues(Args.size()); 6065 if (!EvaluateArgs(Args, ArgValues, Info, Definition)) 6066 return false; 6067 6068 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 6069 Info, Result); 6070 } 6071 6072 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6073 const LValue &This, APValue &Value, 6074 QualType T) { 6075 // Objects can only be destroyed while they're within their lifetimes. 6076 // FIXME: We have no representation for whether an object of type nullptr_t 6077 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6078 // as indeterminate instead? 6079 if (Value.isAbsent() && !T->isNullPtrType()) { 6080 APValue Printable; 6081 This.moveInto(Printable); 6082 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6083 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6084 return false; 6085 } 6086 6087 // Invent an expression for location purposes. 6088 // FIXME: We shouldn't need to do this. 6089 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 6090 6091 // For arrays, destroy elements right-to-left. 6092 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6093 uint64_t Size = CAT->getSize().getZExtValue(); 6094 QualType ElemT = CAT->getElementType(); 6095 6096 LValue ElemLV = This; 6097 ElemLV.addArray(Info, &LocE, CAT); 6098 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6099 return false; 6100 6101 // Ensure that we have actual array elements available to destroy; the 6102 // destructors might mutate the value, so we can't run them on the array 6103 // filler. 6104 if (Size && Size > Value.getArrayInitializedElts()) 6105 expandArray(Value, Value.getArraySize() - 1); 6106 6107 for (; Size != 0; --Size) { 6108 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6109 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6110 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6111 return false; 6112 } 6113 6114 // End the lifetime of this array now. 6115 Value = APValue(); 6116 return true; 6117 } 6118 6119 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6120 if (!RD) { 6121 if (T.isDestructedType()) { 6122 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6123 return false; 6124 } 6125 6126 Value = APValue(); 6127 return true; 6128 } 6129 6130 if (RD->getNumVBases()) { 6131 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6132 return false; 6133 } 6134 6135 const CXXDestructorDecl *DD = RD->getDestructor(); 6136 if (!DD && !RD->hasTrivialDestructor()) { 6137 Info.FFDiag(CallLoc); 6138 return false; 6139 } 6140 6141 if (!DD || DD->isTrivial() || 6142 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6143 // A trivial destructor just ends the lifetime of the object. Check for 6144 // this case before checking for a body, because we might not bother 6145 // building a body for a trivial destructor. Note that it doesn't matter 6146 // whether the destructor is constexpr in this case; all trivial 6147 // destructors are constexpr. 6148 // 6149 // If an anonymous union would be destroyed, some enclosing destructor must 6150 // have been explicitly defined, and the anonymous union destruction should 6151 // have no effect. 6152 Value = APValue(); 6153 return true; 6154 } 6155 6156 if (!Info.CheckCallLimit(CallLoc)) 6157 return false; 6158 6159 const FunctionDecl *Definition = nullptr; 6160 const Stmt *Body = DD->getBody(Definition); 6161 6162 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6163 return false; 6164 6165 CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr); 6166 6167 // We're now in the period of destruction of this object. 6168 unsigned BasesLeft = RD->getNumBases(); 6169 EvalInfo::EvaluatingDestructorRAII EvalObj( 6170 Info, 6171 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6172 if (!EvalObj.DidInsert) { 6173 // C++2a [class.dtor]p19: 6174 // the behavior is undefined if the destructor is invoked for an object 6175 // whose lifetime has ended 6176 // (Note that formally the lifetime ends when the period of destruction 6177 // begins, even though certain uses of the object remain valid until the 6178 // period of destruction ends.) 6179 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6180 return false; 6181 } 6182 6183 // FIXME: Creating an APValue just to hold a nonexistent return value is 6184 // wasteful. 6185 APValue RetVal; 6186 StmtResult Ret = {RetVal, nullptr}; 6187 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6188 return false; 6189 6190 // A union destructor does not implicitly destroy its members. 6191 if (RD->isUnion()) 6192 return true; 6193 6194 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6195 6196 // We don't have a good way to iterate fields in reverse, so collect all the 6197 // fields first and then walk them backwards. 6198 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6199 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6200 if (FD->isUnnamedBitfield()) 6201 continue; 6202 6203 LValue Subobject = This; 6204 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6205 return false; 6206 6207 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6208 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6209 FD->getType())) 6210 return false; 6211 } 6212 6213 if (BasesLeft != 0) 6214 EvalObj.startedDestroyingBases(); 6215 6216 // Destroy base classes in reverse order. 6217 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6218 --BasesLeft; 6219 6220 QualType BaseType = Base.getType(); 6221 LValue Subobject = This; 6222 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6223 BaseType->getAsCXXRecordDecl(), &Layout)) 6224 return false; 6225 6226 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6227 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6228 BaseType)) 6229 return false; 6230 } 6231 assert(BasesLeft == 0 && "NumBases was wrong?"); 6232 6233 // The period of destruction ends now. The object is gone. 6234 Value = APValue(); 6235 return true; 6236 } 6237 6238 namespace { 6239 struct DestroyObjectHandler { 6240 EvalInfo &Info; 6241 const Expr *E; 6242 const LValue &This; 6243 const AccessKinds AccessKind; 6244 6245 typedef bool result_type; 6246 bool failed() { return false; } 6247 bool found(APValue &Subobj, QualType SubobjType) { 6248 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6249 SubobjType); 6250 } 6251 bool found(APSInt &Value, QualType SubobjType) { 6252 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6253 return false; 6254 } 6255 bool found(APFloat &Value, QualType SubobjType) { 6256 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6257 return false; 6258 } 6259 }; 6260 } 6261 6262 /// Perform a destructor or pseudo-destructor call on the given object, which 6263 /// might in general not be a complete object. 6264 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6265 const LValue &This, QualType ThisType) { 6266 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6267 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6268 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6269 } 6270 6271 /// Destroy and end the lifetime of the given complete object. 6272 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6273 APValue::LValueBase LVBase, APValue &Value, 6274 QualType T) { 6275 // If we've had an unmodeled side-effect, we can't rely on mutable state 6276 // (such as the object we're about to destroy) being correct. 6277 if (Info.EvalStatus.HasSideEffects) 6278 return false; 6279 6280 LValue LV; 6281 LV.set({LVBase}); 6282 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6283 } 6284 6285 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6286 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6287 LValue &Result) { 6288 if (Info.checkingPotentialConstantExpression() || 6289 Info.SpeculativeEvaluationDepth) 6290 return false; 6291 6292 // This is permitted only within a call to std::allocator<T>::allocate. 6293 auto Caller = Info.getStdAllocatorCaller("allocate"); 6294 if (!Caller) { 6295 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6296 ? diag::note_constexpr_new_untyped 6297 : diag::note_constexpr_new); 6298 return false; 6299 } 6300 6301 QualType ElemType = Caller.ElemType; 6302 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6303 Info.FFDiag(E->getExprLoc(), 6304 diag::note_constexpr_new_not_complete_object_type) 6305 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6306 return false; 6307 } 6308 6309 APSInt ByteSize; 6310 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6311 return false; 6312 bool IsNothrow = false; 6313 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6314 EvaluateIgnoredValue(Info, E->getArg(I)); 6315 IsNothrow |= E->getType()->isNothrowT(); 6316 } 6317 6318 CharUnits ElemSize; 6319 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6320 return false; 6321 APInt Size, Remainder; 6322 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6323 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6324 if (Remainder != 0) { 6325 // This likely indicates a bug in the implementation of 'std::allocator'. 6326 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6327 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6328 return false; 6329 } 6330 6331 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6332 if (IsNothrow) { 6333 Result.setNull(Info.Ctx, E->getType()); 6334 return true; 6335 } 6336 6337 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6338 return false; 6339 } 6340 6341 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6342 ArrayType::Normal, 0); 6343 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6344 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6345 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6346 return true; 6347 } 6348 6349 static bool hasVirtualDestructor(QualType T) { 6350 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6351 if (CXXDestructorDecl *DD = RD->getDestructor()) 6352 return DD->isVirtual(); 6353 return false; 6354 } 6355 6356 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6357 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6358 if (CXXDestructorDecl *DD = RD->getDestructor()) 6359 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6360 return nullptr; 6361 } 6362 6363 /// Check that the given object is a suitable pointer to a heap allocation that 6364 /// still exists and is of the right kind for the purpose of a deletion. 6365 /// 6366 /// On success, returns the heap allocation to deallocate. On failure, produces 6367 /// a diagnostic and returns None. 6368 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6369 const LValue &Pointer, 6370 DynAlloc::Kind DeallocKind) { 6371 auto PointerAsString = [&] { 6372 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6373 }; 6374 6375 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6376 if (!DA) { 6377 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6378 << PointerAsString(); 6379 if (Pointer.Base) 6380 NoteLValueLocation(Info, Pointer.Base); 6381 return None; 6382 } 6383 6384 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6385 if (!Alloc) { 6386 Info.FFDiag(E, diag::note_constexpr_double_delete); 6387 return None; 6388 } 6389 6390 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6391 if (DeallocKind != (*Alloc)->getKind()) { 6392 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6393 << DeallocKind << (*Alloc)->getKind() << AllocType; 6394 NoteLValueLocation(Info, Pointer.Base); 6395 return None; 6396 } 6397 6398 bool Subobject = false; 6399 if (DeallocKind == DynAlloc::New) { 6400 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6401 Pointer.Designator.isOnePastTheEnd(); 6402 } else { 6403 Subobject = Pointer.Designator.Entries.size() != 1 || 6404 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6405 } 6406 if (Subobject) { 6407 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6408 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6409 return None; 6410 } 6411 6412 return Alloc; 6413 } 6414 6415 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6416 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6417 if (Info.checkingPotentialConstantExpression() || 6418 Info.SpeculativeEvaluationDepth) 6419 return false; 6420 6421 // This is permitted only within a call to std::allocator<T>::deallocate. 6422 if (!Info.getStdAllocatorCaller("deallocate")) { 6423 Info.FFDiag(E->getExprLoc()); 6424 return true; 6425 } 6426 6427 LValue Pointer; 6428 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6429 return false; 6430 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6431 EvaluateIgnoredValue(Info, E->getArg(I)); 6432 6433 if (Pointer.Designator.Invalid) 6434 return false; 6435 6436 // Deleting a null pointer has no effect. 6437 if (Pointer.isNullPointer()) 6438 return true; 6439 6440 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6441 return false; 6442 6443 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6444 return true; 6445 } 6446 6447 //===----------------------------------------------------------------------===// 6448 // Generic Evaluation 6449 //===----------------------------------------------------------------------===// 6450 namespace { 6451 6452 class BitCastBuffer { 6453 // FIXME: We're going to need bit-level granularity when we support 6454 // bit-fields. 6455 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6456 // we don't support a host or target where that is the case. Still, we should 6457 // use a more generic type in case we ever do. 6458 SmallVector<Optional<unsigned char>, 32> Bytes; 6459 6460 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6461 "Need at least 8 bit unsigned char"); 6462 6463 bool TargetIsLittleEndian; 6464 6465 public: 6466 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6467 : Bytes(Width.getQuantity()), 6468 TargetIsLittleEndian(TargetIsLittleEndian) {} 6469 6470 LLVM_NODISCARD 6471 bool readObject(CharUnits Offset, CharUnits Width, 6472 SmallVectorImpl<unsigned char> &Output) const { 6473 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6474 // If a byte of an integer is uninitialized, then the whole integer is 6475 // uninitalized. 6476 if (!Bytes[I.getQuantity()]) 6477 return false; 6478 Output.push_back(*Bytes[I.getQuantity()]); 6479 } 6480 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6481 std::reverse(Output.begin(), Output.end()); 6482 return true; 6483 } 6484 6485 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6486 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6487 std::reverse(Input.begin(), Input.end()); 6488 6489 size_t Index = 0; 6490 for (unsigned char Byte : Input) { 6491 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6492 Bytes[Offset.getQuantity() + Index] = Byte; 6493 ++Index; 6494 } 6495 } 6496 6497 size_t size() { return Bytes.size(); } 6498 }; 6499 6500 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6501 /// target would represent the value at runtime. 6502 class APValueToBufferConverter { 6503 EvalInfo &Info; 6504 BitCastBuffer Buffer; 6505 const CastExpr *BCE; 6506 6507 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6508 const CastExpr *BCE) 6509 : Info(Info), 6510 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6511 BCE(BCE) {} 6512 6513 bool visit(const APValue &Val, QualType Ty) { 6514 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6515 } 6516 6517 // Write out Val with type Ty into Buffer starting at Offset. 6518 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6519 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6520 6521 // As a special case, nullptr_t has an indeterminate value. 6522 if (Ty->isNullPtrType()) 6523 return true; 6524 6525 // Dig through Src to find the byte at SrcOffset. 6526 switch (Val.getKind()) { 6527 case APValue::Indeterminate: 6528 case APValue::None: 6529 return true; 6530 6531 case APValue::Int: 6532 return visitInt(Val.getInt(), Ty, Offset); 6533 case APValue::Float: 6534 return visitFloat(Val.getFloat(), Ty, Offset); 6535 case APValue::Array: 6536 return visitArray(Val, Ty, Offset); 6537 case APValue::Struct: 6538 return visitRecord(Val, Ty, Offset); 6539 6540 case APValue::ComplexInt: 6541 case APValue::ComplexFloat: 6542 case APValue::Vector: 6543 case APValue::FixedPoint: 6544 // FIXME: We should support these. 6545 6546 case APValue::Union: 6547 case APValue::MemberPointer: 6548 case APValue::AddrLabelDiff: { 6549 Info.FFDiag(BCE->getBeginLoc(), 6550 diag::note_constexpr_bit_cast_unsupported_type) 6551 << Ty; 6552 return false; 6553 } 6554 6555 case APValue::LValue: 6556 llvm_unreachable("LValue subobject in bit_cast?"); 6557 } 6558 llvm_unreachable("Unhandled APValue::ValueKind"); 6559 } 6560 6561 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6562 const RecordDecl *RD = Ty->getAsRecordDecl(); 6563 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6564 6565 // Visit the base classes. 6566 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6567 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6568 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6569 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6570 6571 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6572 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6573 return false; 6574 } 6575 } 6576 6577 // Visit the fields. 6578 unsigned FieldIdx = 0; 6579 for (FieldDecl *FD : RD->fields()) { 6580 if (FD->isBitField()) { 6581 Info.FFDiag(BCE->getBeginLoc(), 6582 diag::note_constexpr_bit_cast_unsupported_bitfield); 6583 return false; 6584 } 6585 6586 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6587 6588 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6589 "only bit-fields can have sub-char alignment"); 6590 CharUnits FieldOffset = 6591 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6592 QualType FieldTy = FD->getType(); 6593 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6594 return false; 6595 ++FieldIdx; 6596 } 6597 6598 return true; 6599 } 6600 6601 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6602 const auto *CAT = 6603 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6604 if (!CAT) 6605 return false; 6606 6607 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6608 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6609 unsigned ArraySize = Val.getArraySize(); 6610 // First, initialize the initialized elements. 6611 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6612 const APValue &SubObj = Val.getArrayInitializedElt(I); 6613 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6614 return false; 6615 } 6616 6617 // Next, initialize the rest of the array using the filler. 6618 if (Val.hasArrayFiller()) { 6619 const APValue &Filler = Val.getArrayFiller(); 6620 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6621 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6622 return false; 6623 } 6624 } 6625 6626 return true; 6627 } 6628 6629 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6630 APSInt AdjustedVal = Val; 6631 unsigned Width = AdjustedVal.getBitWidth(); 6632 if (Ty->isBooleanType()) { 6633 Width = Info.Ctx.getTypeSize(Ty); 6634 AdjustedVal = AdjustedVal.extend(Width); 6635 } 6636 6637 SmallVector<unsigned char, 8> Bytes(Width / 8); 6638 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6639 Buffer.writeObject(Offset, Bytes); 6640 return true; 6641 } 6642 6643 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6644 APSInt AsInt(Val.bitcastToAPInt()); 6645 return visitInt(AsInt, Ty, Offset); 6646 } 6647 6648 public: 6649 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6650 const CastExpr *BCE) { 6651 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6652 APValueToBufferConverter Converter(Info, DstSize, BCE); 6653 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6654 return None; 6655 return Converter.Buffer; 6656 } 6657 }; 6658 6659 /// Write an BitCastBuffer into an APValue. 6660 class BufferToAPValueConverter { 6661 EvalInfo &Info; 6662 const BitCastBuffer &Buffer; 6663 const CastExpr *BCE; 6664 6665 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6666 const CastExpr *BCE) 6667 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6668 6669 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6670 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6671 // Ideally this will be unreachable. 6672 llvm::NoneType unsupportedType(QualType Ty) { 6673 Info.FFDiag(BCE->getBeginLoc(), 6674 diag::note_constexpr_bit_cast_unsupported_type) 6675 << Ty; 6676 return None; 6677 } 6678 6679 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6680 Info.FFDiag(BCE->getBeginLoc(), 6681 diag::note_constexpr_bit_cast_unrepresentable_value) 6682 << Ty << Val.toString(/*Radix=*/10); 6683 return None; 6684 } 6685 6686 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6687 const EnumType *EnumSugar = nullptr) { 6688 if (T->isNullPtrType()) { 6689 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6690 return APValue((Expr *)nullptr, 6691 /*Offset=*/CharUnits::fromQuantity(NullValue), 6692 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6693 } 6694 6695 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6696 6697 // Work around floating point types that contain unused padding bytes. This 6698 // is really just `long double` on x86, which is the only fundamental type 6699 // with padding bytes. 6700 if (T->isRealFloatingType()) { 6701 const llvm::fltSemantics &Semantics = 6702 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6703 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 6704 assert(NumBits % 8 == 0); 6705 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 6706 if (NumBytes != SizeOf) 6707 SizeOf = NumBytes; 6708 } 6709 6710 SmallVector<uint8_t, 8> Bytes; 6711 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6712 // If this is std::byte or unsigned char, then its okay to store an 6713 // indeterminate value. 6714 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 6715 bool IsUChar = 6716 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 6717 T->isSpecificBuiltinType(BuiltinType::Char_U)); 6718 if (!IsStdByte && !IsUChar) { 6719 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 6720 Info.FFDiag(BCE->getExprLoc(), 6721 diag::note_constexpr_bit_cast_indet_dest) 6722 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 6723 return None; 6724 } 6725 6726 return APValue::IndeterminateValue(); 6727 } 6728 6729 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 6730 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 6731 6732 if (T->isIntegralOrEnumerationType()) { 6733 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 6734 6735 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 6736 if (IntWidth != Val.getBitWidth()) { 6737 APSInt Truncated = Val.trunc(IntWidth); 6738 if (Truncated.extend(Val.getBitWidth()) != Val) 6739 return unrepresentableValue(QualType(T, 0), Val); 6740 Val = Truncated; 6741 } 6742 6743 return APValue(Val); 6744 } 6745 6746 if (T->isRealFloatingType()) { 6747 const llvm::fltSemantics &Semantics = 6748 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6749 return APValue(APFloat(Semantics, Val)); 6750 } 6751 6752 return unsupportedType(QualType(T, 0)); 6753 } 6754 6755 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 6756 const RecordDecl *RD = RTy->getAsRecordDecl(); 6757 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6758 6759 unsigned NumBases = 0; 6760 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6761 NumBases = CXXRD->getNumBases(); 6762 6763 APValue ResultVal(APValue::UninitStruct(), NumBases, 6764 std::distance(RD->field_begin(), RD->field_end())); 6765 6766 // Visit the base classes. 6767 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6768 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6769 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6770 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6771 if (BaseDecl->isEmpty() || 6772 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 6773 continue; 6774 6775 Optional<APValue> SubObj = visitType( 6776 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 6777 if (!SubObj) 6778 return None; 6779 ResultVal.getStructBase(I) = *SubObj; 6780 } 6781 } 6782 6783 // Visit the fields. 6784 unsigned FieldIdx = 0; 6785 for (FieldDecl *FD : RD->fields()) { 6786 // FIXME: We don't currently support bit-fields. A lot of the logic for 6787 // this is in CodeGen, so we need to factor it around. 6788 if (FD->isBitField()) { 6789 Info.FFDiag(BCE->getBeginLoc(), 6790 diag::note_constexpr_bit_cast_unsupported_bitfield); 6791 return None; 6792 } 6793 6794 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6795 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 6796 6797 CharUnits FieldOffset = 6798 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 6799 Offset; 6800 QualType FieldTy = FD->getType(); 6801 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 6802 if (!SubObj) 6803 return None; 6804 ResultVal.getStructField(FieldIdx) = *SubObj; 6805 ++FieldIdx; 6806 } 6807 6808 return ResultVal; 6809 } 6810 6811 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 6812 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 6813 assert(!RepresentationType.isNull() && 6814 "enum forward decl should be caught by Sema"); 6815 const auto *AsBuiltin = 6816 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 6817 // Recurse into the underlying type. Treat std::byte transparently as 6818 // unsigned char. 6819 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 6820 } 6821 6822 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 6823 size_t Size = Ty->getSize().getLimitedValue(); 6824 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 6825 6826 APValue ArrayValue(APValue::UninitArray(), Size, Size); 6827 for (size_t I = 0; I != Size; ++I) { 6828 Optional<APValue> ElementValue = 6829 visitType(Ty->getElementType(), Offset + I * ElementWidth); 6830 if (!ElementValue) 6831 return None; 6832 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 6833 } 6834 6835 return ArrayValue; 6836 } 6837 6838 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 6839 return unsupportedType(QualType(Ty, 0)); 6840 } 6841 6842 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 6843 QualType Can = Ty.getCanonicalType(); 6844 6845 switch (Can->getTypeClass()) { 6846 #define TYPE(Class, Base) \ 6847 case Type::Class: \ 6848 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 6849 #define ABSTRACT_TYPE(Class, Base) 6850 #define NON_CANONICAL_TYPE(Class, Base) \ 6851 case Type::Class: \ 6852 llvm_unreachable("non-canonical type should be impossible!"); 6853 #define DEPENDENT_TYPE(Class, Base) \ 6854 case Type::Class: \ 6855 llvm_unreachable( \ 6856 "dependent types aren't supported in the constant evaluator!"); 6857 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 6858 case Type::Class: \ 6859 llvm_unreachable("either dependent or not canonical!"); 6860 #include "clang/AST/TypeNodes.inc" 6861 } 6862 llvm_unreachable("Unhandled Type::TypeClass"); 6863 } 6864 6865 public: 6866 // Pull out a full value of type DstType. 6867 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 6868 const CastExpr *BCE) { 6869 BufferToAPValueConverter Converter(Info, Buffer, BCE); 6870 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 6871 } 6872 }; 6873 6874 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 6875 QualType Ty, EvalInfo *Info, 6876 const ASTContext &Ctx, 6877 bool CheckingDest) { 6878 Ty = Ty.getCanonicalType(); 6879 6880 auto diag = [&](int Reason) { 6881 if (Info) 6882 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 6883 << CheckingDest << (Reason == 4) << Reason; 6884 return false; 6885 }; 6886 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 6887 if (Info) 6888 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 6889 << NoteTy << Construct << Ty; 6890 return false; 6891 }; 6892 6893 if (Ty->isUnionType()) 6894 return diag(0); 6895 if (Ty->isPointerType()) 6896 return diag(1); 6897 if (Ty->isMemberPointerType()) 6898 return diag(2); 6899 if (Ty.isVolatileQualified()) 6900 return diag(3); 6901 6902 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 6903 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 6904 for (CXXBaseSpecifier &BS : CXXRD->bases()) 6905 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 6906 CheckingDest)) 6907 return note(1, BS.getType(), BS.getBeginLoc()); 6908 } 6909 for (FieldDecl *FD : Record->fields()) { 6910 if (FD->getType()->isReferenceType()) 6911 return diag(4); 6912 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 6913 CheckingDest)) 6914 return note(0, FD->getType(), FD->getBeginLoc()); 6915 } 6916 } 6917 6918 if (Ty->isArrayType() && 6919 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 6920 Info, Ctx, CheckingDest)) 6921 return false; 6922 6923 return true; 6924 } 6925 6926 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 6927 const ASTContext &Ctx, 6928 const CastExpr *BCE) { 6929 bool DestOK = checkBitCastConstexprEligibilityType( 6930 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 6931 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 6932 BCE->getBeginLoc(), 6933 BCE->getSubExpr()->getType(), Info, Ctx, false); 6934 return SourceOK; 6935 } 6936 6937 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 6938 APValue &SourceValue, 6939 const CastExpr *BCE) { 6940 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 6941 "no host or target supports non 8-bit chars"); 6942 assert(SourceValue.isLValue() && 6943 "LValueToRValueBitcast requires an lvalue operand!"); 6944 6945 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 6946 return false; 6947 6948 LValue SourceLValue; 6949 APValue SourceRValue; 6950 SourceLValue.setFrom(Info.Ctx, SourceValue); 6951 if (!handleLValueToRValueConversion( 6952 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 6953 SourceRValue, /*WantObjectRepresentation=*/true)) 6954 return false; 6955 6956 // Read out SourceValue into a char buffer. 6957 Optional<BitCastBuffer> Buffer = 6958 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 6959 if (!Buffer) 6960 return false; 6961 6962 // Write out the buffer into a new APValue. 6963 Optional<APValue> MaybeDestValue = 6964 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 6965 if (!MaybeDestValue) 6966 return false; 6967 6968 DestValue = std::move(*MaybeDestValue); 6969 return true; 6970 } 6971 6972 template <class Derived> 6973 class ExprEvaluatorBase 6974 : public ConstStmtVisitor<Derived, bool> { 6975 private: 6976 Derived &getDerived() { return static_cast<Derived&>(*this); } 6977 bool DerivedSuccess(const APValue &V, const Expr *E) { 6978 return getDerived().Success(V, E); 6979 } 6980 bool DerivedZeroInitialization(const Expr *E) { 6981 return getDerived().ZeroInitialization(E); 6982 } 6983 6984 // Check whether a conditional operator with a non-constant condition is a 6985 // potential constant expression. If neither arm is a potential constant 6986 // expression, then the conditional operator is not either. 6987 template<typename ConditionalOperator> 6988 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 6989 assert(Info.checkingPotentialConstantExpression()); 6990 6991 // Speculatively evaluate both arms. 6992 SmallVector<PartialDiagnosticAt, 8> Diag; 6993 { 6994 SpeculativeEvaluationRAII Speculate(Info, &Diag); 6995 StmtVisitorTy::Visit(E->getFalseExpr()); 6996 if (Diag.empty()) 6997 return; 6998 } 6999 7000 { 7001 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7002 Diag.clear(); 7003 StmtVisitorTy::Visit(E->getTrueExpr()); 7004 if (Diag.empty()) 7005 return; 7006 } 7007 7008 Error(E, diag::note_constexpr_conditional_never_const); 7009 } 7010 7011 7012 template<typename ConditionalOperator> 7013 bool HandleConditionalOperator(const ConditionalOperator *E) { 7014 bool BoolResult; 7015 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7016 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7017 CheckPotentialConstantConditional(E); 7018 return false; 7019 } 7020 if (Info.noteFailure()) { 7021 StmtVisitorTy::Visit(E->getTrueExpr()); 7022 StmtVisitorTy::Visit(E->getFalseExpr()); 7023 } 7024 return false; 7025 } 7026 7027 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7028 return StmtVisitorTy::Visit(EvalExpr); 7029 } 7030 7031 protected: 7032 EvalInfo &Info; 7033 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7034 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7035 7036 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7037 return Info.CCEDiag(E, D); 7038 } 7039 7040 bool ZeroInitialization(const Expr *E) { return Error(E); } 7041 7042 public: 7043 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7044 7045 EvalInfo &getEvalInfo() { return Info; } 7046 7047 /// Report an evaluation error. This should only be called when an error is 7048 /// first discovered. When propagating an error, just return false. 7049 bool Error(const Expr *E, diag::kind D) { 7050 Info.FFDiag(E, D); 7051 return false; 7052 } 7053 bool Error(const Expr *E) { 7054 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7055 } 7056 7057 bool VisitStmt(const Stmt *) { 7058 llvm_unreachable("Expression evaluator should not be called on stmts"); 7059 } 7060 bool VisitExpr(const Expr *E) { 7061 return Error(E); 7062 } 7063 7064 bool VisitConstantExpr(const ConstantExpr *E) { 7065 if (E->hasAPValueResult()) 7066 return DerivedSuccess(E->getAPValueResult(), E); 7067 7068 return StmtVisitorTy::Visit(E->getSubExpr()); 7069 } 7070 7071 bool VisitParenExpr(const ParenExpr *E) 7072 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7073 bool VisitUnaryExtension(const UnaryOperator *E) 7074 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7075 bool VisitUnaryPlus(const UnaryOperator *E) 7076 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7077 bool VisitChooseExpr(const ChooseExpr *E) 7078 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7079 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7080 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7081 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7082 { return StmtVisitorTy::Visit(E->getReplacement()); } 7083 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7084 TempVersionRAII RAII(*Info.CurrentCall); 7085 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7086 return StmtVisitorTy::Visit(E->getExpr()); 7087 } 7088 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7089 TempVersionRAII RAII(*Info.CurrentCall); 7090 // The initializer may not have been parsed yet, or might be erroneous. 7091 if (!E->getExpr()) 7092 return Error(E); 7093 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7094 return StmtVisitorTy::Visit(E->getExpr()); 7095 } 7096 7097 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7098 FullExpressionRAII Scope(Info); 7099 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7100 } 7101 7102 // Temporaries are registered when created, so we don't care about 7103 // CXXBindTemporaryExpr. 7104 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7105 return StmtVisitorTy::Visit(E->getSubExpr()); 7106 } 7107 7108 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7109 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7110 return static_cast<Derived*>(this)->VisitCastExpr(E); 7111 } 7112 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7113 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7114 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7115 return static_cast<Derived*>(this)->VisitCastExpr(E); 7116 } 7117 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7118 return static_cast<Derived*>(this)->VisitCastExpr(E); 7119 } 7120 7121 bool VisitBinaryOperator(const BinaryOperator *E) { 7122 switch (E->getOpcode()) { 7123 default: 7124 return Error(E); 7125 7126 case BO_Comma: 7127 VisitIgnoredValue(E->getLHS()); 7128 return StmtVisitorTy::Visit(E->getRHS()); 7129 7130 case BO_PtrMemD: 7131 case BO_PtrMemI: { 7132 LValue Obj; 7133 if (!HandleMemberPointerAccess(Info, E, Obj)) 7134 return false; 7135 APValue Result; 7136 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7137 return false; 7138 return DerivedSuccess(Result, E); 7139 } 7140 } 7141 } 7142 7143 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7144 return StmtVisitorTy::Visit(E->getSemanticForm()); 7145 } 7146 7147 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7148 // Evaluate and cache the common expression. We treat it as a temporary, 7149 // even though it's not quite the same thing. 7150 LValue CommonLV; 7151 if (!Evaluate(Info.CurrentCall->createTemporary( 7152 E->getOpaqueValue(), 7153 getStorageType(Info.Ctx, E->getOpaqueValue()), false, 7154 CommonLV), 7155 Info, E->getCommon())) 7156 return false; 7157 7158 return HandleConditionalOperator(E); 7159 } 7160 7161 bool VisitConditionalOperator(const ConditionalOperator *E) { 7162 bool IsBcpCall = false; 7163 // If the condition (ignoring parens) is a __builtin_constant_p call, 7164 // the result is a constant expression if it can be folded without 7165 // side-effects. This is an important GNU extension. See GCC PR38377 7166 // for discussion. 7167 if (const CallExpr *CallCE = 7168 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7169 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7170 IsBcpCall = true; 7171 7172 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7173 // constant expression; we can't check whether it's potentially foldable. 7174 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7175 // it would return 'false' in this mode. 7176 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7177 return false; 7178 7179 FoldConstant Fold(Info, IsBcpCall); 7180 if (!HandleConditionalOperator(E)) { 7181 Fold.keepDiagnostics(); 7182 return false; 7183 } 7184 7185 return true; 7186 } 7187 7188 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7189 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7190 return DerivedSuccess(*Value, E); 7191 7192 const Expr *Source = E->getSourceExpr(); 7193 if (!Source) 7194 return Error(E); 7195 if (Source == E) { // sanity checking. 7196 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7197 return Error(E); 7198 } 7199 return StmtVisitorTy::Visit(Source); 7200 } 7201 7202 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7203 for (const Expr *SemE : E->semantics()) { 7204 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7205 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7206 // result expression: there could be two different LValues that would 7207 // refer to the same object in that case, and we can't model that. 7208 if (SemE == E->getResultExpr()) 7209 return Error(E); 7210 7211 // Unique OVEs get evaluated if and when we encounter them when 7212 // emitting the rest of the semantic form, rather than eagerly. 7213 if (OVE->isUnique()) 7214 continue; 7215 7216 LValue LV; 7217 if (!Evaluate(Info.CurrentCall->createTemporary( 7218 OVE, getStorageType(Info.Ctx, OVE), false, LV), 7219 Info, OVE->getSourceExpr())) 7220 return false; 7221 } else if (SemE == E->getResultExpr()) { 7222 if (!StmtVisitorTy::Visit(SemE)) 7223 return false; 7224 } else { 7225 if (!EvaluateIgnoredValue(Info, SemE)) 7226 return false; 7227 } 7228 } 7229 return true; 7230 } 7231 7232 bool VisitCallExpr(const CallExpr *E) { 7233 APValue Result; 7234 if (!handleCallExpr(E, Result, nullptr)) 7235 return false; 7236 return DerivedSuccess(Result, E); 7237 } 7238 7239 bool handleCallExpr(const CallExpr *E, APValue &Result, 7240 const LValue *ResultSlot) { 7241 const Expr *Callee = E->getCallee()->IgnoreParens(); 7242 QualType CalleeType = Callee->getType(); 7243 7244 const FunctionDecl *FD = nullptr; 7245 LValue *This = nullptr, ThisVal; 7246 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7247 bool HasQualifier = false; 7248 7249 // Extract function decl and 'this' pointer from the callee. 7250 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7251 const CXXMethodDecl *Member = nullptr; 7252 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7253 // Explicit bound member calls, such as x.f() or p->g(); 7254 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7255 return false; 7256 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7257 if (!Member) 7258 return Error(Callee); 7259 This = &ThisVal; 7260 HasQualifier = ME->hasQualifier(); 7261 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7262 // Indirect bound member calls ('.*' or '->*'). 7263 const ValueDecl *D = 7264 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7265 if (!D) 7266 return false; 7267 Member = dyn_cast<CXXMethodDecl>(D); 7268 if (!Member) 7269 return Error(Callee); 7270 This = &ThisVal; 7271 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7272 if (!Info.getLangOpts().CPlusPlus20) 7273 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7274 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7275 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7276 } else 7277 return Error(Callee); 7278 FD = Member; 7279 } else if (CalleeType->isFunctionPointerType()) { 7280 LValue Call; 7281 if (!EvaluatePointer(Callee, Call, Info)) 7282 return false; 7283 7284 if (!Call.getLValueOffset().isZero()) 7285 return Error(Callee); 7286 FD = dyn_cast_or_null<FunctionDecl>( 7287 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 7288 if (!FD) 7289 return Error(Callee); 7290 // Don't call function pointers which have been cast to some other type. 7291 // Per DR (no number yet), the caller and callee can differ in noexcept. 7292 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7293 CalleeType->getPointeeType(), FD->getType())) { 7294 return Error(E); 7295 } 7296 7297 // Overloaded operator calls to member functions are represented as normal 7298 // calls with '*this' as the first argument. 7299 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7300 if (MD && !MD->isStatic()) { 7301 // FIXME: When selecting an implicit conversion for an overloaded 7302 // operator delete, we sometimes try to evaluate calls to conversion 7303 // operators without a 'this' parameter! 7304 if (Args.empty()) 7305 return Error(E); 7306 7307 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7308 return false; 7309 This = &ThisVal; 7310 Args = Args.slice(1); 7311 } else if (MD && MD->isLambdaStaticInvoker()) { 7312 // Map the static invoker for the lambda back to the call operator. 7313 // Conveniently, we don't have to slice out the 'this' argument (as is 7314 // being done for the non-static case), since a static member function 7315 // doesn't have an implicit argument passed in. 7316 const CXXRecordDecl *ClosureClass = MD->getParent(); 7317 assert( 7318 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7319 "Number of captures must be zero for conversion to function-ptr"); 7320 7321 const CXXMethodDecl *LambdaCallOp = 7322 ClosureClass->getLambdaCallOperator(); 7323 7324 // Set 'FD', the function that will be called below, to the call 7325 // operator. If the closure object represents a generic lambda, find 7326 // the corresponding specialization of the call operator. 7327 7328 if (ClosureClass->isGenericLambda()) { 7329 assert(MD->isFunctionTemplateSpecialization() && 7330 "A generic lambda's static-invoker function must be a " 7331 "template specialization"); 7332 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7333 FunctionTemplateDecl *CallOpTemplate = 7334 LambdaCallOp->getDescribedFunctionTemplate(); 7335 void *InsertPos = nullptr; 7336 FunctionDecl *CorrespondingCallOpSpecialization = 7337 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7338 assert(CorrespondingCallOpSpecialization && 7339 "We must always have a function call operator specialization " 7340 "that corresponds to our static invoker specialization"); 7341 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7342 } else 7343 FD = LambdaCallOp; 7344 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7345 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7346 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7347 LValue Ptr; 7348 if (!HandleOperatorNewCall(Info, E, Ptr)) 7349 return false; 7350 Ptr.moveInto(Result); 7351 return true; 7352 } else { 7353 return HandleOperatorDeleteCall(Info, E); 7354 } 7355 } 7356 } else 7357 return Error(E); 7358 7359 SmallVector<QualType, 4> CovariantAdjustmentPath; 7360 if (This) { 7361 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7362 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7363 // Perform virtual dispatch, if necessary. 7364 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7365 CovariantAdjustmentPath); 7366 if (!FD) 7367 return false; 7368 } else { 7369 // Check that the 'this' pointer points to an object of the right type. 7370 // FIXME: If this is an assignment operator call, we may need to change 7371 // the active union member before we check this. 7372 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7373 return false; 7374 } 7375 } 7376 7377 // Destructor calls are different enough that they have their own codepath. 7378 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7379 assert(This && "no 'this' pointer for destructor call"); 7380 return HandleDestruction(Info, E, *This, 7381 Info.Ctx.getRecordType(DD->getParent())); 7382 } 7383 7384 const FunctionDecl *Definition = nullptr; 7385 Stmt *Body = FD->getBody(Definition); 7386 7387 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7388 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 7389 Result, ResultSlot)) 7390 return false; 7391 7392 if (!CovariantAdjustmentPath.empty() && 7393 !HandleCovariantReturnAdjustment(Info, E, Result, 7394 CovariantAdjustmentPath)) 7395 return false; 7396 7397 return true; 7398 } 7399 7400 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7401 return StmtVisitorTy::Visit(E->getInitializer()); 7402 } 7403 bool VisitInitListExpr(const InitListExpr *E) { 7404 if (E->getNumInits() == 0) 7405 return DerivedZeroInitialization(E); 7406 if (E->getNumInits() == 1) 7407 return StmtVisitorTy::Visit(E->getInit(0)); 7408 return Error(E); 7409 } 7410 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7411 return DerivedZeroInitialization(E); 7412 } 7413 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7414 return DerivedZeroInitialization(E); 7415 } 7416 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7417 return DerivedZeroInitialization(E); 7418 } 7419 7420 /// A member expression where the object is a prvalue is itself a prvalue. 7421 bool VisitMemberExpr(const MemberExpr *E) { 7422 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7423 "missing temporary materialization conversion"); 7424 assert(!E->isArrow() && "missing call to bound member function?"); 7425 7426 APValue Val; 7427 if (!Evaluate(Val, Info, E->getBase())) 7428 return false; 7429 7430 QualType BaseTy = E->getBase()->getType(); 7431 7432 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7433 if (!FD) return Error(E); 7434 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7435 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7436 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7437 7438 // Note: there is no lvalue base here. But this case should only ever 7439 // happen in C or in C++98, where we cannot be evaluating a constexpr 7440 // constructor, which is the only case the base matters. 7441 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7442 SubobjectDesignator Designator(BaseTy); 7443 Designator.addDeclUnchecked(FD); 7444 7445 APValue Result; 7446 return extractSubobject(Info, E, Obj, Designator, Result) && 7447 DerivedSuccess(Result, E); 7448 } 7449 7450 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7451 APValue Val; 7452 if (!Evaluate(Val, Info, E->getBase())) 7453 return false; 7454 7455 if (Val.isVector()) { 7456 SmallVector<uint32_t, 4> Indices; 7457 E->getEncodedElementAccess(Indices); 7458 if (Indices.size() == 1) { 7459 // Return scalar. 7460 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7461 } else { 7462 // Construct new APValue vector. 7463 SmallVector<APValue, 4> Elts; 7464 for (unsigned I = 0; I < Indices.size(); ++I) { 7465 Elts.push_back(Val.getVectorElt(Indices[I])); 7466 } 7467 APValue VecResult(Elts.data(), Indices.size()); 7468 return DerivedSuccess(VecResult, E); 7469 } 7470 } 7471 7472 return false; 7473 } 7474 7475 bool VisitCastExpr(const CastExpr *E) { 7476 switch (E->getCastKind()) { 7477 default: 7478 break; 7479 7480 case CK_AtomicToNonAtomic: { 7481 APValue AtomicVal; 7482 // This does not need to be done in place even for class/array types: 7483 // atomic-to-non-atomic conversion implies copying the object 7484 // representation. 7485 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7486 return false; 7487 return DerivedSuccess(AtomicVal, E); 7488 } 7489 7490 case CK_NoOp: 7491 case CK_UserDefinedConversion: 7492 return StmtVisitorTy::Visit(E->getSubExpr()); 7493 7494 case CK_LValueToRValue: { 7495 LValue LVal; 7496 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7497 return false; 7498 APValue RVal; 7499 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7500 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7501 LVal, RVal)) 7502 return false; 7503 return DerivedSuccess(RVal, E); 7504 } 7505 case CK_LValueToRValueBitCast: { 7506 APValue DestValue, SourceValue; 7507 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7508 return false; 7509 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7510 return false; 7511 return DerivedSuccess(DestValue, E); 7512 } 7513 7514 case CK_AddressSpaceConversion: { 7515 APValue Value; 7516 if (!Evaluate(Value, Info, E->getSubExpr())) 7517 return false; 7518 return DerivedSuccess(Value, E); 7519 } 7520 } 7521 7522 return Error(E); 7523 } 7524 7525 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7526 return VisitUnaryPostIncDec(UO); 7527 } 7528 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7529 return VisitUnaryPostIncDec(UO); 7530 } 7531 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7532 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7533 return Error(UO); 7534 7535 LValue LVal; 7536 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7537 return false; 7538 APValue RVal; 7539 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7540 UO->isIncrementOp(), &RVal)) 7541 return false; 7542 return DerivedSuccess(RVal, UO); 7543 } 7544 7545 bool VisitStmtExpr(const StmtExpr *E) { 7546 // We will have checked the full-expressions inside the statement expression 7547 // when they were completed, and don't need to check them again now. 7548 if (Info.checkingForUndefinedBehavior()) 7549 return Error(E); 7550 7551 const CompoundStmt *CS = E->getSubStmt(); 7552 if (CS->body_empty()) 7553 return true; 7554 7555 BlockScopeRAII Scope(Info); 7556 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7557 BE = CS->body_end(); 7558 /**/; ++BI) { 7559 if (BI + 1 == BE) { 7560 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7561 if (!FinalExpr) { 7562 Info.FFDiag((*BI)->getBeginLoc(), 7563 diag::note_constexpr_stmt_expr_unsupported); 7564 return false; 7565 } 7566 return this->Visit(FinalExpr) && Scope.destroy(); 7567 } 7568 7569 APValue ReturnValue; 7570 StmtResult Result = { ReturnValue, nullptr }; 7571 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7572 if (ESR != ESR_Succeeded) { 7573 // FIXME: If the statement-expression terminated due to 'return', 7574 // 'break', or 'continue', it would be nice to propagate that to 7575 // the outer statement evaluation rather than bailing out. 7576 if (ESR != ESR_Failed) 7577 Info.FFDiag((*BI)->getBeginLoc(), 7578 diag::note_constexpr_stmt_expr_unsupported); 7579 return false; 7580 } 7581 } 7582 7583 llvm_unreachable("Return from function from the loop above."); 7584 } 7585 7586 /// Visit a value which is evaluated, but whose value is ignored. 7587 void VisitIgnoredValue(const Expr *E) { 7588 EvaluateIgnoredValue(Info, E); 7589 } 7590 7591 /// Potentially visit a MemberExpr's base expression. 7592 void VisitIgnoredBaseExpression(const Expr *E) { 7593 // While MSVC doesn't evaluate the base expression, it does diagnose the 7594 // presence of side-effecting behavior. 7595 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7596 return; 7597 VisitIgnoredValue(E); 7598 } 7599 }; 7600 7601 } // namespace 7602 7603 //===----------------------------------------------------------------------===// 7604 // Common base class for lvalue and temporary evaluation. 7605 //===----------------------------------------------------------------------===// 7606 namespace { 7607 template<class Derived> 7608 class LValueExprEvaluatorBase 7609 : public ExprEvaluatorBase<Derived> { 7610 protected: 7611 LValue &Result; 7612 bool InvalidBaseOK; 7613 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7614 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7615 7616 bool Success(APValue::LValueBase B) { 7617 Result.set(B); 7618 return true; 7619 } 7620 7621 bool evaluatePointer(const Expr *E, LValue &Result) { 7622 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7623 } 7624 7625 public: 7626 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7627 : ExprEvaluatorBaseTy(Info), Result(Result), 7628 InvalidBaseOK(InvalidBaseOK) {} 7629 7630 bool Success(const APValue &V, const Expr *E) { 7631 Result.setFrom(this->Info.Ctx, V); 7632 return true; 7633 } 7634 7635 bool VisitMemberExpr(const MemberExpr *E) { 7636 // Handle non-static data members. 7637 QualType BaseTy; 7638 bool EvalOK; 7639 if (E->isArrow()) { 7640 EvalOK = evaluatePointer(E->getBase(), Result); 7641 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7642 } else if (E->getBase()->isRValue()) { 7643 assert(E->getBase()->getType()->isRecordType()); 7644 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7645 BaseTy = E->getBase()->getType(); 7646 } else { 7647 EvalOK = this->Visit(E->getBase()); 7648 BaseTy = E->getBase()->getType(); 7649 } 7650 if (!EvalOK) { 7651 if (!InvalidBaseOK) 7652 return false; 7653 Result.setInvalid(E); 7654 return true; 7655 } 7656 7657 const ValueDecl *MD = E->getMemberDecl(); 7658 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7659 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7660 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7661 (void)BaseTy; 7662 if (!HandleLValueMember(this->Info, E, Result, FD)) 7663 return false; 7664 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7665 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7666 return false; 7667 } else 7668 return this->Error(E); 7669 7670 if (MD->getType()->isReferenceType()) { 7671 APValue RefValue; 7672 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7673 RefValue)) 7674 return false; 7675 return Success(RefValue, E); 7676 } 7677 return true; 7678 } 7679 7680 bool VisitBinaryOperator(const BinaryOperator *E) { 7681 switch (E->getOpcode()) { 7682 default: 7683 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7684 7685 case BO_PtrMemD: 7686 case BO_PtrMemI: 7687 return HandleMemberPointerAccess(this->Info, E, Result); 7688 } 7689 } 7690 7691 bool VisitCastExpr(const CastExpr *E) { 7692 switch (E->getCastKind()) { 7693 default: 7694 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7695 7696 case CK_DerivedToBase: 7697 case CK_UncheckedDerivedToBase: 7698 if (!this->Visit(E->getSubExpr())) 7699 return false; 7700 7701 // Now figure out the necessary offset to add to the base LV to get from 7702 // the derived class to the base class. 7703 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 7704 Result); 7705 } 7706 } 7707 }; 7708 } 7709 7710 //===----------------------------------------------------------------------===// 7711 // LValue Evaluation 7712 // 7713 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 7714 // function designators (in C), decl references to void objects (in C), and 7715 // temporaries (if building with -Wno-address-of-temporary). 7716 // 7717 // LValue evaluation produces values comprising a base expression of one of the 7718 // following types: 7719 // - Declarations 7720 // * VarDecl 7721 // * FunctionDecl 7722 // - Literals 7723 // * CompoundLiteralExpr in C (and in global scope in C++) 7724 // * StringLiteral 7725 // * PredefinedExpr 7726 // * ObjCStringLiteralExpr 7727 // * ObjCEncodeExpr 7728 // * AddrLabelExpr 7729 // * BlockExpr 7730 // * CallExpr for a MakeStringConstant builtin 7731 // - typeid(T) expressions, as TypeInfoLValues 7732 // - Locals and temporaries 7733 // * MaterializeTemporaryExpr 7734 // * Any Expr, with a CallIndex indicating the function in which the temporary 7735 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 7736 // from the AST (FIXME). 7737 // * A MaterializeTemporaryExpr that has static storage duration, with no 7738 // CallIndex, for a lifetime-extended temporary. 7739 // * The ConstantExpr that is currently being evaluated during evaluation of an 7740 // immediate invocation. 7741 // plus an offset in bytes. 7742 //===----------------------------------------------------------------------===// 7743 namespace { 7744 class LValueExprEvaluator 7745 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 7746 public: 7747 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 7748 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 7749 7750 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 7751 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 7752 7753 bool VisitDeclRefExpr(const DeclRefExpr *E); 7754 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 7755 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 7756 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 7757 bool VisitMemberExpr(const MemberExpr *E); 7758 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 7759 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 7760 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 7761 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 7762 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 7763 bool VisitUnaryDeref(const UnaryOperator *E); 7764 bool VisitUnaryReal(const UnaryOperator *E); 7765 bool VisitUnaryImag(const UnaryOperator *E); 7766 bool VisitUnaryPreInc(const UnaryOperator *UO) { 7767 return VisitUnaryPreIncDec(UO); 7768 } 7769 bool VisitUnaryPreDec(const UnaryOperator *UO) { 7770 return VisitUnaryPreIncDec(UO); 7771 } 7772 bool VisitBinAssign(const BinaryOperator *BO); 7773 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 7774 7775 bool VisitCastExpr(const CastExpr *E) { 7776 switch (E->getCastKind()) { 7777 default: 7778 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 7779 7780 case CK_LValueBitCast: 7781 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7782 if (!Visit(E->getSubExpr())) 7783 return false; 7784 Result.Designator.setInvalid(); 7785 return true; 7786 7787 case CK_BaseToDerived: 7788 if (!Visit(E->getSubExpr())) 7789 return false; 7790 return HandleBaseToDerivedCast(Info, E, Result); 7791 7792 case CK_Dynamic: 7793 if (!Visit(E->getSubExpr())) 7794 return false; 7795 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 7796 } 7797 } 7798 }; 7799 } // end anonymous namespace 7800 7801 /// Evaluate an expression as an lvalue. This can be legitimately called on 7802 /// expressions which are not glvalues, in three cases: 7803 /// * function designators in C, and 7804 /// * "extern void" objects 7805 /// * @selector() expressions in Objective-C 7806 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 7807 bool InvalidBaseOK) { 7808 assert(E->isGLValue() || E->getType()->isFunctionType() || 7809 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 7810 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 7811 } 7812 7813 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 7814 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 7815 return Success(FD); 7816 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 7817 return VisitVarDecl(E, VD); 7818 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 7819 return Visit(BD->getBinding()); 7820 if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(E->getDecl())) 7821 return Success(GD); 7822 return Error(E); 7823 } 7824 7825 7826 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 7827 7828 // If we are within a lambda's call operator, check whether the 'VD' referred 7829 // to within 'E' actually represents a lambda-capture that maps to a 7830 // data-member/field within the closure object, and if so, evaluate to the 7831 // field or what the field refers to. 7832 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 7833 isa<DeclRefExpr>(E) && 7834 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 7835 // We don't always have a complete capture-map when checking or inferring if 7836 // the function call operator meets the requirements of a constexpr function 7837 // - but we don't need to evaluate the captures to determine constexprness 7838 // (dcl.constexpr C++17). 7839 if (Info.checkingPotentialConstantExpression()) 7840 return false; 7841 7842 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 7843 // Start with 'Result' referring to the complete closure object... 7844 Result = *Info.CurrentCall->This; 7845 // ... then update it to refer to the field of the closure object 7846 // that represents the capture. 7847 if (!HandleLValueMember(Info, E, Result, FD)) 7848 return false; 7849 // And if the field is of reference type, update 'Result' to refer to what 7850 // the field refers to. 7851 if (FD->getType()->isReferenceType()) { 7852 APValue RVal; 7853 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 7854 RVal)) 7855 return false; 7856 Result.setFrom(Info.Ctx, RVal); 7857 } 7858 return true; 7859 } 7860 } 7861 CallStackFrame *Frame = nullptr; 7862 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 7863 // Only if a local variable was declared in the function currently being 7864 // evaluated, do we expect to be able to find its value in the current 7865 // frame. (Otherwise it was likely declared in an enclosing context and 7866 // could either have a valid evaluatable value (for e.g. a constexpr 7867 // variable) or be ill-formed (and trigger an appropriate evaluation 7868 // diagnostic)). 7869 if (Info.CurrentCall->Callee && 7870 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 7871 Frame = Info.CurrentCall; 7872 } 7873 } 7874 7875 if (!VD->getType()->isReferenceType()) { 7876 if (Frame) { 7877 Result.set({VD, Frame->Index, 7878 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 7879 return true; 7880 } 7881 return Success(VD); 7882 } 7883 7884 APValue *V; 7885 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 7886 return false; 7887 if (!V->hasValue()) { 7888 // FIXME: Is it possible for V to be indeterminate here? If so, we should 7889 // adjust the diagnostic to say that. 7890 if (!Info.checkingPotentialConstantExpression()) 7891 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 7892 return false; 7893 } 7894 return Success(*V, E); 7895 } 7896 7897 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 7898 const MaterializeTemporaryExpr *E) { 7899 // Walk through the expression to find the materialized temporary itself. 7900 SmallVector<const Expr *, 2> CommaLHSs; 7901 SmallVector<SubobjectAdjustment, 2> Adjustments; 7902 const Expr *Inner = 7903 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 7904 7905 // If we passed any comma operators, evaluate their LHSs. 7906 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 7907 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 7908 return false; 7909 7910 // A materialized temporary with static storage duration can appear within the 7911 // result of a constant expression evaluation, so we need to preserve its 7912 // value for use outside this evaluation. 7913 APValue *Value; 7914 if (E->getStorageDuration() == SD_Static) { 7915 Value = E->getOrCreateValue(true); 7916 *Value = APValue(); 7917 Result.set(E); 7918 } else { 7919 Value = &Info.CurrentCall->createTemporary( 7920 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result); 7921 } 7922 7923 QualType Type = Inner->getType(); 7924 7925 // Materialize the temporary itself. 7926 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 7927 *Value = APValue(); 7928 return false; 7929 } 7930 7931 // Adjust our lvalue to refer to the desired subobject. 7932 for (unsigned I = Adjustments.size(); I != 0; /**/) { 7933 --I; 7934 switch (Adjustments[I].Kind) { 7935 case SubobjectAdjustment::DerivedToBaseAdjustment: 7936 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 7937 Type, Result)) 7938 return false; 7939 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 7940 break; 7941 7942 case SubobjectAdjustment::FieldAdjustment: 7943 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 7944 return false; 7945 Type = Adjustments[I].Field->getType(); 7946 break; 7947 7948 case SubobjectAdjustment::MemberPointerAdjustment: 7949 if (!HandleMemberPointerAccess(this->Info, Type, Result, 7950 Adjustments[I].Ptr.RHS)) 7951 return false; 7952 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 7953 break; 7954 } 7955 } 7956 7957 return true; 7958 } 7959 7960 bool 7961 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7962 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 7963 "lvalue compound literal in c++?"); 7964 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 7965 // only see this when folding in C, so there's no standard to follow here. 7966 return Success(E); 7967 } 7968 7969 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 7970 TypeInfoLValue TypeInfo; 7971 7972 if (!E->isPotentiallyEvaluated()) { 7973 if (E->isTypeOperand()) 7974 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 7975 else 7976 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 7977 } else { 7978 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 7979 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 7980 << E->getExprOperand()->getType() 7981 << E->getExprOperand()->getSourceRange(); 7982 } 7983 7984 if (!Visit(E->getExprOperand())) 7985 return false; 7986 7987 Optional<DynamicType> DynType = 7988 ComputeDynamicType(Info, E, Result, AK_TypeId); 7989 if (!DynType) 7990 return false; 7991 7992 TypeInfo = 7993 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 7994 } 7995 7996 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 7997 } 7998 7999 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8000 return Success(E->getGuidDecl()); 8001 } 8002 8003 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8004 // Handle static data members. 8005 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8006 VisitIgnoredBaseExpression(E->getBase()); 8007 return VisitVarDecl(E, VD); 8008 } 8009 8010 // Handle static member functions. 8011 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8012 if (MD->isStatic()) { 8013 VisitIgnoredBaseExpression(E->getBase()); 8014 return Success(MD); 8015 } 8016 } 8017 8018 // Handle non-static data members. 8019 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8020 } 8021 8022 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8023 // FIXME: Deal with vectors as array subscript bases. 8024 if (E->getBase()->getType()->isVectorType()) 8025 return Error(E); 8026 8027 bool Success = true; 8028 if (!evaluatePointer(E->getBase(), Result)) { 8029 if (!Info.noteFailure()) 8030 return false; 8031 Success = false; 8032 } 8033 8034 APSInt Index; 8035 if (!EvaluateInteger(E->getIdx(), Index, Info)) 8036 return false; 8037 8038 return Success && 8039 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8040 } 8041 8042 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8043 return evaluatePointer(E->getSubExpr(), Result); 8044 } 8045 8046 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8047 if (!Visit(E->getSubExpr())) 8048 return false; 8049 // __real is a no-op on scalar lvalues. 8050 if (E->getSubExpr()->getType()->isAnyComplexType()) 8051 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8052 return true; 8053 } 8054 8055 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8056 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8057 "lvalue __imag__ on scalar?"); 8058 if (!Visit(E->getSubExpr())) 8059 return false; 8060 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8061 return true; 8062 } 8063 8064 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8065 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8066 return Error(UO); 8067 8068 if (!this->Visit(UO->getSubExpr())) 8069 return false; 8070 8071 return handleIncDec( 8072 this->Info, UO, Result, UO->getSubExpr()->getType(), 8073 UO->isIncrementOp(), nullptr); 8074 } 8075 8076 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8077 const CompoundAssignOperator *CAO) { 8078 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8079 return Error(CAO); 8080 8081 APValue RHS; 8082 8083 // The overall lvalue result is the result of evaluating the LHS. 8084 if (!this->Visit(CAO->getLHS())) { 8085 if (Info.noteFailure()) 8086 Evaluate(RHS, this->Info, CAO->getRHS()); 8087 return false; 8088 } 8089 8090 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 8091 return false; 8092 8093 return handleCompoundAssignment( 8094 this->Info, CAO, 8095 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8096 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8097 } 8098 8099 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8100 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8101 return Error(E); 8102 8103 APValue NewVal; 8104 8105 if (!this->Visit(E->getLHS())) { 8106 if (Info.noteFailure()) 8107 Evaluate(NewVal, this->Info, E->getRHS()); 8108 return false; 8109 } 8110 8111 if (!Evaluate(NewVal, this->Info, E->getRHS())) 8112 return false; 8113 8114 if (Info.getLangOpts().CPlusPlus20 && 8115 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8116 return false; 8117 8118 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8119 NewVal); 8120 } 8121 8122 //===----------------------------------------------------------------------===// 8123 // Pointer Evaluation 8124 //===----------------------------------------------------------------------===// 8125 8126 /// Attempts to compute the number of bytes available at the pointer 8127 /// returned by a function with the alloc_size attribute. Returns true if we 8128 /// were successful. Places an unsigned number into `Result`. 8129 /// 8130 /// This expects the given CallExpr to be a call to a function with an 8131 /// alloc_size attribute. 8132 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8133 const CallExpr *Call, 8134 llvm::APInt &Result) { 8135 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8136 8137 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8138 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8139 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8140 if (Call->getNumArgs() <= SizeArgNo) 8141 return false; 8142 8143 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8144 Expr::EvalResult ExprResult; 8145 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8146 return false; 8147 Into = ExprResult.Val.getInt(); 8148 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8149 return false; 8150 Into = Into.zextOrSelf(BitsInSizeT); 8151 return true; 8152 }; 8153 8154 APSInt SizeOfElem; 8155 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8156 return false; 8157 8158 if (!AllocSize->getNumElemsParam().isValid()) { 8159 Result = std::move(SizeOfElem); 8160 return true; 8161 } 8162 8163 APSInt NumberOfElems; 8164 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8165 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8166 return false; 8167 8168 bool Overflow; 8169 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8170 if (Overflow) 8171 return false; 8172 8173 Result = std::move(BytesAvailable); 8174 return true; 8175 } 8176 8177 /// Convenience function. LVal's base must be a call to an alloc_size 8178 /// function. 8179 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8180 const LValue &LVal, 8181 llvm::APInt &Result) { 8182 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8183 "Can't get the size of a non alloc_size function"); 8184 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8185 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8186 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8187 } 8188 8189 /// Attempts to evaluate the given LValueBase as the result of a call to 8190 /// a function with the alloc_size attribute. If it was possible to do so, this 8191 /// function will return true, make Result's Base point to said function call, 8192 /// and mark Result's Base as invalid. 8193 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8194 LValue &Result) { 8195 if (Base.isNull()) 8196 return false; 8197 8198 // Because we do no form of static analysis, we only support const variables. 8199 // 8200 // Additionally, we can't support parameters, nor can we support static 8201 // variables (in the latter case, use-before-assign isn't UB; in the former, 8202 // we have no clue what they'll be assigned to). 8203 const auto *VD = 8204 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8205 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8206 return false; 8207 8208 const Expr *Init = VD->getAnyInitializer(); 8209 if (!Init) 8210 return false; 8211 8212 const Expr *E = Init->IgnoreParens(); 8213 if (!tryUnwrapAllocSizeCall(E)) 8214 return false; 8215 8216 // Store E instead of E unwrapped so that the type of the LValue's base is 8217 // what the user wanted. 8218 Result.setInvalid(E); 8219 8220 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8221 Result.addUnsizedArray(Info, E, Pointee); 8222 return true; 8223 } 8224 8225 namespace { 8226 class PointerExprEvaluator 8227 : public ExprEvaluatorBase<PointerExprEvaluator> { 8228 LValue &Result; 8229 bool InvalidBaseOK; 8230 8231 bool Success(const Expr *E) { 8232 Result.set(E); 8233 return true; 8234 } 8235 8236 bool evaluateLValue(const Expr *E, LValue &Result) { 8237 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8238 } 8239 8240 bool evaluatePointer(const Expr *E, LValue &Result) { 8241 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8242 } 8243 8244 bool visitNonBuiltinCallExpr(const CallExpr *E); 8245 public: 8246 8247 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8248 : ExprEvaluatorBaseTy(info), Result(Result), 8249 InvalidBaseOK(InvalidBaseOK) {} 8250 8251 bool Success(const APValue &V, const Expr *E) { 8252 Result.setFrom(Info.Ctx, V); 8253 return true; 8254 } 8255 bool ZeroInitialization(const Expr *E) { 8256 Result.setNull(Info.Ctx, E->getType()); 8257 return true; 8258 } 8259 8260 bool VisitBinaryOperator(const BinaryOperator *E); 8261 bool VisitCastExpr(const CastExpr* E); 8262 bool VisitUnaryAddrOf(const UnaryOperator *E); 8263 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8264 { return Success(E); } 8265 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8266 if (E->isExpressibleAsConstantInitializer()) 8267 return Success(E); 8268 if (Info.noteFailure()) 8269 EvaluateIgnoredValue(Info, E->getSubExpr()); 8270 return Error(E); 8271 } 8272 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8273 { return Success(E); } 8274 bool VisitCallExpr(const CallExpr *E); 8275 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8276 bool VisitBlockExpr(const BlockExpr *E) { 8277 if (!E->getBlockDecl()->hasCaptures()) 8278 return Success(E); 8279 return Error(E); 8280 } 8281 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8282 // Can't look at 'this' when checking a potential constant expression. 8283 if (Info.checkingPotentialConstantExpression()) 8284 return false; 8285 if (!Info.CurrentCall->This) { 8286 if (Info.getLangOpts().CPlusPlus11) 8287 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8288 else 8289 Info.FFDiag(E); 8290 return false; 8291 } 8292 Result = *Info.CurrentCall->This; 8293 // If we are inside a lambda's call operator, the 'this' expression refers 8294 // to the enclosing '*this' object (either by value or reference) which is 8295 // either copied into the closure object's field that represents the '*this' 8296 // or refers to '*this'. 8297 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8298 // Ensure we actually have captured 'this'. (an error will have 8299 // been previously reported if not). 8300 if (!Info.CurrentCall->LambdaThisCaptureField) 8301 return false; 8302 8303 // Update 'Result' to refer to the data member/field of the closure object 8304 // that represents the '*this' capture. 8305 if (!HandleLValueMember(Info, E, Result, 8306 Info.CurrentCall->LambdaThisCaptureField)) 8307 return false; 8308 // If we captured '*this' by reference, replace the field with its referent. 8309 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8310 ->isPointerType()) { 8311 APValue RVal; 8312 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8313 RVal)) 8314 return false; 8315 8316 Result.setFrom(Info.Ctx, RVal); 8317 } 8318 } 8319 return true; 8320 } 8321 8322 bool VisitCXXNewExpr(const CXXNewExpr *E); 8323 8324 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8325 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8326 APValue LValResult = E->EvaluateInContext( 8327 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8328 Result.setFrom(Info.Ctx, LValResult); 8329 return true; 8330 } 8331 8332 // FIXME: Missing: @protocol, @selector 8333 }; 8334 } // end anonymous namespace 8335 8336 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8337 bool InvalidBaseOK) { 8338 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8339 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8340 } 8341 8342 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8343 if (E->getOpcode() != BO_Add && 8344 E->getOpcode() != BO_Sub) 8345 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8346 8347 const Expr *PExp = E->getLHS(); 8348 const Expr *IExp = E->getRHS(); 8349 if (IExp->getType()->isPointerType()) 8350 std::swap(PExp, IExp); 8351 8352 bool EvalPtrOK = evaluatePointer(PExp, Result); 8353 if (!EvalPtrOK && !Info.noteFailure()) 8354 return false; 8355 8356 llvm::APSInt Offset; 8357 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8358 return false; 8359 8360 if (E->getOpcode() == BO_Sub) 8361 negateAsSigned(Offset); 8362 8363 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8364 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8365 } 8366 8367 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8368 return evaluateLValue(E->getSubExpr(), Result); 8369 } 8370 8371 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8372 const Expr *SubExpr = E->getSubExpr(); 8373 8374 switch (E->getCastKind()) { 8375 default: 8376 break; 8377 case CK_BitCast: 8378 case CK_CPointerToObjCPointerCast: 8379 case CK_BlockPointerToObjCPointerCast: 8380 case CK_AnyPointerToBlockPointerCast: 8381 case CK_AddressSpaceConversion: 8382 if (!Visit(SubExpr)) 8383 return false; 8384 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8385 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8386 // also static_casts, but we disallow them as a resolution to DR1312. 8387 if (!E->getType()->isVoidPointerType()) { 8388 if (!Result.InvalidBase && !Result.Designator.Invalid && 8389 !Result.IsNullPtr && 8390 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8391 E->getType()->getPointeeType()) && 8392 Info.getStdAllocatorCaller("allocate")) { 8393 // Inside a call to std::allocator::allocate and friends, we permit 8394 // casting from void* back to cv1 T* for a pointer that points to a 8395 // cv2 T. 8396 } else { 8397 Result.Designator.setInvalid(); 8398 if (SubExpr->getType()->isVoidPointerType()) 8399 CCEDiag(E, diag::note_constexpr_invalid_cast) 8400 << 3 << SubExpr->getType(); 8401 else 8402 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8403 } 8404 } 8405 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8406 ZeroInitialization(E); 8407 return true; 8408 8409 case CK_DerivedToBase: 8410 case CK_UncheckedDerivedToBase: 8411 if (!evaluatePointer(E->getSubExpr(), Result)) 8412 return false; 8413 if (!Result.Base && Result.Offset.isZero()) 8414 return true; 8415 8416 // Now figure out the necessary offset to add to the base LV to get from 8417 // the derived class to the base class. 8418 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8419 castAs<PointerType>()->getPointeeType(), 8420 Result); 8421 8422 case CK_BaseToDerived: 8423 if (!Visit(E->getSubExpr())) 8424 return false; 8425 if (!Result.Base && Result.Offset.isZero()) 8426 return true; 8427 return HandleBaseToDerivedCast(Info, E, Result); 8428 8429 case CK_Dynamic: 8430 if (!Visit(E->getSubExpr())) 8431 return false; 8432 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8433 8434 case CK_NullToPointer: 8435 VisitIgnoredValue(E->getSubExpr()); 8436 return ZeroInitialization(E); 8437 8438 case CK_IntegralToPointer: { 8439 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8440 8441 APValue Value; 8442 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8443 break; 8444 8445 if (Value.isInt()) { 8446 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8447 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8448 Result.Base = (Expr*)nullptr; 8449 Result.InvalidBase = false; 8450 Result.Offset = CharUnits::fromQuantity(N); 8451 Result.Designator.setInvalid(); 8452 Result.IsNullPtr = false; 8453 return true; 8454 } else { 8455 // Cast is of an lvalue, no need to change value. 8456 Result.setFrom(Info.Ctx, Value); 8457 return true; 8458 } 8459 } 8460 8461 case CK_ArrayToPointerDecay: { 8462 if (SubExpr->isGLValue()) { 8463 if (!evaluateLValue(SubExpr, Result)) 8464 return false; 8465 } else { 8466 APValue &Value = Info.CurrentCall->createTemporary( 8467 SubExpr, SubExpr->getType(), false, Result); 8468 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8469 return false; 8470 } 8471 // The result is a pointer to the first element of the array. 8472 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8473 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8474 Result.addArray(Info, E, CAT); 8475 else 8476 Result.addUnsizedArray(Info, E, AT->getElementType()); 8477 return true; 8478 } 8479 8480 case CK_FunctionToPointerDecay: 8481 return evaluateLValue(SubExpr, Result); 8482 8483 case CK_LValueToRValue: { 8484 LValue LVal; 8485 if (!evaluateLValue(E->getSubExpr(), LVal)) 8486 return false; 8487 8488 APValue RVal; 8489 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8490 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8491 LVal, RVal)) 8492 return InvalidBaseOK && 8493 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8494 return Success(RVal, E); 8495 } 8496 } 8497 8498 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8499 } 8500 8501 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8502 UnaryExprOrTypeTrait ExprKind) { 8503 // C++ [expr.alignof]p3: 8504 // When alignof is applied to a reference type, the result is the 8505 // alignment of the referenced type. 8506 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8507 T = Ref->getPointeeType(); 8508 8509 if (T.getQualifiers().hasUnaligned()) 8510 return CharUnits::One(); 8511 8512 const bool AlignOfReturnsPreferred = 8513 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8514 8515 // __alignof is defined to return the preferred alignment. 8516 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8517 // as well. 8518 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8519 return Info.Ctx.toCharUnitsFromBits( 8520 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8521 // alignof and _Alignof are defined to return the ABI alignment. 8522 else if (ExprKind == UETT_AlignOf) 8523 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8524 else 8525 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8526 } 8527 8528 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8529 UnaryExprOrTypeTrait ExprKind) { 8530 E = E->IgnoreParens(); 8531 8532 // The kinds of expressions that we have special-case logic here for 8533 // should be kept up to date with the special checks for those 8534 // expressions in Sema. 8535 8536 // alignof decl is always accepted, even if it doesn't make sense: we default 8537 // to 1 in those cases. 8538 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8539 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8540 /*RefAsPointee*/true); 8541 8542 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8543 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8544 /*RefAsPointee*/true); 8545 8546 return GetAlignOfType(Info, E->getType(), ExprKind); 8547 } 8548 8549 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8550 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8551 return Info.Ctx.getDeclAlign(VD); 8552 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8553 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8554 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8555 } 8556 8557 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8558 /// __builtin_is_aligned and __builtin_assume_aligned. 8559 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8560 EvalInfo &Info, APSInt &Alignment) { 8561 if (!EvaluateInteger(E, Alignment, Info)) 8562 return false; 8563 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8564 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8565 return false; 8566 } 8567 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8568 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8569 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8570 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8571 << MaxValue << ForType << Alignment; 8572 return false; 8573 } 8574 // Ensure both alignment and source value have the same bit width so that we 8575 // don't assert when computing the resulting value. 8576 APSInt ExtAlignment = 8577 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8578 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8579 "Alignment should not be changed by ext/trunc"); 8580 Alignment = ExtAlignment; 8581 assert(Alignment.getBitWidth() == SrcWidth); 8582 return true; 8583 } 8584 8585 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8586 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8587 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8588 return true; 8589 8590 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8591 return false; 8592 8593 Result.setInvalid(E); 8594 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8595 Result.addUnsizedArray(Info, E, PointeeTy); 8596 return true; 8597 } 8598 8599 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8600 if (IsStringLiteralCall(E)) 8601 return Success(E); 8602 8603 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8604 return VisitBuiltinCallExpr(E, BuiltinOp); 8605 8606 return visitNonBuiltinCallExpr(E); 8607 } 8608 8609 // Determine if T is a character type for which we guarantee that 8610 // sizeof(T) == 1. 8611 static bool isOneByteCharacterType(QualType T) { 8612 return T->isCharType() || T->isChar8Type(); 8613 } 8614 8615 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8616 unsigned BuiltinOp) { 8617 switch (BuiltinOp) { 8618 case Builtin::BI__builtin_addressof: 8619 return evaluateLValue(E->getArg(0), Result); 8620 case Builtin::BI__builtin_assume_aligned: { 8621 // We need to be very careful here because: if the pointer does not have the 8622 // asserted alignment, then the behavior is undefined, and undefined 8623 // behavior is non-constant. 8624 if (!evaluatePointer(E->getArg(0), Result)) 8625 return false; 8626 8627 LValue OffsetResult(Result); 8628 APSInt Alignment; 8629 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8630 Alignment)) 8631 return false; 8632 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8633 8634 if (E->getNumArgs() > 2) { 8635 APSInt Offset; 8636 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8637 return false; 8638 8639 int64_t AdditionalOffset = -Offset.getZExtValue(); 8640 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8641 } 8642 8643 // If there is a base object, then it must have the correct alignment. 8644 if (OffsetResult.Base) { 8645 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 8646 8647 if (BaseAlignment < Align) { 8648 Result.Designator.setInvalid(); 8649 // FIXME: Add support to Diagnostic for long / long long. 8650 CCEDiag(E->getArg(0), 8651 diag::note_constexpr_baa_insufficient_alignment) << 0 8652 << (unsigned)BaseAlignment.getQuantity() 8653 << (unsigned)Align.getQuantity(); 8654 return false; 8655 } 8656 } 8657 8658 // The offset must also have the correct alignment. 8659 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 8660 Result.Designator.setInvalid(); 8661 8662 (OffsetResult.Base 8663 ? CCEDiag(E->getArg(0), 8664 diag::note_constexpr_baa_insufficient_alignment) << 1 8665 : CCEDiag(E->getArg(0), 8666 diag::note_constexpr_baa_value_insufficient_alignment)) 8667 << (int)OffsetResult.Offset.getQuantity() 8668 << (unsigned)Align.getQuantity(); 8669 return false; 8670 } 8671 8672 return true; 8673 } 8674 case Builtin::BI__builtin_align_up: 8675 case Builtin::BI__builtin_align_down: { 8676 if (!evaluatePointer(E->getArg(0), Result)) 8677 return false; 8678 APSInt Alignment; 8679 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8680 Alignment)) 8681 return false; 8682 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 8683 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 8684 // For align_up/align_down, we can return the same value if the alignment 8685 // is known to be greater or equal to the requested value. 8686 if (PtrAlign.getQuantity() >= Alignment) 8687 return true; 8688 8689 // The alignment could be greater than the minimum at run-time, so we cannot 8690 // infer much about the resulting pointer value. One case is possible: 8691 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 8692 // can infer the correct index if the requested alignment is smaller than 8693 // the base alignment so we can perform the computation on the offset. 8694 if (BaseAlignment.getQuantity() >= Alignment) { 8695 assert(Alignment.getBitWidth() <= 64 && 8696 "Cannot handle > 64-bit address-space"); 8697 uint64_t Alignment64 = Alignment.getZExtValue(); 8698 CharUnits NewOffset = CharUnits::fromQuantity( 8699 BuiltinOp == Builtin::BI__builtin_align_down 8700 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 8701 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 8702 Result.adjustOffset(NewOffset - Result.Offset); 8703 // TODO: diagnose out-of-bounds values/only allow for arrays? 8704 return true; 8705 } 8706 // Otherwise, we cannot constant-evaluate the result. 8707 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 8708 << Alignment; 8709 return false; 8710 } 8711 case Builtin::BI__builtin_operator_new: 8712 return HandleOperatorNewCall(Info, E, Result); 8713 case Builtin::BI__builtin_launder: 8714 return evaluatePointer(E->getArg(0), Result); 8715 case Builtin::BIstrchr: 8716 case Builtin::BIwcschr: 8717 case Builtin::BImemchr: 8718 case Builtin::BIwmemchr: 8719 if (Info.getLangOpts().CPlusPlus11) 8720 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8721 << /*isConstexpr*/0 << /*isConstructor*/0 8722 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8723 else 8724 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8725 LLVM_FALLTHROUGH; 8726 case Builtin::BI__builtin_strchr: 8727 case Builtin::BI__builtin_wcschr: 8728 case Builtin::BI__builtin_memchr: 8729 case Builtin::BI__builtin_char_memchr: 8730 case Builtin::BI__builtin_wmemchr: { 8731 if (!Visit(E->getArg(0))) 8732 return false; 8733 APSInt Desired; 8734 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 8735 return false; 8736 uint64_t MaxLength = uint64_t(-1); 8737 if (BuiltinOp != Builtin::BIstrchr && 8738 BuiltinOp != Builtin::BIwcschr && 8739 BuiltinOp != Builtin::BI__builtin_strchr && 8740 BuiltinOp != Builtin::BI__builtin_wcschr) { 8741 APSInt N; 8742 if (!EvaluateInteger(E->getArg(2), N, Info)) 8743 return false; 8744 MaxLength = N.getExtValue(); 8745 } 8746 // We cannot find the value if there are no candidates to match against. 8747 if (MaxLength == 0u) 8748 return ZeroInitialization(E); 8749 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 8750 Result.Designator.Invalid) 8751 return false; 8752 QualType CharTy = Result.Designator.getType(Info.Ctx); 8753 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 8754 BuiltinOp == Builtin::BI__builtin_memchr; 8755 assert(IsRawByte || 8756 Info.Ctx.hasSameUnqualifiedType( 8757 CharTy, E->getArg(0)->getType()->getPointeeType())); 8758 // Pointers to const void may point to objects of incomplete type. 8759 if (IsRawByte && CharTy->isIncompleteType()) { 8760 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 8761 return false; 8762 } 8763 // Give up on byte-oriented matching against multibyte elements. 8764 // FIXME: We can compare the bytes in the correct order. 8765 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 8766 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 8767 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 8768 << CharTy; 8769 return false; 8770 } 8771 // Figure out what value we're actually looking for (after converting to 8772 // the corresponding unsigned type if necessary). 8773 uint64_t DesiredVal; 8774 bool StopAtNull = false; 8775 switch (BuiltinOp) { 8776 case Builtin::BIstrchr: 8777 case Builtin::BI__builtin_strchr: 8778 // strchr compares directly to the passed integer, and therefore 8779 // always fails if given an int that is not a char. 8780 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 8781 E->getArg(1)->getType(), 8782 Desired), 8783 Desired)) 8784 return ZeroInitialization(E); 8785 StopAtNull = true; 8786 LLVM_FALLTHROUGH; 8787 case Builtin::BImemchr: 8788 case Builtin::BI__builtin_memchr: 8789 case Builtin::BI__builtin_char_memchr: 8790 // memchr compares by converting both sides to unsigned char. That's also 8791 // correct for strchr if we get this far (to cope with plain char being 8792 // unsigned in the strchr case). 8793 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 8794 break; 8795 8796 case Builtin::BIwcschr: 8797 case Builtin::BI__builtin_wcschr: 8798 StopAtNull = true; 8799 LLVM_FALLTHROUGH; 8800 case Builtin::BIwmemchr: 8801 case Builtin::BI__builtin_wmemchr: 8802 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 8803 DesiredVal = Desired.getZExtValue(); 8804 break; 8805 } 8806 8807 for (; MaxLength; --MaxLength) { 8808 APValue Char; 8809 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 8810 !Char.isInt()) 8811 return false; 8812 if (Char.getInt().getZExtValue() == DesiredVal) 8813 return true; 8814 if (StopAtNull && !Char.getInt()) 8815 break; 8816 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 8817 return false; 8818 } 8819 // Not found: return nullptr. 8820 return ZeroInitialization(E); 8821 } 8822 8823 case Builtin::BImemcpy: 8824 case Builtin::BImemmove: 8825 case Builtin::BIwmemcpy: 8826 case Builtin::BIwmemmove: 8827 if (Info.getLangOpts().CPlusPlus11) 8828 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8829 << /*isConstexpr*/0 << /*isConstructor*/0 8830 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8831 else 8832 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8833 LLVM_FALLTHROUGH; 8834 case Builtin::BI__builtin_memcpy: 8835 case Builtin::BI__builtin_memmove: 8836 case Builtin::BI__builtin_wmemcpy: 8837 case Builtin::BI__builtin_wmemmove: { 8838 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 8839 BuiltinOp == Builtin::BIwmemmove || 8840 BuiltinOp == Builtin::BI__builtin_wmemcpy || 8841 BuiltinOp == Builtin::BI__builtin_wmemmove; 8842 bool Move = BuiltinOp == Builtin::BImemmove || 8843 BuiltinOp == Builtin::BIwmemmove || 8844 BuiltinOp == Builtin::BI__builtin_memmove || 8845 BuiltinOp == Builtin::BI__builtin_wmemmove; 8846 8847 // The result of mem* is the first argument. 8848 if (!Visit(E->getArg(0))) 8849 return false; 8850 LValue Dest = Result; 8851 8852 LValue Src; 8853 if (!EvaluatePointer(E->getArg(1), Src, Info)) 8854 return false; 8855 8856 APSInt N; 8857 if (!EvaluateInteger(E->getArg(2), N, Info)) 8858 return false; 8859 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 8860 8861 // If the size is zero, we treat this as always being a valid no-op. 8862 // (Even if one of the src and dest pointers is null.) 8863 if (!N) 8864 return true; 8865 8866 // Otherwise, if either of the operands is null, we can't proceed. Don't 8867 // try to determine the type of the copied objects, because there aren't 8868 // any. 8869 if (!Src.Base || !Dest.Base) { 8870 APValue Val; 8871 (!Src.Base ? Src : Dest).moveInto(Val); 8872 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 8873 << Move << WChar << !!Src.Base 8874 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 8875 return false; 8876 } 8877 if (Src.Designator.Invalid || Dest.Designator.Invalid) 8878 return false; 8879 8880 // We require that Src and Dest are both pointers to arrays of 8881 // trivially-copyable type. (For the wide version, the designator will be 8882 // invalid if the designated object is not a wchar_t.) 8883 QualType T = Dest.Designator.getType(Info.Ctx); 8884 QualType SrcT = Src.Designator.getType(Info.Ctx); 8885 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 8886 // FIXME: Consider using our bit_cast implementation to support this. 8887 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 8888 return false; 8889 } 8890 if (T->isIncompleteType()) { 8891 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 8892 return false; 8893 } 8894 if (!T.isTriviallyCopyableType(Info.Ctx)) { 8895 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 8896 return false; 8897 } 8898 8899 // Figure out how many T's we're copying. 8900 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 8901 if (!WChar) { 8902 uint64_t Remainder; 8903 llvm::APInt OrigN = N; 8904 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 8905 if (Remainder) { 8906 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8907 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 8908 << (unsigned)TSize; 8909 return false; 8910 } 8911 } 8912 8913 // Check that the copying will remain within the arrays, just so that we 8914 // can give a more meaningful diagnostic. This implicitly also checks that 8915 // N fits into 64 bits. 8916 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 8917 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 8918 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 8919 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8920 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 8921 << N.toString(10, /*Signed*/false); 8922 return false; 8923 } 8924 uint64_t NElems = N.getZExtValue(); 8925 uint64_t NBytes = NElems * TSize; 8926 8927 // Check for overlap. 8928 int Direction = 1; 8929 if (HasSameBase(Src, Dest)) { 8930 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 8931 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 8932 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 8933 // Dest is inside the source region. 8934 if (!Move) { 8935 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 8936 return false; 8937 } 8938 // For memmove and friends, copy backwards. 8939 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 8940 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 8941 return false; 8942 Direction = -1; 8943 } else if (!Move && SrcOffset >= DestOffset && 8944 SrcOffset - DestOffset < NBytes) { 8945 // Src is inside the destination region for memcpy: invalid. 8946 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 8947 return false; 8948 } 8949 } 8950 8951 while (true) { 8952 APValue Val; 8953 // FIXME: Set WantObjectRepresentation to true if we're copying a 8954 // char-like type? 8955 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 8956 !handleAssignment(Info, E, Dest, T, Val)) 8957 return false; 8958 // Do not iterate past the last element; if we're copying backwards, that 8959 // might take us off the start of the array. 8960 if (--NElems == 0) 8961 return true; 8962 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 8963 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 8964 return false; 8965 } 8966 } 8967 8968 default: 8969 break; 8970 } 8971 8972 return visitNonBuiltinCallExpr(E); 8973 } 8974 8975 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 8976 APValue &Result, const InitListExpr *ILE, 8977 QualType AllocType); 8978 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 8979 APValue &Result, 8980 const CXXConstructExpr *CCE, 8981 QualType AllocType); 8982 8983 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 8984 if (!Info.getLangOpts().CPlusPlus20) 8985 Info.CCEDiag(E, diag::note_constexpr_new); 8986 8987 // We cannot speculatively evaluate a delete expression. 8988 if (Info.SpeculativeEvaluationDepth) 8989 return false; 8990 8991 FunctionDecl *OperatorNew = E->getOperatorNew(); 8992 8993 bool IsNothrow = false; 8994 bool IsPlacement = false; 8995 if (OperatorNew->isReservedGlobalPlacementOperator() && 8996 Info.CurrentCall->isStdFunction() && !E->isArray()) { 8997 // FIXME Support array placement new. 8998 assert(E->getNumPlacementArgs() == 1); 8999 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9000 return false; 9001 if (Result.Designator.Invalid) 9002 return false; 9003 IsPlacement = true; 9004 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9005 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9006 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9007 return false; 9008 } else if (E->getNumPlacementArgs()) { 9009 // The only new-placement list we support is of the form (std::nothrow). 9010 // 9011 // FIXME: There is no restriction on this, but it's not clear that any 9012 // other form makes any sense. We get here for cases such as: 9013 // 9014 // new (std::align_val_t{N}) X(int) 9015 // 9016 // (which should presumably be valid only if N is a multiple of 9017 // alignof(int), and in any case can't be deallocated unless N is 9018 // alignof(X) and X has new-extended alignment). 9019 if (E->getNumPlacementArgs() != 1 || 9020 !E->getPlacementArg(0)->getType()->isNothrowT()) 9021 return Error(E, diag::note_constexpr_new_placement); 9022 9023 LValue Nothrow; 9024 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9025 return false; 9026 IsNothrow = true; 9027 } 9028 9029 const Expr *Init = E->getInitializer(); 9030 const InitListExpr *ResizedArrayILE = nullptr; 9031 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9032 bool ValueInit = false; 9033 9034 QualType AllocType = E->getAllocatedType(); 9035 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9036 const Expr *Stripped = *ArraySize; 9037 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9038 Stripped = ICE->getSubExpr()) 9039 if (ICE->getCastKind() != CK_NoOp && 9040 ICE->getCastKind() != CK_IntegralCast) 9041 break; 9042 9043 llvm::APSInt ArrayBound; 9044 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9045 return false; 9046 9047 // C++ [expr.new]p9: 9048 // The expression is erroneous if: 9049 // -- [...] its value before converting to size_t [or] applying the 9050 // second standard conversion sequence is less than zero 9051 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9052 if (IsNothrow) 9053 return ZeroInitialization(E); 9054 9055 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9056 << ArrayBound << (*ArraySize)->getSourceRange(); 9057 return false; 9058 } 9059 9060 // -- its value is such that the size of the allocated object would 9061 // exceed the implementation-defined limit 9062 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9063 ArrayBound) > 9064 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9065 if (IsNothrow) 9066 return ZeroInitialization(E); 9067 9068 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9069 << ArrayBound << (*ArraySize)->getSourceRange(); 9070 return false; 9071 } 9072 9073 // -- the new-initializer is a braced-init-list and the number of 9074 // array elements for which initializers are provided [...] 9075 // exceeds the number of elements to initialize 9076 if (!Init) { 9077 // No initialization is performed. 9078 } else if (isa<CXXScalarValueInitExpr>(Init) || 9079 isa<ImplicitValueInitExpr>(Init)) { 9080 ValueInit = true; 9081 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9082 ResizedArrayCCE = CCE; 9083 } else { 9084 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9085 assert(CAT && "unexpected type for array initializer"); 9086 9087 unsigned Bits = 9088 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9089 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9090 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9091 if (InitBound.ugt(AllocBound)) { 9092 if (IsNothrow) 9093 return ZeroInitialization(E); 9094 9095 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9096 << AllocBound.toString(10, /*Signed=*/false) 9097 << InitBound.toString(10, /*Signed=*/false) 9098 << (*ArraySize)->getSourceRange(); 9099 return false; 9100 } 9101 9102 // If the sizes differ, we must have an initializer list, and we need 9103 // special handling for this case when we initialize. 9104 if (InitBound != AllocBound) 9105 ResizedArrayILE = cast<InitListExpr>(Init); 9106 } 9107 9108 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9109 ArrayType::Normal, 0); 9110 } else { 9111 assert(!AllocType->isArrayType() && 9112 "array allocation with non-array new"); 9113 } 9114 9115 APValue *Val; 9116 if (IsPlacement) { 9117 AccessKinds AK = AK_Construct; 9118 struct FindObjectHandler { 9119 EvalInfo &Info; 9120 const Expr *E; 9121 QualType AllocType; 9122 const AccessKinds AccessKind; 9123 APValue *Value; 9124 9125 typedef bool result_type; 9126 bool failed() { return false; } 9127 bool found(APValue &Subobj, QualType SubobjType) { 9128 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9129 // old name of the object to be used to name the new object. 9130 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9131 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9132 SubobjType << AllocType; 9133 return false; 9134 } 9135 Value = &Subobj; 9136 return true; 9137 } 9138 bool found(APSInt &Value, QualType SubobjType) { 9139 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9140 return false; 9141 } 9142 bool found(APFloat &Value, QualType SubobjType) { 9143 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9144 return false; 9145 } 9146 } Handler = {Info, E, AllocType, AK, nullptr}; 9147 9148 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9149 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9150 return false; 9151 9152 Val = Handler.Value; 9153 9154 // [basic.life]p1: 9155 // The lifetime of an object o of type T ends when [...] the storage 9156 // which the object occupies is [...] reused by an object that is not 9157 // nested within o (6.6.2). 9158 *Val = APValue(); 9159 } else { 9160 // Perform the allocation and obtain a pointer to the resulting object. 9161 Val = Info.createHeapAlloc(E, AllocType, Result); 9162 if (!Val) 9163 return false; 9164 } 9165 9166 if (ValueInit) { 9167 ImplicitValueInitExpr VIE(AllocType); 9168 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9169 return false; 9170 } else if (ResizedArrayILE) { 9171 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9172 AllocType)) 9173 return false; 9174 } else if (ResizedArrayCCE) { 9175 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9176 AllocType)) 9177 return false; 9178 } else if (Init) { 9179 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9180 return false; 9181 } else if (!getDefaultInitValue(AllocType, *Val)) { 9182 return false; 9183 } 9184 9185 // Array new returns a pointer to the first element, not a pointer to the 9186 // array. 9187 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9188 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9189 9190 return true; 9191 } 9192 //===----------------------------------------------------------------------===// 9193 // Member Pointer Evaluation 9194 //===----------------------------------------------------------------------===// 9195 9196 namespace { 9197 class MemberPointerExprEvaluator 9198 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9199 MemberPtr &Result; 9200 9201 bool Success(const ValueDecl *D) { 9202 Result = MemberPtr(D); 9203 return true; 9204 } 9205 public: 9206 9207 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9208 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9209 9210 bool Success(const APValue &V, const Expr *E) { 9211 Result.setFrom(V); 9212 return true; 9213 } 9214 bool ZeroInitialization(const Expr *E) { 9215 return Success((const ValueDecl*)nullptr); 9216 } 9217 9218 bool VisitCastExpr(const CastExpr *E); 9219 bool VisitUnaryAddrOf(const UnaryOperator *E); 9220 }; 9221 } // end anonymous namespace 9222 9223 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9224 EvalInfo &Info) { 9225 assert(E->isRValue() && E->getType()->isMemberPointerType()); 9226 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9227 } 9228 9229 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9230 switch (E->getCastKind()) { 9231 default: 9232 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9233 9234 case CK_NullToMemberPointer: 9235 VisitIgnoredValue(E->getSubExpr()); 9236 return ZeroInitialization(E); 9237 9238 case CK_BaseToDerivedMemberPointer: { 9239 if (!Visit(E->getSubExpr())) 9240 return false; 9241 if (E->path_empty()) 9242 return true; 9243 // Base-to-derived member pointer casts store the path in derived-to-base 9244 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9245 // the wrong end of the derived->base arc, so stagger the path by one class. 9246 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9247 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9248 PathI != PathE; ++PathI) { 9249 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9250 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9251 if (!Result.castToDerived(Derived)) 9252 return Error(E); 9253 } 9254 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9255 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9256 return Error(E); 9257 return true; 9258 } 9259 9260 case CK_DerivedToBaseMemberPointer: 9261 if (!Visit(E->getSubExpr())) 9262 return false; 9263 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9264 PathE = E->path_end(); PathI != PathE; ++PathI) { 9265 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9266 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9267 if (!Result.castToBase(Base)) 9268 return Error(E); 9269 } 9270 return true; 9271 } 9272 } 9273 9274 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9275 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9276 // member can be formed. 9277 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9278 } 9279 9280 //===----------------------------------------------------------------------===// 9281 // Record Evaluation 9282 //===----------------------------------------------------------------------===// 9283 9284 namespace { 9285 class RecordExprEvaluator 9286 : public ExprEvaluatorBase<RecordExprEvaluator> { 9287 const LValue &This; 9288 APValue &Result; 9289 public: 9290 9291 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9292 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9293 9294 bool Success(const APValue &V, const Expr *E) { 9295 Result = V; 9296 return true; 9297 } 9298 bool ZeroInitialization(const Expr *E) { 9299 return ZeroInitialization(E, E->getType()); 9300 } 9301 bool ZeroInitialization(const Expr *E, QualType T); 9302 9303 bool VisitCallExpr(const CallExpr *E) { 9304 return handleCallExpr(E, Result, &This); 9305 } 9306 bool VisitCastExpr(const CastExpr *E); 9307 bool VisitInitListExpr(const InitListExpr *E); 9308 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9309 return VisitCXXConstructExpr(E, E->getType()); 9310 } 9311 bool VisitLambdaExpr(const LambdaExpr *E); 9312 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9313 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9314 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9315 bool VisitBinCmp(const BinaryOperator *E); 9316 }; 9317 } 9318 9319 /// Perform zero-initialization on an object of non-union class type. 9320 /// C++11 [dcl.init]p5: 9321 /// To zero-initialize an object or reference of type T means: 9322 /// [...] 9323 /// -- if T is a (possibly cv-qualified) non-union class type, 9324 /// each non-static data member and each base-class subobject is 9325 /// zero-initialized 9326 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9327 const RecordDecl *RD, 9328 const LValue &This, APValue &Result) { 9329 assert(!RD->isUnion() && "Expected non-union class type"); 9330 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9331 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9332 std::distance(RD->field_begin(), RD->field_end())); 9333 9334 if (RD->isInvalidDecl()) return false; 9335 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9336 9337 if (CD) { 9338 unsigned Index = 0; 9339 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9340 End = CD->bases_end(); I != End; ++I, ++Index) { 9341 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9342 LValue Subobject = This; 9343 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9344 return false; 9345 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9346 Result.getStructBase(Index))) 9347 return false; 9348 } 9349 } 9350 9351 for (const auto *I : RD->fields()) { 9352 // -- if T is a reference type, no initialization is performed. 9353 if (I->getType()->isReferenceType()) 9354 continue; 9355 9356 LValue Subobject = This; 9357 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9358 return false; 9359 9360 ImplicitValueInitExpr VIE(I->getType()); 9361 if (!EvaluateInPlace( 9362 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9363 return false; 9364 } 9365 9366 return true; 9367 } 9368 9369 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9370 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9371 if (RD->isInvalidDecl()) return false; 9372 if (RD->isUnion()) { 9373 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9374 // object's first non-static named data member is zero-initialized 9375 RecordDecl::field_iterator I = RD->field_begin(); 9376 if (I == RD->field_end()) { 9377 Result = APValue((const FieldDecl*)nullptr); 9378 return true; 9379 } 9380 9381 LValue Subobject = This; 9382 if (!HandleLValueMember(Info, E, Subobject, *I)) 9383 return false; 9384 Result = APValue(*I); 9385 ImplicitValueInitExpr VIE(I->getType()); 9386 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9387 } 9388 9389 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9390 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9391 return false; 9392 } 9393 9394 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9395 } 9396 9397 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9398 switch (E->getCastKind()) { 9399 default: 9400 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9401 9402 case CK_ConstructorConversion: 9403 return Visit(E->getSubExpr()); 9404 9405 case CK_DerivedToBase: 9406 case CK_UncheckedDerivedToBase: { 9407 APValue DerivedObject; 9408 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9409 return false; 9410 if (!DerivedObject.isStruct()) 9411 return Error(E->getSubExpr()); 9412 9413 // Derived-to-base rvalue conversion: just slice off the derived part. 9414 APValue *Value = &DerivedObject; 9415 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9416 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9417 PathE = E->path_end(); PathI != PathE; ++PathI) { 9418 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9419 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9420 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9421 RD = Base; 9422 } 9423 Result = *Value; 9424 return true; 9425 } 9426 } 9427 } 9428 9429 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9430 if (E->isTransparent()) 9431 return Visit(E->getInit(0)); 9432 9433 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9434 if (RD->isInvalidDecl()) return false; 9435 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9436 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9437 9438 EvalInfo::EvaluatingConstructorRAII EvalObj( 9439 Info, 9440 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9441 CXXRD && CXXRD->getNumBases()); 9442 9443 if (RD->isUnion()) { 9444 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9445 Result = APValue(Field); 9446 if (!Field) 9447 return true; 9448 9449 // If the initializer list for a union does not contain any elements, the 9450 // first element of the union is value-initialized. 9451 // FIXME: The element should be initialized from an initializer list. 9452 // Is this difference ever observable for initializer lists which 9453 // we don't build? 9454 ImplicitValueInitExpr VIE(Field->getType()); 9455 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9456 9457 LValue Subobject = This; 9458 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9459 return false; 9460 9461 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9462 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9463 isa<CXXDefaultInitExpr>(InitExpr)); 9464 9465 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 9466 } 9467 9468 if (!Result.hasValue()) 9469 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9470 std::distance(RD->field_begin(), RD->field_end())); 9471 unsigned ElementNo = 0; 9472 bool Success = true; 9473 9474 // Initialize base classes. 9475 if (CXXRD && CXXRD->getNumBases()) { 9476 for (const auto &Base : CXXRD->bases()) { 9477 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9478 const Expr *Init = E->getInit(ElementNo); 9479 9480 LValue Subobject = This; 9481 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9482 return false; 9483 9484 APValue &FieldVal = Result.getStructBase(ElementNo); 9485 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9486 if (!Info.noteFailure()) 9487 return false; 9488 Success = false; 9489 } 9490 ++ElementNo; 9491 } 9492 9493 EvalObj.finishedConstructingBases(); 9494 } 9495 9496 // Initialize members. 9497 for (const auto *Field : RD->fields()) { 9498 // Anonymous bit-fields are not considered members of the class for 9499 // purposes of aggregate initialization. 9500 if (Field->isUnnamedBitfield()) 9501 continue; 9502 9503 LValue Subobject = This; 9504 9505 bool HaveInit = ElementNo < E->getNumInits(); 9506 9507 // FIXME: Diagnostics here should point to the end of the initializer 9508 // list, not the start. 9509 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9510 Subobject, Field, &Layout)) 9511 return false; 9512 9513 // Perform an implicit value-initialization for members beyond the end of 9514 // the initializer list. 9515 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9516 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9517 9518 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9519 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9520 isa<CXXDefaultInitExpr>(Init)); 9521 9522 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9523 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9524 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9525 FieldVal, Field))) { 9526 if (!Info.noteFailure()) 9527 return false; 9528 Success = false; 9529 } 9530 } 9531 9532 EvalObj.finishedConstructingFields(); 9533 9534 return Success; 9535 } 9536 9537 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9538 QualType T) { 9539 // Note that E's type is not necessarily the type of our class here; we might 9540 // be initializing an array element instead. 9541 const CXXConstructorDecl *FD = E->getConstructor(); 9542 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9543 9544 bool ZeroInit = E->requiresZeroInitialization(); 9545 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9546 // If we've already performed zero-initialization, we're already done. 9547 if (Result.hasValue()) 9548 return true; 9549 9550 if (ZeroInit) 9551 return ZeroInitialization(E, T); 9552 9553 return getDefaultInitValue(T, Result); 9554 } 9555 9556 const FunctionDecl *Definition = nullptr; 9557 auto Body = FD->getBody(Definition); 9558 9559 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9560 return false; 9561 9562 // Avoid materializing a temporary for an elidable copy/move constructor. 9563 if (E->isElidable() && !ZeroInit) 9564 if (const MaterializeTemporaryExpr *ME 9565 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9566 return Visit(ME->getSubExpr()); 9567 9568 if (ZeroInit && !ZeroInitialization(E, T)) 9569 return false; 9570 9571 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9572 return HandleConstructorCall(E, This, Args, 9573 cast<CXXConstructorDecl>(Definition), Info, 9574 Result); 9575 } 9576 9577 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9578 const CXXInheritedCtorInitExpr *E) { 9579 if (!Info.CurrentCall) { 9580 assert(Info.checkingPotentialConstantExpression()); 9581 return false; 9582 } 9583 9584 const CXXConstructorDecl *FD = E->getConstructor(); 9585 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9586 return false; 9587 9588 const FunctionDecl *Definition = nullptr; 9589 auto Body = FD->getBody(Definition); 9590 9591 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9592 return false; 9593 9594 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9595 cast<CXXConstructorDecl>(Definition), Info, 9596 Result); 9597 } 9598 9599 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9600 const CXXStdInitializerListExpr *E) { 9601 const ConstantArrayType *ArrayType = 9602 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9603 9604 LValue Array; 9605 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9606 return false; 9607 9608 // Get a pointer to the first element of the array. 9609 Array.addArray(Info, E, ArrayType); 9610 9611 auto InvalidType = [&] { 9612 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9613 << E->getType(); 9614 return false; 9615 }; 9616 9617 // FIXME: Perform the checks on the field types in SemaInit. 9618 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9619 RecordDecl::field_iterator Field = Record->field_begin(); 9620 if (Field == Record->field_end()) 9621 return InvalidType(); 9622 9623 // Start pointer. 9624 if (!Field->getType()->isPointerType() || 9625 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9626 ArrayType->getElementType())) 9627 return InvalidType(); 9628 9629 // FIXME: What if the initializer_list type has base classes, etc? 9630 Result = APValue(APValue::UninitStruct(), 0, 2); 9631 Array.moveInto(Result.getStructField(0)); 9632 9633 if (++Field == Record->field_end()) 9634 return InvalidType(); 9635 9636 if (Field->getType()->isPointerType() && 9637 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9638 ArrayType->getElementType())) { 9639 // End pointer. 9640 if (!HandleLValueArrayAdjustment(Info, E, Array, 9641 ArrayType->getElementType(), 9642 ArrayType->getSize().getZExtValue())) 9643 return false; 9644 Array.moveInto(Result.getStructField(1)); 9645 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9646 // Length. 9647 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9648 else 9649 return InvalidType(); 9650 9651 if (++Field != Record->field_end()) 9652 return InvalidType(); 9653 9654 return true; 9655 } 9656 9657 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 9658 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 9659 if (ClosureClass->isInvalidDecl()) 9660 return false; 9661 9662 const size_t NumFields = 9663 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 9664 9665 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 9666 E->capture_init_end()) && 9667 "The number of lambda capture initializers should equal the number of " 9668 "fields within the closure type"); 9669 9670 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 9671 // Iterate through all the lambda's closure object's fields and initialize 9672 // them. 9673 auto *CaptureInitIt = E->capture_init_begin(); 9674 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 9675 bool Success = true; 9676 for (const auto *Field : ClosureClass->fields()) { 9677 assert(CaptureInitIt != E->capture_init_end()); 9678 // Get the initializer for this field 9679 Expr *const CurFieldInit = *CaptureInitIt++; 9680 9681 // If there is no initializer, either this is a VLA or an error has 9682 // occurred. 9683 if (!CurFieldInit) 9684 return Error(E); 9685 9686 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9687 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 9688 if (!Info.keepEvaluatingAfterFailure()) 9689 return false; 9690 Success = false; 9691 } 9692 ++CaptureIt; 9693 } 9694 return Success; 9695 } 9696 9697 static bool EvaluateRecord(const Expr *E, const LValue &This, 9698 APValue &Result, EvalInfo &Info) { 9699 assert(E->isRValue() && E->getType()->isRecordType() && 9700 "can't evaluate expression as a record rvalue"); 9701 return RecordExprEvaluator(Info, This, Result).Visit(E); 9702 } 9703 9704 //===----------------------------------------------------------------------===// 9705 // Temporary Evaluation 9706 // 9707 // Temporaries are represented in the AST as rvalues, but generally behave like 9708 // lvalues. The full-object of which the temporary is a subobject is implicitly 9709 // materialized so that a reference can bind to it. 9710 //===----------------------------------------------------------------------===// 9711 namespace { 9712 class TemporaryExprEvaluator 9713 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 9714 public: 9715 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 9716 LValueExprEvaluatorBaseTy(Info, Result, false) {} 9717 9718 /// Visit an expression which constructs the value of this temporary. 9719 bool VisitConstructExpr(const Expr *E) { 9720 APValue &Value = 9721 Info.CurrentCall->createTemporary(E, E->getType(), false, Result); 9722 return EvaluateInPlace(Value, Info, Result, E); 9723 } 9724 9725 bool VisitCastExpr(const CastExpr *E) { 9726 switch (E->getCastKind()) { 9727 default: 9728 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 9729 9730 case CK_ConstructorConversion: 9731 return VisitConstructExpr(E->getSubExpr()); 9732 } 9733 } 9734 bool VisitInitListExpr(const InitListExpr *E) { 9735 return VisitConstructExpr(E); 9736 } 9737 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9738 return VisitConstructExpr(E); 9739 } 9740 bool VisitCallExpr(const CallExpr *E) { 9741 return VisitConstructExpr(E); 9742 } 9743 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 9744 return VisitConstructExpr(E); 9745 } 9746 bool VisitLambdaExpr(const LambdaExpr *E) { 9747 return VisitConstructExpr(E); 9748 } 9749 }; 9750 } // end anonymous namespace 9751 9752 /// Evaluate an expression of record type as a temporary. 9753 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 9754 assert(E->isRValue() && E->getType()->isRecordType()); 9755 return TemporaryExprEvaluator(Info, Result).Visit(E); 9756 } 9757 9758 //===----------------------------------------------------------------------===// 9759 // Vector Evaluation 9760 //===----------------------------------------------------------------------===// 9761 9762 namespace { 9763 class VectorExprEvaluator 9764 : public ExprEvaluatorBase<VectorExprEvaluator> { 9765 APValue &Result; 9766 public: 9767 9768 VectorExprEvaluator(EvalInfo &info, APValue &Result) 9769 : ExprEvaluatorBaseTy(info), Result(Result) {} 9770 9771 bool Success(ArrayRef<APValue> V, const Expr *E) { 9772 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 9773 // FIXME: remove this APValue copy. 9774 Result = APValue(V.data(), V.size()); 9775 return true; 9776 } 9777 bool Success(const APValue &V, const Expr *E) { 9778 assert(V.isVector()); 9779 Result = V; 9780 return true; 9781 } 9782 bool ZeroInitialization(const Expr *E); 9783 9784 bool VisitUnaryReal(const UnaryOperator *E) 9785 { return Visit(E->getSubExpr()); } 9786 bool VisitCastExpr(const CastExpr* E); 9787 bool VisitInitListExpr(const InitListExpr *E); 9788 bool VisitUnaryImag(const UnaryOperator *E); 9789 bool VisitBinaryOperator(const BinaryOperator *E); 9790 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 9791 // conditional select), shufflevector, ExtVectorElementExpr 9792 }; 9793 } // end anonymous namespace 9794 9795 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 9796 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 9797 return VectorExprEvaluator(Info, Result).Visit(E); 9798 } 9799 9800 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 9801 const VectorType *VTy = E->getType()->castAs<VectorType>(); 9802 unsigned NElts = VTy->getNumElements(); 9803 9804 const Expr *SE = E->getSubExpr(); 9805 QualType SETy = SE->getType(); 9806 9807 switch (E->getCastKind()) { 9808 case CK_VectorSplat: { 9809 APValue Val = APValue(); 9810 if (SETy->isIntegerType()) { 9811 APSInt IntResult; 9812 if (!EvaluateInteger(SE, IntResult, Info)) 9813 return false; 9814 Val = APValue(std::move(IntResult)); 9815 } else if (SETy->isRealFloatingType()) { 9816 APFloat FloatResult(0.0); 9817 if (!EvaluateFloat(SE, FloatResult, Info)) 9818 return false; 9819 Val = APValue(std::move(FloatResult)); 9820 } else { 9821 return Error(E); 9822 } 9823 9824 // Splat and create vector APValue. 9825 SmallVector<APValue, 4> Elts(NElts, Val); 9826 return Success(Elts, E); 9827 } 9828 case CK_BitCast: { 9829 // Evaluate the operand into an APInt we can extract from. 9830 llvm::APInt SValInt; 9831 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 9832 return false; 9833 // Extract the elements 9834 QualType EltTy = VTy->getElementType(); 9835 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 9836 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 9837 SmallVector<APValue, 4> Elts; 9838 if (EltTy->isRealFloatingType()) { 9839 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 9840 unsigned FloatEltSize = EltSize; 9841 if (&Sem == &APFloat::x87DoubleExtended()) 9842 FloatEltSize = 80; 9843 for (unsigned i = 0; i < NElts; i++) { 9844 llvm::APInt Elt; 9845 if (BigEndian) 9846 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 9847 else 9848 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 9849 Elts.push_back(APValue(APFloat(Sem, Elt))); 9850 } 9851 } else if (EltTy->isIntegerType()) { 9852 for (unsigned i = 0; i < NElts; i++) { 9853 llvm::APInt Elt; 9854 if (BigEndian) 9855 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 9856 else 9857 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 9858 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 9859 } 9860 } else { 9861 return Error(E); 9862 } 9863 return Success(Elts, E); 9864 } 9865 default: 9866 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9867 } 9868 } 9869 9870 bool 9871 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9872 const VectorType *VT = E->getType()->castAs<VectorType>(); 9873 unsigned NumInits = E->getNumInits(); 9874 unsigned NumElements = VT->getNumElements(); 9875 9876 QualType EltTy = VT->getElementType(); 9877 SmallVector<APValue, 4> Elements; 9878 9879 // The number of initializers can be less than the number of 9880 // vector elements. For OpenCL, this can be due to nested vector 9881 // initialization. For GCC compatibility, missing trailing elements 9882 // should be initialized with zeroes. 9883 unsigned CountInits = 0, CountElts = 0; 9884 while (CountElts < NumElements) { 9885 // Handle nested vector initialization. 9886 if (CountInits < NumInits 9887 && E->getInit(CountInits)->getType()->isVectorType()) { 9888 APValue v; 9889 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 9890 return Error(E); 9891 unsigned vlen = v.getVectorLength(); 9892 for (unsigned j = 0; j < vlen; j++) 9893 Elements.push_back(v.getVectorElt(j)); 9894 CountElts += vlen; 9895 } else if (EltTy->isIntegerType()) { 9896 llvm::APSInt sInt(32); 9897 if (CountInits < NumInits) { 9898 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 9899 return false; 9900 } else // trailing integer zero. 9901 sInt = Info.Ctx.MakeIntValue(0, EltTy); 9902 Elements.push_back(APValue(sInt)); 9903 CountElts++; 9904 } else { 9905 llvm::APFloat f(0.0); 9906 if (CountInits < NumInits) { 9907 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 9908 return false; 9909 } else // trailing float zero. 9910 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 9911 Elements.push_back(APValue(f)); 9912 CountElts++; 9913 } 9914 CountInits++; 9915 } 9916 return Success(Elements, E); 9917 } 9918 9919 bool 9920 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 9921 const auto *VT = E->getType()->castAs<VectorType>(); 9922 QualType EltTy = VT->getElementType(); 9923 APValue ZeroElement; 9924 if (EltTy->isIntegerType()) 9925 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 9926 else 9927 ZeroElement = 9928 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 9929 9930 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 9931 return Success(Elements, E); 9932 } 9933 9934 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9935 VisitIgnoredValue(E->getSubExpr()); 9936 return ZeroInitialization(E); 9937 } 9938 9939 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9940 BinaryOperatorKind Op = E->getOpcode(); 9941 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 9942 "Operation not supported on vector types"); 9943 9944 if (Op == BO_Comma) 9945 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9946 9947 Expr *LHS = E->getLHS(); 9948 Expr *RHS = E->getRHS(); 9949 9950 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 9951 "Must both be vector types"); 9952 // Checking JUST the types are the same would be fine, except shifts don't 9953 // need to have their types be the same (since you always shift by an int). 9954 assert(LHS->getType()->getAs<VectorType>()->getNumElements() == 9955 E->getType()->getAs<VectorType>()->getNumElements() && 9956 RHS->getType()->getAs<VectorType>()->getNumElements() == 9957 E->getType()->getAs<VectorType>()->getNumElements() && 9958 "All operands must be the same size."); 9959 9960 APValue LHSValue; 9961 APValue RHSValue; 9962 bool LHSOK = Evaluate(LHSValue, Info, LHS); 9963 if (!LHSOK && !Info.noteFailure()) 9964 return false; 9965 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 9966 return false; 9967 9968 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 9969 return false; 9970 9971 return Success(LHSValue, E); 9972 } 9973 9974 //===----------------------------------------------------------------------===// 9975 // Array Evaluation 9976 //===----------------------------------------------------------------------===// 9977 9978 namespace { 9979 class ArrayExprEvaluator 9980 : public ExprEvaluatorBase<ArrayExprEvaluator> { 9981 const LValue &This; 9982 APValue &Result; 9983 public: 9984 9985 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 9986 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 9987 9988 bool Success(const APValue &V, const Expr *E) { 9989 assert(V.isArray() && "expected array"); 9990 Result = V; 9991 return true; 9992 } 9993 9994 bool ZeroInitialization(const Expr *E) { 9995 const ConstantArrayType *CAT = 9996 Info.Ctx.getAsConstantArrayType(E->getType()); 9997 if (!CAT) { 9998 if (E->getType()->isIncompleteArrayType()) { 9999 // We can be asked to zero-initialize a flexible array member; this 10000 // is represented as an ImplicitValueInitExpr of incomplete array 10001 // type. In this case, the array has zero elements. 10002 Result = APValue(APValue::UninitArray(), 0, 0); 10003 return true; 10004 } 10005 // FIXME: We could handle VLAs here. 10006 return Error(E); 10007 } 10008 10009 Result = APValue(APValue::UninitArray(), 0, 10010 CAT->getSize().getZExtValue()); 10011 if (!Result.hasArrayFiller()) return true; 10012 10013 // Zero-initialize all elements. 10014 LValue Subobject = This; 10015 Subobject.addArray(Info, E, CAT); 10016 ImplicitValueInitExpr VIE(CAT->getElementType()); 10017 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10018 } 10019 10020 bool VisitCallExpr(const CallExpr *E) { 10021 return handleCallExpr(E, Result, &This); 10022 } 10023 bool VisitInitListExpr(const InitListExpr *E, 10024 QualType AllocType = QualType()); 10025 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10026 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10027 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10028 const LValue &Subobject, 10029 APValue *Value, QualType Type); 10030 bool VisitStringLiteral(const StringLiteral *E, 10031 QualType AllocType = QualType()) { 10032 expandStringLiteral(Info, E, Result, AllocType); 10033 return true; 10034 } 10035 }; 10036 } // end anonymous namespace 10037 10038 static bool EvaluateArray(const Expr *E, const LValue &This, 10039 APValue &Result, EvalInfo &Info) { 10040 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 10041 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10042 } 10043 10044 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10045 APValue &Result, const InitListExpr *ILE, 10046 QualType AllocType) { 10047 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 10048 "not an array rvalue"); 10049 return ArrayExprEvaluator(Info, This, Result) 10050 .VisitInitListExpr(ILE, AllocType); 10051 } 10052 10053 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10054 APValue &Result, 10055 const CXXConstructExpr *CCE, 10056 QualType AllocType) { 10057 assert(CCE->isRValue() && CCE->getType()->isArrayType() && 10058 "not an array rvalue"); 10059 return ArrayExprEvaluator(Info, This, Result) 10060 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10061 } 10062 10063 // Return true iff the given array filler may depend on the element index. 10064 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10065 // For now, just allow non-class value-initialization and initialization 10066 // lists comprised of them. 10067 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10068 return false; 10069 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10070 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10071 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10072 return true; 10073 } 10074 return false; 10075 } 10076 return true; 10077 } 10078 10079 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10080 QualType AllocType) { 10081 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10082 AllocType.isNull() ? E->getType() : AllocType); 10083 if (!CAT) 10084 return Error(E); 10085 10086 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10087 // an appropriately-typed string literal enclosed in braces. 10088 if (E->isStringLiteralInit()) { 10089 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 10090 // FIXME: Support ObjCEncodeExpr here once we support it in 10091 // ArrayExprEvaluator generally. 10092 if (!SL) 10093 return Error(E); 10094 return VisitStringLiteral(SL, AllocType); 10095 } 10096 10097 bool Success = true; 10098 10099 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10100 "zero-initialized array shouldn't have any initialized elts"); 10101 APValue Filler; 10102 if (Result.isArray() && Result.hasArrayFiller()) 10103 Filler = Result.getArrayFiller(); 10104 10105 unsigned NumEltsToInit = E->getNumInits(); 10106 unsigned NumElts = CAT->getSize().getZExtValue(); 10107 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10108 10109 // If the initializer might depend on the array index, run it for each 10110 // array element. 10111 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10112 NumEltsToInit = NumElts; 10113 10114 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10115 << NumEltsToInit << ".\n"); 10116 10117 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10118 10119 // If the array was previously zero-initialized, preserve the 10120 // zero-initialized values. 10121 if (Filler.hasValue()) { 10122 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10123 Result.getArrayInitializedElt(I) = Filler; 10124 if (Result.hasArrayFiller()) 10125 Result.getArrayFiller() = Filler; 10126 } 10127 10128 LValue Subobject = This; 10129 Subobject.addArray(Info, E, CAT); 10130 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10131 const Expr *Init = 10132 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10133 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10134 Info, Subobject, Init) || 10135 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10136 CAT->getElementType(), 1)) { 10137 if (!Info.noteFailure()) 10138 return false; 10139 Success = false; 10140 } 10141 } 10142 10143 if (!Result.hasArrayFiller()) 10144 return Success; 10145 10146 // If we get here, we have a trivial filler, which we can just evaluate 10147 // once and splat over the rest of the array elements. 10148 assert(FillerExpr && "no array filler for incomplete init list"); 10149 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10150 FillerExpr) && Success; 10151 } 10152 10153 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10154 LValue CommonLV; 10155 if (E->getCommonExpr() && 10156 !Evaluate(Info.CurrentCall->createTemporary( 10157 E->getCommonExpr(), 10158 getStorageType(Info.Ctx, E->getCommonExpr()), false, 10159 CommonLV), 10160 Info, E->getCommonExpr()->getSourceExpr())) 10161 return false; 10162 10163 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10164 10165 uint64_t Elements = CAT->getSize().getZExtValue(); 10166 Result = APValue(APValue::UninitArray(), Elements, Elements); 10167 10168 LValue Subobject = This; 10169 Subobject.addArray(Info, E, CAT); 10170 10171 bool Success = true; 10172 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10173 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10174 Info, Subobject, E->getSubExpr()) || 10175 !HandleLValueArrayAdjustment(Info, E, Subobject, 10176 CAT->getElementType(), 1)) { 10177 if (!Info.noteFailure()) 10178 return false; 10179 Success = false; 10180 } 10181 } 10182 10183 return Success; 10184 } 10185 10186 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10187 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10188 } 10189 10190 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10191 const LValue &Subobject, 10192 APValue *Value, 10193 QualType Type) { 10194 bool HadZeroInit = Value->hasValue(); 10195 10196 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10197 unsigned N = CAT->getSize().getZExtValue(); 10198 10199 // Preserve the array filler if we had prior zero-initialization. 10200 APValue Filler = 10201 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10202 : APValue(); 10203 10204 *Value = APValue(APValue::UninitArray(), N, N); 10205 10206 if (HadZeroInit) 10207 for (unsigned I = 0; I != N; ++I) 10208 Value->getArrayInitializedElt(I) = Filler; 10209 10210 // Initialize the elements. 10211 LValue ArrayElt = Subobject; 10212 ArrayElt.addArray(Info, E, CAT); 10213 for (unsigned I = 0; I != N; ++I) 10214 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10215 CAT->getElementType()) || 10216 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10217 CAT->getElementType(), 1)) 10218 return false; 10219 10220 return true; 10221 } 10222 10223 if (!Type->isRecordType()) 10224 return Error(E); 10225 10226 return RecordExprEvaluator(Info, Subobject, *Value) 10227 .VisitCXXConstructExpr(E, Type); 10228 } 10229 10230 //===----------------------------------------------------------------------===// 10231 // Integer Evaluation 10232 // 10233 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10234 // types and back in constant folding. Integer values are thus represented 10235 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10236 //===----------------------------------------------------------------------===// 10237 10238 namespace { 10239 class IntExprEvaluator 10240 : public ExprEvaluatorBase<IntExprEvaluator> { 10241 APValue &Result; 10242 public: 10243 IntExprEvaluator(EvalInfo &info, APValue &result) 10244 : ExprEvaluatorBaseTy(info), Result(result) {} 10245 10246 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10247 assert(E->getType()->isIntegralOrEnumerationType() && 10248 "Invalid evaluation result."); 10249 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10250 "Invalid evaluation result."); 10251 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10252 "Invalid evaluation result."); 10253 Result = APValue(SI); 10254 return true; 10255 } 10256 bool Success(const llvm::APSInt &SI, const Expr *E) { 10257 return Success(SI, E, Result); 10258 } 10259 10260 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10261 assert(E->getType()->isIntegralOrEnumerationType() && 10262 "Invalid evaluation result."); 10263 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10264 "Invalid evaluation result."); 10265 Result = APValue(APSInt(I)); 10266 Result.getInt().setIsUnsigned( 10267 E->getType()->isUnsignedIntegerOrEnumerationType()); 10268 return true; 10269 } 10270 bool Success(const llvm::APInt &I, const Expr *E) { 10271 return Success(I, E, Result); 10272 } 10273 10274 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10275 assert(E->getType()->isIntegralOrEnumerationType() && 10276 "Invalid evaluation result."); 10277 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10278 return true; 10279 } 10280 bool Success(uint64_t Value, const Expr *E) { 10281 return Success(Value, E, Result); 10282 } 10283 10284 bool Success(CharUnits Size, const Expr *E) { 10285 return Success(Size.getQuantity(), E); 10286 } 10287 10288 bool Success(const APValue &V, const Expr *E) { 10289 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10290 Result = V; 10291 return true; 10292 } 10293 return Success(V.getInt(), E); 10294 } 10295 10296 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10297 10298 //===--------------------------------------------------------------------===// 10299 // Visitor Methods 10300 //===--------------------------------------------------------------------===// 10301 10302 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10303 return Success(E->getValue(), E); 10304 } 10305 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10306 return Success(E->getValue(), E); 10307 } 10308 10309 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10310 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10311 if (CheckReferencedDecl(E, E->getDecl())) 10312 return true; 10313 10314 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10315 } 10316 bool VisitMemberExpr(const MemberExpr *E) { 10317 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10318 VisitIgnoredBaseExpression(E->getBase()); 10319 return true; 10320 } 10321 10322 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10323 } 10324 10325 bool VisitCallExpr(const CallExpr *E); 10326 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10327 bool VisitBinaryOperator(const BinaryOperator *E); 10328 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10329 bool VisitUnaryOperator(const UnaryOperator *E); 10330 10331 bool VisitCastExpr(const CastExpr* E); 10332 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10333 10334 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10335 return Success(E->getValue(), E); 10336 } 10337 10338 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10339 return Success(E->getValue(), E); 10340 } 10341 10342 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10343 if (Info.ArrayInitIndex == uint64_t(-1)) { 10344 // We were asked to evaluate this subexpression independent of the 10345 // enclosing ArrayInitLoopExpr. We can't do that. 10346 Info.FFDiag(E); 10347 return false; 10348 } 10349 return Success(Info.ArrayInitIndex, E); 10350 } 10351 10352 // Note, GNU defines __null as an integer, not a pointer. 10353 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10354 return ZeroInitialization(E); 10355 } 10356 10357 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10358 return Success(E->getValue(), E); 10359 } 10360 10361 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10362 return Success(E->getValue(), E); 10363 } 10364 10365 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10366 return Success(E->getValue(), E); 10367 } 10368 10369 bool VisitUnaryReal(const UnaryOperator *E); 10370 bool VisitUnaryImag(const UnaryOperator *E); 10371 10372 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10373 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10374 bool VisitSourceLocExpr(const SourceLocExpr *E); 10375 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10376 bool VisitRequiresExpr(const RequiresExpr *E); 10377 // FIXME: Missing: array subscript of vector, member of vector 10378 }; 10379 10380 class FixedPointExprEvaluator 10381 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10382 APValue &Result; 10383 10384 public: 10385 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10386 : ExprEvaluatorBaseTy(info), Result(result) {} 10387 10388 bool Success(const llvm::APInt &I, const Expr *E) { 10389 return Success( 10390 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10391 } 10392 10393 bool Success(uint64_t Value, const Expr *E) { 10394 return Success( 10395 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10396 } 10397 10398 bool Success(const APValue &V, const Expr *E) { 10399 return Success(V.getFixedPoint(), E); 10400 } 10401 10402 bool Success(const APFixedPoint &V, const Expr *E) { 10403 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10404 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10405 "Invalid evaluation result."); 10406 Result = APValue(V); 10407 return true; 10408 } 10409 10410 //===--------------------------------------------------------------------===// 10411 // Visitor Methods 10412 //===--------------------------------------------------------------------===// 10413 10414 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10415 return Success(E->getValue(), E); 10416 } 10417 10418 bool VisitCastExpr(const CastExpr *E); 10419 bool VisitUnaryOperator(const UnaryOperator *E); 10420 bool VisitBinaryOperator(const BinaryOperator *E); 10421 }; 10422 } // end anonymous namespace 10423 10424 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10425 /// produce either the integer value or a pointer. 10426 /// 10427 /// GCC has a heinous extension which folds casts between pointer types and 10428 /// pointer-sized integral types. We support this by allowing the evaluation of 10429 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10430 /// Some simple arithmetic on such values is supported (they are treated much 10431 /// like char*). 10432 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10433 EvalInfo &Info) { 10434 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10435 return IntExprEvaluator(Info, Result).Visit(E); 10436 } 10437 10438 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10439 APValue Val; 10440 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10441 return false; 10442 if (!Val.isInt()) { 10443 // FIXME: It would be better to produce the diagnostic for casting 10444 // a pointer to an integer. 10445 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10446 return false; 10447 } 10448 Result = Val.getInt(); 10449 return true; 10450 } 10451 10452 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10453 APValue Evaluated = E->EvaluateInContext( 10454 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10455 return Success(Evaluated, E); 10456 } 10457 10458 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10459 EvalInfo &Info) { 10460 if (E->getType()->isFixedPointType()) { 10461 APValue Val; 10462 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10463 return false; 10464 if (!Val.isFixedPoint()) 10465 return false; 10466 10467 Result = Val.getFixedPoint(); 10468 return true; 10469 } 10470 return false; 10471 } 10472 10473 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10474 EvalInfo &Info) { 10475 if (E->getType()->isIntegerType()) { 10476 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10477 APSInt Val; 10478 if (!EvaluateInteger(E, Val, Info)) 10479 return false; 10480 Result = APFixedPoint(Val, FXSema); 10481 return true; 10482 } else if (E->getType()->isFixedPointType()) { 10483 return EvaluateFixedPoint(E, Result, Info); 10484 } 10485 return false; 10486 } 10487 10488 /// Check whether the given declaration can be directly converted to an integral 10489 /// rvalue. If not, no diagnostic is produced; there are other things we can 10490 /// try. 10491 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10492 // Enums are integer constant exprs. 10493 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10494 // Check for signedness/width mismatches between E type and ECD value. 10495 bool SameSign = (ECD->getInitVal().isSigned() 10496 == E->getType()->isSignedIntegerOrEnumerationType()); 10497 bool SameWidth = (ECD->getInitVal().getBitWidth() 10498 == Info.Ctx.getIntWidth(E->getType())); 10499 if (SameSign && SameWidth) 10500 return Success(ECD->getInitVal(), E); 10501 else { 10502 // Get rid of mismatch (otherwise Success assertions will fail) 10503 // by computing a new value matching the type of E. 10504 llvm::APSInt Val = ECD->getInitVal(); 10505 if (!SameSign) 10506 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10507 if (!SameWidth) 10508 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10509 return Success(Val, E); 10510 } 10511 } 10512 return false; 10513 } 10514 10515 /// Values returned by __builtin_classify_type, chosen to match the values 10516 /// produced by GCC's builtin. 10517 enum class GCCTypeClass { 10518 None = -1, 10519 Void = 0, 10520 Integer = 1, 10521 // GCC reserves 2 for character types, but instead classifies them as 10522 // integers. 10523 Enum = 3, 10524 Bool = 4, 10525 Pointer = 5, 10526 // GCC reserves 6 for references, but appears to never use it (because 10527 // expressions never have reference type, presumably). 10528 PointerToDataMember = 7, 10529 RealFloat = 8, 10530 Complex = 9, 10531 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10532 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10533 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10534 // uses 12 for that purpose, same as for a class or struct. Maybe it 10535 // internally implements a pointer to member as a struct? Who knows. 10536 PointerToMemberFunction = 12, // Not a bug, see above. 10537 ClassOrStruct = 12, 10538 Union = 13, 10539 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10540 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10541 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10542 // literals. 10543 }; 10544 10545 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10546 /// as GCC. 10547 static GCCTypeClass 10548 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10549 assert(!T->isDependentType() && "unexpected dependent type"); 10550 10551 QualType CanTy = T.getCanonicalType(); 10552 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10553 10554 switch (CanTy->getTypeClass()) { 10555 #define TYPE(ID, BASE) 10556 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10557 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10558 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10559 #include "clang/AST/TypeNodes.inc" 10560 case Type::Auto: 10561 case Type::DeducedTemplateSpecialization: 10562 llvm_unreachable("unexpected non-canonical or dependent type"); 10563 10564 case Type::Builtin: 10565 switch (BT->getKind()) { 10566 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10567 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10568 case BuiltinType::ID: return GCCTypeClass::Integer; 10569 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10570 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10571 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10572 case BuiltinType::ID: break; 10573 #include "clang/AST/BuiltinTypes.def" 10574 case BuiltinType::Void: 10575 return GCCTypeClass::Void; 10576 10577 case BuiltinType::Bool: 10578 return GCCTypeClass::Bool; 10579 10580 case BuiltinType::Char_U: 10581 case BuiltinType::UChar: 10582 case BuiltinType::WChar_U: 10583 case BuiltinType::Char8: 10584 case BuiltinType::Char16: 10585 case BuiltinType::Char32: 10586 case BuiltinType::UShort: 10587 case BuiltinType::UInt: 10588 case BuiltinType::ULong: 10589 case BuiltinType::ULongLong: 10590 case BuiltinType::UInt128: 10591 return GCCTypeClass::Integer; 10592 10593 case BuiltinType::UShortAccum: 10594 case BuiltinType::UAccum: 10595 case BuiltinType::ULongAccum: 10596 case BuiltinType::UShortFract: 10597 case BuiltinType::UFract: 10598 case BuiltinType::ULongFract: 10599 case BuiltinType::SatUShortAccum: 10600 case BuiltinType::SatUAccum: 10601 case BuiltinType::SatULongAccum: 10602 case BuiltinType::SatUShortFract: 10603 case BuiltinType::SatUFract: 10604 case BuiltinType::SatULongFract: 10605 return GCCTypeClass::None; 10606 10607 case BuiltinType::NullPtr: 10608 10609 case BuiltinType::ObjCId: 10610 case BuiltinType::ObjCClass: 10611 case BuiltinType::ObjCSel: 10612 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10613 case BuiltinType::Id: 10614 #include "clang/Basic/OpenCLImageTypes.def" 10615 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10616 case BuiltinType::Id: 10617 #include "clang/Basic/OpenCLExtensionTypes.def" 10618 case BuiltinType::OCLSampler: 10619 case BuiltinType::OCLEvent: 10620 case BuiltinType::OCLClkEvent: 10621 case BuiltinType::OCLQueue: 10622 case BuiltinType::OCLReserveID: 10623 #define SVE_TYPE(Name, Id, SingletonId) \ 10624 case BuiltinType::Id: 10625 #include "clang/Basic/AArch64SVEACLETypes.def" 10626 return GCCTypeClass::None; 10627 10628 case BuiltinType::Dependent: 10629 llvm_unreachable("unexpected dependent type"); 10630 }; 10631 llvm_unreachable("unexpected placeholder type"); 10632 10633 case Type::Enum: 10634 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 10635 10636 case Type::Pointer: 10637 case Type::ConstantArray: 10638 case Type::VariableArray: 10639 case Type::IncompleteArray: 10640 case Type::FunctionNoProto: 10641 case Type::FunctionProto: 10642 return GCCTypeClass::Pointer; 10643 10644 case Type::MemberPointer: 10645 return CanTy->isMemberDataPointerType() 10646 ? GCCTypeClass::PointerToDataMember 10647 : GCCTypeClass::PointerToMemberFunction; 10648 10649 case Type::Complex: 10650 return GCCTypeClass::Complex; 10651 10652 case Type::Record: 10653 return CanTy->isUnionType() ? GCCTypeClass::Union 10654 : GCCTypeClass::ClassOrStruct; 10655 10656 case Type::Atomic: 10657 // GCC classifies _Atomic T the same as T. 10658 return EvaluateBuiltinClassifyType( 10659 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 10660 10661 case Type::BlockPointer: 10662 case Type::Vector: 10663 case Type::ExtVector: 10664 case Type::ConstantMatrix: 10665 case Type::ObjCObject: 10666 case Type::ObjCInterface: 10667 case Type::ObjCObjectPointer: 10668 case Type::Pipe: 10669 case Type::ExtInt: 10670 // GCC classifies vectors as None. We follow its lead and classify all 10671 // other types that don't fit into the regular classification the same way. 10672 return GCCTypeClass::None; 10673 10674 case Type::LValueReference: 10675 case Type::RValueReference: 10676 llvm_unreachable("invalid type for expression"); 10677 } 10678 10679 llvm_unreachable("unexpected type class"); 10680 } 10681 10682 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10683 /// as GCC. 10684 static GCCTypeClass 10685 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 10686 // If no argument was supplied, default to None. This isn't 10687 // ideal, however it is what gcc does. 10688 if (E->getNumArgs() == 0) 10689 return GCCTypeClass::None; 10690 10691 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 10692 // being an ICE, but still folds it to a constant using the type of the first 10693 // argument. 10694 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 10695 } 10696 10697 /// EvaluateBuiltinConstantPForLValue - Determine the result of 10698 /// __builtin_constant_p when applied to the given pointer. 10699 /// 10700 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 10701 /// or it points to the first character of a string literal. 10702 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 10703 APValue::LValueBase Base = LV.getLValueBase(); 10704 if (Base.isNull()) { 10705 // A null base is acceptable. 10706 return true; 10707 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 10708 if (!isa<StringLiteral>(E)) 10709 return false; 10710 return LV.getLValueOffset().isZero(); 10711 } else if (Base.is<TypeInfoLValue>()) { 10712 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 10713 // evaluate to true. 10714 return true; 10715 } else { 10716 // Any other base is not constant enough for GCC. 10717 return false; 10718 } 10719 } 10720 10721 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 10722 /// GCC as we can manage. 10723 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 10724 // This evaluation is not permitted to have side-effects, so evaluate it in 10725 // a speculative evaluation context. 10726 SpeculativeEvaluationRAII SpeculativeEval(Info); 10727 10728 // Constant-folding is always enabled for the operand of __builtin_constant_p 10729 // (even when the enclosing evaluation context otherwise requires a strict 10730 // language-specific constant expression). 10731 FoldConstant Fold(Info, true); 10732 10733 QualType ArgType = Arg->getType(); 10734 10735 // __builtin_constant_p always has one operand. The rules which gcc follows 10736 // are not precisely documented, but are as follows: 10737 // 10738 // - If the operand is of integral, floating, complex or enumeration type, 10739 // and can be folded to a known value of that type, it returns 1. 10740 // - If the operand can be folded to a pointer to the first character 10741 // of a string literal (or such a pointer cast to an integral type) 10742 // or to a null pointer or an integer cast to a pointer, it returns 1. 10743 // 10744 // Otherwise, it returns 0. 10745 // 10746 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 10747 // its support for this did not work prior to GCC 9 and is not yet well 10748 // understood. 10749 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 10750 ArgType->isAnyComplexType() || ArgType->isPointerType() || 10751 ArgType->isNullPtrType()) { 10752 APValue V; 10753 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 10754 Fold.keepDiagnostics(); 10755 return false; 10756 } 10757 10758 // For a pointer (possibly cast to integer), there are special rules. 10759 if (V.getKind() == APValue::LValue) 10760 return EvaluateBuiltinConstantPForLValue(V); 10761 10762 // Otherwise, any constant value is good enough. 10763 return V.hasValue(); 10764 } 10765 10766 // Anything else isn't considered to be sufficiently constant. 10767 return false; 10768 } 10769 10770 /// Retrieves the "underlying object type" of the given expression, 10771 /// as used by __builtin_object_size. 10772 static QualType getObjectType(APValue::LValueBase B) { 10773 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 10774 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 10775 return VD->getType(); 10776 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 10777 if (isa<CompoundLiteralExpr>(E)) 10778 return E->getType(); 10779 } else if (B.is<TypeInfoLValue>()) { 10780 return B.getTypeInfoType(); 10781 } else if (B.is<DynamicAllocLValue>()) { 10782 return B.getDynamicAllocType(); 10783 } 10784 10785 return QualType(); 10786 } 10787 10788 /// A more selective version of E->IgnoreParenCasts for 10789 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 10790 /// to change the type of E. 10791 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 10792 /// 10793 /// Always returns an RValue with a pointer representation. 10794 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 10795 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 10796 10797 auto *NoParens = E->IgnoreParens(); 10798 auto *Cast = dyn_cast<CastExpr>(NoParens); 10799 if (Cast == nullptr) 10800 return NoParens; 10801 10802 // We only conservatively allow a few kinds of casts, because this code is 10803 // inherently a simple solution that seeks to support the common case. 10804 auto CastKind = Cast->getCastKind(); 10805 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 10806 CastKind != CK_AddressSpaceConversion) 10807 return NoParens; 10808 10809 auto *SubExpr = Cast->getSubExpr(); 10810 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 10811 return NoParens; 10812 return ignorePointerCastsAndParens(SubExpr); 10813 } 10814 10815 /// Checks to see if the given LValue's Designator is at the end of the LValue's 10816 /// record layout. e.g. 10817 /// struct { struct { int a, b; } fst, snd; } obj; 10818 /// obj.fst // no 10819 /// obj.snd // yes 10820 /// obj.fst.a // no 10821 /// obj.fst.b // no 10822 /// obj.snd.a // no 10823 /// obj.snd.b // yes 10824 /// 10825 /// Please note: this function is specialized for how __builtin_object_size 10826 /// views "objects". 10827 /// 10828 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 10829 /// correct result, it will always return true. 10830 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 10831 assert(!LVal.Designator.Invalid); 10832 10833 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 10834 const RecordDecl *Parent = FD->getParent(); 10835 Invalid = Parent->isInvalidDecl(); 10836 if (Invalid || Parent->isUnion()) 10837 return true; 10838 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 10839 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 10840 }; 10841 10842 auto &Base = LVal.getLValueBase(); 10843 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 10844 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 10845 bool Invalid; 10846 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10847 return Invalid; 10848 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 10849 for (auto *FD : IFD->chain()) { 10850 bool Invalid; 10851 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 10852 return Invalid; 10853 } 10854 } 10855 } 10856 10857 unsigned I = 0; 10858 QualType BaseType = getType(Base); 10859 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 10860 // If we don't know the array bound, conservatively assume we're looking at 10861 // the final array element. 10862 ++I; 10863 if (BaseType->isIncompleteArrayType()) 10864 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 10865 else 10866 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 10867 } 10868 10869 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 10870 const auto &Entry = LVal.Designator.Entries[I]; 10871 if (BaseType->isArrayType()) { 10872 // Because __builtin_object_size treats arrays as objects, we can ignore 10873 // the index iff this is the last array in the Designator. 10874 if (I + 1 == E) 10875 return true; 10876 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 10877 uint64_t Index = Entry.getAsArrayIndex(); 10878 if (Index + 1 != CAT->getSize()) 10879 return false; 10880 BaseType = CAT->getElementType(); 10881 } else if (BaseType->isAnyComplexType()) { 10882 const auto *CT = BaseType->castAs<ComplexType>(); 10883 uint64_t Index = Entry.getAsArrayIndex(); 10884 if (Index != 1) 10885 return false; 10886 BaseType = CT->getElementType(); 10887 } else if (auto *FD = getAsField(Entry)) { 10888 bool Invalid; 10889 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10890 return Invalid; 10891 BaseType = FD->getType(); 10892 } else { 10893 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 10894 return false; 10895 } 10896 } 10897 return true; 10898 } 10899 10900 /// Tests to see if the LValue has a user-specified designator (that isn't 10901 /// necessarily valid). Note that this always returns 'true' if the LValue has 10902 /// an unsized array as its first designator entry, because there's currently no 10903 /// way to tell if the user typed *foo or foo[0]. 10904 static bool refersToCompleteObject(const LValue &LVal) { 10905 if (LVal.Designator.Invalid) 10906 return false; 10907 10908 if (!LVal.Designator.Entries.empty()) 10909 return LVal.Designator.isMostDerivedAnUnsizedArray(); 10910 10911 if (!LVal.InvalidBase) 10912 return true; 10913 10914 // If `E` is a MemberExpr, then the first part of the designator is hiding in 10915 // the LValueBase. 10916 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 10917 return !E || !isa<MemberExpr>(E); 10918 } 10919 10920 /// Attempts to detect a user writing into a piece of memory that's impossible 10921 /// to figure out the size of by just using types. 10922 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 10923 const SubobjectDesignator &Designator = LVal.Designator; 10924 // Notes: 10925 // - Users can only write off of the end when we have an invalid base. Invalid 10926 // bases imply we don't know where the memory came from. 10927 // - We used to be a bit more aggressive here; we'd only be conservative if 10928 // the array at the end was flexible, or if it had 0 or 1 elements. This 10929 // broke some common standard library extensions (PR30346), but was 10930 // otherwise seemingly fine. It may be useful to reintroduce this behavior 10931 // with some sort of list. OTOH, it seems that GCC is always 10932 // conservative with the last element in structs (if it's an array), so our 10933 // current behavior is more compatible than an explicit list approach would 10934 // be. 10935 return LVal.InvalidBase && 10936 Designator.Entries.size() == Designator.MostDerivedPathLength && 10937 Designator.MostDerivedIsArrayElement && 10938 isDesignatorAtObjectEnd(Ctx, LVal); 10939 } 10940 10941 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 10942 /// Fails if the conversion would cause loss of precision. 10943 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 10944 CharUnits &Result) { 10945 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 10946 if (Int.ugt(CharUnitsMax)) 10947 return false; 10948 Result = CharUnits::fromQuantity(Int.getZExtValue()); 10949 return true; 10950 } 10951 10952 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 10953 /// determine how many bytes exist from the beginning of the object to either 10954 /// the end of the current subobject, or the end of the object itself, depending 10955 /// on what the LValue looks like + the value of Type. 10956 /// 10957 /// If this returns false, the value of Result is undefined. 10958 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 10959 unsigned Type, const LValue &LVal, 10960 CharUnits &EndOffset) { 10961 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 10962 10963 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 10964 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 10965 return false; 10966 return HandleSizeof(Info, ExprLoc, Ty, Result); 10967 }; 10968 10969 // We want to evaluate the size of the entire object. This is a valid fallback 10970 // for when Type=1 and the designator is invalid, because we're asked for an 10971 // upper-bound. 10972 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 10973 // Type=3 wants a lower bound, so we can't fall back to this. 10974 if (Type == 3 && !DetermineForCompleteObject) 10975 return false; 10976 10977 llvm::APInt APEndOffset; 10978 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 10979 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 10980 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 10981 10982 if (LVal.InvalidBase) 10983 return false; 10984 10985 QualType BaseTy = getObjectType(LVal.getLValueBase()); 10986 return CheckedHandleSizeof(BaseTy, EndOffset); 10987 } 10988 10989 // We want to evaluate the size of a subobject. 10990 const SubobjectDesignator &Designator = LVal.Designator; 10991 10992 // The following is a moderately common idiom in C: 10993 // 10994 // struct Foo { int a; char c[1]; }; 10995 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 10996 // strcpy(&F->c[0], Bar); 10997 // 10998 // In order to not break too much legacy code, we need to support it. 10999 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11000 // If we can resolve this to an alloc_size call, we can hand that back, 11001 // because we know for certain how many bytes there are to write to. 11002 llvm::APInt APEndOffset; 11003 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11004 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11005 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11006 11007 // If we cannot determine the size of the initial allocation, then we can't 11008 // given an accurate upper-bound. However, we are still able to give 11009 // conservative lower-bounds for Type=3. 11010 if (Type == 1) 11011 return false; 11012 } 11013 11014 CharUnits BytesPerElem; 11015 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11016 return false; 11017 11018 // According to the GCC documentation, we want the size of the subobject 11019 // denoted by the pointer. But that's not quite right -- what we actually 11020 // want is the size of the immediately-enclosing array, if there is one. 11021 int64_t ElemsRemaining; 11022 if (Designator.MostDerivedIsArrayElement && 11023 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11024 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11025 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11026 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11027 } else { 11028 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11029 } 11030 11031 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11032 return true; 11033 } 11034 11035 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11036 /// returns true and stores the result in @p Size. 11037 /// 11038 /// If @p WasError is non-null, this will report whether the failure to evaluate 11039 /// is to be treated as an Error in IntExprEvaluator. 11040 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11041 EvalInfo &Info, uint64_t &Size) { 11042 // Determine the denoted object. 11043 LValue LVal; 11044 { 11045 // The operand of __builtin_object_size is never evaluated for side-effects. 11046 // If there are any, but we can determine the pointed-to object anyway, then 11047 // ignore the side-effects. 11048 SpeculativeEvaluationRAII SpeculativeEval(Info); 11049 IgnoreSideEffectsRAII Fold(Info); 11050 11051 if (E->isGLValue()) { 11052 // It's possible for us to be given GLValues if we're called via 11053 // Expr::tryEvaluateObjectSize. 11054 APValue RVal; 11055 if (!EvaluateAsRValue(Info, E, RVal)) 11056 return false; 11057 LVal.setFrom(Info.Ctx, RVal); 11058 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11059 /*InvalidBaseOK=*/true)) 11060 return false; 11061 } 11062 11063 // If we point to before the start of the object, there are no accessible 11064 // bytes. 11065 if (LVal.getLValueOffset().isNegative()) { 11066 Size = 0; 11067 return true; 11068 } 11069 11070 CharUnits EndOffset; 11071 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11072 return false; 11073 11074 // If we've fallen outside of the end offset, just pretend there's nothing to 11075 // write to/read from. 11076 if (EndOffset <= LVal.getLValueOffset()) 11077 Size = 0; 11078 else 11079 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11080 return true; 11081 } 11082 11083 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11084 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11085 return VisitBuiltinCallExpr(E, BuiltinOp); 11086 11087 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11088 } 11089 11090 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11091 APValue &Val, APSInt &Alignment) { 11092 QualType SrcTy = E->getArg(0)->getType(); 11093 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11094 return false; 11095 // Even though we are evaluating integer expressions we could get a pointer 11096 // argument for the __builtin_is_aligned() case. 11097 if (SrcTy->isPointerType()) { 11098 LValue Ptr; 11099 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11100 return false; 11101 Ptr.moveInto(Val); 11102 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11103 Info.FFDiag(E->getArg(0)); 11104 return false; 11105 } else { 11106 APSInt SrcInt; 11107 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11108 return false; 11109 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11110 "Bit widths must be the same"); 11111 Val = APValue(SrcInt); 11112 } 11113 assert(Val.hasValue()); 11114 return true; 11115 } 11116 11117 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11118 unsigned BuiltinOp) { 11119 switch (BuiltinOp) { 11120 default: 11121 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11122 11123 case Builtin::BI__builtin_dynamic_object_size: 11124 case Builtin::BI__builtin_object_size: { 11125 // The type was checked when we built the expression. 11126 unsigned Type = 11127 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11128 assert(Type <= 3 && "unexpected type"); 11129 11130 uint64_t Size; 11131 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11132 return Success(Size, E); 11133 11134 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11135 return Success((Type & 2) ? 0 : -1, E); 11136 11137 // Expression had no side effects, but we couldn't statically determine the 11138 // size of the referenced object. 11139 switch (Info.EvalMode) { 11140 case EvalInfo::EM_ConstantExpression: 11141 case EvalInfo::EM_ConstantFold: 11142 case EvalInfo::EM_IgnoreSideEffects: 11143 // Leave it to IR generation. 11144 return Error(E); 11145 case EvalInfo::EM_ConstantExpressionUnevaluated: 11146 // Reduce it to a constant now. 11147 return Success((Type & 2) ? 0 : -1, E); 11148 } 11149 11150 llvm_unreachable("unexpected EvalMode"); 11151 } 11152 11153 case Builtin::BI__builtin_os_log_format_buffer_size: { 11154 analyze_os_log::OSLogBufferLayout Layout; 11155 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11156 return Success(Layout.size().getQuantity(), E); 11157 } 11158 11159 case Builtin::BI__builtin_is_aligned: { 11160 APValue Src; 11161 APSInt Alignment; 11162 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11163 return false; 11164 if (Src.isLValue()) { 11165 // If we evaluated a pointer, check the minimum known alignment. 11166 LValue Ptr; 11167 Ptr.setFrom(Info.Ctx, Src); 11168 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11169 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11170 // We can return true if the known alignment at the computed offset is 11171 // greater than the requested alignment. 11172 assert(PtrAlign.isPowerOfTwo()); 11173 assert(Alignment.isPowerOf2()); 11174 if (PtrAlign.getQuantity() >= Alignment) 11175 return Success(1, E); 11176 // If the alignment is not known to be sufficient, some cases could still 11177 // be aligned at run time. However, if the requested alignment is less or 11178 // equal to the base alignment and the offset is not aligned, we know that 11179 // the run-time value can never be aligned. 11180 if (BaseAlignment.getQuantity() >= Alignment && 11181 PtrAlign.getQuantity() < Alignment) 11182 return Success(0, E); 11183 // Otherwise we can't infer whether the value is sufficiently aligned. 11184 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11185 // in cases where we can't fully evaluate the pointer. 11186 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11187 << Alignment; 11188 return false; 11189 } 11190 assert(Src.isInt()); 11191 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11192 } 11193 case Builtin::BI__builtin_align_up: { 11194 APValue Src; 11195 APSInt Alignment; 11196 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11197 return false; 11198 if (!Src.isInt()) 11199 return Error(E); 11200 APSInt AlignedVal = 11201 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11202 Src.getInt().isUnsigned()); 11203 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11204 return Success(AlignedVal, E); 11205 } 11206 case Builtin::BI__builtin_align_down: { 11207 APValue Src; 11208 APSInt Alignment; 11209 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11210 return false; 11211 if (!Src.isInt()) 11212 return Error(E); 11213 APSInt AlignedVal = 11214 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11215 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11216 return Success(AlignedVal, E); 11217 } 11218 11219 case Builtin::BI__builtin_bitreverse8: 11220 case Builtin::BI__builtin_bitreverse16: 11221 case Builtin::BI__builtin_bitreverse32: 11222 case Builtin::BI__builtin_bitreverse64: { 11223 APSInt Val; 11224 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11225 return false; 11226 11227 return Success(Val.reverseBits(), E); 11228 } 11229 11230 case Builtin::BI__builtin_bswap16: 11231 case Builtin::BI__builtin_bswap32: 11232 case Builtin::BI__builtin_bswap64: { 11233 APSInt Val; 11234 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11235 return false; 11236 11237 return Success(Val.byteSwap(), E); 11238 } 11239 11240 case Builtin::BI__builtin_classify_type: 11241 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11242 11243 case Builtin::BI__builtin_clrsb: 11244 case Builtin::BI__builtin_clrsbl: 11245 case Builtin::BI__builtin_clrsbll: { 11246 APSInt Val; 11247 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11248 return false; 11249 11250 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11251 } 11252 11253 case Builtin::BI__builtin_clz: 11254 case Builtin::BI__builtin_clzl: 11255 case Builtin::BI__builtin_clzll: 11256 case Builtin::BI__builtin_clzs: { 11257 APSInt Val; 11258 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11259 return false; 11260 if (!Val) 11261 return Error(E); 11262 11263 return Success(Val.countLeadingZeros(), E); 11264 } 11265 11266 case Builtin::BI__builtin_constant_p: { 11267 const Expr *Arg = E->getArg(0); 11268 if (EvaluateBuiltinConstantP(Info, Arg)) 11269 return Success(true, E); 11270 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11271 // Outside a constant context, eagerly evaluate to false in the presence 11272 // of side-effects in order to avoid -Wunsequenced false-positives in 11273 // a branch on __builtin_constant_p(expr). 11274 return Success(false, E); 11275 } 11276 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11277 return false; 11278 } 11279 11280 case Builtin::BI__builtin_is_constant_evaluated: { 11281 const auto *Callee = Info.CurrentCall->getCallee(); 11282 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11283 (Info.CallStackDepth == 1 || 11284 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11285 Callee->getIdentifier() && 11286 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11287 // FIXME: Find a better way to avoid duplicated diagnostics. 11288 if (Info.EvalStatus.Diag) 11289 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11290 : Info.CurrentCall->CallLoc, 11291 diag::warn_is_constant_evaluated_always_true_constexpr) 11292 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11293 : "std::is_constant_evaluated"); 11294 } 11295 11296 return Success(Info.InConstantContext, E); 11297 } 11298 11299 case Builtin::BI__builtin_ctz: 11300 case Builtin::BI__builtin_ctzl: 11301 case Builtin::BI__builtin_ctzll: 11302 case Builtin::BI__builtin_ctzs: { 11303 APSInt Val; 11304 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11305 return false; 11306 if (!Val) 11307 return Error(E); 11308 11309 return Success(Val.countTrailingZeros(), E); 11310 } 11311 11312 case Builtin::BI__builtin_eh_return_data_regno: { 11313 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11314 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11315 return Success(Operand, E); 11316 } 11317 11318 case Builtin::BI__builtin_expect: 11319 case Builtin::BI__builtin_expect_with_probability: 11320 return Visit(E->getArg(0)); 11321 11322 case Builtin::BI__builtin_ffs: 11323 case Builtin::BI__builtin_ffsl: 11324 case Builtin::BI__builtin_ffsll: { 11325 APSInt Val; 11326 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11327 return false; 11328 11329 unsigned N = Val.countTrailingZeros(); 11330 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11331 } 11332 11333 case Builtin::BI__builtin_fpclassify: { 11334 APFloat Val(0.0); 11335 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11336 return false; 11337 unsigned Arg; 11338 switch (Val.getCategory()) { 11339 case APFloat::fcNaN: Arg = 0; break; 11340 case APFloat::fcInfinity: Arg = 1; break; 11341 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11342 case APFloat::fcZero: Arg = 4; break; 11343 } 11344 return Visit(E->getArg(Arg)); 11345 } 11346 11347 case Builtin::BI__builtin_isinf_sign: { 11348 APFloat Val(0.0); 11349 return EvaluateFloat(E->getArg(0), Val, Info) && 11350 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11351 } 11352 11353 case Builtin::BI__builtin_isinf: { 11354 APFloat Val(0.0); 11355 return EvaluateFloat(E->getArg(0), Val, Info) && 11356 Success(Val.isInfinity() ? 1 : 0, E); 11357 } 11358 11359 case Builtin::BI__builtin_isfinite: { 11360 APFloat Val(0.0); 11361 return EvaluateFloat(E->getArg(0), Val, Info) && 11362 Success(Val.isFinite() ? 1 : 0, E); 11363 } 11364 11365 case Builtin::BI__builtin_isnan: { 11366 APFloat Val(0.0); 11367 return EvaluateFloat(E->getArg(0), Val, Info) && 11368 Success(Val.isNaN() ? 1 : 0, E); 11369 } 11370 11371 case Builtin::BI__builtin_isnormal: { 11372 APFloat Val(0.0); 11373 return EvaluateFloat(E->getArg(0), Val, Info) && 11374 Success(Val.isNormal() ? 1 : 0, E); 11375 } 11376 11377 case Builtin::BI__builtin_parity: 11378 case Builtin::BI__builtin_parityl: 11379 case Builtin::BI__builtin_parityll: { 11380 APSInt Val; 11381 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11382 return false; 11383 11384 return Success(Val.countPopulation() % 2, E); 11385 } 11386 11387 case Builtin::BI__builtin_popcount: 11388 case Builtin::BI__builtin_popcountl: 11389 case Builtin::BI__builtin_popcountll: { 11390 APSInt Val; 11391 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11392 return false; 11393 11394 return Success(Val.countPopulation(), E); 11395 } 11396 11397 case Builtin::BI__builtin_rotateleft8: 11398 case Builtin::BI__builtin_rotateleft16: 11399 case Builtin::BI__builtin_rotateleft32: 11400 case Builtin::BI__builtin_rotateleft64: 11401 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11402 case Builtin::BI_rotl16: 11403 case Builtin::BI_rotl: 11404 case Builtin::BI_lrotl: 11405 case Builtin::BI_rotl64: { 11406 APSInt Val, Amt; 11407 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11408 !EvaluateInteger(E->getArg(1), Amt, Info)) 11409 return false; 11410 11411 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11412 } 11413 11414 case Builtin::BI__builtin_rotateright8: 11415 case Builtin::BI__builtin_rotateright16: 11416 case Builtin::BI__builtin_rotateright32: 11417 case Builtin::BI__builtin_rotateright64: 11418 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11419 case Builtin::BI_rotr16: 11420 case Builtin::BI_rotr: 11421 case Builtin::BI_lrotr: 11422 case Builtin::BI_rotr64: { 11423 APSInt Val, Amt; 11424 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11425 !EvaluateInteger(E->getArg(1), Amt, Info)) 11426 return false; 11427 11428 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11429 } 11430 11431 case Builtin::BIstrlen: 11432 case Builtin::BIwcslen: 11433 // A call to strlen is not a constant expression. 11434 if (Info.getLangOpts().CPlusPlus11) 11435 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11436 << /*isConstexpr*/0 << /*isConstructor*/0 11437 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11438 else 11439 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11440 LLVM_FALLTHROUGH; 11441 case Builtin::BI__builtin_strlen: 11442 case Builtin::BI__builtin_wcslen: { 11443 // As an extension, we support __builtin_strlen() as a constant expression, 11444 // and support folding strlen() to a constant. 11445 LValue String; 11446 if (!EvaluatePointer(E->getArg(0), String, Info)) 11447 return false; 11448 11449 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11450 11451 // Fast path: if it's a string literal, search the string value. 11452 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11453 String.getLValueBase().dyn_cast<const Expr *>())) { 11454 // The string literal may have embedded null characters. Find the first 11455 // one and truncate there. 11456 StringRef Str = S->getBytes(); 11457 int64_t Off = String.Offset.getQuantity(); 11458 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11459 S->getCharByteWidth() == 1 && 11460 // FIXME: Add fast-path for wchar_t too. 11461 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11462 Str = Str.substr(Off); 11463 11464 StringRef::size_type Pos = Str.find(0); 11465 if (Pos != StringRef::npos) 11466 Str = Str.substr(0, Pos); 11467 11468 return Success(Str.size(), E); 11469 } 11470 11471 // Fall through to slow path to issue appropriate diagnostic. 11472 } 11473 11474 // Slow path: scan the bytes of the string looking for the terminating 0. 11475 for (uint64_t Strlen = 0; /**/; ++Strlen) { 11476 APValue Char; 11477 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11478 !Char.isInt()) 11479 return false; 11480 if (!Char.getInt()) 11481 return Success(Strlen, E); 11482 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11483 return false; 11484 } 11485 } 11486 11487 case Builtin::BIstrcmp: 11488 case Builtin::BIwcscmp: 11489 case Builtin::BIstrncmp: 11490 case Builtin::BIwcsncmp: 11491 case Builtin::BImemcmp: 11492 case Builtin::BIbcmp: 11493 case Builtin::BIwmemcmp: 11494 // A call to strlen is not a constant expression. 11495 if (Info.getLangOpts().CPlusPlus11) 11496 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11497 << /*isConstexpr*/0 << /*isConstructor*/0 11498 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11499 else 11500 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11501 LLVM_FALLTHROUGH; 11502 case Builtin::BI__builtin_strcmp: 11503 case Builtin::BI__builtin_wcscmp: 11504 case Builtin::BI__builtin_strncmp: 11505 case Builtin::BI__builtin_wcsncmp: 11506 case Builtin::BI__builtin_memcmp: 11507 case Builtin::BI__builtin_bcmp: 11508 case Builtin::BI__builtin_wmemcmp: { 11509 LValue String1, String2; 11510 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11511 !EvaluatePointer(E->getArg(1), String2, Info)) 11512 return false; 11513 11514 uint64_t MaxLength = uint64_t(-1); 11515 if (BuiltinOp != Builtin::BIstrcmp && 11516 BuiltinOp != Builtin::BIwcscmp && 11517 BuiltinOp != Builtin::BI__builtin_strcmp && 11518 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11519 APSInt N; 11520 if (!EvaluateInteger(E->getArg(2), N, Info)) 11521 return false; 11522 MaxLength = N.getExtValue(); 11523 } 11524 11525 // Empty substrings compare equal by definition. 11526 if (MaxLength == 0u) 11527 return Success(0, E); 11528 11529 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11530 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11531 String1.Designator.Invalid || String2.Designator.Invalid) 11532 return false; 11533 11534 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11535 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11536 11537 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11538 BuiltinOp == Builtin::BIbcmp || 11539 BuiltinOp == Builtin::BI__builtin_memcmp || 11540 BuiltinOp == Builtin::BI__builtin_bcmp; 11541 11542 assert(IsRawByte || 11543 (Info.Ctx.hasSameUnqualifiedType( 11544 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11545 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11546 11547 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11548 // 'char8_t', but no other types. 11549 if (IsRawByte && 11550 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11551 // FIXME: Consider using our bit_cast implementation to support this. 11552 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11553 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11554 << CharTy1 << CharTy2; 11555 return false; 11556 } 11557 11558 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11559 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11560 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11561 Char1.isInt() && Char2.isInt(); 11562 }; 11563 const auto &AdvanceElems = [&] { 11564 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11565 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11566 }; 11567 11568 bool StopAtNull = 11569 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11570 BuiltinOp != Builtin::BIwmemcmp && 11571 BuiltinOp != Builtin::BI__builtin_memcmp && 11572 BuiltinOp != Builtin::BI__builtin_bcmp && 11573 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11574 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11575 BuiltinOp == Builtin::BIwcsncmp || 11576 BuiltinOp == Builtin::BIwmemcmp || 11577 BuiltinOp == Builtin::BI__builtin_wcscmp || 11578 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11579 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11580 11581 for (; MaxLength; --MaxLength) { 11582 APValue Char1, Char2; 11583 if (!ReadCurElems(Char1, Char2)) 11584 return false; 11585 if (Char1.getInt().ne(Char2.getInt())) { 11586 if (IsWide) // wmemcmp compares with wchar_t signedness. 11587 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11588 // memcmp always compares unsigned chars. 11589 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11590 } 11591 if (StopAtNull && !Char1.getInt()) 11592 return Success(0, E); 11593 assert(!(StopAtNull && !Char2.getInt())); 11594 if (!AdvanceElems()) 11595 return false; 11596 } 11597 // We hit the strncmp / memcmp limit. 11598 return Success(0, E); 11599 } 11600 11601 case Builtin::BI__atomic_always_lock_free: 11602 case Builtin::BI__atomic_is_lock_free: 11603 case Builtin::BI__c11_atomic_is_lock_free: { 11604 APSInt SizeVal; 11605 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11606 return false; 11607 11608 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11609 // of two less than or equal to the maximum inline atomic width, we know it 11610 // is lock-free. If the size isn't a power of two, or greater than the 11611 // maximum alignment where we promote atomics, we know it is not lock-free 11612 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11613 // the answer can only be determined at runtime; for example, 16-byte 11614 // atomics have lock-free implementations on some, but not all, 11615 // x86-64 processors. 11616 11617 // Check power-of-two. 11618 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11619 if (Size.isPowerOfTwo()) { 11620 // Check against inlining width. 11621 unsigned InlineWidthBits = 11622 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11623 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11624 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11625 Size == CharUnits::One() || 11626 E->getArg(1)->isNullPointerConstant(Info.Ctx, 11627 Expr::NPC_NeverValueDependent)) 11628 // OK, we will inline appropriately-aligned operations of this size, 11629 // and _Atomic(T) is appropriately-aligned. 11630 return Success(1, E); 11631 11632 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 11633 castAs<PointerType>()->getPointeeType(); 11634 if (!PointeeType->isIncompleteType() && 11635 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 11636 // OK, we will inline operations on this object. 11637 return Success(1, E); 11638 } 11639 } 11640 } 11641 11642 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 11643 Success(0, E) : Error(E); 11644 } 11645 case Builtin::BIomp_is_initial_device: 11646 // We can decide statically which value the runtime would return if called. 11647 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 11648 case Builtin::BI__builtin_add_overflow: 11649 case Builtin::BI__builtin_sub_overflow: 11650 case Builtin::BI__builtin_mul_overflow: 11651 case Builtin::BI__builtin_sadd_overflow: 11652 case Builtin::BI__builtin_uadd_overflow: 11653 case Builtin::BI__builtin_uaddl_overflow: 11654 case Builtin::BI__builtin_uaddll_overflow: 11655 case Builtin::BI__builtin_usub_overflow: 11656 case Builtin::BI__builtin_usubl_overflow: 11657 case Builtin::BI__builtin_usubll_overflow: 11658 case Builtin::BI__builtin_umul_overflow: 11659 case Builtin::BI__builtin_umull_overflow: 11660 case Builtin::BI__builtin_umulll_overflow: 11661 case Builtin::BI__builtin_saddl_overflow: 11662 case Builtin::BI__builtin_saddll_overflow: 11663 case Builtin::BI__builtin_ssub_overflow: 11664 case Builtin::BI__builtin_ssubl_overflow: 11665 case Builtin::BI__builtin_ssubll_overflow: 11666 case Builtin::BI__builtin_smul_overflow: 11667 case Builtin::BI__builtin_smull_overflow: 11668 case Builtin::BI__builtin_smulll_overflow: { 11669 LValue ResultLValue; 11670 APSInt LHS, RHS; 11671 11672 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 11673 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 11674 !EvaluateInteger(E->getArg(1), RHS, Info) || 11675 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 11676 return false; 11677 11678 APSInt Result; 11679 bool DidOverflow = false; 11680 11681 // If the types don't have to match, enlarge all 3 to the largest of them. 11682 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11683 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11684 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11685 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 11686 ResultType->isSignedIntegerOrEnumerationType(); 11687 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 11688 ResultType->isSignedIntegerOrEnumerationType(); 11689 uint64_t LHSSize = LHS.getBitWidth(); 11690 uint64_t RHSSize = RHS.getBitWidth(); 11691 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 11692 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 11693 11694 // Add an additional bit if the signedness isn't uniformly agreed to. We 11695 // could do this ONLY if there is a signed and an unsigned that both have 11696 // MaxBits, but the code to check that is pretty nasty. The issue will be 11697 // caught in the shrink-to-result later anyway. 11698 if (IsSigned && !AllSigned) 11699 ++MaxBits; 11700 11701 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 11702 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 11703 Result = APSInt(MaxBits, !IsSigned); 11704 } 11705 11706 // Find largest int. 11707 switch (BuiltinOp) { 11708 default: 11709 llvm_unreachable("Invalid value for BuiltinOp"); 11710 case Builtin::BI__builtin_add_overflow: 11711 case Builtin::BI__builtin_sadd_overflow: 11712 case Builtin::BI__builtin_saddl_overflow: 11713 case Builtin::BI__builtin_saddll_overflow: 11714 case Builtin::BI__builtin_uadd_overflow: 11715 case Builtin::BI__builtin_uaddl_overflow: 11716 case Builtin::BI__builtin_uaddll_overflow: 11717 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 11718 : LHS.uadd_ov(RHS, DidOverflow); 11719 break; 11720 case Builtin::BI__builtin_sub_overflow: 11721 case Builtin::BI__builtin_ssub_overflow: 11722 case Builtin::BI__builtin_ssubl_overflow: 11723 case Builtin::BI__builtin_ssubll_overflow: 11724 case Builtin::BI__builtin_usub_overflow: 11725 case Builtin::BI__builtin_usubl_overflow: 11726 case Builtin::BI__builtin_usubll_overflow: 11727 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 11728 : LHS.usub_ov(RHS, DidOverflow); 11729 break; 11730 case Builtin::BI__builtin_mul_overflow: 11731 case Builtin::BI__builtin_smul_overflow: 11732 case Builtin::BI__builtin_smull_overflow: 11733 case Builtin::BI__builtin_smulll_overflow: 11734 case Builtin::BI__builtin_umul_overflow: 11735 case Builtin::BI__builtin_umull_overflow: 11736 case Builtin::BI__builtin_umulll_overflow: 11737 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 11738 : LHS.umul_ov(RHS, DidOverflow); 11739 break; 11740 } 11741 11742 // In the case where multiple sizes are allowed, truncate and see if 11743 // the values are the same. 11744 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11745 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11746 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11747 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 11748 // since it will give us the behavior of a TruncOrSelf in the case where 11749 // its parameter <= its size. We previously set Result to be at least the 11750 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 11751 // will work exactly like TruncOrSelf. 11752 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 11753 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 11754 11755 if (!APSInt::isSameValue(Temp, Result)) 11756 DidOverflow = true; 11757 Result = Temp; 11758 } 11759 11760 APValue APV{Result}; 11761 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 11762 return false; 11763 return Success(DidOverflow, E); 11764 } 11765 } 11766 } 11767 11768 /// Determine whether this is a pointer past the end of the complete 11769 /// object referred to by the lvalue. 11770 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 11771 const LValue &LV) { 11772 // A null pointer can be viewed as being "past the end" but we don't 11773 // choose to look at it that way here. 11774 if (!LV.getLValueBase()) 11775 return false; 11776 11777 // If the designator is valid and refers to a subobject, we're not pointing 11778 // past the end. 11779 if (!LV.getLValueDesignator().Invalid && 11780 !LV.getLValueDesignator().isOnePastTheEnd()) 11781 return false; 11782 11783 // A pointer to an incomplete type might be past-the-end if the type's size is 11784 // zero. We cannot tell because the type is incomplete. 11785 QualType Ty = getType(LV.getLValueBase()); 11786 if (Ty->isIncompleteType()) 11787 return true; 11788 11789 // We're a past-the-end pointer if we point to the byte after the object, 11790 // no matter what our type or path is. 11791 auto Size = Ctx.getTypeSizeInChars(Ty); 11792 return LV.getLValueOffset() == Size; 11793 } 11794 11795 namespace { 11796 11797 /// Data recursive integer evaluator of certain binary operators. 11798 /// 11799 /// We use a data recursive algorithm for binary operators so that we are able 11800 /// to handle extreme cases of chained binary operators without causing stack 11801 /// overflow. 11802 class DataRecursiveIntBinOpEvaluator { 11803 struct EvalResult { 11804 APValue Val; 11805 bool Failed; 11806 11807 EvalResult() : Failed(false) { } 11808 11809 void swap(EvalResult &RHS) { 11810 Val.swap(RHS.Val); 11811 Failed = RHS.Failed; 11812 RHS.Failed = false; 11813 } 11814 }; 11815 11816 struct Job { 11817 const Expr *E; 11818 EvalResult LHSResult; // meaningful only for binary operator expression. 11819 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 11820 11821 Job() = default; 11822 Job(Job &&) = default; 11823 11824 void startSpeculativeEval(EvalInfo &Info) { 11825 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 11826 } 11827 11828 private: 11829 SpeculativeEvaluationRAII SpecEvalRAII; 11830 }; 11831 11832 SmallVector<Job, 16> Queue; 11833 11834 IntExprEvaluator &IntEval; 11835 EvalInfo &Info; 11836 APValue &FinalResult; 11837 11838 public: 11839 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 11840 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 11841 11842 /// True if \param E is a binary operator that we are going to handle 11843 /// data recursively. 11844 /// We handle binary operators that are comma, logical, or that have operands 11845 /// with integral or enumeration type. 11846 static bool shouldEnqueue(const BinaryOperator *E) { 11847 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 11848 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 11849 E->getLHS()->getType()->isIntegralOrEnumerationType() && 11850 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11851 } 11852 11853 bool Traverse(const BinaryOperator *E) { 11854 enqueue(E); 11855 EvalResult PrevResult; 11856 while (!Queue.empty()) 11857 process(PrevResult); 11858 11859 if (PrevResult.Failed) return false; 11860 11861 FinalResult.swap(PrevResult.Val); 11862 return true; 11863 } 11864 11865 private: 11866 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 11867 return IntEval.Success(Value, E, Result); 11868 } 11869 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 11870 return IntEval.Success(Value, E, Result); 11871 } 11872 bool Error(const Expr *E) { 11873 return IntEval.Error(E); 11874 } 11875 bool Error(const Expr *E, diag::kind D) { 11876 return IntEval.Error(E, D); 11877 } 11878 11879 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 11880 return Info.CCEDiag(E, D); 11881 } 11882 11883 // Returns true if visiting the RHS is necessary, false otherwise. 11884 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11885 bool &SuppressRHSDiags); 11886 11887 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 11888 const BinaryOperator *E, APValue &Result); 11889 11890 void EvaluateExpr(const Expr *E, EvalResult &Result) { 11891 Result.Failed = !Evaluate(Result.Val, Info, E); 11892 if (Result.Failed) 11893 Result.Val = APValue(); 11894 } 11895 11896 void process(EvalResult &Result); 11897 11898 void enqueue(const Expr *E) { 11899 E = E->IgnoreParens(); 11900 Queue.resize(Queue.size()+1); 11901 Queue.back().E = E; 11902 Queue.back().Kind = Job::AnyExprKind; 11903 } 11904 }; 11905 11906 } 11907 11908 bool DataRecursiveIntBinOpEvaluator:: 11909 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11910 bool &SuppressRHSDiags) { 11911 if (E->getOpcode() == BO_Comma) { 11912 // Ignore LHS but note if we could not evaluate it. 11913 if (LHSResult.Failed) 11914 return Info.noteSideEffect(); 11915 return true; 11916 } 11917 11918 if (E->isLogicalOp()) { 11919 bool LHSAsBool; 11920 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 11921 // We were able to evaluate the LHS, see if we can get away with not 11922 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 11923 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 11924 Success(LHSAsBool, E, LHSResult.Val); 11925 return false; // Ignore RHS 11926 } 11927 } else { 11928 LHSResult.Failed = true; 11929 11930 // Since we weren't able to evaluate the left hand side, it 11931 // might have had side effects. 11932 if (!Info.noteSideEffect()) 11933 return false; 11934 11935 // We can't evaluate the LHS; however, sometimes the result 11936 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 11937 // Don't ignore RHS and suppress diagnostics from this arm. 11938 SuppressRHSDiags = true; 11939 } 11940 11941 return true; 11942 } 11943 11944 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 11945 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11946 11947 if (LHSResult.Failed && !Info.noteFailure()) 11948 return false; // Ignore RHS; 11949 11950 return true; 11951 } 11952 11953 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 11954 bool IsSub) { 11955 // Compute the new offset in the appropriate width, wrapping at 64 bits. 11956 // FIXME: When compiling for a 32-bit target, we should use 32-bit 11957 // offsets. 11958 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 11959 CharUnits &Offset = LVal.getLValueOffset(); 11960 uint64_t Offset64 = Offset.getQuantity(); 11961 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 11962 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 11963 : Offset64 + Index64); 11964 } 11965 11966 bool DataRecursiveIntBinOpEvaluator:: 11967 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 11968 const BinaryOperator *E, APValue &Result) { 11969 if (E->getOpcode() == BO_Comma) { 11970 if (RHSResult.Failed) 11971 return false; 11972 Result = RHSResult.Val; 11973 return true; 11974 } 11975 11976 if (E->isLogicalOp()) { 11977 bool lhsResult, rhsResult; 11978 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 11979 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 11980 11981 if (LHSIsOK) { 11982 if (RHSIsOK) { 11983 if (E->getOpcode() == BO_LOr) 11984 return Success(lhsResult || rhsResult, E, Result); 11985 else 11986 return Success(lhsResult && rhsResult, E, Result); 11987 } 11988 } else { 11989 if (RHSIsOK) { 11990 // We can't evaluate the LHS; however, sometimes the result 11991 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 11992 if (rhsResult == (E->getOpcode() == BO_LOr)) 11993 return Success(rhsResult, E, Result); 11994 } 11995 } 11996 11997 return false; 11998 } 11999 12000 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12001 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12002 12003 if (LHSResult.Failed || RHSResult.Failed) 12004 return false; 12005 12006 const APValue &LHSVal = LHSResult.Val; 12007 const APValue &RHSVal = RHSResult.Val; 12008 12009 // Handle cases like (unsigned long)&a + 4. 12010 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12011 Result = LHSVal; 12012 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12013 return true; 12014 } 12015 12016 // Handle cases like 4 + (unsigned long)&a 12017 if (E->getOpcode() == BO_Add && 12018 RHSVal.isLValue() && LHSVal.isInt()) { 12019 Result = RHSVal; 12020 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12021 return true; 12022 } 12023 12024 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12025 // Handle (intptr_t)&&A - (intptr_t)&&B. 12026 if (!LHSVal.getLValueOffset().isZero() || 12027 !RHSVal.getLValueOffset().isZero()) 12028 return false; 12029 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12030 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12031 if (!LHSExpr || !RHSExpr) 12032 return false; 12033 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12034 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12035 if (!LHSAddrExpr || !RHSAddrExpr) 12036 return false; 12037 // Make sure both labels come from the same function. 12038 if (LHSAddrExpr->getLabel()->getDeclContext() != 12039 RHSAddrExpr->getLabel()->getDeclContext()) 12040 return false; 12041 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12042 return true; 12043 } 12044 12045 // All the remaining cases expect both operands to be an integer 12046 if (!LHSVal.isInt() || !RHSVal.isInt()) 12047 return Error(E); 12048 12049 // Set up the width and signedness manually, in case it can't be deduced 12050 // from the operation we're performing. 12051 // FIXME: Don't do this in the cases where we can deduce it. 12052 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12053 E->getType()->isUnsignedIntegerOrEnumerationType()); 12054 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12055 RHSVal.getInt(), Value)) 12056 return false; 12057 return Success(Value, E, Result); 12058 } 12059 12060 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12061 Job &job = Queue.back(); 12062 12063 switch (job.Kind) { 12064 case Job::AnyExprKind: { 12065 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12066 if (shouldEnqueue(Bop)) { 12067 job.Kind = Job::BinOpKind; 12068 enqueue(Bop->getLHS()); 12069 return; 12070 } 12071 } 12072 12073 EvaluateExpr(job.E, Result); 12074 Queue.pop_back(); 12075 return; 12076 } 12077 12078 case Job::BinOpKind: { 12079 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12080 bool SuppressRHSDiags = false; 12081 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12082 Queue.pop_back(); 12083 return; 12084 } 12085 if (SuppressRHSDiags) 12086 job.startSpeculativeEval(Info); 12087 job.LHSResult.swap(Result); 12088 job.Kind = Job::BinOpVisitedLHSKind; 12089 enqueue(Bop->getRHS()); 12090 return; 12091 } 12092 12093 case Job::BinOpVisitedLHSKind: { 12094 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12095 EvalResult RHS; 12096 RHS.swap(Result); 12097 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12098 Queue.pop_back(); 12099 return; 12100 } 12101 } 12102 12103 llvm_unreachable("Invalid Job::Kind!"); 12104 } 12105 12106 namespace { 12107 /// Used when we determine that we should fail, but can keep evaluating prior to 12108 /// noting that we had a failure. 12109 class DelayedNoteFailureRAII { 12110 EvalInfo &Info; 12111 bool NoteFailure; 12112 12113 public: 12114 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 12115 : Info(Info), NoteFailure(NoteFailure) {} 12116 ~DelayedNoteFailureRAII() { 12117 if (NoteFailure) { 12118 bool ContinueAfterFailure = Info.noteFailure(); 12119 (void)ContinueAfterFailure; 12120 assert(ContinueAfterFailure && 12121 "Shouldn't have kept evaluating on failure."); 12122 } 12123 } 12124 }; 12125 12126 enum class CmpResult { 12127 Unequal, 12128 Less, 12129 Equal, 12130 Greater, 12131 Unordered, 12132 }; 12133 } 12134 12135 template <class SuccessCB, class AfterCB> 12136 static bool 12137 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12138 SuccessCB &&Success, AfterCB &&DoAfter) { 12139 assert(E->isComparisonOp() && "expected comparison operator"); 12140 assert((E->getOpcode() == BO_Cmp || 12141 E->getType()->isIntegralOrEnumerationType()) && 12142 "unsupported binary expression evaluation"); 12143 auto Error = [&](const Expr *E) { 12144 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12145 return false; 12146 }; 12147 12148 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12149 bool IsEquality = E->isEqualityOp(); 12150 12151 QualType LHSTy = E->getLHS()->getType(); 12152 QualType RHSTy = E->getRHS()->getType(); 12153 12154 if (LHSTy->isIntegralOrEnumerationType() && 12155 RHSTy->isIntegralOrEnumerationType()) { 12156 APSInt LHS, RHS; 12157 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12158 if (!LHSOK && !Info.noteFailure()) 12159 return false; 12160 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12161 return false; 12162 if (LHS < RHS) 12163 return Success(CmpResult::Less, E); 12164 if (LHS > RHS) 12165 return Success(CmpResult::Greater, E); 12166 return Success(CmpResult::Equal, E); 12167 } 12168 12169 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12170 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12171 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12172 12173 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12174 if (!LHSOK && !Info.noteFailure()) 12175 return false; 12176 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12177 return false; 12178 if (LHSFX < RHSFX) 12179 return Success(CmpResult::Less, E); 12180 if (LHSFX > RHSFX) 12181 return Success(CmpResult::Greater, E); 12182 return Success(CmpResult::Equal, E); 12183 } 12184 12185 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12186 ComplexValue LHS, RHS; 12187 bool LHSOK; 12188 if (E->isAssignmentOp()) { 12189 LValue LV; 12190 EvaluateLValue(E->getLHS(), LV, Info); 12191 LHSOK = false; 12192 } else if (LHSTy->isRealFloatingType()) { 12193 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12194 if (LHSOK) { 12195 LHS.makeComplexFloat(); 12196 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12197 } 12198 } else { 12199 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12200 } 12201 if (!LHSOK && !Info.noteFailure()) 12202 return false; 12203 12204 if (E->getRHS()->getType()->isRealFloatingType()) { 12205 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12206 return false; 12207 RHS.makeComplexFloat(); 12208 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12209 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12210 return false; 12211 12212 if (LHS.isComplexFloat()) { 12213 APFloat::cmpResult CR_r = 12214 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12215 APFloat::cmpResult CR_i = 12216 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12217 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12218 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12219 } else { 12220 assert(IsEquality && "invalid complex comparison"); 12221 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12222 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12223 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12224 } 12225 } 12226 12227 if (LHSTy->isRealFloatingType() && 12228 RHSTy->isRealFloatingType()) { 12229 APFloat RHS(0.0), LHS(0.0); 12230 12231 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12232 if (!LHSOK && !Info.noteFailure()) 12233 return false; 12234 12235 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12236 return false; 12237 12238 assert(E->isComparisonOp() && "Invalid binary operator!"); 12239 auto GetCmpRes = [&]() { 12240 switch (LHS.compare(RHS)) { 12241 case APFloat::cmpEqual: 12242 return CmpResult::Equal; 12243 case APFloat::cmpLessThan: 12244 return CmpResult::Less; 12245 case APFloat::cmpGreaterThan: 12246 return CmpResult::Greater; 12247 case APFloat::cmpUnordered: 12248 return CmpResult::Unordered; 12249 } 12250 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12251 }; 12252 return Success(GetCmpRes(), E); 12253 } 12254 12255 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12256 LValue LHSValue, RHSValue; 12257 12258 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12259 if (!LHSOK && !Info.noteFailure()) 12260 return false; 12261 12262 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12263 return false; 12264 12265 // Reject differing bases from the normal codepath; we special-case 12266 // comparisons to null. 12267 if (!HasSameBase(LHSValue, RHSValue)) { 12268 // Inequalities and subtractions between unrelated pointers have 12269 // unspecified or undefined behavior. 12270 if (!IsEquality) { 12271 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12272 return false; 12273 } 12274 // A constant address may compare equal to the address of a symbol. 12275 // The one exception is that address of an object cannot compare equal 12276 // to a null pointer constant. 12277 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12278 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12279 return Error(E); 12280 // It's implementation-defined whether distinct literals will have 12281 // distinct addresses. In clang, the result of such a comparison is 12282 // unspecified, so it is not a constant expression. However, we do know 12283 // that the address of a literal will be non-null. 12284 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12285 LHSValue.Base && RHSValue.Base) 12286 return Error(E); 12287 // We can't tell whether weak symbols will end up pointing to the same 12288 // object. 12289 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12290 return Error(E); 12291 // We can't compare the address of the start of one object with the 12292 // past-the-end address of another object, per C++ DR1652. 12293 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12294 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12295 (RHSValue.Base && RHSValue.Offset.isZero() && 12296 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12297 return Error(E); 12298 // We can't tell whether an object is at the same address as another 12299 // zero sized object. 12300 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12301 (LHSValue.Base && isZeroSized(RHSValue))) 12302 return Error(E); 12303 return Success(CmpResult::Unequal, E); 12304 } 12305 12306 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12307 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12308 12309 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12310 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12311 12312 // C++11 [expr.rel]p3: 12313 // Pointers to void (after pointer conversions) can be compared, with a 12314 // result defined as follows: If both pointers represent the same 12315 // address or are both the null pointer value, the result is true if the 12316 // operator is <= or >= and false otherwise; otherwise the result is 12317 // unspecified. 12318 // We interpret this as applying to pointers to *cv* void. 12319 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12320 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12321 12322 // C++11 [expr.rel]p2: 12323 // - If two pointers point to non-static data members of the same object, 12324 // or to subobjects or array elements fo such members, recursively, the 12325 // pointer to the later declared member compares greater provided the 12326 // two members have the same access control and provided their class is 12327 // not a union. 12328 // [...] 12329 // - Otherwise pointer comparisons are unspecified. 12330 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12331 bool WasArrayIndex; 12332 unsigned Mismatch = FindDesignatorMismatch( 12333 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12334 // At the point where the designators diverge, the comparison has a 12335 // specified value if: 12336 // - we are comparing array indices 12337 // - we are comparing fields of a union, or fields with the same access 12338 // Otherwise, the result is unspecified and thus the comparison is not a 12339 // constant expression. 12340 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12341 Mismatch < RHSDesignator.Entries.size()) { 12342 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12343 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12344 if (!LF && !RF) 12345 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12346 else if (!LF) 12347 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12348 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12349 << RF->getParent() << RF; 12350 else if (!RF) 12351 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12352 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12353 << LF->getParent() << LF; 12354 else if (!LF->getParent()->isUnion() && 12355 LF->getAccess() != RF->getAccess()) 12356 Info.CCEDiag(E, 12357 diag::note_constexpr_pointer_comparison_differing_access) 12358 << LF << LF->getAccess() << RF << RF->getAccess() 12359 << LF->getParent(); 12360 } 12361 } 12362 12363 // The comparison here must be unsigned, and performed with the same 12364 // width as the pointer. 12365 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12366 uint64_t CompareLHS = LHSOffset.getQuantity(); 12367 uint64_t CompareRHS = RHSOffset.getQuantity(); 12368 assert(PtrSize <= 64 && "Unexpected pointer width"); 12369 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12370 CompareLHS &= Mask; 12371 CompareRHS &= Mask; 12372 12373 // If there is a base and this is a relational operator, we can only 12374 // compare pointers within the object in question; otherwise, the result 12375 // depends on where the object is located in memory. 12376 if (!LHSValue.Base.isNull() && IsRelational) { 12377 QualType BaseTy = getType(LHSValue.Base); 12378 if (BaseTy->isIncompleteType()) 12379 return Error(E); 12380 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12381 uint64_t OffsetLimit = Size.getQuantity(); 12382 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12383 return Error(E); 12384 } 12385 12386 if (CompareLHS < CompareRHS) 12387 return Success(CmpResult::Less, E); 12388 if (CompareLHS > CompareRHS) 12389 return Success(CmpResult::Greater, E); 12390 return Success(CmpResult::Equal, E); 12391 } 12392 12393 if (LHSTy->isMemberPointerType()) { 12394 assert(IsEquality && "unexpected member pointer operation"); 12395 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12396 12397 MemberPtr LHSValue, RHSValue; 12398 12399 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12400 if (!LHSOK && !Info.noteFailure()) 12401 return false; 12402 12403 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12404 return false; 12405 12406 // C++11 [expr.eq]p2: 12407 // If both operands are null, they compare equal. Otherwise if only one is 12408 // null, they compare unequal. 12409 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12410 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12411 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12412 } 12413 12414 // Otherwise if either is a pointer to a virtual member function, the 12415 // result is unspecified. 12416 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12417 if (MD->isVirtual()) 12418 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12419 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12420 if (MD->isVirtual()) 12421 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12422 12423 // Otherwise they compare equal if and only if they would refer to the 12424 // same member of the same most derived object or the same subobject if 12425 // they were dereferenced with a hypothetical object of the associated 12426 // class type. 12427 bool Equal = LHSValue == RHSValue; 12428 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12429 } 12430 12431 if (LHSTy->isNullPtrType()) { 12432 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12433 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12434 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12435 // are compared, the result is true of the operator is <=, >= or ==, and 12436 // false otherwise. 12437 return Success(CmpResult::Equal, E); 12438 } 12439 12440 return DoAfter(); 12441 } 12442 12443 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12444 if (!CheckLiteralType(Info, E)) 12445 return false; 12446 12447 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12448 ComparisonCategoryResult CCR; 12449 switch (CR) { 12450 case CmpResult::Unequal: 12451 llvm_unreachable("should never produce Unequal for three-way comparison"); 12452 case CmpResult::Less: 12453 CCR = ComparisonCategoryResult::Less; 12454 break; 12455 case CmpResult::Equal: 12456 CCR = ComparisonCategoryResult::Equal; 12457 break; 12458 case CmpResult::Greater: 12459 CCR = ComparisonCategoryResult::Greater; 12460 break; 12461 case CmpResult::Unordered: 12462 CCR = ComparisonCategoryResult::Unordered; 12463 break; 12464 } 12465 // Evaluation succeeded. Lookup the information for the comparison category 12466 // type and fetch the VarDecl for the result. 12467 const ComparisonCategoryInfo &CmpInfo = 12468 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12469 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12470 // Check and evaluate the result as a constant expression. 12471 LValue LV; 12472 LV.set(VD); 12473 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12474 return false; 12475 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 12476 }; 12477 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12478 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12479 }); 12480 } 12481 12482 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12483 // We don't call noteFailure immediately because the assignment happens after 12484 // we evaluate LHS and RHS. 12485 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 12486 return Error(E); 12487 12488 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 12489 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12490 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12491 12492 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12493 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12494 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12495 12496 if (E->isComparisonOp()) { 12497 // Evaluate builtin binary comparisons by evaluating them as three-way 12498 // comparisons and then translating the result. 12499 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12500 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12501 "should only produce Unequal for equality comparisons"); 12502 bool IsEqual = CR == CmpResult::Equal, 12503 IsLess = CR == CmpResult::Less, 12504 IsGreater = CR == CmpResult::Greater; 12505 auto Op = E->getOpcode(); 12506 switch (Op) { 12507 default: 12508 llvm_unreachable("unsupported binary operator"); 12509 case BO_EQ: 12510 case BO_NE: 12511 return Success(IsEqual == (Op == BO_EQ), E); 12512 case BO_LT: 12513 return Success(IsLess, E); 12514 case BO_GT: 12515 return Success(IsGreater, E); 12516 case BO_LE: 12517 return Success(IsEqual || IsLess, E); 12518 case BO_GE: 12519 return Success(IsEqual || IsGreater, E); 12520 } 12521 }; 12522 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12523 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12524 }); 12525 } 12526 12527 QualType LHSTy = E->getLHS()->getType(); 12528 QualType RHSTy = E->getRHS()->getType(); 12529 12530 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12531 E->getOpcode() == BO_Sub) { 12532 LValue LHSValue, RHSValue; 12533 12534 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12535 if (!LHSOK && !Info.noteFailure()) 12536 return false; 12537 12538 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12539 return false; 12540 12541 // Reject differing bases from the normal codepath; we special-case 12542 // comparisons to null. 12543 if (!HasSameBase(LHSValue, RHSValue)) { 12544 // Handle &&A - &&B. 12545 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12546 return Error(E); 12547 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12548 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12549 if (!LHSExpr || !RHSExpr) 12550 return Error(E); 12551 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12552 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12553 if (!LHSAddrExpr || !RHSAddrExpr) 12554 return Error(E); 12555 // Make sure both labels come from the same function. 12556 if (LHSAddrExpr->getLabel()->getDeclContext() != 12557 RHSAddrExpr->getLabel()->getDeclContext()) 12558 return Error(E); 12559 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12560 } 12561 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12562 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12563 12564 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12565 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12566 12567 // C++11 [expr.add]p6: 12568 // Unless both pointers point to elements of the same array object, or 12569 // one past the last element of the array object, the behavior is 12570 // undefined. 12571 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12572 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12573 RHSDesignator)) 12574 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12575 12576 QualType Type = E->getLHS()->getType(); 12577 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12578 12579 CharUnits ElementSize; 12580 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12581 return false; 12582 12583 // As an extension, a type may have zero size (empty struct or union in 12584 // C, array of zero length). Pointer subtraction in such cases has 12585 // undefined behavior, so is not constant. 12586 if (ElementSize.isZero()) { 12587 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12588 << ElementType; 12589 return false; 12590 } 12591 12592 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12593 // and produce incorrect results when it overflows. Such behavior 12594 // appears to be non-conforming, but is common, so perhaps we should 12595 // assume the standard intended for such cases to be undefined behavior 12596 // and check for them. 12597 12598 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12599 // overflow in the final conversion to ptrdiff_t. 12600 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12601 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12602 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12603 false); 12604 APSInt TrueResult = (LHS - RHS) / ElemSize; 12605 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12606 12607 if (Result.extend(65) != TrueResult && 12608 !HandleOverflow(Info, E, TrueResult, E->getType())) 12609 return false; 12610 return Success(Result, E); 12611 } 12612 12613 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12614 } 12615 12616 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12617 /// a result as the expression's type. 12618 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12619 const UnaryExprOrTypeTraitExpr *E) { 12620 switch(E->getKind()) { 12621 case UETT_PreferredAlignOf: 12622 case UETT_AlignOf: { 12623 if (E->isArgumentType()) 12624 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 12625 E); 12626 else 12627 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 12628 E); 12629 } 12630 12631 case UETT_VecStep: { 12632 QualType Ty = E->getTypeOfArgument(); 12633 12634 if (Ty->isVectorType()) { 12635 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 12636 12637 // The vec_step built-in functions that take a 3-component 12638 // vector return 4. (OpenCL 1.1 spec 6.11.12) 12639 if (n == 3) 12640 n = 4; 12641 12642 return Success(n, E); 12643 } else 12644 return Success(1, E); 12645 } 12646 12647 case UETT_SizeOf: { 12648 QualType SrcTy = E->getTypeOfArgument(); 12649 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 12650 // the result is the size of the referenced type." 12651 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 12652 SrcTy = Ref->getPointeeType(); 12653 12654 CharUnits Sizeof; 12655 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 12656 return false; 12657 return Success(Sizeof, E); 12658 } 12659 case UETT_OpenMPRequiredSimdAlign: 12660 assert(E->isArgumentType()); 12661 return Success( 12662 Info.Ctx.toCharUnitsFromBits( 12663 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 12664 .getQuantity(), 12665 E); 12666 } 12667 12668 llvm_unreachable("unknown expr/type trait"); 12669 } 12670 12671 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 12672 CharUnits Result; 12673 unsigned n = OOE->getNumComponents(); 12674 if (n == 0) 12675 return Error(OOE); 12676 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 12677 for (unsigned i = 0; i != n; ++i) { 12678 OffsetOfNode ON = OOE->getComponent(i); 12679 switch (ON.getKind()) { 12680 case OffsetOfNode::Array: { 12681 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 12682 APSInt IdxResult; 12683 if (!EvaluateInteger(Idx, IdxResult, Info)) 12684 return false; 12685 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 12686 if (!AT) 12687 return Error(OOE); 12688 CurrentType = AT->getElementType(); 12689 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 12690 Result += IdxResult.getSExtValue() * ElementSize; 12691 break; 12692 } 12693 12694 case OffsetOfNode::Field: { 12695 FieldDecl *MemberDecl = ON.getField(); 12696 const RecordType *RT = CurrentType->getAs<RecordType>(); 12697 if (!RT) 12698 return Error(OOE); 12699 RecordDecl *RD = RT->getDecl(); 12700 if (RD->isInvalidDecl()) return false; 12701 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12702 unsigned i = MemberDecl->getFieldIndex(); 12703 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 12704 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 12705 CurrentType = MemberDecl->getType().getNonReferenceType(); 12706 break; 12707 } 12708 12709 case OffsetOfNode::Identifier: 12710 llvm_unreachable("dependent __builtin_offsetof"); 12711 12712 case OffsetOfNode::Base: { 12713 CXXBaseSpecifier *BaseSpec = ON.getBase(); 12714 if (BaseSpec->isVirtual()) 12715 return Error(OOE); 12716 12717 // Find the layout of the class whose base we are looking into. 12718 const RecordType *RT = CurrentType->getAs<RecordType>(); 12719 if (!RT) 12720 return Error(OOE); 12721 RecordDecl *RD = RT->getDecl(); 12722 if (RD->isInvalidDecl()) return false; 12723 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12724 12725 // Find the base class itself. 12726 CurrentType = BaseSpec->getType(); 12727 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 12728 if (!BaseRT) 12729 return Error(OOE); 12730 12731 // Add the offset to the base. 12732 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 12733 break; 12734 } 12735 } 12736 } 12737 return Success(Result, OOE); 12738 } 12739 12740 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12741 switch (E->getOpcode()) { 12742 default: 12743 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 12744 // See C99 6.6p3. 12745 return Error(E); 12746 case UO_Extension: 12747 // FIXME: Should extension allow i-c-e extension expressions in its scope? 12748 // If so, we could clear the diagnostic ID. 12749 return Visit(E->getSubExpr()); 12750 case UO_Plus: 12751 // The result is just the value. 12752 return Visit(E->getSubExpr()); 12753 case UO_Minus: { 12754 if (!Visit(E->getSubExpr())) 12755 return false; 12756 if (!Result.isInt()) return Error(E); 12757 const APSInt &Value = Result.getInt(); 12758 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 12759 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 12760 E->getType())) 12761 return false; 12762 return Success(-Value, E); 12763 } 12764 case UO_Not: { 12765 if (!Visit(E->getSubExpr())) 12766 return false; 12767 if (!Result.isInt()) return Error(E); 12768 return Success(~Result.getInt(), E); 12769 } 12770 case UO_LNot: { 12771 bool bres; 12772 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 12773 return false; 12774 return Success(!bres, E); 12775 } 12776 } 12777 } 12778 12779 /// HandleCast - This is used to evaluate implicit or explicit casts where the 12780 /// result type is integer. 12781 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 12782 const Expr *SubExpr = E->getSubExpr(); 12783 QualType DestType = E->getType(); 12784 QualType SrcType = SubExpr->getType(); 12785 12786 switch (E->getCastKind()) { 12787 case CK_BaseToDerived: 12788 case CK_DerivedToBase: 12789 case CK_UncheckedDerivedToBase: 12790 case CK_Dynamic: 12791 case CK_ToUnion: 12792 case CK_ArrayToPointerDecay: 12793 case CK_FunctionToPointerDecay: 12794 case CK_NullToPointer: 12795 case CK_NullToMemberPointer: 12796 case CK_BaseToDerivedMemberPointer: 12797 case CK_DerivedToBaseMemberPointer: 12798 case CK_ReinterpretMemberPointer: 12799 case CK_ConstructorConversion: 12800 case CK_IntegralToPointer: 12801 case CK_ToVoid: 12802 case CK_VectorSplat: 12803 case CK_IntegralToFloating: 12804 case CK_FloatingCast: 12805 case CK_CPointerToObjCPointerCast: 12806 case CK_BlockPointerToObjCPointerCast: 12807 case CK_AnyPointerToBlockPointerCast: 12808 case CK_ObjCObjectLValueCast: 12809 case CK_FloatingRealToComplex: 12810 case CK_FloatingComplexToReal: 12811 case CK_FloatingComplexCast: 12812 case CK_FloatingComplexToIntegralComplex: 12813 case CK_IntegralRealToComplex: 12814 case CK_IntegralComplexCast: 12815 case CK_IntegralComplexToFloatingComplex: 12816 case CK_BuiltinFnToFnPtr: 12817 case CK_ZeroToOCLOpaqueType: 12818 case CK_NonAtomicToAtomic: 12819 case CK_AddressSpaceConversion: 12820 case CK_IntToOCLSampler: 12821 case CK_FixedPointCast: 12822 case CK_IntegralToFixedPoint: 12823 llvm_unreachable("invalid cast kind for integral value"); 12824 12825 case CK_BitCast: 12826 case CK_Dependent: 12827 case CK_LValueBitCast: 12828 case CK_ARCProduceObject: 12829 case CK_ARCConsumeObject: 12830 case CK_ARCReclaimReturnedObject: 12831 case CK_ARCExtendBlockObject: 12832 case CK_CopyAndAutoreleaseBlockObject: 12833 return Error(E); 12834 12835 case CK_UserDefinedConversion: 12836 case CK_LValueToRValue: 12837 case CK_AtomicToNonAtomic: 12838 case CK_NoOp: 12839 case CK_LValueToRValueBitCast: 12840 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12841 12842 case CK_MemberPointerToBoolean: 12843 case CK_PointerToBoolean: 12844 case CK_IntegralToBoolean: 12845 case CK_FloatingToBoolean: 12846 case CK_BooleanToSignedIntegral: 12847 case CK_FloatingComplexToBoolean: 12848 case CK_IntegralComplexToBoolean: { 12849 bool BoolResult; 12850 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 12851 return false; 12852 uint64_t IntResult = BoolResult; 12853 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 12854 IntResult = (uint64_t)-1; 12855 return Success(IntResult, E); 12856 } 12857 12858 case CK_FixedPointToIntegral: { 12859 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 12860 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 12861 return false; 12862 bool Overflowed; 12863 llvm::APSInt Result = Src.convertToInt( 12864 Info.Ctx.getIntWidth(DestType), 12865 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 12866 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 12867 return false; 12868 return Success(Result, E); 12869 } 12870 12871 case CK_FixedPointToBoolean: { 12872 // Unsigned padding does not affect this. 12873 APValue Val; 12874 if (!Evaluate(Val, Info, SubExpr)) 12875 return false; 12876 return Success(Val.getFixedPoint().getBoolValue(), E); 12877 } 12878 12879 case CK_IntegralCast: { 12880 if (!Visit(SubExpr)) 12881 return false; 12882 12883 if (!Result.isInt()) { 12884 // Allow casts of address-of-label differences if they are no-ops 12885 // or narrowing. (The narrowing case isn't actually guaranteed to 12886 // be constant-evaluatable except in some narrow cases which are hard 12887 // to detect here. We let it through on the assumption the user knows 12888 // what they are doing.) 12889 if (Result.isAddrLabelDiff()) 12890 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 12891 // Only allow casts of lvalues if they are lossless. 12892 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 12893 } 12894 12895 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 12896 Result.getInt()), E); 12897 } 12898 12899 case CK_PointerToIntegral: { 12900 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 12901 12902 LValue LV; 12903 if (!EvaluatePointer(SubExpr, LV, Info)) 12904 return false; 12905 12906 if (LV.getLValueBase()) { 12907 // Only allow based lvalue casts if they are lossless. 12908 // FIXME: Allow a larger integer size than the pointer size, and allow 12909 // narrowing back down to pointer width in subsequent integral casts. 12910 // FIXME: Check integer type's active bits, not its type size. 12911 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 12912 return Error(E); 12913 12914 LV.Designator.setInvalid(); 12915 LV.moveInto(Result); 12916 return true; 12917 } 12918 12919 APSInt AsInt; 12920 APValue V; 12921 LV.moveInto(V); 12922 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 12923 llvm_unreachable("Can't cast this!"); 12924 12925 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 12926 } 12927 12928 case CK_IntegralComplexToReal: { 12929 ComplexValue C; 12930 if (!EvaluateComplex(SubExpr, C, Info)) 12931 return false; 12932 return Success(C.getComplexIntReal(), E); 12933 } 12934 12935 case CK_FloatingToIntegral: { 12936 APFloat F(0.0); 12937 if (!EvaluateFloat(SubExpr, F, Info)) 12938 return false; 12939 12940 APSInt Value; 12941 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 12942 return false; 12943 return Success(Value, E); 12944 } 12945 } 12946 12947 llvm_unreachable("unknown cast resulting in integral value"); 12948 } 12949 12950 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 12951 if (E->getSubExpr()->getType()->isAnyComplexType()) { 12952 ComplexValue LV; 12953 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 12954 return false; 12955 if (!LV.isComplexInt()) 12956 return Error(E); 12957 return Success(LV.getComplexIntReal(), E); 12958 } 12959 12960 return Visit(E->getSubExpr()); 12961 } 12962 12963 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 12964 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 12965 ComplexValue LV; 12966 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 12967 return false; 12968 if (!LV.isComplexInt()) 12969 return Error(E); 12970 return Success(LV.getComplexIntImag(), E); 12971 } 12972 12973 VisitIgnoredValue(E->getSubExpr()); 12974 return Success(0, E); 12975 } 12976 12977 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 12978 return Success(E->getPackLength(), E); 12979 } 12980 12981 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 12982 return Success(E->getValue(), E); 12983 } 12984 12985 bool IntExprEvaluator::VisitConceptSpecializationExpr( 12986 const ConceptSpecializationExpr *E) { 12987 return Success(E->isSatisfied(), E); 12988 } 12989 12990 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 12991 return Success(E->isSatisfied(), E); 12992 } 12993 12994 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12995 switch (E->getOpcode()) { 12996 default: 12997 // Invalid unary operators 12998 return Error(E); 12999 case UO_Plus: 13000 // The result is just the value. 13001 return Visit(E->getSubExpr()); 13002 case UO_Minus: { 13003 if (!Visit(E->getSubExpr())) return false; 13004 if (!Result.isFixedPoint()) 13005 return Error(E); 13006 bool Overflowed; 13007 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13008 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13009 return false; 13010 return Success(Negated, E); 13011 } 13012 case UO_LNot: { 13013 bool bres; 13014 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13015 return false; 13016 return Success(!bres, E); 13017 } 13018 } 13019 } 13020 13021 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13022 const Expr *SubExpr = E->getSubExpr(); 13023 QualType DestType = E->getType(); 13024 assert(DestType->isFixedPointType() && 13025 "Expected destination type to be a fixed point type"); 13026 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13027 13028 switch (E->getCastKind()) { 13029 case CK_FixedPointCast: { 13030 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13031 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13032 return false; 13033 bool Overflowed; 13034 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13035 if (Overflowed) { 13036 if (Info.checkingForUndefinedBehavior()) 13037 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13038 diag::warn_fixedpoint_constant_overflow) 13039 << Result.toString() << E->getType(); 13040 else if (!HandleOverflow(Info, E, Result, E->getType())) 13041 return false; 13042 } 13043 return Success(Result, E); 13044 } 13045 case CK_IntegralToFixedPoint: { 13046 APSInt Src; 13047 if (!EvaluateInteger(SubExpr, Src, Info)) 13048 return false; 13049 13050 bool Overflowed; 13051 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13052 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13053 13054 if (Overflowed) { 13055 if (Info.checkingForUndefinedBehavior()) 13056 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13057 diag::warn_fixedpoint_constant_overflow) 13058 << IntResult.toString() << E->getType(); 13059 else if (!HandleOverflow(Info, E, IntResult, E->getType())) 13060 return false; 13061 } 13062 13063 return Success(IntResult, E); 13064 } 13065 case CK_NoOp: 13066 case CK_LValueToRValue: 13067 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13068 default: 13069 return Error(E); 13070 } 13071 } 13072 13073 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13074 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13075 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13076 13077 const Expr *LHS = E->getLHS(); 13078 const Expr *RHS = E->getRHS(); 13079 FixedPointSemantics ResultFXSema = 13080 Info.Ctx.getFixedPointSemantics(E->getType()); 13081 13082 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13083 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13084 return false; 13085 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13086 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13087 return false; 13088 13089 bool OpOverflow = false, ConversionOverflow = false; 13090 APFixedPoint Result(LHSFX.getSemantics()); 13091 switch (E->getOpcode()) { 13092 case BO_Add: { 13093 Result = LHSFX.add(RHSFX, &OpOverflow) 13094 .convert(ResultFXSema, &ConversionOverflow); 13095 break; 13096 } 13097 case BO_Sub: { 13098 Result = LHSFX.sub(RHSFX, &OpOverflow) 13099 .convert(ResultFXSema, &ConversionOverflow); 13100 break; 13101 } 13102 case BO_Mul: { 13103 Result = LHSFX.mul(RHSFX, &OpOverflow) 13104 .convert(ResultFXSema, &ConversionOverflow); 13105 break; 13106 } 13107 case BO_Div: { 13108 if (RHSFX.getValue() == 0) { 13109 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13110 return false; 13111 } 13112 Result = LHSFX.div(RHSFX, &OpOverflow) 13113 .convert(ResultFXSema, &ConversionOverflow); 13114 break; 13115 } 13116 case BO_Shl: 13117 case BO_Shr: { 13118 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13119 llvm::APSInt RHSVal = RHSFX.getValue(); 13120 13121 unsigned ShiftBW = 13122 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13123 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13124 // Embedded-C 4.1.6.2.2: 13125 // The right operand must be nonnegative and less than the total number 13126 // of (nonpadding) bits of the fixed-point operand ... 13127 if (RHSVal.isNegative()) 13128 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13129 else if (Amt != RHSVal) 13130 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13131 << RHSVal << E->getType() << ShiftBW; 13132 13133 if (E->getOpcode() == BO_Shl) 13134 Result = LHSFX.shl(Amt, &OpOverflow); 13135 else 13136 Result = LHSFX.shr(Amt, &OpOverflow); 13137 break; 13138 } 13139 default: 13140 return false; 13141 } 13142 if (OpOverflow || ConversionOverflow) { 13143 if (Info.checkingForUndefinedBehavior()) 13144 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13145 diag::warn_fixedpoint_constant_overflow) 13146 << Result.toString() << E->getType(); 13147 else if (!HandleOverflow(Info, E, Result, E->getType())) 13148 return false; 13149 } 13150 return Success(Result, E); 13151 } 13152 13153 //===----------------------------------------------------------------------===// 13154 // Float Evaluation 13155 //===----------------------------------------------------------------------===// 13156 13157 namespace { 13158 class FloatExprEvaluator 13159 : public ExprEvaluatorBase<FloatExprEvaluator> { 13160 APFloat &Result; 13161 public: 13162 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13163 : ExprEvaluatorBaseTy(info), Result(result) {} 13164 13165 bool Success(const APValue &V, const Expr *e) { 13166 Result = V.getFloat(); 13167 return true; 13168 } 13169 13170 bool ZeroInitialization(const Expr *E) { 13171 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13172 return true; 13173 } 13174 13175 bool VisitCallExpr(const CallExpr *E); 13176 13177 bool VisitUnaryOperator(const UnaryOperator *E); 13178 bool VisitBinaryOperator(const BinaryOperator *E); 13179 bool VisitFloatingLiteral(const FloatingLiteral *E); 13180 bool VisitCastExpr(const CastExpr *E); 13181 13182 bool VisitUnaryReal(const UnaryOperator *E); 13183 bool VisitUnaryImag(const UnaryOperator *E); 13184 13185 // FIXME: Missing: array subscript of vector, member of vector 13186 }; 13187 } // end anonymous namespace 13188 13189 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13190 assert(E->isRValue() && E->getType()->isRealFloatingType()); 13191 return FloatExprEvaluator(Info, Result).Visit(E); 13192 } 13193 13194 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13195 QualType ResultTy, 13196 const Expr *Arg, 13197 bool SNaN, 13198 llvm::APFloat &Result) { 13199 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13200 if (!S) return false; 13201 13202 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13203 13204 llvm::APInt fill; 13205 13206 // Treat empty strings as if they were zero. 13207 if (S->getString().empty()) 13208 fill = llvm::APInt(32, 0); 13209 else if (S->getString().getAsInteger(0, fill)) 13210 return false; 13211 13212 if (Context.getTargetInfo().isNan2008()) { 13213 if (SNaN) 13214 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13215 else 13216 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13217 } else { 13218 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13219 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13220 // a different encoding to what became a standard in 2008, and for pre- 13221 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13222 // sNaN. This is now known as "legacy NaN" encoding. 13223 if (SNaN) 13224 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13225 else 13226 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13227 } 13228 13229 return true; 13230 } 13231 13232 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13233 switch (E->getBuiltinCallee()) { 13234 default: 13235 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13236 13237 case Builtin::BI__builtin_huge_val: 13238 case Builtin::BI__builtin_huge_valf: 13239 case Builtin::BI__builtin_huge_vall: 13240 case Builtin::BI__builtin_huge_valf128: 13241 case Builtin::BI__builtin_inf: 13242 case Builtin::BI__builtin_inff: 13243 case Builtin::BI__builtin_infl: 13244 case Builtin::BI__builtin_inff128: { 13245 const llvm::fltSemantics &Sem = 13246 Info.Ctx.getFloatTypeSemantics(E->getType()); 13247 Result = llvm::APFloat::getInf(Sem); 13248 return true; 13249 } 13250 13251 case Builtin::BI__builtin_nans: 13252 case Builtin::BI__builtin_nansf: 13253 case Builtin::BI__builtin_nansl: 13254 case Builtin::BI__builtin_nansf128: 13255 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13256 true, Result)) 13257 return Error(E); 13258 return true; 13259 13260 case Builtin::BI__builtin_nan: 13261 case Builtin::BI__builtin_nanf: 13262 case Builtin::BI__builtin_nanl: 13263 case Builtin::BI__builtin_nanf128: 13264 // If this is __builtin_nan() turn this into a nan, otherwise we 13265 // can't constant fold it. 13266 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13267 false, Result)) 13268 return Error(E); 13269 return true; 13270 13271 case Builtin::BI__builtin_fabs: 13272 case Builtin::BI__builtin_fabsf: 13273 case Builtin::BI__builtin_fabsl: 13274 case Builtin::BI__builtin_fabsf128: 13275 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13276 return false; 13277 13278 if (Result.isNegative()) 13279 Result.changeSign(); 13280 return true; 13281 13282 // FIXME: Builtin::BI__builtin_powi 13283 // FIXME: Builtin::BI__builtin_powif 13284 // FIXME: Builtin::BI__builtin_powil 13285 13286 case Builtin::BI__builtin_copysign: 13287 case Builtin::BI__builtin_copysignf: 13288 case Builtin::BI__builtin_copysignl: 13289 case Builtin::BI__builtin_copysignf128: { 13290 APFloat RHS(0.); 13291 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13292 !EvaluateFloat(E->getArg(1), RHS, Info)) 13293 return false; 13294 Result.copySign(RHS); 13295 return true; 13296 } 13297 } 13298 } 13299 13300 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13301 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13302 ComplexValue CV; 13303 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13304 return false; 13305 Result = CV.FloatReal; 13306 return true; 13307 } 13308 13309 return Visit(E->getSubExpr()); 13310 } 13311 13312 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13313 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13314 ComplexValue CV; 13315 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13316 return false; 13317 Result = CV.FloatImag; 13318 return true; 13319 } 13320 13321 VisitIgnoredValue(E->getSubExpr()); 13322 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13323 Result = llvm::APFloat::getZero(Sem); 13324 return true; 13325 } 13326 13327 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13328 switch (E->getOpcode()) { 13329 default: return Error(E); 13330 case UO_Plus: 13331 return EvaluateFloat(E->getSubExpr(), Result, Info); 13332 case UO_Minus: 13333 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13334 return false; 13335 Result.changeSign(); 13336 return true; 13337 } 13338 } 13339 13340 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13341 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13342 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13343 13344 APFloat RHS(0.0); 13345 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13346 if (!LHSOK && !Info.noteFailure()) 13347 return false; 13348 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13349 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13350 } 13351 13352 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13353 Result = E->getValue(); 13354 return true; 13355 } 13356 13357 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13358 const Expr* SubExpr = E->getSubExpr(); 13359 13360 switch (E->getCastKind()) { 13361 default: 13362 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13363 13364 case CK_IntegralToFloating: { 13365 APSInt IntResult; 13366 return EvaluateInteger(SubExpr, IntResult, Info) && 13367 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 13368 E->getType(), Result); 13369 } 13370 13371 case CK_FloatingCast: { 13372 if (!Visit(SubExpr)) 13373 return false; 13374 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13375 Result); 13376 } 13377 13378 case CK_FloatingComplexToReal: { 13379 ComplexValue V; 13380 if (!EvaluateComplex(SubExpr, V, Info)) 13381 return false; 13382 Result = V.getComplexFloatReal(); 13383 return true; 13384 } 13385 } 13386 } 13387 13388 //===----------------------------------------------------------------------===// 13389 // Complex Evaluation (for float and integer) 13390 //===----------------------------------------------------------------------===// 13391 13392 namespace { 13393 class ComplexExprEvaluator 13394 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13395 ComplexValue &Result; 13396 13397 public: 13398 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13399 : ExprEvaluatorBaseTy(info), Result(Result) {} 13400 13401 bool Success(const APValue &V, const Expr *e) { 13402 Result.setFrom(V); 13403 return true; 13404 } 13405 13406 bool ZeroInitialization(const Expr *E); 13407 13408 //===--------------------------------------------------------------------===// 13409 // Visitor Methods 13410 //===--------------------------------------------------------------------===// 13411 13412 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13413 bool VisitCastExpr(const CastExpr *E); 13414 bool VisitBinaryOperator(const BinaryOperator *E); 13415 bool VisitUnaryOperator(const UnaryOperator *E); 13416 bool VisitInitListExpr(const InitListExpr *E); 13417 bool VisitCallExpr(const CallExpr *E); 13418 }; 13419 } // end anonymous namespace 13420 13421 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13422 EvalInfo &Info) { 13423 assert(E->isRValue() && E->getType()->isAnyComplexType()); 13424 return ComplexExprEvaluator(Info, Result).Visit(E); 13425 } 13426 13427 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13428 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13429 if (ElemTy->isRealFloatingType()) { 13430 Result.makeComplexFloat(); 13431 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13432 Result.FloatReal = Zero; 13433 Result.FloatImag = Zero; 13434 } else { 13435 Result.makeComplexInt(); 13436 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13437 Result.IntReal = Zero; 13438 Result.IntImag = Zero; 13439 } 13440 return true; 13441 } 13442 13443 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13444 const Expr* SubExpr = E->getSubExpr(); 13445 13446 if (SubExpr->getType()->isRealFloatingType()) { 13447 Result.makeComplexFloat(); 13448 APFloat &Imag = Result.FloatImag; 13449 if (!EvaluateFloat(SubExpr, Imag, Info)) 13450 return false; 13451 13452 Result.FloatReal = APFloat(Imag.getSemantics()); 13453 return true; 13454 } else { 13455 assert(SubExpr->getType()->isIntegerType() && 13456 "Unexpected imaginary literal."); 13457 13458 Result.makeComplexInt(); 13459 APSInt &Imag = Result.IntImag; 13460 if (!EvaluateInteger(SubExpr, Imag, Info)) 13461 return false; 13462 13463 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13464 return true; 13465 } 13466 } 13467 13468 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13469 13470 switch (E->getCastKind()) { 13471 case CK_BitCast: 13472 case CK_BaseToDerived: 13473 case CK_DerivedToBase: 13474 case CK_UncheckedDerivedToBase: 13475 case CK_Dynamic: 13476 case CK_ToUnion: 13477 case CK_ArrayToPointerDecay: 13478 case CK_FunctionToPointerDecay: 13479 case CK_NullToPointer: 13480 case CK_NullToMemberPointer: 13481 case CK_BaseToDerivedMemberPointer: 13482 case CK_DerivedToBaseMemberPointer: 13483 case CK_MemberPointerToBoolean: 13484 case CK_ReinterpretMemberPointer: 13485 case CK_ConstructorConversion: 13486 case CK_IntegralToPointer: 13487 case CK_PointerToIntegral: 13488 case CK_PointerToBoolean: 13489 case CK_ToVoid: 13490 case CK_VectorSplat: 13491 case CK_IntegralCast: 13492 case CK_BooleanToSignedIntegral: 13493 case CK_IntegralToBoolean: 13494 case CK_IntegralToFloating: 13495 case CK_FloatingToIntegral: 13496 case CK_FloatingToBoolean: 13497 case CK_FloatingCast: 13498 case CK_CPointerToObjCPointerCast: 13499 case CK_BlockPointerToObjCPointerCast: 13500 case CK_AnyPointerToBlockPointerCast: 13501 case CK_ObjCObjectLValueCast: 13502 case CK_FloatingComplexToReal: 13503 case CK_FloatingComplexToBoolean: 13504 case CK_IntegralComplexToReal: 13505 case CK_IntegralComplexToBoolean: 13506 case CK_ARCProduceObject: 13507 case CK_ARCConsumeObject: 13508 case CK_ARCReclaimReturnedObject: 13509 case CK_ARCExtendBlockObject: 13510 case CK_CopyAndAutoreleaseBlockObject: 13511 case CK_BuiltinFnToFnPtr: 13512 case CK_ZeroToOCLOpaqueType: 13513 case CK_NonAtomicToAtomic: 13514 case CK_AddressSpaceConversion: 13515 case CK_IntToOCLSampler: 13516 case CK_FixedPointCast: 13517 case CK_FixedPointToBoolean: 13518 case CK_FixedPointToIntegral: 13519 case CK_IntegralToFixedPoint: 13520 llvm_unreachable("invalid cast kind for complex value"); 13521 13522 case CK_LValueToRValue: 13523 case CK_AtomicToNonAtomic: 13524 case CK_NoOp: 13525 case CK_LValueToRValueBitCast: 13526 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13527 13528 case CK_Dependent: 13529 case CK_LValueBitCast: 13530 case CK_UserDefinedConversion: 13531 return Error(E); 13532 13533 case CK_FloatingRealToComplex: { 13534 APFloat &Real = Result.FloatReal; 13535 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13536 return false; 13537 13538 Result.makeComplexFloat(); 13539 Result.FloatImag = APFloat(Real.getSemantics()); 13540 return true; 13541 } 13542 13543 case CK_FloatingComplexCast: { 13544 if (!Visit(E->getSubExpr())) 13545 return false; 13546 13547 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13548 QualType From 13549 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13550 13551 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13552 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13553 } 13554 13555 case CK_FloatingComplexToIntegralComplex: { 13556 if (!Visit(E->getSubExpr())) 13557 return false; 13558 13559 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13560 QualType From 13561 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13562 Result.makeComplexInt(); 13563 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13564 To, Result.IntReal) && 13565 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13566 To, Result.IntImag); 13567 } 13568 13569 case CK_IntegralRealToComplex: { 13570 APSInt &Real = Result.IntReal; 13571 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13572 return false; 13573 13574 Result.makeComplexInt(); 13575 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13576 return true; 13577 } 13578 13579 case CK_IntegralComplexCast: { 13580 if (!Visit(E->getSubExpr())) 13581 return false; 13582 13583 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13584 QualType From 13585 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13586 13587 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 13588 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 13589 return true; 13590 } 13591 13592 case CK_IntegralComplexToFloatingComplex: { 13593 if (!Visit(E->getSubExpr())) 13594 return false; 13595 13596 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13597 QualType From 13598 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13599 Result.makeComplexFloat(); 13600 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 13601 To, Result.FloatReal) && 13602 HandleIntToFloatCast(Info, E, From, Result.IntImag, 13603 To, Result.FloatImag); 13604 } 13605 } 13606 13607 llvm_unreachable("unknown cast resulting in complex value"); 13608 } 13609 13610 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13611 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13612 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13613 13614 // Track whether the LHS or RHS is real at the type system level. When this is 13615 // the case we can simplify our evaluation strategy. 13616 bool LHSReal = false, RHSReal = false; 13617 13618 bool LHSOK; 13619 if (E->getLHS()->getType()->isRealFloatingType()) { 13620 LHSReal = true; 13621 APFloat &Real = Result.FloatReal; 13622 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 13623 if (LHSOK) { 13624 Result.makeComplexFloat(); 13625 Result.FloatImag = APFloat(Real.getSemantics()); 13626 } 13627 } else { 13628 LHSOK = Visit(E->getLHS()); 13629 } 13630 if (!LHSOK && !Info.noteFailure()) 13631 return false; 13632 13633 ComplexValue RHS; 13634 if (E->getRHS()->getType()->isRealFloatingType()) { 13635 RHSReal = true; 13636 APFloat &Real = RHS.FloatReal; 13637 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 13638 return false; 13639 RHS.makeComplexFloat(); 13640 RHS.FloatImag = APFloat(Real.getSemantics()); 13641 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 13642 return false; 13643 13644 assert(!(LHSReal && RHSReal) && 13645 "Cannot have both operands of a complex operation be real."); 13646 switch (E->getOpcode()) { 13647 default: return Error(E); 13648 case BO_Add: 13649 if (Result.isComplexFloat()) { 13650 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 13651 APFloat::rmNearestTiesToEven); 13652 if (LHSReal) 13653 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13654 else if (!RHSReal) 13655 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 13656 APFloat::rmNearestTiesToEven); 13657 } else { 13658 Result.getComplexIntReal() += RHS.getComplexIntReal(); 13659 Result.getComplexIntImag() += RHS.getComplexIntImag(); 13660 } 13661 break; 13662 case BO_Sub: 13663 if (Result.isComplexFloat()) { 13664 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 13665 APFloat::rmNearestTiesToEven); 13666 if (LHSReal) { 13667 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13668 Result.getComplexFloatImag().changeSign(); 13669 } else if (!RHSReal) { 13670 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 13671 APFloat::rmNearestTiesToEven); 13672 } 13673 } else { 13674 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 13675 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 13676 } 13677 break; 13678 case BO_Mul: 13679 if (Result.isComplexFloat()) { 13680 // This is an implementation of complex multiplication according to the 13681 // constraints laid out in C11 Annex G. The implementation uses the 13682 // following naming scheme: 13683 // (a + ib) * (c + id) 13684 ComplexValue LHS = Result; 13685 APFloat &A = LHS.getComplexFloatReal(); 13686 APFloat &B = LHS.getComplexFloatImag(); 13687 APFloat &C = RHS.getComplexFloatReal(); 13688 APFloat &D = RHS.getComplexFloatImag(); 13689 APFloat &ResR = Result.getComplexFloatReal(); 13690 APFloat &ResI = Result.getComplexFloatImag(); 13691 if (LHSReal) { 13692 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 13693 ResR = A * C; 13694 ResI = A * D; 13695 } else if (RHSReal) { 13696 ResR = C * A; 13697 ResI = C * B; 13698 } else { 13699 // In the fully general case, we need to handle NaNs and infinities 13700 // robustly. 13701 APFloat AC = A * C; 13702 APFloat BD = B * D; 13703 APFloat AD = A * D; 13704 APFloat BC = B * C; 13705 ResR = AC - BD; 13706 ResI = AD + BC; 13707 if (ResR.isNaN() && ResI.isNaN()) { 13708 bool Recalc = false; 13709 if (A.isInfinity() || B.isInfinity()) { 13710 A = APFloat::copySign( 13711 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13712 B = APFloat::copySign( 13713 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13714 if (C.isNaN()) 13715 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13716 if (D.isNaN()) 13717 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13718 Recalc = true; 13719 } 13720 if (C.isInfinity() || D.isInfinity()) { 13721 C = APFloat::copySign( 13722 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13723 D = APFloat::copySign( 13724 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13725 if (A.isNaN()) 13726 A = APFloat::copySign(APFloat(A.getSemantics()), A); 13727 if (B.isNaN()) 13728 B = APFloat::copySign(APFloat(B.getSemantics()), B); 13729 Recalc = true; 13730 } 13731 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 13732 AD.isInfinity() || BC.isInfinity())) { 13733 if (A.isNaN()) 13734 A = APFloat::copySign(APFloat(A.getSemantics()), A); 13735 if (B.isNaN()) 13736 B = APFloat::copySign(APFloat(B.getSemantics()), B); 13737 if (C.isNaN()) 13738 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13739 if (D.isNaN()) 13740 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13741 Recalc = true; 13742 } 13743 if (Recalc) { 13744 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 13745 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 13746 } 13747 } 13748 } 13749 } else { 13750 ComplexValue LHS = Result; 13751 Result.getComplexIntReal() = 13752 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 13753 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 13754 Result.getComplexIntImag() = 13755 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 13756 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 13757 } 13758 break; 13759 case BO_Div: 13760 if (Result.isComplexFloat()) { 13761 // This is an implementation of complex division according to the 13762 // constraints laid out in C11 Annex G. The implementation uses the 13763 // following naming scheme: 13764 // (a + ib) / (c + id) 13765 ComplexValue LHS = Result; 13766 APFloat &A = LHS.getComplexFloatReal(); 13767 APFloat &B = LHS.getComplexFloatImag(); 13768 APFloat &C = RHS.getComplexFloatReal(); 13769 APFloat &D = RHS.getComplexFloatImag(); 13770 APFloat &ResR = Result.getComplexFloatReal(); 13771 APFloat &ResI = Result.getComplexFloatImag(); 13772 if (RHSReal) { 13773 ResR = A / C; 13774 ResI = B / C; 13775 } else { 13776 if (LHSReal) { 13777 // No real optimizations we can do here, stub out with zero. 13778 B = APFloat::getZero(A.getSemantics()); 13779 } 13780 int DenomLogB = 0; 13781 APFloat MaxCD = maxnum(abs(C), abs(D)); 13782 if (MaxCD.isFinite()) { 13783 DenomLogB = ilogb(MaxCD); 13784 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 13785 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 13786 } 13787 APFloat Denom = C * C + D * D; 13788 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 13789 APFloat::rmNearestTiesToEven); 13790 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 13791 APFloat::rmNearestTiesToEven); 13792 if (ResR.isNaN() && ResI.isNaN()) { 13793 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 13794 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 13795 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 13796 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 13797 D.isFinite()) { 13798 A = APFloat::copySign( 13799 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13800 B = APFloat::copySign( 13801 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13802 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 13803 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 13804 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 13805 C = APFloat::copySign( 13806 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13807 D = APFloat::copySign( 13808 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13809 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 13810 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 13811 } 13812 } 13813 } 13814 } else { 13815 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 13816 return Error(E, diag::note_expr_divide_by_zero); 13817 13818 ComplexValue LHS = Result; 13819 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 13820 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 13821 Result.getComplexIntReal() = 13822 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 13823 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 13824 Result.getComplexIntImag() = 13825 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 13826 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 13827 } 13828 break; 13829 } 13830 13831 return true; 13832 } 13833 13834 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13835 // Get the operand value into 'Result'. 13836 if (!Visit(E->getSubExpr())) 13837 return false; 13838 13839 switch (E->getOpcode()) { 13840 default: 13841 return Error(E); 13842 case UO_Extension: 13843 return true; 13844 case UO_Plus: 13845 // The result is always just the subexpr. 13846 return true; 13847 case UO_Minus: 13848 if (Result.isComplexFloat()) { 13849 Result.getComplexFloatReal().changeSign(); 13850 Result.getComplexFloatImag().changeSign(); 13851 } 13852 else { 13853 Result.getComplexIntReal() = -Result.getComplexIntReal(); 13854 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13855 } 13856 return true; 13857 case UO_Not: 13858 if (Result.isComplexFloat()) 13859 Result.getComplexFloatImag().changeSign(); 13860 else 13861 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13862 return true; 13863 } 13864 } 13865 13866 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 13867 if (E->getNumInits() == 2) { 13868 if (E->getType()->isComplexType()) { 13869 Result.makeComplexFloat(); 13870 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 13871 return false; 13872 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 13873 return false; 13874 } else { 13875 Result.makeComplexInt(); 13876 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 13877 return false; 13878 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 13879 return false; 13880 } 13881 return true; 13882 } 13883 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 13884 } 13885 13886 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 13887 switch (E->getBuiltinCallee()) { 13888 case Builtin::BI__builtin_complex: 13889 Result.makeComplexFloat(); 13890 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 13891 return false; 13892 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 13893 return false; 13894 return true; 13895 13896 default: 13897 break; 13898 } 13899 13900 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13901 } 13902 13903 //===----------------------------------------------------------------------===// 13904 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 13905 // implicit conversion. 13906 //===----------------------------------------------------------------------===// 13907 13908 namespace { 13909 class AtomicExprEvaluator : 13910 public ExprEvaluatorBase<AtomicExprEvaluator> { 13911 const LValue *This; 13912 APValue &Result; 13913 public: 13914 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 13915 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 13916 13917 bool Success(const APValue &V, const Expr *E) { 13918 Result = V; 13919 return true; 13920 } 13921 13922 bool ZeroInitialization(const Expr *E) { 13923 ImplicitValueInitExpr VIE( 13924 E->getType()->castAs<AtomicType>()->getValueType()); 13925 // For atomic-qualified class (and array) types in C++, initialize the 13926 // _Atomic-wrapped subobject directly, in-place. 13927 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 13928 : Evaluate(Result, Info, &VIE); 13929 } 13930 13931 bool VisitCastExpr(const CastExpr *E) { 13932 switch (E->getCastKind()) { 13933 default: 13934 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13935 case CK_NonAtomicToAtomic: 13936 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 13937 : Evaluate(Result, Info, E->getSubExpr()); 13938 } 13939 } 13940 }; 13941 } // end anonymous namespace 13942 13943 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 13944 EvalInfo &Info) { 13945 assert(E->isRValue() && E->getType()->isAtomicType()); 13946 return AtomicExprEvaluator(Info, This, Result).Visit(E); 13947 } 13948 13949 //===----------------------------------------------------------------------===// 13950 // Void expression evaluation, primarily for a cast to void on the LHS of a 13951 // comma operator 13952 //===----------------------------------------------------------------------===// 13953 13954 namespace { 13955 class VoidExprEvaluator 13956 : public ExprEvaluatorBase<VoidExprEvaluator> { 13957 public: 13958 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 13959 13960 bool Success(const APValue &V, const Expr *e) { return true; } 13961 13962 bool ZeroInitialization(const Expr *E) { return true; } 13963 13964 bool VisitCastExpr(const CastExpr *E) { 13965 switch (E->getCastKind()) { 13966 default: 13967 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13968 case CK_ToVoid: 13969 VisitIgnoredValue(E->getSubExpr()); 13970 return true; 13971 } 13972 } 13973 13974 bool VisitCallExpr(const CallExpr *E) { 13975 switch (E->getBuiltinCallee()) { 13976 case Builtin::BI__assume: 13977 case Builtin::BI__builtin_assume: 13978 // The argument is not evaluated! 13979 return true; 13980 13981 case Builtin::BI__builtin_operator_delete: 13982 return HandleOperatorDeleteCall(Info, E); 13983 13984 default: 13985 break; 13986 } 13987 13988 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13989 } 13990 13991 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 13992 }; 13993 } // end anonymous namespace 13994 13995 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 13996 // We cannot speculatively evaluate a delete expression. 13997 if (Info.SpeculativeEvaluationDepth) 13998 return false; 13999 14000 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14001 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14002 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14003 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14004 return false; 14005 } 14006 14007 const Expr *Arg = E->getArgument(); 14008 14009 LValue Pointer; 14010 if (!EvaluatePointer(Arg, Pointer, Info)) 14011 return false; 14012 if (Pointer.Designator.Invalid) 14013 return false; 14014 14015 // Deleting a null pointer has no effect. 14016 if (Pointer.isNullPointer()) { 14017 // This is the only case where we need to produce an extension warning: 14018 // the only other way we can succeed is if we find a dynamic allocation, 14019 // and we will have warned when we allocated it in that case. 14020 if (!Info.getLangOpts().CPlusPlus20) 14021 Info.CCEDiag(E, diag::note_constexpr_new); 14022 return true; 14023 } 14024 14025 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14026 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14027 if (!Alloc) 14028 return false; 14029 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14030 14031 // For the non-array case, the designator must be empty if the static type 14032 // does not have a virtual destructor. 14033 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14034 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14035 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14036 << Arg->getType()->getPointeeType() << AllocType; 14037 return false; 14038 } 14039 14040 // For a class type with a virtual destructor, the selected operator delete 14041 // is the one looked up when building the destructor. 14042 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14043 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14044 if (VirtualDelete && 14045 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14046 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14047 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14048 return false; 14049 } 14050 } 14051 14052 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14053 (*Alloc)->Value, AllocType)) 14054 return false; 14055 14056 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14057 // The element was already erased. This means the destructor call also 14058 // deleted the object. 14059 // FIXME: This probably results in undefined behavior before we get this 14060 // far, and should be diagnosed elsewhere first. 14061 Info.FFDiag(E, diag::note_constexpr_double_delete); 14062 return false; 14063 } 14064 14065 return true; 14066 } 14067 14068 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14069 assert(E->isRValue() && E->getType()->isVoidType()); 14070 return VoidExprEvaluator(Info).Visit(E); 14071 } 14072 14073 //===----------------------------------------------------------------------===// 14074 // Top level Expr::EvaluateAsRValue method. 14075 //===----------------------------------------------------------------------===// 14076 14077 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14078 // In C, function designators are not lvalues, but we evaluate them as if they 14079 // are. 14080 QualType T = E->getType(); 14081 if (E->isGLValue() || T->isFunctionType()) { 14082 LValue LV; 14083 if (!EvaluateLValue(E, LV, Info)) 14084 return false; 14085 LV.moveInto(Result); 14086 } else if (T->isVectorType()) { 14087 if (!EvaluateVector(E, Result, Info)) 14088 return false; 14089 } else if (T->isIntegralOrEnumerationType()) { 14090 if (!IntExprEvaluator(Info, Result).Visit(E)) 14091 return false; 14092 } else if (T->hasPointerRepresentation()) { 14093 LValue LV; 14094 if (!EvaluatePointer(E, LV, Info)) 14095 return false; 14096 LV.moveInto(Result); 14097 } else if (T->isRealFloatingType()) { 14098 llvm::APFloat F(0.0); 14099 if (!EvaluateFloat(E, F, Info)) 14100 return false; 14101 Result = APValue(F); 14102 } else if (T->isAnyComplexType()) { 14103 ComplexValue C; 14104 if (!EvaluateComplex(E, C, Info)) 14105 return false; 14106 C.moveInto(Result); 14107 } else if (T->isFixedPointType()) { 14108 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14109 } else if (T->isMemberPointerType()) { 14110 MemberPtr P; 14111 if (!EvaluateMemberPointer(E, P, Info)) 14112 return false; 14113 P.moveInto(Result); 14114 return true; 14115 } else if (T->isArrayType()) { 14116 LValue LV; 14117 APValue &Value = 14118 Info.CurrentCall->createTemporary(E, T, false, LV); 14119 if (!EvaluateArray(E, LV, Value, Info)) 14120 return false; 14121 Result = Value; 14122 } else if (T->isRecordType()) { 14123 LValue LV; 14124 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV); 14125 if (!EvaluateRecord(E, LV, Value, Info)) 14126 return false; 14127 Result = Value; 14128 } else if (T->isVoidType()) { 14129 if (!Info.getLangOpts().CPlusPlus11) 14130 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14131 << E->getType(); 14132 if (!EvaluateVoid(E, Info)) 14133 return false; 14134 } else if (T->isAtomicType()) { 14135 QualType Unqual = T.getAtomicUnqualifiedType(); 14136 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14137 LValue LV; 14138 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV); 14139 if (!EvaluateAtomic(E, &LV, Value, Info)) 14140 return false; 14141 } else { 14142 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14143 return false; 14144 } 14145 } else if (Info.getLangOpts().CPlusPlus11) { 14146 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14147 return false; 14148 } else { 14149 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14150 return false; 14151 } 14152 14153 return true; 14154 } 14155 14156 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14157 /// cases, the in-place evaluation is essential, since later initializers for 14158 /// an object can indirectly refer to subobjects which were initialized earlier. 14159 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14160 const Expr *E, bool AllowNonLiteralTypes) { 14161 assert(!E->isValueDependent()); 14162 14163 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14164 return false; 14165 14166 if (E->isRValue()) { 14167 // Evaluate arrays and record types in-place, so that later initializers can 14168 // refer to earlier-initialized members of the object. 14169 QualType T = E->getType(); 14170 if (T->isArrayType()) 14171 return EvaluateArray(E, This, Result, Info); 14172 else if (T->isRecordType()) 14173 return EvaluateRecord(E, This, Result, Info); 14174 else if (T->isAtomicType()) { 14175 QualType Unqual = T.getAtomicUnqualifiedType(); 14176 if (Unqual->isArrayType() || Unqual->isRecordType()) 14177 return EvaluateAtomic(E, &This, Result, Info); 14178 } 14179 } 14180 14181 // For any other type, in-place evaluation is unimportant. 14182 return Evaluate(Result, Info, E); 14183 } 14184 14185 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14186 /// lvalue-to-rvalue cast if it is an lvalue. 14187 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14188 if (Info.EnableNewConstInterp) { 14189 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14190 return false; 14191 } else { 14192 if (E->getType().isNull()) 14193 return false; 14194 14195 if (!CheckLiteralType(Info, E)) 14196 return false; 14197 14198 if (!::Evaluate(Result, Info, E)) 14199 return false; 14200 14201 if (E->isGLValue()) { 14202 LValue LV; 14203 LV.setFrom(Info.Ctx, Result); 14204 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14205 return false; 14206 } 14207 } 14208 14209 // Check this core constant expression is a constant expression. 14210 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) && 14211 CheckMemoryLeaks(Info); 14212 } 14213 14214 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14215 const ASTContext &Ctx, bool &IsConst) { 14216 // Fast-path evaluations of integer literals, since we sometimes see files 14217 // containing vast quantities of these. 14218 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14219 Result.Val = APValue(APSInt(L->getValue(), 14220 L->getType()->isUnsignedIntegerType())); 14221 IsConst = true; 14222 return true; 14223 } 14224 14225 // This case should be rare, but we need to check it before we check on 14226 // the type below. 14227 if (Exp->getType().isNull()) { 14228 IsConst = false; 14229 return true; 14230 } 14231 14232 // FIXME: Evaluating values of large array and record types can cause 14233 // performance problems. Only do so in C++11 for now. 14234 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 14235 Exp->getType()->isRecordType()) && 14236 !Ctx.getLangOpts().CPlusPlus11) { 14237 IsConst = false; 14238 return true; 14239 } 14240 return false; 14241 } 14242 14243 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14244 Expr::SideEffectsKind SEK) { 14245 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14246 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14247 } 14248 14249 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14250 const ASTContext &Ctx, EvalInfo &Info) { 14251 bool IsConst; 14252 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14253 return IsConst; 14254 14255 return EvaluateAsRValue(Info, E, Result.Val); 14256 } 14257 14258 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14259 const ASTContext &Ctx, 14260 Expr::SideEffectsKind AllowSideEffects, 14261 EvalInfo &Info) { 14262 if (!E->getType()->isIntegralOrEnumerationType()) 14263 return false; 14264 14265 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14266 !ExprResult.Val.isInt() || 14267 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14268 return false; 14269 14270 return true; 14271 } 14272 14273 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14274 const ASTContext &Ctx, 14275 Expr::SideEffectsKind AllowSideEffects, 14276 EvalInfo &Info) { 14277 if (!E->getType()->isFixedPointType()) 14278 return false; 14279 14280 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14281 return false; 14282 14283 if (!ExprResult.Val.isFixedPoint() || 14284 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14285 return false; 14286 14287 return true; 14288 } 14289 14290 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14291 /// any crazy technique (that has nothing to do with language standards) that 14292 /// we want to. If this function returns true, it returns the folded constant 14293 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14294 /// will be applied to the result. 14295 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14296 bool InConstantContext) const { 14297 assert(!isValueDependent() && 14298 "Expression evaluator can't be called on a dependent expression."); 14299 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14300 Info.InConstantContext = InConstantContext; 14301 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14302 } 14303 14304 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14305 bool InConstantContext) const { 14306 assert(!isValueDependent() && 14307 "Expression evaluator can't be called on a dependent expression."); 14308 EvalResult Scratch; 14309 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14310 HandleConversionToBool(Scratch.Val, Result); 14311 } 14312 14313 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14314 SideEffectsKind AllowSideEffects, 14315 bool InConstantContext) const { 14316 assert(!isValueDependent() && 14317 "Expression evaluator can't be called on a dependent expression."); 14318 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14319 Info.InConstantContext = InConstantContext; 14320 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14321 } 14322 14323 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14324 SideEffectsKind AllowSideEffects, 14325 bool InConstantContext) const { 14326 assert(!isValueDependent() && 14327 "Expression evaluator can't be called on a dependent expression."); 14328 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14329 Info.InConstantContext = InConstantContext; 14330 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14331 } 14332 14333 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14334 SideEffectsKind AllowSideEffects, 14335 bool InConstantContext) const { 14336 assert(!isValueDependent() && 14337 "Expression evaluator can't be called on a dependent expression."); 14338 14339 if (!getType()->isRealFloatingType()) 14340 return false; 14341 14342 EvalResult ExprResult; 14343 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14344 !ExprResult.Val.isFloat() || 14345 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14346 return false; 14347 14348 Result = ExprResult.Val.getFloat(); 14349 return true; 14350 } 14351 14352 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14353 bool InConstantContext) const { 14354 assert(!isValueDependent() && 14355 "Expression evaluator can't be called on a dependent expression."); 14356 14357 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14358 Info.InConstantContext = InConstantContext; 14359 LValue LV; 14360 CheckedTemporaries CheckedTemps; 14361 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14362 Result.HasSideEffects || 14363 !CheckLValueConstantExpression(Info, getExprLoc(), 14364 Ctx.getLValueReferenceType(getType()), LV, 14365 Expr::EvaluateForCodeGen, CheckedTemps)) 14366 return false; 14367 14368 LV.moveInto(Result.Val); 14369 return true; 14370 } 14371 14372 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 14373 const ASTContext &Ctx, bool InPlace) const { 14374 assert(!isValueDependent() && 14375 "Expression evaluator can't be called on a dependent expression."); 14376 14377 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14378 EvalInfo Info(Ctx, Result, EM); 14379 Info.InConstantContext = true; 14380 14381 if (InPlace) { 14382 Info.setEvaluatingDecl(this, Result.Val); 14383 LValue LVal; 14384 LVal.set(this); 14385 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || 14386 Result.HasSideEffects) 14387 return false; 14388 } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects) 14389 return false; 14390 14391 if (!Info.discardCleanups()) 14392 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14393 14394 return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14395 Result.Val, Usage) && 14396 CheckMemoryLeaks(Info); 14397 } 14398 14399 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14400 const VarDecl *VD, 14401 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14402 assert(!isValueDependent() && 14403 "Expression evaluator can't be called on a dependent expression."); 14404 14405 // FIXME: Evaluating initializers for large array and record types can cause 14406 // performance problems. Only do so in C++11 for now. 14407 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14408 !Ctx.getLangOpts().CPlusPlus11) 14409 return false; 14410 14411 Expr::EvalStatus EStatus; 14412 EStatus.Diag = &Notes; 14413 14414 EvalInfo Info(Ctx, EStatus, VD->isConstexpr() 14415 ? EvalInfo::EM_ConstantExpression 14416 : EvalInfo::EM_ConstantFold); 14417 Info.setEvaluatingDecl(VD, Value); 14418 Info.InConstantContext = true; 14419 14420 SourceLocation DeclLoc = VD->getLocation(); 14421 QualType DeclTy = VD->getType(); 14422 14423 if (Info.EnableNewConstInterp) { 14424 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14425 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14426 return false; 14427 } else { 14428 LValue LVal; 14429 LVal.set(VD); 14430 14431 if (!EvaluateInPlace(Value, Info, LVal, this, 14432 /*AllowNonLiteralTypes=*/true) || 14433 EStatus.HasSideEffects) 14434 return false; 14435 14436 // At this point, any lifetime-extended temporaries are completely 14437 // initialized. 14438 Info.performLifetimeExtension(); 14439 14440 if (!Info.discardCleanups()) 14441 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14442 } 14443 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) && 14444 CheckMemoryLeaks(Info); 14445 } 14446 14447 bool VarDecl::evaluateDestruction( 14448 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14449 Expr::EvalStatus EStatus; 14450 EStatus.Diag = &Notes; 14451 14452 // Make a copy of the value for the destructor to mutate, if we know it. 14453 // Otherwise, treat the value as default-initialized; if the destructor works 14454 // anyway, then the destruction is constant (and must be essentially empty). 14455 APValue DestroyedValue; 14456 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14457 DestroyedValue = *getEvaluatedValue(); 14458 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14459 return false; 14460 14461 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression); 14462 Info.setEvaluatingDecl(this, DestroyedValue, 14463 EvalInfo::EvaluatingDeclKind::Dtor); 14464 Info.InConstantContext = true; 14465 14466 SourceLocation DeclLoc = getLocation(); 14467 QualType DeclTy = getType(); 14468 14469 LValue LVal; 14470 LVal.set(this); 14471 14472 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) || 14473 EStatus.HasSideEffects) 14474 return false; 14475 14476 if (!Info.discardCleanups()) 14477 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14478 14479 ensureEvaluatedStmt()->HasConstantDestruction = true; 14480 return true; 14481 } 14482 14483 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14484 /// constant folded, but discard the result. 14485 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14486 assert(!isValueDependent() && 14487 "Expression evaluator can't be called on a dependent expression."); 14488 14489 EvalResult Result; 14490 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14491 !hasUnacceptableSideEffect(Result, SEK); 14492 } 14493 14494 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14495 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14496 assert(!isValueDependent() && 14497 "Expression evaluator can't be called on a dependent expression."); 14498 14499 EvalResult EVResult; 14500 EVResult.Diag = Diag; 14501 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14502 Info.InConstantContext = true; 14503 14504 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14505 (void)Result; 14506 assert(Result && "Could not evaluate expression"); 14507 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14508 14509 return EVResult.Val.getInt(); 14510 } 14511 14512 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14513 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14514 assert(!isValueDependent() && 14515 "Expression evaluator can't be called on a dependent expression."); 14516 14517 EvalResult EVResult; 14518 EVResult.Diag = Diag; 14519 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14520 Info.InConstantContext = true; 14521 Info.CheckingForUndefinedBehavior = true; 14522 14523 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 14524 (void)Result; 14525 assert(Result && "Could not evaluate expression"); 14526 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14527 14528 return EVResult.Val.getInt(); 14529 } 14530 14531 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 14532 assert(!isValueDependent() && 14533 "Expression evaluator can't be called on a dependent expression."); 14534 14535 bool IsConst; 14536 EvalResult EVResult; 14537 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 14538 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14539 Info.CheckingForUndefinedBehavior = true; 14540 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 14541 } 14542 } 14543 14544 bool Expr::EvalResult::isGlobalLValue() const { 14545 assert(Val.isLValue()); 14546 return IsGlobalLValue(Val.getLValueBase()); 14547 } 14548 14549 14550 /// isIntegerConstantExpr - this recursive routine will test if an expression is 14551 /// an integer constant expression. 14552 14553 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 14554 /// comma, etc 14555 14556 // CheckICE - This function does the fundamental ICE checking: the returned 14557 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 14558 // and a (possibly null) SourceLocation indicating the location of the problem. 14559 // 14560 // Note that to reduce code duplication, this helper does no evaluation 14561 // itself; the caller checks whether the expression is evaluatable, and 14562 // in the rare cases where CheckICE actually cares about the evaluated 14563 // value, it calls into Evaluate. 14564 14565 namespace { 14566 14567 enum ICEKind { 14568 /// This expression is an ICE. 14569 IK_ICE, 14570 /// This expression is not an ICE, but if it isn't evaluated, it's 14571 /// a legal subexpression for an ICE. This return value is used to handle 14572 /// the comma operator in C99 mode, and non-constant subexpressions. 14573 IK_ICEIfUnevaluated, 14574 /// This expression is not an ICE, and is not a legal subexpression for one. 14575 IK_NotICE 14576 }; 14577 14578 struct ICEDiag { 14579 ICEKind Kind; 14580 SourceLocation Loc; 14581 14582 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 14583 }; 14584 14585 } 14586 14587 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 14588 14589 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 14590 14591 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 14592 Expr::EvalResult EVResult; 14593 Expr::EvalStatus Status; 14594 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 14595 14596 Info.InConstantContext = true; 14597 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 14598 !EVResult.Val.isInt()) 14599 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14600 14601 return NoDiag(); 14602 } 14603 14604 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 14605 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 14606 if (!E->getType()->isIntegralOrEnumerationType()) 14607 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14608 14609 switch (E->getStmtClass()) { 14610 #define ABSTRACT_STMT(Node) 14611 #define STMT(Node, Base) case Expr::Node##Class: 14612 #define EXPR(Node, Base) 14613 #include "clang/AST/StmtNodes.inc" 14614 case Expr::PredefinedExprClass: 14615 case Expr::FloatingLiteralClass: 14616 case Expr::ImaginaryLiteralClass: 14617 case Expr::StringLiteralClass: 14618 case Expr::ArraySubscriptExprClass: 14619 case Expr::MatrixSubscriptExprClass: 14620 case Expr::OMPArraySectionExprClass: 14621 case Expr::OMPArrayShapingExprClass: 14622 case Expr::OMPIteratorExprClass: 14623 case Expr::MemberExprClass: 14624 case Expr::CompoundAssignOperatorClass: 14625 case Expr::CompoundLiteralExprClass: 14626 case Expr::ExtVectorElementExprClass: 14627 case Expr::DesignatedInitExprClass: 14628 case Expr::ArrayInitLoopExprClass: 14629 case Expr::ArrayInitIndexExprClass: 14630 case Expr::NoInitExprClass: 14631 case Expr::DesignatedInitUpdateExprClass: 14632 case Expr::ImplicitValueInitExprClass: 14633 case Expr::ParenListExprClass: 14634 case Expr::VAArgExprClass: 14635 case Expr::AddrLabelExprClass: 14636 case Expr::StmtExprClass: 14637 case Expr::CXXMemberCallExprClass: 14638 case Expr::CUDAKernelCallExprClass: 14639 case Expr::CXXAddrspaceCastExprClass: 14640 case Expr::CXXDynamicCastExprClass: 14641 case Expr::CXXTypeidExprClass: 14642 case Expr::CXXUuidofExprClass: 14643 case Expr::MSPropertyRefExprClass: 14644 case Expr::MSPropertySubscriptExprClass: 14645 case Expr::CXXNullPtrLiteralExprClass: 14646 case Expr::UserDefinedLiteralClass: 14647 case Expr::CXXThisExprClass: 14648 case Expr::CXXThrowExprClass: 14649 case Expr::CXXNewExprClass: 14650 case Expr::CXXDeleteExprClass: 14651 case Expr::CXXPseudoDestructorExprClass: 14652 case Expr::UnresolvedLookupExprClass: 14653 case Expr::TypoExprClass: 14654 case Expr::RecoveryExprClass: 14655 case Expr::DependentScopeDeclRefExprClass: 14656 case Expr::CXXConstructExprClass: 14657 case Expr::CXXInheritedCtorInitExprClass: 14658 case Expr::CXXStdInitializerListExprClass: 14659 case Expr::CXXBindTemporaryExprClass: 14660 case Expr::ExprWithCleanupsClass: 14661 case Expr::CXXTemporaryObjectExprClass: 14662 case Expr::CXXUnresolvedConstructExprClass: 14663 case Expr::CXXDependentScopeMemberExprClass: 14664 case Expr::UnresolvedMemberExprClass: 14665 case Expr::ObjCStringLiteralClass: 14666 case Expr::ObjCBoxedExprClass: 14667 case Expr::ObjCArrayLiteralClass: 14668 case Expr::ObjCDictionaryLiteralClass: 14669 case Expr::ObjCEncodeExprClass: 14670 case Expr::ObjCMessageExprClass: 14671 case Expr::ObjCSelectorExprClass: 14672 case Expr::ObjCProtocolExprClass: 14673 case Expr::ObjCIvarRefExprClass: 14674 case Expr::ObjCPropertyRefExprClass: 14675 case Expr::ObjCSubscriptRefExprClass: 14676 case Expr::ObjCIsaExprClass: 14677 case Expr::ObjCAvailabilityCheckExprClass: 14678 case Expr::ShuffleVectorExprClass: 14679 case Expr::ConvertVectorExprClass: 14680 case Expr::BlockExprClass: 14681 case Expr::NoStmtClass: 14682 case Expr::OpaqueValueExprClass: 14683 case Expr::PackExpansionExprClass: 14684 case Expr::SubstNonTypeTemplateParmPackExprClass: 14685 case Expr::FunctionParmPackExprClass: 14686 case Expr::AsTypeExprClass: 14687 case Expr::ObjCIndirectCopyRestoreExprClass: 14688 case Expr::MaterializeTemporaryExprClass: 14689 case Expr::PseudoObjectExprClass: 14690 case Expr::AtomicExprClass: 14691 case Expr::LambdaExprClass: 14692 case Expr::CXXFoldExprClass: 14693 case Expr::CoawaitExprClass: 14694 case Expr::DependentCoawaitExprClass: 14695 case Expr::CoyieldExprClass: 14696 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14697 14698 case Expr::InitListExprClass: { 14699 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 14700 // form "T x = { a };" is equivalent to "T x = a;". 14701 // Unless we're initializing a reference, T is a scalar as it is known to be 14702 // of integral or enumeration type. 14703 if (E->isRValue()) 14704 if (cast<InitListExpr>(E)->getNumInits() == 1) 14705 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 14706 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14707 } 14708 14709 case Expr::SizeOfPackExprClass: 14710 case Expr::GNUNullExprClass: 14711 case Expr::SourceLocExprClass: 14712 return NoDiag(); 14713 14714 case Expr::SubstNonTypeTemplateParmExprClass: 14715 return 14716 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 14717 14718 case Expr::ConstantExprClass: 14719 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 14720 14721 case Expr::ParenExprClass: 14722 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 14723 case Expr::GenericSelectionExprClass: 14724 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 14725 case Expr::IntegerLiteralClass: 14726 case Expr::FixedPointLiteralClass: 14727 case Expr::CharacterLiteralClass: 14728 case Expr::ObjCBoolLiteralExprClass: 14729 case Expr::CXXBoolLiteralExprClass: 14730 case Expr::CXXScalarValueInitExprClass: 14731 case Expr::TypeTraitExprClass: 14732 case Expr::ConceptSpecializationExprClass: 14733 case Expr::RequiresExprClass: 14734 case Expr::ArrayTypeTraitExprClass: 14735 case Expr::ExpressionTraitExprClass: 14736 case Expr::CXXNoexceptExprClass: 14737 return NoDiag(); 14738 case Expr::CallExprClass: 14739 case Expr::CXXOperatorCallExprClass: { 14740 // C99 6.6/3 allows function calls within unevaluated subexpressions of 14741 // constant expressions, but they can never be ICEs because an ICE cannot 14742 // contain an operand of (pointer to) function type. 14743 const CallExpr *CE = cast<CallExpr>(E); 14744 if (CE->getBuiltinCallee()) 14745 return CheckEvalInICE(E, Ctx); 14746 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14747 } 14748 case Expr::CXXRewrittenBinaryOperatorClass: 14749 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 14750 Ctx); 14751 case Expr::DeclRefExprClass: { 14752 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 14753 return NoDiag(); 14754 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 14755 if (Ctx.getLangOpts().CPlusPlus && 14756 D && IsConstNonVolatile(D->getType())) { 14757 // Parameter variables are never constants. Without this check, 14758 // getAnyInitializer() can find a default argument, which leads 14759 // to chaos. 14760 if (isa<ParmVarDecl>(D)) 14761 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14762 14763 // C++ 7.1.5.1p2 14764 // A variable of non-volatile const-qualified integral or enumeration 14765 // type initialized by an ICE can be used in ICEs. 14766 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 14767 if (!Dcl->getType()->isIntegralOrEnumerationType()) 14768 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14769 14770 const VarDecl *VD; 14771 // Look for a declaration of this variable that has an initializer, and 14772 // check whether it is an ICE. 14773 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 14774 return NoDiag(); 14775 else 14776 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14777 } 14778 } 14779 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14780 } 14781 case Expr::UnaryOperatorClass: { 14782 const UnaryOperator *Exp = cast<UnaryOperator>(E); 14783 switch (Exp->getOpcode()) { 14784 case UO_PostInc: 14785 case UO_PostDec: 14786 case UO_PreInc: 14787 case UO_PreDec: 14788 case UO_AddrOf: 14789 case UO_Deref: 14790 case UO_Coawait: 14791 // C99 6.6/3 allows increment and decrement within unevaluated 14792 // subexpressions of constant expressions, but they can never be ICEs 14793 // because an ICE cannot contain an lvalue operand. 14794 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14795 case UO_Extension: 14796 case UO_LNot: 14797 case UO_Plus: 14798 case UO_Minus: 14799 case UO_Not: 14800 case UO_Real: 14801 case UO_Imag: 14802 return CheckICE(Exp->getSubExpr(), Ctx); 14803 } 14804 llvm_unreachable("invalid unary operator class"); 14805 } 14806 case Expr::OffsetOfExprClass: { 14807 // Note that per C99, offsetof must be an ICE. And AFAIK, using 14808 // EvaluateAsRValue matches the proposed gcc behavior for cases like 14809 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 14810 // compliance: we should warn earlier for offsetof expressions with 14811 // array subscripts that aren't ICEs, and if the array subscripts 14812 // are ICEs, the value of the offsetof must be an integer constant. 14813 return CheckEvalInICE(E, Ctx); 14814 } 14815 case Expr::UnaryExprOrTypeTraitExprClass: { 14816 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 14817 if ((Exp->getKind() == UETT_SizeOf) && 14818 Exp->getTypeOfArgument()->isVariableArrayType()) 14819 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14820 return NoDiag(); 14821 } 14822 case Expr::BinaryOperatorClass: { 14823 const BinaryOperator *Exp = cast<BinaryOperator>(E); 14824 switch (Exp->getOpcode()) { 14825 case BO_PtrMemD: 14826 case BO_PtrMemI: 14827 case BO_Assign: 14828 case BO_MulAssign: 14829 case BO_DivAssign: 14830 case BO_RemAssign: 14831 case BO_AddAssign: 14832 case BO_SubAssign: 14833 case BO_ShlAssign: 14834 case BO_ShrAssign: 14835 case BO_AndAssign: 14836 case BO_XorAssign: 14837 case BO_OrAssign: 14838 // C99 6.6/3 allows assignments within unevaluated subexpressions of 14839 // constant expressions, but they can never be ICEs because an ICE cannot 14840 // contain an lvalue operand. 14841 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14842 14843 case BO_Mul: 14844 case BO_Div: 14845 case BO_Rem: 14846 case BO_Add: 14847 case BO_Sub: 14848 case BO_Shl: 14849 case BO_Shr: 14850 case BO_LT: 14851 case BO_GT: 14852 case BO_LE: 14853 case BO_GE: 14854 case BO_EQ: 14855 case BO_NE: 14856 case BO_And: 14857 case BO_Xor: 14858 case BO_Or: 14859 case BO_Comma: 14860 case BO_Cmp: { 14861 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14862 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14863 if (Exp->getOpcode() == BO_Div || 14864 Exp->getOpcode() == BO_Rem) { 14865 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 14866 // we don't evaluate one. 14867 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 14868 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 14869 if (REval == 0) 14870 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14871 if (REval.isSigned() && REval.isAllOnesValue()) { 14872 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 14873 if (LEval.isMinSignedValue()) 14874 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14875 } 14876 } 14877 } 14878 if (Exp->getOpcode() == BO_Comma) { 14879 if (Ctx.getLangOpts().C99) { 14880 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 14881 // if it isn't evaluated. 14882 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 14883 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14884 } else { 14885 // In both C89 and C++, commas in ICEs are illegal. 14886 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14887 } 14888 } 14889 return Worst(LHSResult, RHSResult); 14890 } 14891 case BO_LAnd: 14892 case BO_LOr: { 14893 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14894 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14895 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 14896 // Rare case where the RHS has a comma "side-effect"; we need 14897 // to actually check the condition to see whether the side 14898 // with the comma is evaluated. 14899 if ((Exp->getOpcode() == BO_LAnd) != 14900 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 14901 return RHSResult; 14902 return NoDiag(); 14903 } 14904 14905 return Worst(LHSResult, RHSResult); 14906 } 14907 } 14908 llvm_unreachable("invalid binary operator kind"); 14909 } 14910 case Expr::ImplicitCastExprClass: 14911 case Expr::CStyleCastExprClass: 14912 case Expr::CXXFunctionalCastExprClass: 14913 case Expr::CXXStaticCastExprClass: 14914 case Expr::CXXReinterpretCastExprClass: 14915 case Expr::CXXConstCastExprClass: 14916 case Expr::ObjCBridgedCastExprClass: { 14917 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 14918 if (isa<ExplicitCastExpr>(E)) { 14919 if (const FloatingLiteral *FL 14920 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 14921 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 14922 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 14923 APSInt IgnoredVal(DestWidth, !DestSigned); 14924 bool Ignored; 14925 // If the value does not fit in the destination type, the behavior is 14926 // undefined, so we are not required to treat it as a constant 14927 // expression. 14928 if (FL->getValue().convertToInteger(IgnoredVal, 14929 llvm::APFloat::rmTowardZero, 14930 &Ignored) & APFloat::opInvalidOp) 14931 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14932 return NoDiag(); 14933 } 14934 } 14935 switch (cast<CastExpr>(E)->getCastKind()) { 14936 case CK_LValueToRValue: 14937 case CK_AtomicToNonAtomic: 14938 case CK_NonAtomicToAtomic: 14939 case CK_NoOp: 14940 case CK_IntegralToBoolean: 14941 case CK_IntegralCast: 14942 return CheckICE(SubExpr, Ctx); 14943 default: 14944 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14945 } 14946 } 14947 case Expr::BinaryConditionalOperatorClass: { 14948 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 14949 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 14950 if (CommonResult.Kind == IK_NotICE) return CommonResult; 14951 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 14952 if (FalseResult.Kind == IK_NotICE) return FalseResult; 14953 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 14954 if (FalseResult.Kind == IK_ICEIfUnevaluated && 14955 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 14956 return FalseResult; 14957 } 14958 case Expr::ConditionalOperatorClass: { 14959 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 14960 // If the condition (ignoring parens) is a __builtin_constant_p call, 14961 // then only the true side is actually considered in an integer constant 14962 // expression, and it is fully evaluated. This is an important GNU 14963 // extension. See GCC PR38377 for discussion. 14964 if (const CallExpr *CallCE 14965 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 14966 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 14967 return CheckEvalInICE(E, Ctx); 14968 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 14969 if (CondResult.Kind == IK_NotICE) 14970 return CondResult; 14971 14972 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 14973 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 14974 14975 if (TrueResult.Kind == IK_NotICE) 14976 return TrueResult; 14977 if (FalseResult.Kind == IK_NotICE) 14978 return FalseResult; 14979 if (CondResult.Kind == IK_ICEIfUnevaluated) 14980 return CondResult; 14981 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 14982 return NoDiag(); 14983 // Rare case where the diagnostics depend on which side is evaluated 14984 // Note that if we get here, CondResult is 0, and at least one of 14985 // TrueResult and FalseResult is non-zero. 14986 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 14987 return FalseResult; 14988 return TrueResult; 14989 } 14990 case Expr::CXXDefaultArgExprClass: 14991 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 14992 case Expr::CXXDefaultInitExprClass: 14993 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 14994 case Expr::ChooseExprClass: { 14995 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 14996 } 14997 case Expr::BuiltinBitCastExprClass: { 14998 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 14999 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15000 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15001 } 15002 } 15003 15004 llvm_unreachable("Invalid StmtClass!"); 15005 } 15006 15007 /// Evaluate an expression as a C++11 integral constant expression. 15008 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15009 const Expr *E, 15010 llvm::APSInt *Value, 15011 SourceLocation *Loc) { 15012 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15013 if (Loc) *Loc = E->getExprLoc(); 15014 return false; 15015 } 15016 15017 APValue Result; 15018 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15019 return false; 15020 15021 if (!Result.isInt()) { 15022 if (Loc) *Loc = E->getExprLoc(); 15023 return false; 15024 } 15025 15026 if (Value) *Value = Result.getInt(); 15027 return true; 15028 } 15029 15030 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15031 SourceLocation *Loc) const { 15032 assert(!isValueDependent() && 15033 "Expression evaluator can't be called on a dependent expression."); 15034 15035 if (Ctx.getLangOpts().CPlusPlus11) 15036 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15037 15038 ICEDiag D = CheckICE(this, Ctx); 15039 if (D.Kind != IK_ICE) { 15040 if (Loc) *Loc = D.Loc; 15041 return false; 15042 } 15043 return true; 15044 } 15045 15046 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15047 SourceLocation *Loc, 15048 bool isEvaluated) const { 15049 assert(!isValueDependent() && 15050 "Expression evaluator can't be called on a dependent expression."); 15051 15052 APSInt Value; 15053 15054 if (Ctx.getLangOpts().CPlusPlus11) { 15055 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15056 return Value; 15057 return None; 15058 } 15059 15060 if (!isIntegerConstantExpr(Ctx, Loc)) 15061 return None; 15062 15063 // The only possible side-effects here are due to UB discovered in the 15064 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15065 // required to treat the expression as an ICE, so we produce the folded 15066 // value. 15067 EvalResult ExprResult; 15068 Expr::EvalStatus Status; 15069 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15070 Info.InConstantContext = true; 15071 15072 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15073 llvm_unreachable("ICE cannot be evaluated!"); 15074 15075 return ExprResult.Val.getInt(); 15076 } 15077 15078 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15079 assert(!isValueDependent() && 15080 "Expression evaluator can't be called on a dependent expression."); 15081 15082 return CheckICE(this, Ctx).Kind == IK_ICE; 15083 } 15084 15085 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15086 SourceLocation *Loc) const { 15087 assert(!isValueDependent() && 15088 "Expression evaluator can't be called on a dependent expression."); 15089 15090 // We support this checking in C++98 mode in order to diagnose compatibility 15091 // issues. 15092 assert(Ctx.getLangOpts().CPlusPlus); 15093 15094 // Build evaluation settings. 15095 Expr::EvalStatus Status; 15096 SmallVector<PartialDiagnosticAt, 8> Diags; 15097 Status.Diag = &Diags; 15098 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15099 15100 APValue Scratch; 15101 bool IsConstExpr = 15102 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15103 // FIXME: We don't produce a diagnostic for this, but the callers that 15104 // call us on arbitrary full-expressions should generally not care. 15105 Info.discardCleanups() && !Status.HasSideEffects; 15106 15107 if (!Diags.empty()) { 15108 IsConstExpr = false; 15109 if (Loc) *Loc = Diags[0].first; 15110 } else if (!IsConstExpr) { 15111 // FIXME: This shouldn't happen. 15112 if (Loc) *Loc = getExprLoc(); 15113 } 15114 15115 return IsConstExpr; 15116 } 15117 15118 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15119 const FunctionDecl *Callee, 15120 ArrayRef<const Expr*> Args, 15121 const Expr *This) const { 15122 assert(!isValueDependent() && 15123 "Expression evaluator can't be called on a dependent expression."); 15124 15125 Expr::EvalStatus Status; 15126 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15127 Info.InConstantContext = true; 15128 15129 LValue ThisVal; 15130 const LValue *ThisPtr = nullptr; 15131 if (This) { 15132 #ifndef NDEBUG 15133 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15134 assert(MD && "Don't provide `this` for non-methods."); 15135 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15136 #endif 15137 if (!This->isValueDependent() && 15138 EvaluateObjectArgument(Info, This, ThisVal) && 15139 !Info.EvalStatus.HasSideEffects) 15140 ThisPtr = &ThisVal; 15141 15142 // Ignore any side-effects from a failed evaluation. This is safe because 15143 // they can't interfere with any other argument evaluation. 15144 Info.EvalStatus.HasSideEffects = false; 15145 } 15146 15147 ArgVector ArgValues(Args.size()); 15148 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15149 I != E; ++I) { 15150 if ((*I)->isValueDependent() || 15151 !Evaluate(ArgValues[I - Args.begin()], Info, *I) || 15152 Info.EvalStatus.HasSideEffects) 15153 // If evaluation fails, throw away the argument entirely. 15154 ArgValues[I - Args.begin()] = APValue(); 15155 15156 // Ignore any side-effects from a failed evaluation. This is safe because 15157 // they can't interfere with any other argument evaluation. 15158 Info.EvalStatus.HasSideEffects = false; 15159 } 15160 15161 // Parameter cleanups happen in the caller and are not part of this 15162 // evaluation. 15163 Info.discardCleanups(); 15164 Info.EvalStatus.HasSideEffects = false; 15165 15166 // Build fake call to Callee. 15167 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 15168 ArgValues.data()); 15169 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15170 FullExpressionRAII Scope(Info); 15171 return Evaluate(Value, Info, this) && Scope.destroy() && 15172 !Info.EvalStatus.HasSideEffects; 15173 } 15174 15175 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15176 SmallVectorImpl< 15177 PartialDiagnosticAt> &Diags) { 15178 // FIXME: It would be useful to check constexpr function templates, but at the 15179 // moment the constant expression evaluator cannot cope with the non-rigorous 15180 // ASTs which we build for dependent expressions. 15181 if (FD->isDependentContext()) 15182 return true; 15183 15184 // Bail out if a constexpr constructor has an initializer that contains an 15185 // error. We deliberately don't produce a diagnostic, as we have produced a 15186 // relevant diagnostic when parsing the error initializer. 15187 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 15188 for (const auto *InitExpr : Ctor->inits()) { 15189 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 15190 return false; 15191 } 15192 } 15193 Expr::EvalStatus Status; 15194 Status.Diag = &Diags; 15195 15196 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15197 Info.InConstantContext = true; 15198 Info.CheckingPotentialConstantExpression = true; 15199 15200 // The constexpr VM attempts to compile all methods to bytecode here. 15201 if (Info.EnableNewConstInterp) { 15202 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15203 return Diags.empty(); 15204 } 15205 15206 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15207 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15208 15209 // Fabricate an arbitrary expression on the stack and pretend that it 15210 // is a temporary being used as the 'this' pointer. 15211 LValue This; 15212 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15213 This.set({&VIE, Info.CurrentCall->Index}); 15214 15215 ArrayRef<const Expr*> Args; 15216 15217 APValue Scratch; 15218 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15219 // Evaluate the call as a constant initializer, to allow the construction 15220 // of objects of non-literal types. 15221 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15222 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15223 } else { 15224 SourceLocation Loc = FD->getLocation(); 15225 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15226 Args, FD->getBody(), Info, Scratch, nullptr); 15227 } 15228 15229 return Diags.empty(); 15230 } 15231 15232 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15233 const FunctionDecl *FD, 15234 SmallVectorImpl< 15235 PartialDiagnosticAt> &Diags) { 15236 assert(!E->isValueDependent() && 15237 "Expression evaluator can't be called on a dependent expression."); 15238 15239 Expr::EvalStatus Status; 15240 Status.Diag = &Diags; 15241 15242 EvalInfo Info(FD->getASTContext(), Status, 15243 EvalInfo::EM_ConstantExpressionUnevaluated); 15244 Info.InConstantContext = true; 15245 Info.CheckingPotentialConstantExpression = true; 15246 15247 // Fabricate a call stack frame to give the arguments a plausible cover story. 15248 ArrayRef<const Expr*> Args; 15249 ArgVector ArgValues(0); 15250 bool Success = EvaluateArgs(Args, ArgValues, Info, FD); 15251 (void)Success; 15252 assert(Success && 15253 "Failed to set up arguments for potential constant evaluation"); 15254 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 15255 15256 APValue ResultScratch; 15257 Evaluate(ResultScratch, Info, E); 15258 return Diags.empty(); 15259 } 15260 15261 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15262 unsigned Type) const { 15263 if (!getType()->isPointerType()) 15264 return false; 15265 15266 Expr::EvalStatus Status; 15267 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15268 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15269 } 15270