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 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty); 6631 SmallVector<unsigned char, 8> Bytes(Width.getQuantity()); 6632 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity()); 6633 Buffer.writeObject(Offset, Bytes); 6634 return true; 6635 } 6636 6637 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6638 APSInt AsInt(Val.bitcastToAPInt()); 6639 return visitInt(AsInt, Ty, Offset); 6640 } 6641 6642 public: 6643 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6644 const CastExpr *BCE) { 6645 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6646 APValueToBufferConverter Converter(Info, DstSize, BCE); 6647 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6648 return None; 6649 return Converter.Buffer; 6650 } 6651 }; 6652 6653 /// Write an BitCastBuffer into an APValue. 6654 class BufferToAPValueConverter { 6655 EvalInfo &Info; 6656 const BitCastBuffer &Buffer; 6657 const CastExpr *BCE; 6658 6659 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6660 const CastExpr *BCE) 6661 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6662 6663 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6664 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6665 // Ideally this will be unreachable. 6666 llvm::NoneType unsupportedType(QualType Ty) { 6667 Info.FFDiag(BCE->getBeginLoc(), 6668 diag::note_constexpr_bit_cast_unsupported_type) 6669 << Ty; 6670 return None; 6671 } 6672 6673 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6674 const EnumType *EnumSugar = nullptr) { 6675 if (T->isNullPtrType()) { 6676 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6677 return APValue((Expr *)nullptr, 6678 /*Offset=*/CharUnits::fromQuantity(NullValue), 6679 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6680 } 6681 6682 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6683 SmallVector<uint8_t, 8> Bytes; 6684 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6685 // If this is std::byte or unsigned char, then its okay to store an 6686 // indeterminate value. 6687 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 6688 bool IsUChar = 6689 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 6690 T->isSpecificBuiltinType(BuiltinType::Char_U)); 6691 if (!IsStdByte && !IsUChar) { 6692 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 6693 Info.FFDiag(BCE->getExprLoc(), 6694 diag::note_constexpr_bit_cast_indet_dest) 6695 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 6696 return None; 6697 } 6698 6699 return APValue::IndeterminateValue(); 6700 } 6701 6702 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 6703 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 6704 6705 if (T->isIntegralOrEnumerationType()) { 6706 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 6707 return APValue(Val); 6708 } 6709 6710 if (T->isRealFloatingType()) { 6711 const llvm::fltSemantics &Semantics = 6712 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6713 return APValue(APFloat(Semantics, Val)); 6714 } 6715 6716 return unsupportedType(QualType(T, 0)); 6717 } 6718 6719 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 6720 const RecordDecl *RD = RTy->getAsRecordDecl(); 6721 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6722 6723 unsigned NumBases = 0; 6724 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6725 NumBases = CXXRD->getNumBases(); 6726 6727 APValue ResultVal(APValue::UninitStruct(), NumBases, 6728 std::distance(RD->field_begin(), RD->field_end())); 6729 6730 // Visit the base classes. 6731 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6732 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6733 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6734 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6735 if (BaseDecl->isEmpty() || 6736 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 6737 continue; 6738 6739 Optional<APValue> SubObj = visitType( 6740 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 6741 if (!SubObj) 6742 return None; 6743 ResultVal.getStructBase(I) = *SubObj; 6744 } 6745 } 6746 6747 // Visit the fields. 6748 unsigned FieldIdx = 0; 6749 for (FieldDecl *FD : RD->fields()) { 6750 // FIXME: We don't currently support bit-fields. A lot of the logic for 6751 // this is in CodeGen, so we need to factor it around. 6752 if (FD->isBitField()) { 6753 Info.FFDiag(BCE->getBeginLoc(), 6754 diag::note_constexpr_bit_cast_unsupported_bitfield); 6755 return None; 6756 } 6757 6758 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6759 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 6760 6761 CharUnits FieldOffset = 6762 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 6763 Offset; 6764 QualType FieldTy = FD->getType(); 6765 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 6766 if (!SubObj) 6767 return None; 6768 ResultVal.getStructField(FieldIdx) = *SubObj; 6769 ++FieldIdx; 6770 } 6771 6772 return ResultVal; 6773 } 6774 6775 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 6776 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 6777 assert(!RepresentationType.isNull() && 6778 "enum forward decl should be caught by Sema"); 6779 const auto *AsBuiltin = 6780 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 6781 // Recurse into the underlying type. Treat std::byte transparently as 6782 // unsigned char. 6783 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 6784 } 6785 6786 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 6787 size_t Size = Ty->getSize().getLimitedValue(); 6788 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 6789 6790 APValue ArrayValue(APValue::UninitArray(), Size, Size); 6791 for (size_t I = 0; I != Size; ++I) { 6792 Optional<APValue> ElementValue = 6793 visitType(Ty->getElementType(), Offset + I * ElementWidth); 6794 if (!ElementValue) 6795 return None; 6796 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 6797 } 6798 6799 return ArrayValue; 6800 } 6801 6802 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 6803 return unsupportedType(QualType(Ty, 0)); 6804 } 6805 6806 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 6807 QualType Can = Ty.getCanonicalType(); 6808 6809 switch (Can->getTypeClass()) { 6810 #define TYPE(Class, Base) \ 6811 case Type::Class: \ 6812 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 6813 #define ABSTRACT_TYPE(Class, Base) 6814 #define NON_CANONICAL_TYPE(Class, Base) \ 6815 case Type::Class: \ 6816 llvm_unreachable("non-canonical type should be impossible!"); 6817 #define DEPENDENT_TYPE(Class, Base) \ 6818 case Type::Class: \ 6819 llvm_unreachable( \ 6820 "dependent types aren't supported in the constant evaluator!"); 6821 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 6822 case Type::Class: \ 6823 llvm_unreachable("either dependent or not canonical!"); 6824 #include "clang/AST/TypeNodes.inc" 6825 } 6826 llvm_unreachable("Unhandled Type::TypeClass"); 6827 } 6828 6829 public: 6830 // Pull out a full value of type DstType. 6831 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 6832 const CastExpr *BCE) { 6833 BufferToAPValueConverter Converter(Info, Buffer, BCE); 6834 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 6835 } 6836 }; 6837 6838 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 6839 QualType Ty, EvalInfo *Info, 6840 const ASTContext &Ctx, 6841 bool CheckingDest) { 6842 Ty = Ty.getCanonicalType(); 6843 6844 auto diag = [&](int Reason) { 6845 if (Info) 6846 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 6847 << CheckingDest << (Reason == 4) << Reason; 6848 return false; 6849 }; 6850 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 6851 if (Info) 6852 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 6853 << NoteTy << Construct << Ty; 6854 return false; 6855 }; 6856 6857 if (Ty->isUnionType()) 6858 return diag(0); 6859 if (Ty->isPointerType()) 6860 return diag(1); 6861 if (Ty->isMemberPointerType()) 6862 return diag(2); 6863 if (Ty.isVolatileQualified()) 6864 return diag(3); 6865 6866 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 6867 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 6868 for (CXXBaseSpecifier &BS : CXXRD->bases()) 6869 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 6870 CheckingDest)) 6871 return note(1, BS.getType(), BS.getBeginLoc()); 6872 } 6873 for (FieldDecl *FD : Record->fields()) { 6874 if (FD->getType()->isReferenceType()) 6875 return diag(4); 6876 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 6877 CheckingDest)) 6878 return note(0, FD->getType(), FD->getBeginLoc()); 6879 } 6880 } 6881 6882 if (Ty->isArrayType() && 6883 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 6884 Info, Ctx, CheckingDest)) 6885 return false; 6886 6887 return true; 6888 } 6889 6890 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 6891 const ASTContext &Ctx, 6892 const CastExpr *BCE) { 6893 bool DestOK = checkBitCastConstexprEligibilityType( 6894 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 6895 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 6896 BCE->getBeginLoc(), 6897 BCE->getSubExpr()->getType(), Info, Ctx, false); 6898 return SourceOK; 6899 } 6900 6901 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 6902 APValue &SourceValue, 6903 const CastExpr *BCE) { 6904 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 6905 "no host or target supports non 8-bit chars"); 6906 assert(SourceValue.isLValue() && 6907 "LValueToRValueBitcast requires an lvalue operand!"); 6908 6909 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 6910 return false; 6911 6912 LValue SourceLValue; 6913 APValue SourceRValue; 6914 SourceLValue.setFrom(Info.Ctx, SourceValue); 6915 if (!handleLValueToRValueConversion( 6916 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 6917 SourceRValue, /*WantObjectRepresentation=*/true)) 6918 return false; 6919 6920 // Read out SourceValue into a char buffer. 6921 Optional<BitCastBuffer> Buffer = 6922 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 6923 if (!Buffer) 6924 return false; 6925 6926 // Write out the buffer into a new APValue. 6927 Optional<APValue> MaybeDestValue = 6928 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 6929 if (!MaybeDestValue) 6930 return false; 6931 6932 DestValue = std::move(*MaybeDestValue); 6933 return true; 6934 } 6935 6936 template <class Derived> 6937 class ExprEvaluatorBase 6938 : public ConstStmtVisitor<Derived, bool> { 6939 private: 6940 Derived &getDerived() { return static_cast<Derived&>(*this); } 6941 bool DerivedSuccess(const APValue &V, const Expr *E) { 6942 return getDerived().Success(V, E); 6943 } 6944 bool DerivedZeroInitialization(const Expr *E) { 6945 return getDerived().ZeroInitialization(E); 6946 } 6947 6948 // Check whether a conditional operator with a non-constant condition is a 6949 // potential constant expression. If neither arm is a potential constant 6950 // expression, then the conditional operator is not either. 6951 template<typename ConditionalOperator> 6952 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 6953 assert(Info.checkingPotentialConstantExpression()); 6954 6955 // Speculatively evaluate both arms. 6956 SmallVector<PartialDiagnosticAt, 8> Diag; 6957 { 6958 SpeculativeEvaluationRAII Speculate(Info, &Diag); 6959 StmtVisitorTy::Visit(E->getFalseExpr()); 6960 if (Diag.empty()) 6961 return; 6962 } 6963 6964 { 6965 SpeculativeEvaluationRAII Speculate(Info, &Diag); 6966 Diag.clear(); 6967 StmtVisitorTy::Visit(E->getTrueExpr()); 6968 if (Diag.empty()) 6969 return; 6970 } 6971 6972 Error(E, diag::note_constexpr_conditional_never_const); 6973 } 6974 6975 6976 template<typename ConditionalOperator> 6977 bool HandleConditionalOperator(const ConditionalOperator *E) { 6978 bool BoolResult; 6979 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 6980 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 6981 CheckPotentialConstantConditional(E); 6982 return false; 6983 } 6984 if (Info.noteFailure()) { 6985 StmtVisitorTy::Visit(E->getTrueExpr()); 6986 StmtVisitorTy::Visit(E->getFalseExpr()); 6987 } 6988 return false; 6989 } 6990 6991 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 6992 return StmtVisitorTy::Visit(EvalExpr); 6993 } 6994 6995 protected: 6996 EvalInfo &Info; 6997 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 6998 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 6999 7000 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7001 return Info.CCEDiag(E, D); 7002 } 7003 7004 bool ZeroInitialization(const Expr *E) { return Error(E); } 7005 7006 public: 7007 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7008 7009 EvalInfo &getEvalInfo() { return Info; } 7010 7011 /// Report an evaluation error. This should only be called when an error is 7012 /// first discovered. When propagating an error, just return false. 7013 bool Error(const Expr *E, diag::kind D) { 7014 Info.FFDiag(E, D); 7015 return false; 7016 } 7017 bool Error(const Expr *E) { 7018 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7019 } 7020 7021 bool VisitStmt(const Stmt *) { 7022 llvm_unreachable("Expression evaluator should not be called on stmts"); 7023 } 7024 bool VisitExpr(const Expr *E) { 7025 return Error(E); 7026 } 7027 7028 bool VisitConstantExpr(const ConstantExpr *E) { 7029 if (E->hasAPValueResult()) 7030 return DerivedSuccess(E->getAPValueResult(), E); 7031 7032 return StmtVisitorTy::Visit(E->getSubExpr()); 7033 } 7034 7035 bool VisitParenExpr(const ParenExpr *E) 7036 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7037 bool VisitUnaryExtension(const UnaryOperator *E) 7038 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7039 bool VisitUnaryPlus(const UnaryOperator *E) 7040 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7041 bool VisitChooseExpr(const ChooseExpr *E) 7042 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7043 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7044 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7045 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7046 { return StmtVisitorTy::Visit(E->getReplacement()); } 7047 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7048 TempVersionRAII RAII(*Info.CurrentCall); 7049 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7050 return StmtVisitorTy::Visit(E->getExpr()); 7051 } 7052 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7053 TempVersionRAII RAII(*Info.CurrentCall); 7054 // The initializer may not have been parsed yet, or might be erroneous. 7055 if (!E->getExpr()) 7056 return Error(E); 7057 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7058 return StmtVisitorTy::Visit(E->getExpr()); 7059 } 7060 7061 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7062 FullExpressionRAII Scope(Info); 7063 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7064 } 7065 7066 // Temporaries are registered when created, so we don't care about 7067 // CXXBindTemporaryExpr. 7068 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7069 return StmtVisitorTy::Visit(E->getSubExpr()); 7070 } 7071 7072 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7073 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7074 return static_cast<Derived*>(this)->VisitCastExpr(E); 7075 } 7076 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7077 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7078 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7079 return static_cast<Derived*>(this)->VisitCastExpr(E); 7080 } 7081 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7082 return static_cast<Derived*>(this)->VisitCastExpr(E); 7083 } 7084 7085 bool VisitBinaryOperator(const BinaryOperator *E) { 7086 switch (E->getOpcode()) { 7087 default: 7088 return Error(E); 7089 7090 case BO_Comma: 7091 VisitIgnoredValue(E->getLHS()); 7092 return StmtVisitorTy::Visit(E->getRHS()); 7093 7094 case BO_PtrMemD: 7095 case BO_PtrMemI: { 7096 LValue Obj; 7097 if (!HandleMemberPointerAccess(Info, E, Obj)) 7098 return false; 7099 APValue Result; 7100 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7101 return false; 7102 return DerivedSuccess(Result, E); 7103 } 7104 } 7105 } 7106 7107 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7108 return StmtVisitorTy::Visit(E->getSemanticForm()); 7109 } 7110 7111 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7112 // Evaluate and cache the common expression. We treat it as a temporary, 7113 // even though it's not quite the same thing. 7114 LValue CommonLV; 7115 if (!Evaluate(Info.CurrentCall->createTemporary( 7116 E->getOpaqueValue(), 7117 getStorageType(Info.Ctx, E->getOpaqueValue()), false, 7118 CommonLV), 7119 Info, E->getCommon())) 7120 return false; 7121 7122 return HandleConditionalOperator(E); 7123 } 7124 7125 bool VisitConditionalOperator(const ConditionalOperator *E) { 7126 bool IsBcpCall = false; 7127 // If the condition (ignoring parens) is a __builtin_constant_p call, 7128 // the result is a constant expression if it can be folded without 7129 // side-effects. This is an important GNU extension. See GCC PR38377 7130 // for discussion. 7131 if (const CallExpr *CallCE = 7132 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7133 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7134 IsBcpCall = true; 7135 7136 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7137 // constant expression; we can't check whether it's potentially foldable. 7138 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7139 // it would return 'false' in this mode. 7140 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7141 return false; 7142 7143 FoldConstant Fold(Info, IsBcpCall); 7144 if (!HandleConditionalOperator(E)) { 7145 Fold.keepDiagnostics(); 7146 return false; 7147 } 7148 7149 return true; 7150 } 7151 7152 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7153 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7154 return DerivedSuccess(*Value, E); 7155 7156 const Expr *Source = E->getSourceExpr(); 7157 if (!Source) 7158 return Error(E); 7159 if (Source == E) { // sanity checking. 7160 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7161 return Error(E); 7162 } 7163 return StmtVisitorTy::Visit(Source); 7164 } 7165 7166 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7167 for (const Expr *SemE : E->semantics()) { 7168 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7169 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7170 // result expression: there could be two different LValues that would 7171 // refer to the same object in that case, and we can't model that. 7172 if (SemE == E->getResultExpr()) 7173 return Error(E); 7174 7175 // Unique OVEs get evaluated if and when we encounter them when 7176 // emitting the rest of the semantic form, rather than eagerly. 7177 if (OVE->isUnique()) 7178 continue; 7179 7180 LValue LV; 7181 if (!Evaluate(Info.CurrentCall->createTemporary( 7182 OVE, getStorageType(Info.Ctx, OVE), false, LV), 7183 Info, OVE->getSourceExpr())) 7184 return false; 7185 } else if (SemE == E->getResultExpr()) { 7186 if (!StmtVisitorTy::Visit(SemE)) 7187 return false; 7188 } else { 7189 if (!EvaluateIgnoredValue(Info, SemE)) 7190 return false; 7191 } 7192 } 7193 return true; 7194 } 7195 7196 bool VisitCallExpr(const CallExpr *E) { 7197 APValue Result; 7198 if (!handleCallExpr(E, Result, nullptr)) 7199 return false; 7200 return DerivedSuccess(Result, E); 7201 } 7202 7203 bool handleCallExpr(const CallExpr *E, APValue &Result, 7204 const LValue *ResultSlot) { 7205 const Expr *Callee = E->getCallee()->IgnoreParens(); 7206 QualType CalleeType = Callee->getType(); 7207 7208 const FunctionDecl *FD = nullptr; 7209 LValue *This = nullptr, ThisVal; 7210 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7211 bool HasQualifier = false; 7212 7213 // Extract function decl and 'this' pointer from the callee. 7214 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7215 const CXXMethodDecl *Member = nullptr; 7216 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7217 // Explicit bound member calls, such as x.f() or p->g(); 7218 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7219 return false; 7220 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7221 if (!Member) 7222 return Error(Callee); 7223 This = &ThisVal; 7224 HasQualifier = ME->hasQualifier(); 7225 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7226 // Indirect bound member calls ('.*' or '->*'). 7227 const ValueDecl *D = 7228 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7229 if (!D) 7230 return false; 7231 Member = dyn_cast<CXXMethodDecl>(D); 7232 if (!Member) 7233 return Error(Callee); 7234 This = &ThisVal; 7235 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7236 if (!Info.getLangOpts().CPlusPlus20) 7237 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7238 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7239 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7240 } else 7241 return Error(Callee); 7242 FD = Member; 7243 } else if (CalleeType->isFunctionPointerType()) { 7244 LValue Call; 7245 if (!EvaluatePointer(Callee, Call, Info)) 7246 return false; 7247 7248 if (!Call.getLValueOffset().isZero()) 7249 return Error(Callee); 7250 FD = dyn_cast_or_null<FunctionDecl>( 7251 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 7252 if (!FD) 7253 return Error(Callee); 7254 // Don't call function pointers which have been cast to some other type. 7255 // Per DR (no number yet), the caller and callee can differ in noexcept. 7256 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7257 CalleeType->getPointeeType(), FD->getType())) { 7258 return Error(E); 7259 } 7260 7261 // Overloaded operator calls to member functions are represented as normal 7262 // calls with '*this' as the first argument. 7263 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7264 if (MD && !MD->isStatic()) { 7265 // FIXME: When selecting an implicit conversion for an overloaded 7266 // operator delete, we sometimes try to evaluate calls to conversion 7267 // operators without a 'this' parameter! 7268 if (Args.empty()) 7269 return Error(E); 7270 7271 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7272 return false; 7273 This = &ThisVal; 7274 Args = Args.slice(1); 7275 } else if (MD && MD->isLambdaStaticInvoker()) { 7276 // Map the static invoker for the lambda back to the call operator. 7277 // Conveniently, we don't have to slice out the 'this' argument (as is 7278 // being done for the non-static case), since a static member function 7279 // doesn't have an implicit argument passed in. 7280 const CXXRecordDecl *ClosureClass = MD->getParent(); 7281 assert( 7282 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7283 "Number of captures must be zero for conversion to function-ptr"); 7284 7285 const CXXMethodDecl *LambdaCallOp = 7286 ClosureClass->getLambdaCallOperator(); 7287 7288 // Set 'FD', the function that will be called below, to the call 7289 // operator. If the closure object represents a generic lambda, find 7290 // the corresponding specialization of the call operator. 7291 7292 if (ClosureClass->isGenericLambda()) { 7293 assert(MD->isFunctionTemplateSpecialization() && 7294 "A generic lambda's static-invoker function must be a " 7295 "template specialization"); 7296 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7297 FunctionTemplateDecl *CallOpTemplate = 7298 LambdaCallOp->getDescribedFunctionTemplate(); 7299 void *InsertPos = nullptr; 7300 FunctionDecl *CorrespondingCallOpSpecialization = 7301 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7302 assert(CorrespondingCallOpSpecialization && 7303 "We must always have a function call operator specialization " 7304 "that corresponds to our static invoker specialization"); 7305 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7306 } else 7307 FD = LambdaCallOp; 7308 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7309 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7310 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7311 LValue Ptr; 7312 if (!HandleOperatorNewCall(Info, E, Ptr)) 7313 return false; 7314 Ptr.moveInto(Result); 7315 return true; 7316 } else { 7317 return HandleOperatorDeleteCall(Info, E); 7318 } 7319 } 7320 } else 7321 return Error(E); 7322 7323 SmallVector<QualType, 4> CovariantAdjustmentPath; 7324 if (This) { 7325 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7326 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7327 // Perform virtual dispatch, if necessary. 7328 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7329 CovariantAdjustmentPath); 7330 if (!FD) 7331 return false; 7332 } else { 7333 // Check that the 'this' pointer points to an object of the right type. 7334 // FIXME: If this is an assignment operator call, we may need to change 7335 // the active union member before we check this. 7336 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7337 return false; 7338 } 7339 } 7340 7341 // Destructor calls are different enough that they have their own codepath. 7342 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7343 assert(This && "no 'this' pointer for destructor call"); 7344 return HandleDestruction(Info, E, *This, 7345 Info.Ctx.getRecordType(DD->getParent())); 7346 } 7347 7348 const FunctionDecl *Definition = nullptr; 7349 Stmt *Body = FD->getBody(Definition); 7350 7351 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7352 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 7353 Result, ResultSlot)) 7354 return false; 7355 7356 if (!CovariantAdjustmentPath.empty() && 7357 !HandleCovariantReturnAdjustment(Info, E, Result, 7358 CovariantAdjustmentPath)) 7359 return false; 7360 7361 return true; 7362 } 7363 7364 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7365 return StmtVisitorTy::Visit(E->getInitializer()); 7366 } 7367 bool VisitInitListExpr(const InitListExpr *E) { 7368 if (E->getNumInits() == 0) 7369 return DerivedZeroInitialization(E); 7370 if (E->getNumInits() == 1) 7371 return StmtVisitorTy::Visit(E->getInit(0)); 7372 return Error(E); 7373 } 7374 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7375 return DerivedZeroInitialization(E); 7376 } 7377 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7378 return DerivedZeroInitialization(E); 7379 } 7380 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7381 return DerivedZeroInitialization(E); 7382 } 7383 7384 /// A member expression where the object is a prvalue is itself a prvalue. 7385 bool VisitMemberExpr(const MemberExpr *E) { 7386 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7387 "missing temporary materialization conversion"); 7388 assert(!E->isArrow() && "missing call to bound member function?"); 7389 7390 APValue Val; 7391 if (!Evaluate(Val, Info, E->getBase())) 7392 return false; 7393 7394 QualType BaseTy = E->getBase()->getType(); 7395 7396 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7397 if (!FD) return Error(E); 7398 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7399 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7400 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7401 7402 // Note: there is no lvalue base here. But this case should only ever 7403 // happen in C or in C++98, where we cannot be evaluating a constexpr 7404 // constructor, which is the only case the base matters. 7405 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7406 SubobjectDesignator Designator(BaseTy); 7407 Designator.addDeclUnchecked(FD); 7408 7409 APValue Result; 7410 return extractSubobject(Info, E, Obj, Designator, Result) && 7411 DerivedSuccess(Result, E); 7412 } 7413 7414 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7415 APValue Val; 7416 if (!Evaluate(Val, Info, E->getBase())) 7417 return false; 7418 7419 if (Val.isVector()) { 7420 SmallVector<uint32_t, 4> Indices; 7421 E->getEncodedElementAccess(Indices); 7422 if (Indices.size() == 1) { 7423 // Return scalar. 7424 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7425 } else { 7426 // Construct new APValue vector. 7427 SmallVector<APValue, 4> Elts; 7428 for (unsigned I = 0; I < Indices.size(); ++I) { 7429 Elts.push_back(Val.getVectorElt(Indices[I])); 7430 } 7431 APValue VecResult(Elts.data(), Indices.size()); 7432 return DerivedSuccess(VecResult, E); 7433 } 7434 } 7435 7436 return false; 7437 } 7438 7439 bool VisitCastExpr(const CastExpr *E) { 7440 switch (E->getCastKind()) { 7441 default: 7442 break; 7443 7444 case CK_AtomicToNonAtomic: { 7445 APValue AtomicVal; 7446 // This does not need to be done in place even for class/array types: 7447 // atomic-to-non-atomic conversion implies copying the object 7448 // representation. 7449 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7450 return false; 7451 return DerivedSuccess(AtomicVal, E); 7452 } 7453 7454 case CK_NoOp: 7455 case CK_UserDefinedConversion: 7456 return StmtVisitorTy::Visit(E->getSubExpr()); 7457 7458 case CK_LValueToRValue: { 7459 LValue LVal; 7460 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7461 return false; 7462 APValue RVal; 7463 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7464 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7465 LVal, RVal)) 7466 return false; 7467 return DerivedSuccess(RVal, E); 7468 } 7469 case CK_LValueToRValueBitCast: { 7470 APValue DestValue, SourceValue; 7471 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7472 return false; 7473 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7474 return false; 7475 return DerivedSuccess(DestValue, E); 7476 } 7477 7478 case CK_AddressSpaceConversion: { 7479 APValue Value; 7480 if (!Evaluate(Value, Info, E->getSubExpr())) 7481 return false; 7482 return DerivedSuccess(Value, E); 7483 } 7484 } 7485 7486 return Error(E); 7487 } 7488 7489 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7490 return VisitUnaryPostIncDec(UO); 7491 } 7492 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7493 return VisitUnaryPostIncDec(UO); 7494 } 7495 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7496 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7497 return Error(UO); 7498 7499 LValue LVal; 7500 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7501 return false; 7502 APValue RVal; 7503 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7504 UO->isIncrementOp(), &RVal)) 7505 return false; 7506 return DerivedSuccess(RVal, UO); 7507 } 7508 7509 bool VisitStmtExpr(const StmtExpr *E) { 7510 // We will have checked the full-expressions inside the statement expression 7511 // when they were completed, and don't need to check them again now. 7512 if (Info.checkingForUndefinedBehavior()) 7513 return Error(E); 7514 7515 const CompoundStmt *CS = E->getSubStmt(); 7516 if (CS->body_empty()) 7517 return true; 7518 7519 BlockScopeRAII Scope(Info); 7520 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7521 BE = CS->body_end(); 7522 /**/; ++BI) { 7523 if (BI + 1 == BE) { 7524 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7525 if (!FinalExpr) { 7526 Info.FFDiag((*BI)->getBeginLoc(), 7527 diag::note_constexpr_stmt_expr_unsupported); 7528 return false; 7529 } 7530 return this->Visit(FinalExpr) && Scope.destroy(); 7531 } 7532 7533 APValue ReturnValue; 7534 StmtResult Result = { ReturnValue, nullptr }; 7535 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7536 if (ESR != ESR_Succeeded) { 7537 // FIXME: If the statement-expression terminated due to 'return', 7538 // 'break', or 'continue', it would be nice to propagate that to 7539 // the outer statement evaluation rather than bailing out. 7540 if (ESR != ESR_Failed) 7541 Info.FFDiag((*BI)->getBeginLoc(), 7542 diag::note_constexpr_stmt_expr_unsupported); 7543 return false; 7544 } 7545 } 7546 7547 llvm_unreachable("Return from function from the loop above."); 7548 } 7549 7550 /// Visit a value which is evaluated, but whose value is ignored. 7551 void VisitIgnoredValue(const Expr *E) { 7552 EvaluateIgnoredValue(Info, E); 7553 } 7554 7555 /// Potentially visit a MemberExpr's base expression. 7556 void VisitIgnoredBaseExpression(const Expr *E) { 7557 // While MSVC doesn't evaluate the base expression, it does diagnose the 7558 // presence of side-effecting behavior. 7559 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7560 return; 7561 VisitIgnoredValue(E); 7562 } 7563 }; 7564 7565 } // namespace 7566 7567 //===----------------------------------------------------------------------===// 7568 // Common base class for lvalue and temporary evaluation. 7569 //===----------------------------------------------------------------------===// 7570 namespace { 7571 template<class Derived> 7572 class LValueExprEvaluatorBase 7573 : public ExprEvaluatorBase<Derived> { 7574 protected: 7575 LValue &Result; 7576 bool InvalidBaseOK; 7577 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7578 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7579 7580 bool Success(APValue::LValueBase B) { 7581 Result.set(B); 7582 return true; 7583 } 7584 7585 bool evaluatePointer(const Expr *E, LValue &Result) { 7586 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7587 } 7588 7589 public: 7590 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7591 : ExprEvaluatorBaseTy(Info), Result(Result), 7592 InvalidBaseOK(InvalidBaseOK) {} 7593 7594 bool Success(const APValue &V, const Expr *E) { 7595 Result.setFrom(this->Info.Ctx, V); 7596 return true; 7597 } 7598 7599 bool VisitMemberExpr(const MemberExpr *E) { 7600 // Handle non-static data members. 7601 QualType BaseTy; 7602 bool EvalOK; 7603 if (E->isArrow()) { 7604 EvalOK = evaluatePointer(E->getBase(), Result); 7605 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7606 } else if (E->getBase()->isRValue()) { 7607 assert(E->getBase()->getType()->isRecordType()); 7608 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7609 BaseTy = E->getBase()->getType(); 7610 } else { 7611 EvalOK = this->Visit(E->getBase()); 7612 BaseTy = E->getBase()->getType(); 7613 } 7614 if (!EvalOK) { 7615 if (!InvalidBaseOK) 7616 return false; 7617 Result.setInvalid(E); 7618 return true; 7619 } 7620 7621 const ValueDecl *MD = E->getMemberDecl(); 7622 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7623 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7624 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7625 (void)BaseTy; 7626 if (!HandleLValueMember(this->Info, E, Result, FD)) 7627 return false; 7628 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7629 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7630 return false; 7631 } else 7632 return this->Error(E); 7633 7634 if (MD->getType()->isReferenceType()) { 7635 APValue RefValue; 7636 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7637 RefValue)) 7638 return false; 7639 return Success(RefValue, E); 7640 } 7641 return true; 7642 } 7643 7644 bool VisitBinaryOperator(const BinaryOperator *E) { 7645 switch (E->getOpcode()) { 7646 default: 7647 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7648 7649 case BO_PtrMemD: 7650 case BO_PtrMemI: 7651 return HandleMemberPointerAccess(this->Info, E, Result); 7652 } 7653 } 7654 7655 bool VisitCastExpr(const CastExpr *E) { 7656 switch (E->getCastKind()) { 7657 default: 7658 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7659 7660 case CK_DerivedToBase: 7661 case CK_UncheckedDerivedToBase: 7662 if (!this->Visit(E->getSubExpr())) 7663 return false; 7664 7665 // Now figure out the necessary offset to add to the base LV to get from 7666 // the derived class to the base class. 7667 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 7668 Result); 7669 } 7670 } 7671 }; 7672 } 7673 7674 //===----------------------------------------------------------------------===// 7675 // LValue Evaluation 7676 // 7677 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 7678 // function designators (in C), decl references to void objects (in C), and 7679 // temporaries (if building with -Wno-address-of-temporary). 7680 // 7681 // LValue evaluation produces values comprising a base expression of one of the 7682 // following types: 7683 // - Declarations 7684 // * VarDecl 7685 // * FunctionDecl 7686 // - Literals 7687 // * CompoundLiteralExpr in C (and in global scope in C++) 7688 // * StringLiteral 7689 // * PredefinedExpr 7690 // * ObjCStringLiteralExpr 7691 // * ObjCEncodeExpr 7692 // * AddrLabelExpr 7693 // * BlockExpr 7694 // * CallExpr for a MakeStringConstant builtin 7695 // - typeid(T) expressions, as TypeInfoLValues 7696 // - Locals and temporaries 7697 // * MaterializeTemporaryExpr 7698 // * Any Expr, with a CallIndex indicating the function in which the temporary 7699 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 7700 // from the AST (FIXME). 7701 // * A MaterializeTemporaryExpr that has static storage duration, with no 7702 // CallIndex, for a lifetime-extended temporary. 7703 // * The ConstantExpr that is currently being evaluated during evaluation of an 7704 // immediate invocation. 7705 // plus an offset in bytes. 7706 //===----------------------------------------------------------------------===// 7707 namespace { 7708 class LValueExprEvaluator 7709 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 7710 public: 7711 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 7712 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 7713 7714 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 7715 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 7716 7717 bool VisitDeclRefExpr(const DeclRefExpr *E); 7718 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 7719 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 7720 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 7721 bool VisitMemberExpr(const MemberExpr *E); 7722 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 7723 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 7724 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 7725 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 7726 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 7727 bool VisitUnaryDeref(const UnaryOperator *E); 7728 bool VisitUnaryReal(const UnaryOperator *E); 7729 bool VisitUnaryImag(const UnaryOperator *E); 7730 bool VisitUnaryPreInc(const UnaryOperator *UO) { 7731 return VisitUnaryPreIncDec(UO); 7732 } 7733 bool VisitUnaryPreDec(const UnaryOperator *UO) { 7734 return VisitUnaryPreIncDec(UO); 7735 } 7736 bool VisitBinAssign(const BinaryOperator *BO); 7737 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 7738 7739 bool VisitCastExpr(const CastExpr *E) { 7740 switch (E->getCastKind()) { 7741 default: 7742 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 7743 7744 case CK_LValueBitCast: 7745 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7746 if (!Visit(E->getSubExpr())) 7747 return false; 7748 Result.Designator.setInvalid(); 7749 return true; 7750 7751 case CK_BaseToDerived: 7752 if (!Visit(E->getSubExpr())) 7753 return false; 7754 return HandleBaseToDerivedCast(Info, E, Result); 7755 7756 case CK_Dynamic: 7757 if (!Visit(E->getSubExpr())) 7758 return false; 7759 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 7760 } 7761 } 7762 }; 7763 } // end anonymous namespace 7764 7765 /// Evaluate an expression as an lvalue. This can be legitimately called on 7766 /// expressions which are not glvalues, in three cases: 7767 /// * function designators in C, and 7768 /// * "extern void" objects 7769 /// * @selector() expressions in Objective-C 7770 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 7771 bool InvalidBaseOK) { 7772 assert(E->isGLValue() || E->getType()->isFunctionType() || 7773 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 7774 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 7775 } 7776 7777 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 7778 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 7779 return Success(FD); 7780 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 7781 return VisitVarDecl(E, VD); 7782 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 7783 return Visit(BD->getBinding()); 7784 if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(E->getDecl())) 7785 return Success(GD); 7786 return Error(E); 7787 } 7788 7789 7790 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 7791 7792 // If we are within a lambda's call operator, check whether the 'VD' referred 7793 // to within 'E' actually represents a lambda-capture that maps to a 7794 // data-member/field within the closure object, and if so, evaluate to the 7795 // field or what the field refers to. 7796 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 7797 isa<DeclRefExpr>(E) && 7798 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 7799 // We don't always have a complete capture-map when checking or inferring if 7800 // the function call operator meets the requirements of a constexpr function 7801 // - but we don't need to evaluate the captures to determine constexprness 7802 // (dcl.constexpr C++17). 7803 if (Info.checkingPotentialConstantExpression()) 7804 return false; 7805 7806 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 7807 // Start with 'Result' referring to the complete closure object... 7808 Result = *Info.CurrentCall->This; 7809 // ... then update it to refer to the field of the closure object 7810 // that represents the capture. 7811 if (!HandleLValueMember(Info, E, Result, FD)) 7812 return false; 7813 // And if the field is of reference type, update 'Result' to refer to what 7814 // the field refers to. 7815 if (FD->getType()->isReferenceType()) { 7816 APValue RVal; 7817 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 7818 RVal)) 7819 return false; 7820 Result.setFrom(Info.Ctx, RVal); 7821 } 7822 return true; 7823 } 7824 } 7825 CallStackFrame *Frame = nullptr; 7826 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 7827 // Only if a local variable was declared in the function currently being 7828 // evaluated, do we expect to be able to find its value in the current 7829 // frame. (Otherwise it was likely declared in an enclosing context and 7830 // could either have a valid evaluatable value (for e.g. a constexpr 7831 // variable) or be ill-formed (and trigger an appropriate evaluation 7832 // diagnostic)). 7833 if (Info.CurrentCall->Callee && 7834 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 7835 Frame = Info.CurrentCall; 7836 } 7837 } 7838 7839 if (!VD->getType()->isReferenceType()) { 7840 if (Frame) { 7841 Result.set({VD, Frame->Index, 7842 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 7843 return true; 7844 } 7845 return Success(VD); 7846 } 7847 7848 APValue *V; 7849 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 7850 return false; 7851 if (!V->hasValue()) { 7852 // FIXME: Is it possible for V to be indeterminate here? If so, we should 7853 // adjust the diagnostic to say that. 7854 if (!Info.checkingPotentialConstantExpression()) 7855 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 7856 return false; 7857 } 7858 return Success(*V, E); 7859 } 7860 7861 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 7862 const MaterializeTemporaryExpr *E) { 7863 // Walk through the expression to find the materialized temporary itself. 7864 SmallVector<const Expr *, 2> CommaLHSs; 7865 SmallVector<SubobjectAdjustment, 2> Adjustments; 7866 const Expr *Inner = 7867 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 7868 7869 // If we passed any comma operators, evaluate their LHSs. 7870 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 7871 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 7872 return false; 7873 7874 // A materialized temporary with static storage duration can appear within the 7875 // result of a constant expression evaluation, so we need to preserve its 7876 // value for use outside this evaluation. 7877 APValue *Value; 7878 if (E->getStorageDuration() == SD_Static) { 7879 Value = E->getOrCreateValue(true); 7880 *Value = APValue(); 7881 Result.set(E); 7882 } else { 7883 Value = &Info.CurrentCall->createTemporary( 7884 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result); 7885 } 7886 7887 QualType Type = Inner->getType(); 7888 7889 // Materialize the temporary itself. 7890 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 7891 *Value = APValue(); 7892 return false; 7893 } 7894 7895 // Adjust our lvalue to refer to the desired subobject. 7896 for (unsigned I = Adjustments.size(); I != 0; /**/) { 7897 --I; 7898 switch (Adjustments[I].Kind) { 7899 case SubobjectAdjustment::DerivedToBaseAdjustment: 7900 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 7901 Type, Result)) 7902 return false; 7903 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 7904 break; 7905 7906 case SubobjectAdjustment::FieldAdjustment: 7907 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 7908 return false; 7909 Type = Adjustments[I].Field->getType(); 7910 break; 7911 7912 case SubobjectAdjustment::MemberPointerAdjustment: 7913 if (!HandleMemberPointerAccess(this->Info, Type, Result, 7914 Adjustments[I].Ptr.RHS)) 7915 return false; 7916 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 7917 break; 7918 } 7919 } 7920 7921 return true; 7922 } 7923 7924 bool 7925 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7926 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 7927 "lvalue compound literal in c++?"); 7928 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 7929 // only see this when folding in C, so there's no standard to follow here. 7930 return Success(E); 7931 } 7932 7933 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 7934 TypeInfoLValue TypeInfo; 7935 7936 if (!E->isPotentiallyEvaluated()) { 7937 if (E->isTypeOperand()) 7938 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 7939 else 7940 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 7941 } else { 7942 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 7943 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 7944 << E->getExprOperand()->getType() 7945 << E->getExprOperand()->getSourceRange(); 7946 } 7947 7948 if (!Visit(E->getExprOperand())) 7949 return false; 7950 7951 Optional<DynamicType> DynType = 7952 ComputeDynamicType(Info, E, Result, AK_TypeId); 7953 if (!DynType) 7954 return false; 7955 7956 TypeInfo = 7957 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 7958 } 7959 7960 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 7961 } 7962 7963 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 7964 return Success(E->getGuidDecl()); 7965 } 7966 7967 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 7968 // Handle static data members. 7969 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 7970 VisitIgnoredBaseExpression(E->getBase()); 7971 return VisitVarDecl(E, VD); 7972 } 7973 7974 // Handle static member functions. 7975 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 7976 if (MD->isStatic()) { 7977 VisitIgnoredBaseExpression(E->getBase()); 7978 return Success(MD); 7979 } 7980 } 7981 7982 // Handle non-static data members. 7983 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 7984 } 7985 7986 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 7987 // FIXME: Deal with vectors as array subscript bases. 7988 if (E->getBase()->getType()->isVectorType()) 7989 return Error(E); 7990 7991 bool Success = true; 7992 if (!evaluatePointer(E->getBase(), Result)) { 7993 if (!Info.noteFailure()) 7994 return false; 7995 Success = false; 7996 } 7997 7998 APSInt Index; 7999 if (!EvaluateInteger(E->getIdx(), Index, Info)) 8000 return false; 8001 8002 return Success && 8003 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8004 } 8005 8006 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8007 return evaluatePointer(E->getSubExpr(), Result); 8008 } 8009 8010 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8011 if (!Visit(E->getSubExpr())) 8012 return false; 8013 // __real is a no-op on scalar lvalues. 8014 if (E->getSubExpr()->getType()->isAnyComplexType()) 8015 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8016 return true; 8017 } 8018 8019 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8020 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8021 "lvalue __imag__ on scalar?"); 8022 if (!Visit(E->getSubExpr())) 8023 return false; 8024 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8025 return true; 8026 } 8027 8028 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8029 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8030 return Error(UO); 8031 8032 if (!this->Visit(UO->getSubExpr())) 8033 return false; 8034 8035 return handleIncDec( 8036 this->Info, UO, Result, UO->getSubExpr()->getType(), 8037 UO->isIncrementOp(), nullptr); 8038 } 8039 8040 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8041 const CompoundAssignOperator *CAO) { 8042 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8043 return Error(CAO); 8044 8045 APValue RHS; 8046 8047 // The overall lvalue result is the result of evaluating the LHS. 8048 if (!this->Visit(CAO->getLHS())) { 8049 if (Info.noteFailure()) 8050 Evaluate(RHS, this->Info, CAO->getRHS()); 8051 return false; 8052 } 8053 8054 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 8055 return false; 8056 8057 return handleCompoundAssignment( 8058 this->Info, CAO, 8059 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8060 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8061 } 8062 8063 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8064 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8065 return Error(E); 8066 8067 APValue NewVal; 8068 8069 if (!this->Visit(E->getLHS())) { 8070 if (Info.noteFailure()) 8071 Evaluate(NewVal, this->Info, E->getRHS()); 8072 return false; 8073 } 8074 8075 if (!Evaluate(NewVal, this->Info, E->getRHS())) 8076 return false; 8077 8078 if (Info.getLangOpts().CPlusPlus20 && 8079 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8080 return false; 8081 8082 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8083 NewVal); 8084 } 8085 8086 //===----------------------------------------------------------------------===// 8087 // Pointer Evaluation 8088 //===----------------------------------------------------------------------===// 8089 8090 /// Attempts to compute the number of bytes available at the pointer 8091 /// returned by a function with the alloc_size attribute. Returns true if we 8092 /// were successful. Places an unsigned number into `Result`. 8093 /// 8094 /// This expects the given CallExpr to be a call to a function with an 8095 /// alloc_size attribute. 8096 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8097 const CallExpr *Call, 8098 llvm::APInt &Result) { 8099 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8100 8101 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8102 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8103 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8104 if (Call->getNumArgs() <= SizeArgNo) 8105 return false; 8106 8107 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8108 Expr::EvalResult ExprResult; 8109 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8110 return false; 8111 Into = ExprResult.Val.getInt(); 8112 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8113 return false; 8114 Into = Into.zextOrSelf(BitsInSizeT); 8115 return true; 8116 }; 8117 8118 APSInt SizeOfElem; 8119 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8120 return false; 8121 8122 if (!AllocSize->getNumElemsParam().isValid()) { 8123 Result = std::move(SizeOfElem); 8124 return true; 8125 } 8126 8127 APSInt NumberOfElems; 8128 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8129 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8130 return false; 8131 8132 bool Overflow; 8133 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8134 if (Overflow) 8135 return false; 8136 8137 Result = std::move(BytesAvailable); 8138 return true; 8139 } 8140 8141 /// Convenience function. LVal's base must be a call to an alloc_size 8142 /// function. 8143 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8144 const LValue &LVal, 8145 llvm::APInt &Result) { 8146 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8147 "Can't get the size of a non alloc_size function"); 8148 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8149 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8150 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8151 } 8152 8153 /// Attempts to evaluate the given LValueBase as the result of a call to 8154 /// a function with the alloc_size attribute. If it was possible to do so, this 8155 /// function will return true, make Result's Base point to said function call, 8156 /// and mark Result's Base as invalid. 8157 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8158 LValue &Result) { 8159 if (Base.isNull()) 8160 return false; 8161 8162 // Because we do no form of static analysis, we only support const variables. 8163 // 8164 // Additionally, we can't support parameters, nor can we support static 8165 // variables (in the latter case, use-before-assign isn't UB; in the former, 8166 // we have no clue what they'll be assigned to). 8167 const auto *VD = 8168 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8169 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8170 return false; 8171 8172 const Expr *Init = VD->getAnyInitializer(); 8173 if (!Init) 8174 return false; 8175 8176 const Expr *E = Init->IgnoreParens(); 8177 if (!tryUnwrapAllocSizeCall(E)) 8178 return false; 8179 8180 // Store E instead of E unwrapped so that the type of the LValue's base is 8181 // what the user wanted. 8182 Result.setInvalid(E); 8183 8184 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8185 Result.addUnsizedArray(Info, E, Pointee); 8186 return true; 8187 } 8188 8189 namespace { 8190 class PointerExprEvaluator 8191 : public ExprEvaluatorBase<PointerExprEvaluator> { 8192 LValue &Result; 8193 bool InvalidBaseOK; 8194 8195 bool Success(const Expr *E) { 8196 Result.set(E); 8197 return true; 8198 } 8199 8200 bool evaluateLValue(const Expr *E, LValue &Result) { 8201 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8202 } 8203 8204 bool evaluatePointer(const Expr *E, LValue &Result) { 8205 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8206 } 8207 8208 bool visitNonBuiltinCallExpr(const CallExpr *E); 8209 public: 8210 8211 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8212 : ExprEvaluatorBaseTy(info), Result(Result), 8213 InvalidBaseOK(InvalidBaseOK) {} 8214 8215 bool Success(const APValue &V, const Expr *E) { 8216 Result.setFrom(Info.Ctx, V); 8217 return true; 8218 } 8219 bool ZeroInitialization(const Expr *E) { 8220 Result.setNull(Info.Ctx, E->getType()); 8221 return true; 8222 } 8223 8224 bool VisitBinaryOperator(const BinaryOperator *E); 8225 bool VisitCastExpr(const CastExpr* E); 8226 bool VisitUnaryAddrOf(const UnaryOperator *E); 8227 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8228 { return Success(E); } 8229 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8230 if (E->isExpressibleAsConstantInitializer()) 8231 return Success(E); 8232 if (Info.noteFailure()) 8233 EvaluateIgnoredValue(Info, E->getSubExpr()); 8234 return Error(E); 8235 } 8236 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8237 { return Success(E); } 8238 bool VisitCallExpr(const CallExpr *E); 8239 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8240 bool VisitBlockExpr(const BlockExpr *E) { 8241 if (!E->getBlockDecl()->hasCaptures()) 8242 return Success(E); 8243 return Error(E); 8244 } 8245 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8246 // Can't look at 'this' when checking a potential constant expression. 8247 if (Info.checkingPotentialConstantExpression()) 8248 return false; 8249 if (!Info.CurrentCall->This) { 8250 if (Info.getLangOpts().CPlusPlus11) 8251 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8252 else 8253 Info.FFDiag(E); 8254 return false; 8255 } 8256 Result = *Info.CurrentCall->This; 8257 // If we are inside a lambda's call operator, the 'this' expression refers 8258 // to the enclosing '*this' object (either by value or reference) which is 8259 // either copied into the closure object's field that represents the '*this' 8260 // or refers to '*this'. 8261 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8262 // Ensure we actually have captured 'this'. (an error will have 8263 // been previously reported if not). 8264 if (!Info.CurrentCall->LambdaThisCaptureField) 8265 return false; 8266 8267 // Update 'Result' to refer to the data member/field of the closure object 8268 // that represents the '*this' capture. 8269 if (!HandleLValueMember(Info, E, Result, 8270 Info.CurrentCall->LambdaThisCaptureField)) 8271 return false; 8272 // If we captured '*this' by reference, replace the field with its referent. 8273 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8274 ->isPointerType()) { 8275 APValue RVal; 8276 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8277 RVal)) 8278 return false; 8279 8280 Result.setFrom(Info.Ctx, RVal); 8281 } 8282 } 8283 return true; 8284 } 8285 8286 bool VisitCXXNewExpr(const CXXNewExpr *E); 8287 8288 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8289 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8290 APValue LValResult = E->EvaluateInContext( 8291 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8292 Result.setFrom(Info.Ctx, LValResult); 8293 return true; 8294 } 8295 8296 // FIXME: Missing: @protocol, @selector 8297 }; 8298 } // end anonymous namespace 8299 8300 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8301 bool InvalidBaseOK) { 8302 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8303 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8304 } 8305 8306 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8307 if (E->getOpcode() != BO_Add && 8308 E->getOpcode() != BO_Sub) 8309 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8310 8311 const Expr *PExp = E->getLHS(); 8312 const Expr *IExp = E->getRHS(); 8313 if (IExp->getType()->isPointerType()) 8314 std::swap(PExp, IExp); 8315 8316 bool EvalPtrOK = evaluatePointer(PExp, Result); 8317 if (!EvalPtrOK && !Info.noteFailure()) 8318 return false; 8319 8320 llvm::APSInt Offset; 8321 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8322 return false; 8323 8324 if (E->getOpcode() == BO_Sub) 8325 negateAsSigned(Offset); 8326 8327 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8328 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8329 } 8330 8331 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8332 return evaluateLValue(E->getSubExpr(), Result); 8333 } 8334 8335 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8336 const Expr *SubExpr = E->getSubExpr(); 8337 8338 switch (E->getCastKind()) { 8339 default: 8340 break; 8341 case CK_BitCast: 8342 case CK_CPointerToObjCPointerCast: 8343 case CK_BlockPointerToObjCPointerCast: 8344 case CK_AnyPointerToBlockPointerCast: 8345 case CK_AddressSpaceConversion: 8346 if (!Visit(SubExpr)) 8347 return false; 8348 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8349 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8350 // also static_casts, but we disallow them as a resolution to DR1312. 8351 if (!E->getType()->isVoidPointerType()) { 8352 if (!Result.InvalidBase && !Result.Designator.Invalid && 8353 !Result.IsNullPtr && 8354 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8355 E->getType()->getPointeeType()) && 8356 Info.getStdAllocatorCaller("allocate")) { 8357 // Inside a call to std::allocator::allocate and friends, we permit 8358 // casting from void* back to cv1 T* for a pointer that points to a 8359 // cv2 T. 8360 } else { 8361 Result.Designator.setInvalid(); 8362 if (SubExpr->getType()->isVoidPointerType()) 8363 CCEDiag(E, diag::note_constexpr_invalid_cast) 8364 << 3 << SubExpr->getType(); 8365 else 8366 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8367 } 8368 } 8369 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8370 ZeroInitialization(E); 8371 return true; 8372 8373 case CK_DerivedToBase: 8374 case CK_UncheckedDerivedToBase: 8375 if (!evaluatePointer(E->getSubExpr(), Result)) 8376 return false; 8377 if (!Result.Base && Result.Offset.isZero()) 8378 return true; 8379 8380 // Now figure out the necessary offset to add to the base LV to get from 8381 // the derived class to the base class. 8382 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8383 castAs<PointerType>()->getPointeeType(), 8384 Result); 8385 8386 case CK_BaseToDerived: 8387 if (!Visit(E->getSubExpr())) 8388 return false; 8389 if (!Result.Base && Result.Offset.isZero()) 8390 return true; 8391 return HandleBaseToDerivedCast(Info, E, Result); 8392 8393 case CK_Dynamic: 8394 if (!Visit(E->getSubExpr())) 8395 return false; 8396 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8397 8398 case CK_NullToPointer: 8399 VisitIgnoredValue(E->getSubExpr()); 8400 return ZeroInitialization(E); 8401 8402 case CK_IntegralToPointer: { 8403 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8404 8405 APValue Value; 8406 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8407 break; 8408 8409 if (Value.isInt()) { 8410 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8411 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8412 Result.Base = (Expr*)nullptr; 8413 Result.InvalidBase = false; 8414 Result.Offset = CharUnits::fromQuantity(N); 8415 Result.Designator.setInvalid(); 8416 Result.IsNullPtr = false; 8417 return true; 8418 } else { 8419 // Cast is of an lvalue, no need to change value. 8420 Result.setFrom(Info.Ctx, Value); 8421 return true; 8422 } 8423 } 8424 8425 case CK_ArrayToPointerDecay: { 8426 if (SubExpr->isGLValue()) { 8427 if (!evaluateLValue(SubExpr, Result)) 8428 return false; 8429 } else { 8430 APValue &Value = Info.CurrentCall->createTemporary( 8431 SubExpr, SubExpr->getType(), false, Result); 8432 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8433 return false; 8434 } 8435 // The result is a pointer to the first element of the array. 8436 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8437 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8438 Result.addArray(Info, E, CAT); 8439 else 8440 Result.addUnsizedArray(Info, E, AT->getElementType()); 8441 return true; 8442 } 8443 8444 case CK_FunctionToPointerDecay: 8445 return evaluateLValue(SubExpr, Result); 8446 8447 case CK_LValueToRValue: { 8448 LValue LVal; 8449 if (!evaluateLValue(E->getSubExpr(), LVal)) 8450 return false; 8451 8452 APValue RVal; 8453 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8454 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8455 LVal, RVal)) 8456 return InvalidBaseOK && 8457 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8458 return Success(RVal, E); 8459 } 8460 } 8461 8462 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8463 } 8464 8465 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8466 UnaryExprOrTypeTrait ExprKind) { 8467 // C++ [expr.alignof]p3: 8468 // When alignof is applied to a reference type, the result is the 8469 // alignment of the referenced type. 8470 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8471 T = Ref->getPointeeType(); 8472 8473 if (T.getQualifiers().hasUnaligned()) 8474 return CharUnits::One(); 8475 8476 const bool AlignOfReturnsPreferred = 8477 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8478 8479 // __alignof is defined to return the preferred alignment. 8480 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8481 // as well. 8482 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8483 return Info.Ctx.toCharUnitsFromBits( 8484 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8485 // alignof and _Alignof are defined to return the ABI alignment. 8486 else if (ExprKind == UETT_AlignOf) 8487 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8488 else 8489 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8490 } 8491 8492 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8493 UnaryExprOrTypeTrait ExprKind) { 8494 E = E->IgnoreParens(); 8495 8496 // The kinds of expressions that we have special-case logic here for 8497 // should be kept up to date with the special checks for those 8498 // expressions in Sema. 8499 8500 // alignof decl is always accepted, even if it doesn't make sense: we default 8501 // to 1 in those cases. 8502 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8503 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8504 /*RefAsPointee*/true); 8505 8506 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8507 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8508 /*RefAsPointee*/true); 8509 8510 return GetAlignOfType(Info, E->getType(), ExprKind); 8511 } 8512 8513 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8514 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8515 return Info.Ctx.getDeclAlign(VD); 8516 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8517 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8518 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8519 } 8520 8521 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8522 /// __builtin_is_aligned and __builtin_assume_aligned. 8523 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8524 EvalInfo &Info, APSInt &Alignment) { 8525 if (!EvaluateInteger(E, Alignment, Info)) 8526 return false; 8527 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8528 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8529 return false; 8530 } 8531 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8532 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8533 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8534 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8535 << MaxValue << ForType << Alignment; 8536 return false; 8537 } 8538 // Ensure both alignment and source value have the same bit width so that we 8539 // don't assert when computing the resulting value. 8540 APSInt ExtAlignment = 8541 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8542 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8543 "Alignment should not be changed by ext/trunc"); 8544 Alignment = ExtAlignment; 8545 assert(Alignment.getBitWidth() == SrcWidth); 8546 return true; 8547 } 8548 8549 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8550 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8551 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8552 return true; 8553 8554 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8555 return false; 8556 8557 Result.setInvalid(E); 8558 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8559 Result.addUnsizedArray(Info, E, PointeeTy); 8560 return true; 8561 } 8562 8563 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8564 if (IsStringLiteralCall(E)) 8565 return Success(E); 8566 8567 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8568 return VisitBuiltinCallExpr(E, BuiltinOp); 8569 8570 return visitNonBuiltinCallExpr(E); 8571 } 8572 8573 // Determine if T is a character type for which we guarantee that 8574 // sizeof(T) == 1. 8575 static bool isOneByteCharacterType(QualType T) { 8576 return T->isCharType() || T->isChar8Type(); 8577 } 8578 8579 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8580 unsigned BuiltinOp) { 8581 switch (BuiltinOp) { 8582 case Builtin::BI__builtin_addressof: 8583 return evaluateLValue(E->getArg(0), Result); 8584 case Builtin::BI__builtin_assume_aligned: { 8585 // We need to be very careful here because: if the pointer does not have the 8586 // asserted alignment, then the behavior is undefined, and undefined 8587 // behavior is non-constant. 8588 if (!evaluatePointer(E->getArg(0), Result)) 8589 return false; 8590 8591 LValue OffsetResult(Result); 8592 APSInt Alignment; 8593 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8594 Alignment)) 8595 return false; 8596 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8597 8598 if (E->getNumArgs() > 2) { 8599 APSInt Offset; 8600 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8601 return false; 8602 8603 int64_t AdditionalOffset = -Offset.getZExtValue(); 8604 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8605 } 8606 8607 // If there is a base object, then it must have the correct alignment. 8608 if (OffsetResult.Base) { 8609 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 8610 8611 if (BaseAlignment < Align) { 8612 Result.Designator.setInvalid(); 8613 // FIXME: Add support to Diagnostic for long / long long. 8614 CCEDiag(E->getArg(0), 8615 diag::note_constexpr_baa_insufficient_alignment) << 0 8616 << (unsigned)BaseAlignment.getQuantity() 8617 << (unsigned)Align.getQuantity(); 8618 return false; 8619 } 8620 } 8621 8622 // The offset must also have the correct alignment. 8623 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 8624 Result.Designator.setInvalid(); 8625 8626 (OffsetResult.Base 8627 ? CCEDiag(E->getArg(0), 8628 diag::note_constexpr_baa_insufficient_alignment) << 1 8629 : CCEDiag(E->getArg(0), 8630 diag::note_constexpr_baa_value_insufficient_alignment)) 8631 << (int)OffsetResult.Offset.getQuantity() 8632 << (unsigned)Align.getQuantity(); 8633 return false; 8634 } 8635 8636 return true; 8637 } 8638 case Builtin::BI__builtin_align_up: 8639 case Builtin::BI__builtin_align_down: { 8640 if (!evaluatePointer(E->getArg(0), Result)) 8641 return false; 8642 APSInt Alignment; 8643 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8644 Alignment)) 8645 return false; 8646 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 8647 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 8648 // For align_up/align_down, we can return the same value if the alignment 8649 // is known to be greater or equal to the requested value. 8650 if (PtrAlign.getQuantity() >= Alignment) 8651 return true; 8652 8653 // The alignment could be greater than the minimum at run-time, so we cannot 8654 // infer much about the resulting pointer value. One case is possible: 8655 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 8656 // can infer the correct index if the requested alignment is smaller than 8657 // the base alignment so we can perform the computation on the offset. 8658 if (BaseAlignment.getQuantity() >= Alignment) { 8659 assert(Alignment.getBitWidth() <= 64 && 8660 "Cannot handle > 64-bit address-space"); 8661 uint64_t Alignment64 = Alignment.getZExtValue(); 8662 CharUnits NewOffset = CharUnits::fromQuantity( 8663 BuiltinOp == Builtin::BI__builtin_align_down 8664 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 8665 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 8666 Result.adjustOffset(NewOffset - Result.Offset); 8667 // TODO: diagnose out-of-bounds values/only allow for arrays? 8668 return true; 8669 } 8670 // Otherwise, we cannot constant-evaluate the result. 8671 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 8672 << Alignment; 8673 return false; 8674 } 8675 case Builtin::BI__builtin_operator_new: 8676 return HandleOperatorNewCall(Info, E, Result); 8677 case Builtin::BI__builtin_launder: 8678 return evaluatePointer(E->getArg(0), Result); 8679 case Builtin::BIstrchr: 8680 case Builtin::BIwcschr: 8681 case Builtin::BImemchr: 8682 case Builtin::BIwmemchr: 8683 if (Info.getLangOpts().CPlusPlus11) 8684 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8685 << /*isConstexpr*/0 << /*isConstructor*/0 8686 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8687 else 8688 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8689 LLVM_FALLTHROUGH; 8690 case Builtin::BI__builtin_strchr: 8691 case Builtin::BI__builtin_wcschr: 8692 case Builtin::BI__builtin_memchr: 8693 case Builtin::BI__builtin_char_memchr: 8694 case Builtin::BI__builtin_wmemchr: { 8695 if (!Visit(E->getArg(0))) 8696 return false; 8697 APSInt Desired; 8698 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 8699 return false; 8700 uint64_t MaxLength = uint64_t(-1); 8701 if (BuiltinOp != Builtin::BIstrchr && 8702 BuiltinOp != Builtin::BIwcschr && 8703 BuiltinOp != Builtin::BI__builtin_strchr && 8704 BuiltinOp != Builtin::BI__builtin_wcschr) { 8705 APSInt N; 8706 if (!EvaluateInteger(E->getArg(2), N, Info)) 8707 return false; 8708 MaxLength = N.getExtValue(); 8709 } 8710 // We cannot find the value if there are no candidates to match against. 8711 if (MaxLength == 0u) 8712 return ZeroInitialization(E); 8713 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 8714 Result.Designator.Invalid) 8715 return false; 8716 QualType CharTy = Result.Designator.getType(Info.Ctx); 8717 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 8718 BuiltinOp == Builtin::BI__builtin_memchr; 8719 assert(IsRawByte || 8720 Info.Ctx.hasSameUnqualifiedType( 8721 CharTy, E->getArg(0)->getType()->getPointeeType())); 8722 // Pointers to const void may point to objects of incomplete type. 8723 if (IsRawByte && CharTy->isIncompleteType()) { 8724 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 8725 return false; 8726 } 8727 // Give up on byte-oriented matching against multibyte elements. 8728 // FIXME: We can compare the bytes in the correct order. 8729 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 8730 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 8731 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 8732 << CharTy; 8733 return false; 8734 } 8735 // Figure out what value we're actually looking for (after converting to 8736 // the corresponding unsigned type if necessary). 8737 uint64_t DesiredVal; 8738 bool StopAtNull = false; 8739 switch (BuiltinOp) { 8740 case Builtin::BIstrchr: 8741 case Builtin::BI__builtin_strchr: 8742 // strchr compares directly to the passed integer, and therefore 8743 // always fails if given an int that is not a char. 8744 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 8745 E->getArg(1)->getType(), 8746 Desired), 8747 Desired)) 8748 return ZeroInitialization(E); 8749 StopAtNull = true; 8750 LLVM_FALLTHROUGH; 8751 case Builtin::BImemchr: 8752 case Builtin::BI__builtin_memchr: 8753 case Builtin::BI__builtin_char_memchr: 8754 // memchr compares by converting both sides to unsigned char. That's also 8755 // correct for strchr if we get this far (to cope with plain char being 8756 // unsigned in the strchr case). 8757 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 8758 break; 8759 8760 case Builtin::BIwcschr: 8761 case Builtin::BI__builtin_wcschr: 8762 StopAtNull = true; 8763 LLVM_FALLTHROUGH; 8764 case Builtin::BIwmemchr: 8765 case Builtin::BI__builtin_wmemchr: 8766 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 8767 DesiredVal = Desired.getZExtValue(); 8768 break; 8769 } 8770 8771 for (; MaxLength; --MaxLength) { 8772 APValue Char; 8773 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 8774 !Char.isInt()) 8775 return false; 8776 if (Char.getInt().getZExtValue() == DesiredVal) 8777 return true; 8778 if (StopAtNull && !Char.getInt()) 8779 break; 8780 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 8781 return false; 8782 } 8783 // Not found: return nullptr. 8784 return ZeroInitialization(E); 8785 } 8786 8787 case Builtin::BImemcpy: 8788 case Builtin::BImemmove: 8789 case Builtin::BIwmemcpy: 8790 case Builtin::BIwmemmove: 8791 if (Info.getLangOpts().CPlusPlus11) 8792 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8793 << /*isConstexpr*/0 << /*isConstructor*/0 8794 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8795 else 8796 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8797 LLVM_FALLTHROUGH; 8798 case Builtin::BI__builtin_memcpy: 8799 case Builtin::BI__builtin_memmove: 8800 case Builtin::BI__builtin_wmemcpy: 8801 case Builtin::BI__builtin_wmemmove: { 8802 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 8803 BuiltinOp == Builtin::BIwmemmove || 8804 BuiltinOp == Builtin::BI__builtin_wmemcpy || 8805 BuiltinOp == Builtin::BI__builtin_wmemmove; 8806 bool Move = BuiltinOp == Builtin::BImemmove || 8807 BuiltinOp == Builtin::BIwmemmove || 8808 BuiltinOp == Builtin::BI__builtin_memmove || 8809 BuiltinOp == Builtin::BI__builtin_wmemmove; 8810 8811 // The result of mem* is the first argument. 8812 if (!Visit(E->getArg(0))) 8813 return false; 8814 LValue Dest = Result; 8815 8816 LValue Src; 8817 if (!EvaluatePointer(E->getArg(1), Src, Info)) 8818 return false; 8819 8820 APSInt N; 8821 if (!EvaluateInteger(E->getArg(2), N, Info)) 8822 return false; 8823 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 8824 8825 // If the size is zero, we treat this as always being a valid no-op. 8826 // (Even if one of the src and dest pointers is null.) 8827 if (!N) 8828 return true; 8829 8830 // Otherwise, if either of the operands is null, we can't proceed. Don't 8831 // try to determine the type of the copied objects, because there aren't 8832 // any. 8833 if (!Src.Base || !Dest.Base) { 8834 APValue Val; 8835 (!Src.Base ? Src : Dest).moveInto(Val); 8836 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 8837 << Move << WChar << !!Src.Base 8838 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 8839 return false; 8840 } 8841 if (Src.Designator.Invalid || Dest.Designator.Invalid) 8842 return false; 8843 8844 // We require that Src and Dest are both pointers to arrays of 8845 // trivially-copyable type. (For the wide version, the designator will be 8846 // invalid if the designated object is not a wchar_t.) 8847 QualType T = Dest.Designator.getType(Info.Ctx); 8848 QualType SrcT = Src.Designator.getType(Info.Ctx); 8849 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 8850 // FIXME: Consider using our bit_cast implementation to support this. 8851 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 8852 return false; 8853 } 8854 if (T->isIncompleteType()) { 8855 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 8856 return false; 8857 } 8858 if (!T.isTriviallyCopyableType(Info.Ctx)) { 8859 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 8860 return false; 8861 } 8862 8863 // Figure out how many T's we're copying. 8864 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 8865 if (!WChar) { 8866 uint64_t Remainder; 8867 llvm::APInt OrigN = N; 8868 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 8869 if (Remainder) { 8870 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8871 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 8872 << (unsigned)TSize; 8873 return false; 8874 } 8875 } 8876 8877 // Check that the copying will remain within the arrays, just so that we 8878 // can give a more meaningful diagnostic. This implicitly also checks that 8879 // N fits into 64 bits. 8880 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 8881 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 8882 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 8883 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8884 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 8885 << N.toString(10, /*Signed*/false); 8886 return false; 8887 } 8888 uint64_t NElems = N.getZExtValue(); 8889 uint64_t NBytes = NElems * TSize; 8890 8891 // Check for overlap. 8892 int Direction = 1; 8893 if (HasSameBase(Src, Dest)) { 8894 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 8895 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 8896 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 8897 // Dest is inside the source region. 8898 if (!Move) { 8899 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 8900 return false; 8901 } 8902 // For memmove and friends, copy backwards. 8903 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 8904 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 8905 return false; 8906 Direction = -1; 8907 } else if (!Move && SrcOffset >= DestOffset && 8908 SrcOffset - DestOffset < NBytes) { 8909 // Src is inside the destination region for memcpy: invalid. 8910 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 8911 return false; 8912 } 8913 } 8914 8915 while (true) { 8916 APValue Val; 8917 // FIXME: Set WantObjectRepresentation to true if we're copying a 8918 // char-like type? 8919 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 8920 !handleAssignment(Info, E, Dest, T, Val)) 8921 return false; 8922 // Do not iterate past the last element; if we're copying backwards, that 8923 // might take us off the start of the array. 8924 if (--NElems == 0) 8925 return true; 8926 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 8927 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 8928 return false; 8929 } 8930 } 8931 8932 default: 8933 break; 8934 } 8935 8936 return visitNonBuiltinCallExpr(E); 8937 } 8938 8939 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 8940 APValue &Result, const InitListExpr *ILE, 8941 QualType AllocType); 8942 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 8943 APValue &Result, 8944 const CXXConstructExpr *CCE, 8945 QualType AllocType); 8946 8947 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 8948 if (!Info.getLangOpts().CPlusPlus20) 8949 Info.CCEDiag(E, diag::note_constexpr_new); 8950 8951 // We cannot speculatively evaluate a delete expression. 8952 if (Info.SpeculativeEvaluationDepth) 8953 return false; 8954 8955 FunctionDecl *OperatorNew = E->getOperatorNew(); 8956 8957 bool IsNothrow = false; 8958 bool IsPlacement = false; 8959 if (OperatorNew->isReservedGlobalPlacementOperator() && 8960 Info.CurrentCall->isStdFunction() && !E->isArray()) { 8961 // FIXME Support array placement new. 8962 assert(E->getNumPlacementArgs() == 1); 8963 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 8964 return false; 8965 if (Result.Designator.Invalid) 8966 return false; 8967 IsPlacement = true; 8968 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 8969 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 8970 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 8971 return false; 8972 } else if (E->getNumPlacementArgs()) { 8973 // The only new-placement list we support is of the form (std::nothrow). 8974 // 8975 // FIXME: There is no restriction on this, but it's not clear that any 8976 // other form makes any sense. We get here for cases such as: 8977 // 8978 // new (std::align_val_t{N}) X(int) 8979 // 8980 // (which should presumably be valid only if N is a multiple of 8981 // alignof(int), and in any case can't be deallocated unless N is 8982 // alignof(X) and X has new-extended alignment). 8983 if (E->getNumPlacementArgs() != 1 || 8984 !E->getPlacementArg(0)->getType()->isNothrowT()) 8985 return Error(E, diag::note_constexpr_new_placement); 8986 8987 LValue Nothrow; 8988 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 8989 return false; 8990 IsNothrow = true; 8991 } 8992 8993 const Expr *Init = E->getInitializer(); 8994 const InitListExpr *ResizedArrayILE = nullptr; 8995 const CXXConstructExpr *ResizedArrayCCE = nullptr; 8996 bool ValueInit = false; 8997 8998 QualType AllocType = E->getAllocatedType(); 8999 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9000 const Expr *Stripped = *ArraySize; 9001 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9002 Stripped = ICE->getSubExpr()) 9003 if (ICE->getCastKind() != CK_NoOp && 9004 ICE->getCastKind() != CK_IntegralCast) 9005 break; 9006 9007 llvm::APSInt ArrayBound; 9008 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9009 return false; 9010 9011 // C++ [expr.new]p9: 9012 // The expression is erroneous if: 9013 // -- [...] its value before converting to size_t [or] applying the 9014 // second standard conversion sequence is less than zero 9015 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9016 if (IsNothrow) 9017 return ZeroInitialization(E); 9018 9019 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9020 << ArrayBound << (*ArraySize)->getSourceRange(); 9021 return false; 9022 } 9023 9024 // -- its value is such that the size of the allocated object would 9025 // exceed the implementation-defined limit 9026 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9027 ArrayBound) > 9028 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9029 if (IsNothrow) 9030 return ZeroInitialization(E); 9031 9032 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9033 << ArrayBound << (*ArraySize)->getSourceRange(); 9034 return false; 9035 } 9036 9037 // -- the new-initializer is a braced-init-list and the number of 9038 // array elements for which initializers are provided [...] 9039 // exceeds the number of elements to initialize 9040 if (!Init) { 9041 // No initialization is performed. 9042 } else if (isa<CXXScalarValueInitExpr>(Init) || 9043 isa<ImplicitValueInitExpr>(Init)) { 9044 ValueInit = true; 9045 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9046 ResizedArrayCCE = CCE; 9047 } else { 9048 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9049 assert(CAT && "unexpected type for array initializer"); 9050 9051 unsigned Bits = 9052 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9053 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9054 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9055 if (InitBound.ugt(AllocBound)) { 9056 if (IsNothrow) 9057 return ZeroInitialization(E); 9058 9059 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9060 << AllocBound.toString(10, /*Signed=*/false) 9061 << InitBound.toString(10, /*Signed=*/false) 9062 << (*ArraySize)->getSourceRange(); 9063 return false; 9064 } 9065 9066 // If the sizes differ, we must have an initializer list, and we need 9067 // special handling for this case when we initialize. 9068 if (InitBound != AllocBound) 9069 ResizedArrayILE = cast<InitListExpr>(Init); 9070 } 9071 9072 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9073 ArrayType::Normal, 0); 9074 } else { 9075 assert(!AllocType->isArrayType() && 9076 "array allocation with non-array new"); 9077 } 9078 9079 APValue *Val; 9080 if (IsPlacement) { 9081 AccessKinds AK = AK_Construct; 9082 struct FindObjectHandler { 9083 EvalInfo &Info; 9084 const Expr *E; 9085 QualType AllocType; 9086 const AccessKinds AccessKind; 9087 APValue *Value; 9088 9089 typedef bool result_type; 9090 bool failed() { return false; } 9091 bool found(APValue &Subobj, QualType SubobjType) { 9092 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9093 // old name of the object to be used to name the new object. 9094 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9095 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9096 SubobjType << AllocType; 9097 return false; 9098 } 9099 Value = &Subobj; 9100 return true; 9101 } 9102 bool found(APSInt &Value, QualType SubobjType) { 9103 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9104 return false; 9105 } 9106 bool found(APFloat &Value, QualType SubobjType) { 9107 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9108 return false; 9109 } 9110 } Handler = {Info, E, AllocType, AK, nullptr}; 9111 9112 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9113 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9114 return false; 9115 9116 Val = Handler.Value; 9117 9118 // [basic.life]p1: 9119 // The lifetime of an object o of type T ends when [...] the storage 9120 // which the object occupies is [...] reused by an object that is not 9121 // nested within o (6.6.2). 9122 *Val = APValue(); 9123 } else { 9124 // Perform the allocation and obtain a pointer to the resulting object. 9125 Val = Info.createHeapAlloc(E, AllocType, Result); 9126 if (!Val) 9127 return false; 9128 } 9129 9130 if (ValueInit) { 9131 ImplicitValueInitExpr VIE(AllocType); 9132 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9133 return false; 9134 } else if (ResizedArrayILE) { 9135 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9136 AllocType)) 9137 return false; 9138 } else if (ResizedArrayCCE) { 9139 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9140 AllocType)) 9141 return false; 9142 } else if (Init) { 9143 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9144 return false; 9145 } else if (!getDefaultInitValue(AllocType, *Val)) { 9146 return false; 9147 } 9148 9149 // Array new returns a pointer to the first element, not a pointer to the 9150 // array. 9151 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9152 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9153 9154 return true; 9155 } 9156 //===----------------------------------------------------------------------===// 9157 // Member Pointer Evaluation 9158 //===----------------------------------------------------------------------===// 9159 9160 namespace { 9161 class MemberPointerExprEvaluator 9162 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9163 MemberPtr &Result; 9164 9165 bool Success(const ValueDecl *D) { 9166 Result = MemberPtr(D); 9167 return true; 9168 } 9169 public: 9170 9171 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9172 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9173 9174 bool Success(const APValue &V, const Expr *E) { 9175 Result.setFrom(V); 9176 return true; 9177 } 9178 bool ZeroInitialization(const Expr *E) { 9179 return Success((const ValueDecl*)nullptr); 9180 } 9181 9182 bool VisitCastExpr(const CastExpr *E); 9183 bool VisitUnaryAddrOf(const UnaryOperator *E); 9184 }; 9185 } // end anonymous namespace 9186 9187 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9188 EvalInfo &Info) { 9189 assert(E->isRValue() && E->getType()->isMemberPointerType()); 9190 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9191 } 9192 9193 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9194 switch (E->getCastKind()) { 9195 default: 9196 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9197 9198 case CK_NullToMemberPointer: 9199 VisitIgnoredValue(E->getSubExpr()); 9200 return ZeroInitialization(E); 9201 9202 case CK_BaseToDerivedMemberPointer: { 9203 if (!Visit(E->getSubExpr())) 9204 return false; 9205 if (E->path_empty()) 9206 return true; 9207 // Base-to-derived member pointer casts store the path in derived-to-base 9208 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9209 // the wrong end of the derived->base arc, so stagger the path by one class. 9210 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9211 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9212 PathI != PathE; ++PathI) { 9213 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9214 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9215 if (!Result.castToDerived(Derived)) 9216 return Error(E); 9217 } 9218 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9219 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9220 return Error(E); 9221 return true; 9222 } 9223 9224 case CK_DerivedToBaseMemberPointer: 9225 if (!Visit(E->getSubExpr())) 9226 return false; 9227 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9228 PathE = E->path_end(); PathI != PathE; ++PathI) { 9229 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9230 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9231 if (!Result.castToBase(Base)) 9232 return Error(E); 9233 } 9234 return true; 9235 } 9236 } 9237 9238 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9239 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9240 // member can be formed. 9241 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9242 } 9243 9244 //===----------------------------------------------------------------------===// 9245 // Record Evaluation 9246 //===----------------------------------------------------------------------===// 9247 9248 namespace { 9249 class RecordExprEvaluator 9250 : public ExprEvaluatorBase<RecordExprEvaluator> { 9251 const LValue &This; 9252 APValue &Result; 9253 public: 9254 9255 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9256 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9257 9258 bool Success(const APValue &V, const Expr *E) { 9259 Result = V; 9260 return true; 9261 } 9262 bool ZeroInitialization(const Expr *E) { 9263 return ZeroInitialization(E, E->getType()); 9264 } 9265 bool ZeroInitialization(const Expr *E, QualType T); 9266 9267 bool VisitCallExpr(const CallExpr *E) { 9268 return handleCallExpr(E, Result, &This); 9269 } 9270 bool VisitCastExpr(const CastExpr *E); 9271 bool VisitInitListExpr(const InitListExpr *E); 9272 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9273 return VisitCXXConstructExpr(E, E->getType()); 9274 } 9275 bool VisitLambdaExpr(const LambdaExpr *E); 9276 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9277 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9278 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9279 bool VisitBinCmp(const BinaryOperator *E); 9280 }; 9281 } 9282 9283 /// Perform zero-initialization on an object of non-union class type. 9284 /// C++11 [dcl.init]p5: 9285 /// To zero-initialize an object or reference of type T means: 9286 /// [...] 9287 /// -- if T is a (possibly cv-qualified) non-union class type, 9288 /// each non-static data member and each base-class subobject is 9289 /// zero-initialized 9290 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9291 const RecordDecl *RD, 9292 const LValue &This, APValue &Result) { 9293 assert(!RD->isUnion() && "Expected non-union class type"); 9294 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9295 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9296 std::distance(RD->field_begin(), RD->field_end())); 9297 9298 if (RD->isInvalidDecl()) return false; 9299 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9300 9301 if (CD) { 9302 unsigned Index = 0; 9303 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9304 End = CD->bases_end(); I != End; ++I, ++Index) { 9305 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9306 LValue Subobject = This; 9307 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9308 return false; 9309 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9310 Result.getStructBase(Index))) 9311 return false; 9312 } 9313 } 9314 9315 for (const auto *I : RD->fields()) { 9316 // -- if T is a reference type, no initialization is performed. 9317 if (I->getType()->isReferenceType()) 9318 continue; 9319 9320 LValue Subobject = This; 9321 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9322 return false; 9323 9324 ImplicitValueInitExpr VIE(I->getType()); 9325 if (!EvaluateInPlace( 9326 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9327 return false; 9328 } 9329 9330 return true; 9331 } 9332 9333 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9334 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9335 if (RD->isInvalidDecl()) return false; 9336 if (RD->isUnion()) { 9337 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9338 // object's first non-static named data member is zero-initialized 9339 RecordDecl::field_iterator I = RD->field_begin(); 9340 if (I == RD->field_end()) { 9341 Result = APValue((const FieldDecl*)nullptr); 9342 return true; 9343 } 9344 9345 LValue Subobject = This; 9346 if (!HandleLValueMember(Info, E, Subobject, *I)) 9347 return false; 9348 Result = APValue(*I); 9349 ImplicitValueInitExpr VIE(I->getType()); 9350 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9351 } 9352 9353 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9354 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9355 return false; 9356 } 9357 9358 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9359 } 9360 9361 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9362 switch (E->getCastKind()) { 9363 default: 9364 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9365 9366 case CK_ConstructorConversion: 9367 return Visit(E->getSubExpr()); 9368 9369 case CK_DerivedToBase: 9370 case CK_UncheckedDerivedToBase: { 9371 APValue DerivedObject; 9372 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9373 return false; 9374 if (!DerivedObject.isStruct()) 9375 return Error(E->getSubExpr()); 9376 9377 // Derived-to-base rvalue conversion: just slice off the derived part. 9378 APValue *Value = &DerivedObject; 9379 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9380 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9381 PathE = E->path_end(); PathI != PathE; ++PathI) { 9382 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9383 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9384 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9385 RD = Base; 9386 } 9387 Result = *Value; 9388 return true; 9389 } 9390 } 9391 } 9392 9393 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9394 if (E->isTransparent()) 9395 return Visit(E->getInit(0)); 9396 9397 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9398 if (RD->isInvalidDecl()) return false; 9399 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9400 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9401 9402 EvalInfo::EvaluatingConstructorRAII EvalObj( 9403 Info, 9404 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9405 CXXRD && CXXRD->getNumBases()); 9406 9407 if (RD->isUnion()) { 9408 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9409 Result = APValue(Field); 9410 if (!Field) 9411 return true; 9412 9413 // If the initializer list for a union does not contain any elements, the 9414 // first element of the union is value-initialized. 9415 // FIXME: The element should be initialized from an initializer list. 9416 // Is this difference ever observable for initializer lists which 9417 // we don't build? 9418 ImplicitValueInitExpr VIE(Field->getType()); 9419 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9420 9421 LValue Subobject = This; 9422 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9423 return false; 9424 9425 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9426 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9427 isa<CXXDefaultInitExpr>(InitExpr)); 9428 9429 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 9430 } 9431 9432 if (!Result.hasValue()) 9433 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9434 std::distance(RD->field_begin(), RD->field_end())); 9435 unsigned ElementNo = 0; 9436 bool Success = true; 9437 9438 // Initialize base classes. 9439 if (CXXRD && CXXRD->getNumBases()) { 9440 for (const auto &Base : CXXRD->bases()) { 9441 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9442 const Expr *Init = E->getInit(ElementNo); 9443 9444 LValue Subobject = This; 9445 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9446 return false; 9447 9448 APValue &FieldVal = Result.getStructBase(ElementNo); 9449 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9450 if (!Info.noteFailure()) 9451 return false; 9452 Success = false; 9453 } 9454 ++ElementNo; 9455 } 9456 9457 EvalObj.finishedConstructingBases(); 9458 } 9459 9460 // Initialize members. 9461 for (const auto *Field : RD->fields()) { 9462 // Anonymous bit-fields are not considered members of the class for 9463 // purposes of aggregate initialization. 9464 if (Field->isUnnamedBitfield()) 9465 continue; 9466 9467 LValue Subobject = This; 9468 9469 bool HaveInit = ElementNo < E->getNumInits(); 9470 9471 // FIXME: Diagnostics here should point to the end of the initializer 9472 // list, not the start. 9473 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9474 Subobject, Field, &Layout)) 9475 return false; 9476 9477 // Perform an implicit value-initialization for members beyond the end of 9478 // the initializer list. 9479 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9480 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9481 9482 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9483 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9484 isa<CXXDefaultInitExpr>(Init)); 9485 9486 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9487 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9488 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9489 FieldVal, Field))) { 9490 if (!Info.noteFailure()) 9491 return false; 9492 Success = false; 9493 } 9494 } 9495 9496 EvalObj.finishedConstructingFields(); 9497 9498 return Success; 9499 } 9500 9501 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9502 QualType T) { 9503 // Note that E's type is not necessarily the type of our class here; we might 9504 // be initializing an array element instead. 9505 const CXXConstructorDecl *FD = E->getConstructor(); 9506 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9507 9508 bool ZeroInit = E->requiresZeroInitialization(); 9509 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9510 // If we've already performed zero-initialization, we're already done. 9511 if (Result.hasValue()) 9512 return true; 9513 9514 if (ZeroInit) 9515 return ZeroInitialization(E, T); 9516 9517 return getDefaultInitValue(T, Result); 9518 } 9519 9520 const FunctionDecl *Definition = nullptr; 9521 auto Body = FD->getBody(Definition); 9522 9523 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9524 return false; 9525 9526 // Avoid materializing a temporary for an elidable copy/move constructor. 9527 if (E->isElidable() && !ZeroInit) 9528 if (const MaterializeTemporaryExpr *ME 9529 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9530 return Visit(ME->getSubExpr()); 9531 9532 if (ZeroInit && !ZeroInitialization(E, T)) 9533 return false; 9534 9535 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9536 return HandleConstructorCall(E, This, Args, 9537 cast<CXXConstructorDecl>(Definition), Info, 9538 Result); 9539 } 9540 9541 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9542 const CXXInheritedCtorInitExpr *E) { 9543 if (!Info.CurrentCall) { 9544 assert(Info.checkingPotentialConstantExpression()); 9545 return false; 9546 } 9547 9548 const CXXConstructorDecl *FD = E->getConstructor(); 9549 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9550 return false; 9551 9552 const FunctionDecl *Definition = nullptr; 9553 auto Body = FD->getBody(Definition); 9554 9555 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9556 return false; 9557 9558 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9559 cast<CXXConstructorDecl>(Definition), Info, 9560 Result); 9561 } 9562 9563 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9564 const CXXStdInitializerListExpr *E) { 9565 const ConstantArrayType *ArrayType = 9566 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9567 9568 LValue Array; 9569 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9570 return false; 9571 9572 // Get a pointer to the first element of the array. 9573 Array.addArray(Info, E, ArrayType); 9574 9575 auto InvalidType = [&] { 9576 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9577 << E->getType(); 9578 return false; 9579 }; 9580 9581 // FIXME: Perform the checks on the field types in SemaInit. 9582 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9583 RecordDecl::field_iterator Field = Record->field_begin(); 9584 if (Field == Record->field_end()) 9585 return InvalidType(); 9586 9587 // Start pointer. 9588 if (!Field->getType()->isPointerType() || 9589 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9590 ArrayType->getElementType())) 9591 return InvalidType(); 9592 9593 // FIXME: What if the initializer_list type has base classes, etc? 9594 Result = APValue(APValue::UninitStruct(), 0, 2); 9595 Array.moveInto(Result.getStructField(0)); 9596 9597 if (++Field == Record->field_end()) 9598 return InvalidType(); 9599 9600 if (Field->getType()->isPointerType() && 9601 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9602 ArrayType->getElementType())) { 9603 // End pointer. 9604 if (!HandleLValueArrayAdjustment(Info, E, Array, 9605 ArrayType->getElementType(), 9606 ArrayType->getSize().getZExtValue())) 9607 return false; 9608 Array.moveInto(Result.getStructField(1)); 9609 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9610 // Length. 9611 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9612 else 9613 return InvalidType(); 9614 9615 if (++Field != Record->field_end()) 9616 return InvalidType(); 9617 9618 return true; 9619 } 9620 9621 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 9622 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 9623 if (ClosureClass->isInvalidDecl()) 9624 return false; 9625 9626 const size_t NumFields = 9627 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 9628 9629 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 9630 E->capture_init_end()) && 9631 "The number of lambda capture initializers should equal the number of " 9632 "fields within the closure type"); 9633 9634 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 9635 // Iterate through all the lambda's closure object's fields and initialize 9636 // them. 9637 auto *CaptureInitIt = E->capture_init_begin(); 9638 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 9639 bool Success = true; 9640 for (const auto *Field : ClosureClass->fields()) { 9641 assert(CaptureInitIt != E->capture_init_end()); 9642 // Get the initializer for this field 9643 Expr *const CurFieldInit = *CaptureInitIt++; 9644 9645 // If there is no initializer, either this is a VLA or an error has 9646 // occurred. 9647 if (!CurFieldInit) 9648 return Error(E); 9649 9650 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9651 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 9652 if (!Info.keepEvaluatingAfterFailure()) 9653 return false; 9654 Success = false; 9655 } 9656 ++CaptureIt; 9657 } 9658 return Success; 9659 } 9660 9661 static bool EvaluateRecord(const Expr *E, const LValue &This, 9662 APValue &Result, EvalInfo &Info) { 9663 assert(E->isRValue() && E->getType()->isRecordType() && 9664 "can't evaluate expression as a record rvalue"); 9665 return RecordExprEvaluator(Info, This, Result).Visit(E); 9666 } 9667 9668 //===----------------------------------------------------------------------===// 9669 // Temporary Evaluation 9670 // 9671 // Temporaries are represented in the AST as rvalues, but generally behave like 9672 // lvalues. The full-object of which the temporary is a subobject is implicitly 9673 // materialized so that a reference can bind to it. 9674 //===----------------------------------------------------------------------===// 9675 namespace { 9676 class TemporaryExprEvaluator 9677 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 9678 public: 9679 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 9680 LValueExprEvaluatorBaseTy(Info, Result, false) {} 9681 9682 /// Visit an expression which constructs the value of this temporary. 9683 bool VisitConstructExpr(const Expr *E) { 9684 APValue &Value = 9685 Info.CurrentCall->createTemporary(E, E->getType(), false, Result); 9686 return EvaluateInPlace(Value, Info, Result, E); 9687 } 9688 9689 bool VisitCastExpr(const CastExpr *E) { 9690 switch (E->getCastKind()) { 9691 default: 9692 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 9693 9694 case CK_ConstructorConversion: 9695 return VisitConstructExpr(E->getSubExpr()); 9696 } 9697 } 9698 bool VisitInitListExpr(const InitListExpr *E) { 9699 return VisitConstructExpr(E); 9700 } 9701 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9702 return VisitConstructExpr(E); 9703 } 9704 bool VisitCallExpr(const CallExpr *E) { 9705 return VisitConstructExpr(E); 9706 } 9707 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 9708 return VisitConstructExpr(E); 9709 } 9710 bool VisitLambdaExpr(const LambdaExpr *E) { 9711 return VisitConstructExpr(E); 9712 } 9713 }; 9714 } // end anonymous namespace 9715 9716 /// Evaluate an expression of record type as a temporary. 9717 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 9718 assert(E->isRValue() && E->getType()->isRecordType()); 9719 return TemporaryExprEvaluator(Info, Result).Visit(E); 9720 } 9721 9722 //===----------------------------------------------------------------------===// 9723 // Vector Evaluation 9724 //===----------------------------------------------------------------------===// 9725 9726 namespace { 9727 class VectorExprEvaluator 9728 : public ExprEvaluatorBase<VectorExprEvaluator> { 9729 APValue &Result; 9730 public: 9731 9732 VectorExprEvaluator(EvalInfo &info, APValue &Result) 9733 : ExprEvaluatorBaseTy(info), Result(Result) {} 9734 9735 bool Success(ArrayRef<APValue> V, const Expr *E) { 9736 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 9737 // FIXME: remove this APValue copy. 9738 Result = APValue(V.data(), V.size()); 9739 return true; 9740 } 9741 bool Success(const APValue &V, const Expr *E) { 9742 assert(V.isVector()); 9743 Result = V; 9744 return true; 9745 } 9746 bool ZeroInitialization(const Expr *E); 9747 9748 bool VisitUnaryReal(const UnaryOperator *E) 9749 { return Visit(E->getSubExpr()); } 9750 bool VisitCastExpr(const CastExpr* E); 9751 bool VisitInitListExpr(const InitListExpr *E); 9752 bool VisitUnaryImag(const UnaryOperator *E); 9753 bool VisitBinaryOperator(const BinaryOperator *E); 9754 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 9755 // conditional select), shufflevector, ExtVectorElementExpr 9756 }; 9757 } // end anonymous namespace 9758 9759 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 9760 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 9761 return VectorExprEvaluator(Info, Result).Visit(E); 9762 } 9763 9764 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 9765 const VectorType *VTy = E->getType()->castAs<VectorType>(); 9766 unsigned NElts = VTy->getNumElements(); 9767 9768 const Expr *SE = E->getSubExpr(); 9769 QualType SETy = SE->getType(); 9770 9771 switch (E->getCastKind()) { 9772 case CK_VectorSplat: { 9773 APValue Val = APValue(); 9774 if (SETy->isIntegerType()) { 9775 APSInt IntResult; 9776 if (!EvaluateInteger(SE, IntResult, Info)) 9777 return false; 9778 Val = APValue(std::move(IntResult)); 9779 } else if (SETy->isRealFloatingType()) { 9780 APFloat FloatResult(0.0); 9781 if (!EvaluateFloat(SE, FloatResult, Info)) 9782 return false; 9783 Val = APValue(std::move(FloatResult)); 9784 } else { 9785 return Error(E); 9786 } 9787 9788 // Splat and create vector APValue. 9789 SmallVector<APValue, 4> Elts(NElts, Val); 9790 return Success(Elts, E); 9791 } 9792 case CK_BitCast: { 9793 // Evaluate the operand into an APInt we can extract from. 9794 llvm::APInt SValInt; 9795 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 9796 return false; 9797 // Extract the elements 9798 QualType EltTy = VTy->getElementType(); 9799 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 9800 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 9801 SmallVector<APValue, 4> Elts; 9802 if (EltTy->isRealFloatingType()) { 9803 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 9804 unsigned FloatEltSize = EltSize; 9805 if (&Sem == &APFloat::x87DoubleExtended()) 9806 FloatEltSize = 80; 9807 for (unsigned i = 0; i < NElts; i++) { 9808 llvm::APInt Elt; 9809 if (BigEndian) 9810 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 9811 else 9812 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 9813 Elts.push_back(APValue(APFloat(Sem, Elt))); 9814 } 9815 } else if (EltTy->isIntegerType()) { 9816 for (unsigned i = 0; i < NElts; i++) { 9817 llvm::APInt Elt; 9818 if (BigEndian) 9819 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 9820 else 9821 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 9822 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 9823 } 9824 } else { 9825 return Error(E); 9826 } 9827 return Success(Elts, E); 9828 } 9829 default: 9830 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9831 } 9832 } 9833 9834 bool 9835 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9836 const VectorType *VT = E->getType()->castAs<VectorType>(); 9837 unsigned NumInits = E->getNumInits(); 9838 unsigned NumElements = VT->getNumElements(); 9839 9840 QualType EltTy = VT->getElementType(); 9841 SmallVector<APValue, 4> Elements; 9842 9843 // The number of initializers can be less than the number of 9844 // vector elements. For OpenCL, this can be due to nested vector 9845 // initialization. For GCC compatibility, missing trailing elements 9846 // should be initialized with zeroes. 9847 unsigned CountInits = 0, CountElts = 0; 9848 while (CountElts < NumElements) { 9849 // Handle nested vector initialization. 9850 if (CountInits < NumInits 9851 && E->getInit(CountInits)->getType()->isVectorType()) { 9852 APValue v; 9853 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 9854 return Error(E); 9855 unsigned vlen = v.getVectorLength(); 9856 for (unsigned j = 0; j < vlen; j++) 9857 Elements.push_back(v.getVectorElt(j)); 9858 CountElts += vlen; 9859 } else if (EltTy->isIntegerType()) { 9860 llvm::APSInt sInt(32); 9861 if (CountInits < NumInits) { 9862 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 9863 return false; 9864 } else // trailing integer zero. 9865 sInt = Info.Ctx.MakeIntValue(0, EltTy); 9866 Elements.push_back(APValue(sInt)); 9867 CountElts++; 9868 } else { 9869 llvm::APFloat f(0.0); 9870 if (CountInits < NumInits) { 9871 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 9872 return false; 9873 } else // trailing float zero. 9874 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 9875 Elements.push_back(APValue(f)); 9876 CountElts++; 9877 } 9878 CountInits++; 9879 } 9880 return Success(Elements, E); 9881 } 9882 9883 bool 9884 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 9885 const auto *VT = E->getType()->castAs<VectorType>(); 9886 QualType EltTy = VT->getElementType(); 9887 APValue ZeroElement; 9888 if (EltTy->isIntegerType()) 9889 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 9890 else 9891 ZeroElement = 9892 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 9893 9894 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 9895 return Success(Elements, E); 9896 } 9897 9898 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9899 VisitIgnoredValue(E->getSubExpr()); 9900 return ZeroInitialization(E); 9901 } 9902 9903 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9904 BinaryOperatorKind Op = E->getOpcode(); 9905 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 9906 "Operation not supported on vector types"); 9907 9908 if (Op == BO_Comma) 9909 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9910 9911 Expr *LHS = E->getLHS(); 9912 Expr *RHS = E->getRHS(); 9913 9914 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 9915 "Must both be vector types"); 9916 // Checking JUST the types are the same would be fine, except shifts don't 9917 // need to have their types be the same (since you always shift by an int). 9918 assert(LHS->getType()->getAs<VectorType>()->getNumElements() == 9919 E->getType()->getAs<VectorType>()->getNumElements() && 9920 RHS->getType()->getAs<VectorType>()->getNumElements() == 9921 E->getType()->getAs<VectorType>()->getNumElements() && 9922 "All operands must be the same size."); 9923 9924 APValue LHSValue; 9925 APValue RHSValue; 9926 bool LHSOK = Evaluate(LHSValue, Info, LHS); 9927 if (!LHSOK && !Info.noteFailure()) 9928 return false; 9929 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 9930 return false; 9931 9932 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 9933 return false; 9934 9935 return Success(LHSValue, E); 9936 } 9937 9938 //===----------------------------------------------------------------------===// 9939 // Array Evaluation 9940 //===----------------------------------------------------------------------===// 9941 9942 namespace { 9943 class ArrayExprEvaluator 9944 : public ExprEvaluatorBase<ArrayExprEvaluator> { 9945 const LValue &This; 9946 APValue &Result; 9947 public: 9948 9949 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 9950 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 9951 9952 bool Success(const APValue &V, const Expr *E) { 9953 assert(V.isArray() && "expected array"); 9954 Result = V; 9955 return true; 9956 } 9957 9958 bool ZeroInitialization(const Expr *E) { 9959 const ConstantArrayType *CAT = 9960 Info.Ctx.getAsConstantArrayType(E->getType()); 9961 if (!CAT) { 9962 if (E->getType()->isIncompleteArrayType()) { 9963 // We can be asked to zero-initialize a flexible array member; this 9964 // is represented as an ImplicitValueInitExpr of incomplete array 9965 // type. In this case, the array has zero elements. 9966 Result = APValue(APValue::UninitArray(), 0, 0); 9967 return true; 9968 } 9969 // FIXME: We could handle VLAs here. 9970 return Error(E); 9971 } 9972 9973 Result = APValue(APValue::UninitArray(), 0, 9974 CAT->getSize().getZExtValue()); 9975 if (!Result.hasArrayFiller()) return true; 9976 9977 // Zero-initialize all elements. 9978 LValue Subobject = This; 9979 Subobject.addArray(Info, E, CAT); 9980 ImplicitValueInitExpr VIE(CAT->getElementType()); 9981 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 9982 } 9983 9984 bool VisitCallExpr(const CallExpr *E) { 9985 return handleCallExpr(E, Result, &This); 9986 } 9987 bool VisitInitListExpr(const InitListExpr *E, 9988 QualType AllocType = QualType()); 9989 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 9990 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 9991 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 9992 const LValue &Subobject, 9993 APValue *Value, QualType Type); 9994 bool VisitStringLiteral(const StringLiteral *E, 9995 QualType AllocType = QualType()) { 9996 expandStringLiteral(Info, E, Result, AllocType); 9997 return true; 9998 } 9999 }; 10000 } // end anonymous namespace 10001 10002 static bool EvaluateArray(const Expr *E, const LValue &This, 10003 APValue &Result, EvalInfo &Info) { 10004 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 10005 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10006 } 10007 10008 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10009 APValue &Result, const InitListExpr *ILE, 10010 QualType AllocType) { 10011 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 10012 "not an array rvalue"); 10013 return ArrayExprEvaluator(Info, This, Result) 10014 .VisitInitListExpr(ILE, AllocType); 10015 } 10016 10017 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10018 APValue &Result, 10019 const CXXConstructExpr *CCE, 10020 QualType AllocType) { 10021 assert(CCE->isRValue() && CCE->getType()->isArrayType() && 10022 "not an array rvalue"); 10023 return ArrayExprEvaluator(Info, This, Result) 10024 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10025 } 10026 10027 // Return true iff the given array filler may depend on the element index. 10028 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10029 // For now, just allow non-class value-initialization and initialization 10030 // lists comprised of them. 10031 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10032 return false; 10033 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10034 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10035 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10036 return true; 10037 } 10038 return false; 10039 } 10040 return true; 10041 } 10042 10043 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10044 QualType AllocType) { 10045 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10046 AllocType.isNull() ? E->getType() : AllocType); 10047 if (!CAT) 10048 return Error(E); 10049 10050 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10051 // an appropriately-typed string literal enclosed in braces. 10052 if (E->isStringLiteralInit()) { 10053 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 10054 // FIXME: Support ObjCEncodeExpr here once we support it in 10055 // ArrayExprEvaluator generally. 10056 if (!SL) 10057 return Error(E); 10058 return VisitStringLiteral(SL, AllocType); 10059 } 10060 10061 bool Success = true; 10062 10063 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10064 "zero-initialized array shouldn't have any initialized elts"); 10065 APValue Filler; 10066 if (Result.isArray() && Result.hasArrayFiller()) 10067 Filler = Result.getArrayFiller(); 10068 10069 unsigned NumEltsToInit = E->getNumInits(); 10070 unsigned NumElts = CAT->getSize().getZExtValue(); 10071 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10072 10073 // If the initializer might depend on the array index, run it for each 10074 // array element. 10075 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10076 NumEltsToInit = NumElts; 10077 10078 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10079 << NumEltsToInit << ".\n"); 10080 10081 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10082 10083 // If the array was previously zero-initialized, preserve the 10084 // zero-initialized values. 10085 if (Filler.hasValue()) { 10086 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10087 Result.getArrayInitializedElt(I) = Filler; 10088 if (Result.hasArrayFiller()) 10089 Result.getArrayFiller() = Filler; 10090 } 10091 10092 LValue Subobject = This; 10093 Subobject.addArray(Info, E, CAT); 10094 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10095 const Expr *Init = 10096 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10097 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10098 Info, Subobject, Init) || 10099 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10100 CAT->getElementType(), 1)) { 10101 if (!Info.noteFailure()) 10102 return false; 10103 Success = false; 10104 } 10105 } 10106 10107 if (!Result.hasArrayFiller()) 10108 return Success; 10109 10110 // If we get here, we have a trivial filler, which we can just evaluate 10111 // once and splat over the rest of the array elements. 10112 assert(FillerExpr && "no array filler for incomplete init list"); 10113 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10114 FillerExpr) && Success; 10115 } 10116 10117 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10118 LValue CommonLV; 10119 if (E->getCommonExpr() && 10120 !Evaluate(Info.CurrentCall->createTemporary( 10121 E->getCommonExpr(), 10122 getStorageType(Info.Ctx, E->getCommonExpr()), false, 10123 CommonLV), 10124 Info, E->getCommonExpr()->getSourceExpr())) 10125 return false; 10126 10127 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10128 10129 uint64_t Elements = CAT->getSize().getZExtValue(); 10130 Result = APValue(APValue::UninitArray(), Elements, Elements); 10131 10132 LValue Subobject = This; 10133 Subobject.addArray(Info, E, CAT); 10134 10135 bool Success = true; 10136 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10137 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10138 Info, Subobject, E->getSubExpr()) || 10139 !HandleLValueArrayAdjustment(Info, E, Subobject, 10140 CAT->getElementType(), 1)) { 10141 if (!Info.noteFailure()) 10142 return false; 10143 Success = false; 10144 } 10145 } 10146 10147 return Success; 10148 } 10149 10150 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10151 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10152 } 10153 10154 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10155 const LValue &Subobject, 10156 APValue *Value, 10157 QualType Type) { 10158 bool HadZeroInit = Value->hasValue(); 10159 10160 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10161 unsigned N = CAT->getSize().getZExtValue(); 10162 10163 // Preserve the array filler if we had prior zero-initialization. 10164 APValue Filler = 10165 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10166 : APValue(); 10167 10168 *Value = APValue(APValue::UninitArray(), N, N); 10169 10170 if (HadZeroInit) 10171 for (unsigned I = 0; I != N; ++I) 10172 Value->getArrayInitializedElt(I) = Filler; 10173 10174 // Initialize the elements. 10175 LValue ArrayElt = Subobject; 10176 ArrayElt.addArray(Info, E, CAT); 10177 for (unsigned I = 0; I != N; ++I) 10178 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10179 CAT->getElementType()) || 10180 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10181 CAT->getElementType(), 1)) 10182 return false; 10183 10184 return true; 10185 } 10186 10187 if (!Type->isRecordType()) 10188 return Error(E); 10189 10190 return RecordExprEvaluator(Info, Subobject, *Value) 10191 .VisitCXXConstructExpr(E, Type); 10192 } 10193 10194 //===----------------------------------------------------------------------===// 10195 // Integer Evaluation 10196 // 10197 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10198 // types and back in constant folding. Integer values are thus represented 10199 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10200 //===----------------------------------------------------------------------===// 10201 10202 namespace { 10203 class IntExprEvaluator 10204 : public ExprEvaluatorBase<IntExprEvaluator> { 10205 APValue &Result; 10206 public: 10207 IntExprEvaluator(EvalInfo &info, APValue &result) 10208 : ExprEvaluatorBaseTy(info), Result(result) {} 10209 10210 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10211 assert(E->getType()->isIntegralOrEnumerationType() && 10212 "Invalid evaluation result."); 10213 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10214 "Invalid evaluation result."); 10215 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10216 "Invalid evaluation result."); 10217 Result = APValue(SI); 10218 return true; 10219 } 10220 bool Success(const llvm::APSInt &SI, const Expr *E) { 10221 return Success(SI, E, Result); 10222 } 10223 10224 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10225 assert(E->getType()->isIntegralOrEnumerationType() && 10226 "Invalid evaluation result."); 10227 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10228 "Invalid evaluation result."); 10229 Result = APValue(APSInt(I)); 10230 Result.getInt().setIsUnsigned( 10231 E->getType()->isUnsignedIntegerOrEnumerationType()); 10232 return true; 10233 } 10234 bool Success(const llvm::APInt &I, const Expr *E) { 10235 return Success(I, E, Result); 10236 } 10237 10238 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10239 assert(E->getType()->isIntegralOrEnumerationType() && 10240 "Invalid evaluation result."); 10241 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10242 return true; 10243 } 10244 bool Success(uint64_t Value, const Expr *E) { 10245 return Success(Value, E, Result); 10246 } 10247 10248 bool Success(CharUnits Size, const Expr *E) { 10249 return Success(Size.getQuantity(), E); 10250 } 10251 10252 bool Success(const APValue &V, const Expr *E) { 10253 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10254 Result = V; 10255 return true; 10256 } 10257 return Success(V.getInt(), E); 10258 } 10259 10260 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10261 10262 //===--------------------------------------------------------------------===// 10263 // Visitor Methods 10264 //===--------------------------------------------------------------------===// 10265 10266 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10267 return Success(E->getValue(), E); 10268 } 10269 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10270 return Success(E->getValue(), E); 10271 } 10272 10273 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10274 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10275 if (CheckReferencedDecl(E, E->getDecl())) 10276 return true; 10277 10278 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10279 } 10280 bool VisitMemberExpr(const MemberExpr *E) { 10281 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10282 VisitIgnoredBaseExpression(E->getBase()); 10283 return true; 10284 } 10285 10286 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10287 } 10288 10289 bool VisitCallExpr(const CallExpr *E); 10290 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10291 bool VisitBinaryOperator(const BinaryOperator *E); 10292 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10293 bool VisitUnaryOperator(const UnaryOperator *E); 10294 10295 bool VisitCastExpr(const CastExpr* E); 10296 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10297 10298 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10299 return Success(E->getValue(), E); 10300 } 10301 10302 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10303 return Success(E->getValue(), E); 10304 } 10305 10306 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10307 if (Info.ArrayInitIndex == uint64_t(-1)) { 10308 // We were asked to evaluate this subexpression independent of the 10309 // enclosing ArrayInitLoopExpr. We can't do that. 10310 Info.FFDiag(E); 10311 return false; 10312 } 10313 return Success(Info.ArrayInitIndex, E); 10314 } 10315 10316 // Note, GNU defines __null as an integer, not a pointer. 10317 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10318 return ZeroInitialization(E); 10319 } 10320 10321 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10322 return Success(E->getValue(), E); 10323 } 10324 10325 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10326 return Success(E->getValue(), E); 10327 } 10328 10329 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10330 return Success(E->getValue(), E); 10331 } 10332 10333 bool VisitUnaryReal(const UnaryOperator *E); 10334 bool VisitUnaryImag(const UnaryOperator *E); 10335 10336 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10337 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10338 bool VisitSourceLocExpr(const SourceLocExpr *E); 10339 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10340 bool VisitRequiresExpr(const RequiresExpr *E); 10341 // FIXME: Missing: array subscript of vector, member of vector 10342 }; 10343 10344 class FixedPointExprEvaluator 10345 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10346 APValue &Result; 10347 10348 public: 10349 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10350 : ExprEvaluatorBaseTy(info), Result(result) {} 10351 10352 bool Success(const llvm::APInt &I, const Expr *E) { 10353 return Success( 10354 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10355 } 10356 10357 bool Success(uint64_t Value, const Expr *E) { 10358 return Success( 10359 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10360 } 10361 10362 bool Success(const APValue &V, const Expr *E) { 10363 return Success(V.getFixedPoint(), E); 10364 } 10365 10366 bool Success(const APFixedPoint &V, const Expr *E) { 10367 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10368 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10369 "Invalid evaluation result."); 10370 Result = APValue(V); 10371 return true; 10372 } 10373 10374 //===--------------------------------------------------------------------===// 10375 // Visitor Methods 10376 //===--------------------------------------------------------------------===// 10377 10378 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10379 return Success(E->getValue(), E); 10380 } 10381 10382 bool VisitCastExpr(const CastExpr *E); 10383 bool VisitUnaryOperator(const UnaryOperator *E); 10384 bool VisitBinaryOperator(const BinaryOperator *E); 10385 }; 10386 } // end anonymous namespace 10387 10388 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10389 /// produce either the integer value or a pointer. 10390 /// 10391 /// GCC has a heinous extension which folds casts between pointer types and 10392 /// pointer-sized integral types. We support this by allowing the evaluation of 10393 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10394 /// Some simple arithmetic on such values is supported (they are treated much 10395 /// like char*). 10396 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10397 EvalInfo &Info) { 10398 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10399 return IntExprEvaluator(Info, Result).Visit(E); 10400 } 10401 10402 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10403 APValue Val; 10404 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10405 return false; 10406 if (!Val.isInt()) { 10407 // FIXME: It would be better to produce the diagnostic for casting 10408 // a pointer to an integer. 10409 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10410 return false; 10411 } 10412 Result = Val.getInt(); 10413 return true; 10414 } 10415 10416 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10417 APValue Evaluated = E->EvaluateInContext( 10418 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10419 return Success(Evaluated, E); 10420 } 10421 10422 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10423 EvalInfo &Info) { 10424 if (E->getType()->isFixedPointType()) { 10425 APValue Val; 10426 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10427 return false; 10428 if (!Val.isFixedPoint()) 10429 return false; 10430 10431 Result = Val.getFixedPoint(); 10432 return true; 10433 } 10434 return false; 10435 } 10436 10437 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10438 EvalInfo &Info) { 10439 if (E->getType()->isIntegerType()) { 10440 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10441 APSInt Val; 10442 if (!EvaluateInteger(E, Val, Info)) 10443 return false; 10444 Result = APFixedPoint(Val, FXSema); 10445 return true; 10446 } else if (E->getType()->isFixedPointType()) { 10447 return EvaluateFixedPoint(E, Result, Info); 10448 } 10449 return false; 10450 } 10451 10452 /// Check whether the given declaration can be directly converted to an integral 10453 /// rvalue. If not, no diagnostic is produced; there are other things we can 10454 /// try. 10455 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10456 // Enums are integer constant exprs. 10457 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10458 // Check for signedness/width mismatches between E type and ECD value. 10459 bool SameSign = (ECD->getInitVal().isSigned() 10460 == E->getType()->isSignedIntegerOrEnumerationType()); 10461 bool SameWidth = (ECD->getInitVal().getBitWidth() 10462 == Info.Ctx.getIntWidth(E->getType())); 10463 if (SameSign && SameWidth) 10464 return Success(ECD->getInitVal(), E); 10465 else { 10466 // Get rid of mismatch (otherwise Success assertions will fail) 10467 // by computing a new value matching the type of E. 10468 llvm::APSInt Val = ECD->getInitVal(); 10469 if (!SameSign) 10470 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10471 if (!SameWidth) 10472 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10473 return Success(Val, E); 10474 } 10475 } 10476 return false; 10477 } 10478 10479 /// Values returned by __builtin_classify_type, chosen to match the values 10480 /// produced by GCC's builtin. 10481 enum class GCCTypeClass { 10482 None = -1, 10483 Void = 0, 10484 Integer = 1, 10485 // GCC reserves 2 for character types, but instead classifies them as 10486 // integers. 10487 Enum = 3, 10488 Bool = 4, 10489 Pointer = 5, 10490 // GCC reserves 6 for references, but appears to never use it (because 10491 // expressions never have reference type, presumably). 10492 PointerToDataMember = 7, 10493 RealFloat = 8, 10494 Complex = 9, 10495 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10496 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10497 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10498 // uses 12 for that purpose, same as for a class or struct. Maybe it 10499 // internally implements a pointer to member as a struct? Who knows. 10500 PointerToMemberFunction = 12, // Not a bug, see above. 10501 ClassOrStruct = 12, 10502 Union = 13, 10503 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10504 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10505 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10506 // literals. 10507 }; 10508 10509 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10510 /// as GCC. 10511 static GCCTypeClass 10512 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10513 assert(!T->isDependentType() && "unexpected dependent type"); 10514 10515 QualType CanTy = T.getCanonicalType(); 10516 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10517 10518 switch (CanTy->getTypeClass()) { 10519 #define TYPE(ID, BASE) 10520 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10521 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10522 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10523 #include "clang/AST/TypeNodes.inc" 10524 case Type::Auto: 10525 case Type::DeducedTemplateSpecialization: 10526 llvm_unreachable("unexpected non-canonical or dependent type"); 10527 10528 case Type::Builtin: 10529 switch (BT->getKind()) { 10530 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10531 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10532 case BuiltinType::ID: return GCCTypeClass::Integer; 10533 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10534 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10535 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10536 case BuiltinType::ID: break; 10537 #include "clang/AST/BuiltinTypes.def" 10538 case BuiltinType::Void: 10539 return GCCTypeClass::Void; 10540 10541 case BuiltinType::Bool: 10542 return GCCTypeClass::Bool; 10543 10544 case BuiltinType::Char_U: 10545 case BuiltinType::UChar: 10546 case BuiltinType::WChar_U: 10547 case BuiltinType::Char8: 10548 case BuiltinType::Char16: 10549 case BuiltinType::Char32: 10550 case BuiltinType::UShort: 10551 case BuiltinType::UInt: 10552 case BuiltinType::ULong: 10553 case BuiltinType::ULongLong: 10554 case BuiltinType::UInt128: 10555 return GCCTypeClass::Integer; 10556 10557 case BuiltinType::UShortAccum: 10558 case BuiltinType::UAccum: 10559 case BuiltinType::ULongAccum: 10560 case BuiltinType::UShortFract: 10561 case BuiltinType::UFract: 10562 case BuiltinType::ULongFract: 10563 case BuiltinType::SatUShortAccum: 10564 case BuiltinType::SatUAccum: 10565 case BuiltinType::SatULongAccum: 10566 case BuiltinType::SatUShortFract: 10567 case BuiltinType::SatUFract: 10568 case BuiltinType::SatULongFract: 10569 return GCCTypeClass::None; 10570 10571 case BuiltinType::NullPtr: 10572 10573 case BuiltinType::ObjCId: 10574 case BuiltinType::ObjCClass: 10575 case BuiltinType::ObjCSel: 10576 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10577 case BuiltinType::Id: 10578 #include "clang/Basic/OpenCLImageTypes.def" 10579 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10580 case BuiltinType::Id: 10581 #include "clang/Basic/OpenCLExtensionTypes.def" 10582 case BuiltinType::OCLSampler: 10583 case BuiltinType::OCLEvent: 10584 case BuiltinType::OCLClkEvent: 10585 case BuiltinType::OCLQueue: 10586 case BuiltinType::OCLReserveID: 10587 #define SVE_TYPE(Name, Id, SingletonId) \ 10588 case BuiltinType::Id: 10589 #include "clang/Basic/AArch64SVEACLETypes.def" 10590 return GCCTypeClass::None; 10591 10592 case BuiltinType::Dependent: 10593 llvm_unreachable("unexpected dependent type"); 10594 }; 10595 llvm_unreachable("unexpected placeholder type"); 10596 10597 case Type::Enum: 10598 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 10599 10600 case Type::Pointer: 10601 case Type::ConstantArray: 10602 case Type::VariableArray: 10603 case Type::IncompleteArray: 10604 case Type::FunctionNoProto: 10605 case Type::FunctionProto: 10606 return GCCTypeClass::Pointer; 10607 10608 case Type::MemberPointer: 10609 return CanTy->isMemberDataPointerType() 10610 ? GCCTypeClass::PointerToDataMember 10611 : GCCTypeClass::PointerToMemberFunction; 10612 10613 case Type::Complex: 10614 return GCCTypeClass::Complex; 10615 10616 case Type::Record: 10617 return CanTy->isUnionType() ? GCCTypeClass::Union 10618 : GCCTypeClass::ClassOrStruct; 10619 10620 case Type::Atomic: 10621 // GCC classifies _Atomic T the same as T. 10622 return EvaluateBuiltinClassifyType( 10623 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 10624 10625 case Type::BlockPointer: 10626 case Type::Vector: 10627 case Type::ExtVector: 10628 case Type::ConstantMatrix: 10629 case Type::ObjCObject: 10630 case Type::ObjCInterface: 10631 case Type::ObjCObjectPointer: 10632 case Type::Pipe: 10633 case Type::ExtInt: 10634 // GCC classifies vectors as None. We follow its lead and classify all 10635 // other types that don't fit into the regular classification the same way. 10636 return GCCTypeClass::None; 10637 10638 case Type::LValueReference: 10639 case Type::RValueReference: 10640 llvm_unreachable("invalid type for expression"); 10641 } 10642 10643 llvm_unreachable("unexpected type class"); 10644 } 10645 10646 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10647 /// as GCC. 10648 static GCCTypeClass 10649 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 10650 // If no argument was supplied, default to None. This isn't 10651 // ideal, however it is what gcc does. 10652 if (E->getNumArgs() == 0) 10653 return GCCTypeClass::None; 10654 10655 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 10656 // being an ICE, but still folds it to a constant using the type of the first 10657 // argument. 10658 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 10659 } 10660 10661 /// EvaluateBuiltinConstantPForLValue - Determine the result of 10662 /// __builtin_constant_p when applied to the given pointer. 10663 /// 10664 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 10665 /// or it points to the first character of a string literal. 10666 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 10667 APValue::LValueBase Base = LV.getLValueBase(); 10668 if (Base.isNull()) { 10669 // A null base is acceptable. 10670 return true; 10671 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 10672 if (!isa<StringLiteral>(E)) 10673 return false; 10674 return LV.getLValueOffset().isZero(); 10675 } else if (Base.is<TypeInfoLValue>()) { 10676 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 10677 // evaluate to true. 10678 return true; 10679 } else { 10680 // Any other base is not constant enough for GCC. 10681 return false; 10682 } 10683 } 10684 10685 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 10686 /// GCC as we can manage. 10687 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 10688 // This evaluation is not permitted to have side-effects, so evaluate it in 10689 // a speculative evaluation context. 10690 SpeculativeEvaluationRAII SpeculativeEval(Info); 10691 10692 // Constant-folding is always enabled for the operand of __builtin_constant_p 10693 // (even when the enclosing evaluation context otherwise requires a strict 10694 // language-specific constant expression). 10695 FoldConstant Fold(Info, true); 10696 10697 QualType ArgType = Arg->getType(); 10698 10699 // __builtin_constant_p always has one operand. The rules which gcc follows 10700 // are not precisely documented, but are as follows: 10701 // 10702 // - If the operand is of integral, floating, complex or enumeration type, 10703 // and can be folded to a known value of that type, it returns 1. 10704 // - If the operand can be folded to a pointer to the first character 10705 // of a string literal (or such a pointer cast to an integral type) 10706 // or to a null pointer or an integer cast to a pointer, it returns 1. 10707 // 10708 // Otherwise, it returns 0. 10709 // 10710 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 10711 // its support for this did not work prior to GCC 9 and is not yet well 10712 // understood. 10713 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 10714 ArgType->isAnyComplexType() || ArgType->isPointerType() || 10715 ArgType->isNullPtrType()) { 10716 APValue V; 10717 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 10718 Fold.keepDiagnostics(); 10719 return false; 10720 } 10721 10722 // For a pointer (possibly cast to integer), there are special rules. 10723 if (V.getKind() == APValue::LValue) 10724 return EvaluateBuiltinConstantPForLValue(V); 10725 10726 // Otherwise, any constant value is good enough. 10727 return V.hasValue(); 10728 } 10729 10730 // Anything else isn't considered to be sufficiently constant. 10731 return false; 10732 } 10733 10734 /// Retrieves the "underlying object type" of the given expression, 10735 /// as used by __builtin_object_size. 10736 static QualType getObjectType(APValue::LValueBase B) { 10737 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 10738 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 10739 return VD->getType(); 10740 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 10741 if (isa<CompoundLiteralExpr>(E)) 10742 return E->getType(); 10743 } else if (B.is<TypeInfoLValue>()) { 10744 return B.getTypeInfoType(); 10745 } else if (B.is<DynamicAllocLValue>()) { 10746 return B.getDynamicAllocType(); 10747 } 10748 10749 return QualType(); 10750 } 10751 10752 /// A more selective version of E->IgnoreParenCasts for 10753 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 10754 /// to change the type of E. 10755 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 10756 /// 10757 /// Always returns an RValue with a pointer representation. 10758 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 10759 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 10760 10761 auto *NoParens = E->IgnoreParens(); 10762 auto *Cast = dyn_cast<CastExpr>(NoParens); 10763 if (Cast == nullptr) 10764 return NoParens; 10765 10766 // We only conservatively allow a few kinds of casts, because this code is 10767 // inherently a simple solution that seeks to support the common case. 10768 auto CastKind = Cast->getCastKind(); 10769 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 10770 CastKind != CK_AddressSpaceConversion) 10771 return NoParens; 10772 10773 auto *SubExpr = Cast->getSubExpr(); 10774 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 10775 return NoParens; 10776 return ignorePointerCastsAndParens(SubExpr); 10777 } 10778 10779 /// Checks to see if the given LValue's Designator is at the end of the LValue's 10780 /// record layout. e.g. 10781 /// struct { struct { int a, b; } fst, snd; } obj; 10782 /// obj.fst // no 10783 /// obj.snd // yes 10784 /// obj.fst.a // no 10785 /// obj.fst.b // no 10786 /// obj.snd.a // no 10787 /// obj.snd.b // yes 10788 /// 10789 /// Please note: this function is specialized for how __builtin_object_size 10790 /// views "objects". 10791 /// 10792 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 10793 /// correct result, it will always return true. 10794 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 10795 assert(!LVal.Designator.Invalid); 10796 10797 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 10798 const RecordDecl *Parent = FD->getParent(); 10799 Invalid = Parent->isInvalidDecl(); 10800 if (Invalid || Parent->isUnion()) 10801 return true; 10802 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 10803 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 10804 }; 10805 10806 auto &Base = LVal.getLValueBase(); 10807 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 10808 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 10809 bool Invalid; 10810 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10811 return Invalid; 10812 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 10813 for (auto *FD : IFD->chain()) { 10814 bool Invalid; 10815 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 10816 return Invalid; 10817 } 10818 } 10819 } 10820 10821 unsigned I = 0; 10822 QualType BaseType = getType(Base); 10823 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 10824 // If we don't know the array bound, conservatively assume we're looking at 10825 // the final array element. 10826 ++I; 10827 if (BaseType->isIncompleteArrayType()) 10828 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 10829 else 10830 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 10831 } 10832 10833 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 10834 const auto &Entry = LVal.Designator.Entries[I]; 10835 if (BaseType->isArrayType()) { 10836 // Because __builtin_object_size treats arrays as objects, we can ignore 10837 // the index iff this is the last array in the Designator. 10838 if (I + 1 == E) 10839 return true; 10840 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 10841 uint64_t Index = Entry.getAsArrayIndex(); 10842 if (Index + 1 != CAT->getSize()) 10843 return false; 10844 BaseType = CAT->getElementType(); 10845 } else if (BaseType->isAnyComplexType()) { 10846 const auto *CT = BaseType->castAs<ComplexType>(); 10847 uint64_t Index = Entry.getAsArrayIndex(); 10848 if (Index != 1) 10849 return false; 10850 BaseType = CT->getElementType(); 10851 } else if (auto *FD = getAsField(Entry)) { 10852 bool Invalid; 10853 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10854 return Invalid; 10855 BaseType = FD->getType(); 10856 } else { 10857 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 10858 return false; 10859 } 10860 } 10861 return true; 10862 } 10863 10864 /// Tests to see if the LValue has a user-specified designator (that isn't 10865 /// necessarily valid). Note that this always returns 'true' if the LValue has 10866 /// an unsized array as its first designator entry, because there's currently no 10867 /// way to tell if the user typed *foo or foo[0]. 10868 static bool refersToCompleteObject(const LValue &LVal) { 10869 if (LVal.Designator.Invalid) 10870 return false; 10871 10872 if (!LVal.Designator.Entries.empty()) 10873 return LVal.Designator.isMostDerivedAnUnsizedArray(); 10874 10875 if (!LVal.InvalidBase) 10876 return true; 10877 10878 // If `E` is a MemberExpr, then the first part of the designator is hiding in 10879 // the LValueBase. 10880 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 10881 return !E || !isa<MemberExpr>(E); 10882 } 10883 10884 /// Attempts to detect a user writing into a piece of memory that's impossible 10885 /// to figure out the size of by just using types. 10886 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 10887 const SubobjectDesignator &Designator = LVal.Designator; 10888 // Notes: 10889 // - Users can only write off of the end when we have an invalid base. Invalid 10890 // bases imply we don't know where the memory came from. 10891 // - We used to be a bit more aggressive here; we'd only be conservative if 10892 // the array at the end was flexible, or if it had 0 or 1 elements. This 10893 // broke some common standard library extensions (PR30346), but was 10894 // otherwise seemingly fine. It may be useful to reintroduce this behavior 10895 // with some sort of list. OTOH, it seems that GCC is always 10896 // conservative with the last element in structs (if it's an array), so our 10897 // current behavior is more compatible than an explicit list approach would 10898 // be. 10899 return LVal.InvalidBase && 10900 Designator.Entries.size() == Designator.MostDerivedPathLength && 10901 Designator.MostDerivedIsArrayElement && 10902 isDesignatorAtObjectEnd(Ctx, LVal); 10903 } 10904 10905 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 10906 /// Fails if the conversion would cause loss of precision. 10907 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 10908 CharUnits &Result) { 10909 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 10910 if (Int.ugt(CharUnitsMax)) 10911 return false; 10912 Result = CharUnits::fromQuantity(Int.getZExtValue()); 10913 return true; 10914 } 10915 10916 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 10917 /// determine how many bytes exist from the beginning of the object to either 10918 /// the end of the current subobject, or the end of the object itself, depending 10919 /// on what the LValue looks like + the value of Type. 10920 /// 10921 /// If this returns false, the value of Result is undefined. 10922 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 10923 unsigned Type, const LValue &LVal, 10924 CharUnits &EndOffset) { 10925 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 10926 10927 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 10928 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 10929 return false; 10930 return HandleSizeof(Info, ExprLoc, Ty, Result); 10931 }; 10932 10933 // We want to evaluate the size of the entire object. This is a valid fallback 10934 // for when Type=1 and the designator is invalid, because we're asked for an 10935 // upper-bound. 10936 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 10937 // Type=3 wants a lower bound, so we can't fall back to this. 10938 if (Type == 3 && !DetermineForCompleteObject) 10939 return false; 10940 10941 llvm::APInt APEndOffset; 10942 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 10943 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 10944 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 10945 10946 if (LVal.InvalidBase) 10947 return false; 10948 10949 QualType BaseTy = getObjectType(LVal.getLValueBase()); 10950 return CheckedHandleSizeof(BaseTy, EndOffset); 10951 } 10952 10953 // We want to evaluate the size of a subobject. 10954 const SubobjectDesignator &Designator = LVal.Designator; 10955 10956 // The following is a moderately common idiom in C: 10957 // 10958 // struct Foo { int a; char c[1]; }; 10959 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 10960 // strcpy(&F->c[0], Bar); 10961 // 10962 // In order to not break too much legacy code, we need to support it. 10963 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 10964 // If we can resolve this to an alloc_size call, we can hand that back, 10965 // because we know for certain how many bytes there are to write to. 10966 llvm::APInt APEndOffset; 10967 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 10968 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 10969 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 10970 10971 // If we cannot determine the size of the initial allocation, then we can't 10972 // given an accurate upper-bound. However, we are still able to give 10973 // conservative lower-bounds for Type=3. 10974 if (Type == 1) 10975 return false; 10976 } 10977 10978 CharUnits BytesPerElem; 10979 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 10980 return false; 10981 10982 // According to the GCC documentation, we want the size of the subobject 10983 // denoted by the pointer. But that's not quite right -- what we actually 10984 // want is the size of the immediately-enclosing array, if there is one. 10985 int64_t ElemsRemaining; 10986 if (Designator.MostDerivedIsArrayElement && 10987 Designator.Entries.size() == Designator.MostDerivedPathLength) { 10988 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 10989 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 10990 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 10991 } else { 10992 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 10993 } 10994 10995 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 10996 return true; 10997 } 10998 10999 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11000 /// returns true and stores the result in @p Size. 11001 /// 11002 /// If @p WasError is non-null, this will report whether the failure to evaluate 11003 /// is to be treated as an Error in IntExprEvaluator. 11004 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11005 EvalInfo &Info, uint64_t &Size) { 11006 // Determine the denoted object. 11007 LValue LVal; 11008 { 11009 // The operand of __builtin_object_size is never evaluated for side-effects. 11010 // If there are any, but we can determine the pointed-to object anyway, then 11011 // ignore the side-effects. 11012 SpeculativeEvaluationRAII SpeculativeEval(Info); 11013 IgnoreSideEffectsRAII Fold(Info); 11014 11015 if (E->isGLValue()) { 11016 // It's possible for us to be given GLValues if we're called via 11017 // Expr::tryEvaluateObjectSize. 11018 APValue RVal; 11019 if (!EvaluateAsRValue(Info, E, RVal)) 11020 return false; 11021 LVal.setFrom(Info.Ctx, RVal); 11022 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11023 /*InvalidBaseOK=*/true)) 11024 return false; 11025 } 11026 11027 // If we point to before the start of the object, there are no accessible 11028 // bytes. 11029 if (LVal.getLValueOffset().isNegative()) { 11030 Size = 0; 11031 return true; 11032 } 11033 11034 CharUnits EndOffset; 11035 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11036 return false; 11037 11038 // If we've fallen outside of the end offset, just pretend there's nothing to 11039 // write to/read from. 11040 if (EndOffset <= LVal.getLValueOffset()) 11041 Size = 0; 11042 else 11043 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11044 return true; 11045 } 11046 11047 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11048 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11049 return VisitBuiltinCallExpr(E, BuiltinOp); 11050 11051 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11052 } 11053 11054 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11055 APValue &Val, APSInt &Alignment) { 11056 QualType SrcTy = E->getArg(0)->getType(); 11057 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11058 return false; 11059 // Even though we are evaluating integer expressions we could get a pointer 11060 // argument for the __builtin_is_aligned() case. 11061 if (SrcTy->isPointerType()) { 11062 LValue Ptr; 11063 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11064 return false; 11065 Ptr.moveInto(Val); 11066 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11067 Info.FFDiag(E->getArg(0)); 11068 return false; 11069 } else { 11070 APSInt SrcInt; 11071 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11072 return false; 11073 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11074 "Bit widths must be the same"); 11075 Val = APValue(SrcInt); 11076 } 11077 assert(Val.hasValue()); 11078 return true; 11079 } 11080 11081 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11082 unsigned BuiltinOp) { 11083 switch (BuiltinOp) { 11084 default: 11085 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11086 11087 case Builtin::BI__builtin_dynamic_object_size: 11088 case Builtin::BI__builtin_object_size: { 11089 // The type was checked when we built the expression. 11090 unsigned Type = 11091 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11092 assert(Type <= 3 && "unexpected type"); 11093 11094 uint64_t Size; 11095 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11096 return Success(Size, E); 11097 11098 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11099 return Success((Type & 2) ? 0 : -1, E); 11100 11101 // Expression had no side effects, but we couldn't statically determine the 11102 // size of the referenced object. 11103 switch (Info.EvalMode) { 11104 case EvalInfo::EM_ConstantExpression: 11105 case EvalInfo::EM_ConstantFold: 11106 case EvalInfo::EM_IgnoreSideEffects: 11107 // Leave it to IR generation. 11108 return Error(E); 11109 case EvalInfo::EM_ConstantExpressionUnevaluated: 11110 // Reduce it to a constant now. 11111 return Success((Type & 2) ? 0 : -1, E); 11112 } 11113 11114 llvm_unreachable("unexpected EvalMode"); 11115 } 11116 11117 case Builtin::BI__builtin_os_log_format_buffer_size: { 11118 analyze_os_log::OSLogBufferLayout Layout; 11119 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11120 return Success(Layout.size().getQuantity(), E); 11121 } 11122 11123 case Builtin::BI__builtin_is_aligned: { 11124 APValue Src; 11125 APSInt Alignment; 11126 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11127 return false; 11128 if (Src.isLValue()) { 11129 // If we evaluated a pointer, check the minimum known alignment. 11130 LValue Ptr; 11131 Ptr.setFrom(Info.Ctx, Src); 11132 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11133 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11134 // We can return true if the known alignment at the computed offset is 11135 // greater than the requested alignment. 11136 assert(PtrAlign.isPowerOfTwo()); 11137 assert(Alignment.isPowerOf2()); 11138 if (PtrAlign.getQuantity() >= Alignment) 11139 return Success(1, E); 11140 // If the alignment is not known to be sufficient, some cases could still 11141 // be aligned at run time. However, if the requested alignment is less or 11142 // equal to the base alignment and the offset is not aligned, we know that 11143 // the run-time value can never be aligned. 11144 if (BaseAlignment.getQuantity() >= Alignment && 11145 PtrAlign.getQuantity() < Alignment) 11146 return Success(0, E); 11147 // Otherwise we can't infer whether the value is sufficiently aligned. 11148 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11149 // in cases where we can't fully evaluate the pointer. 11150 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11151 << Alignment; 11152 return false; 11153 } 11154 assert(Src.isInt()); 11155 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11156 } 11157 case Builtin::BI__builtin_align_up: { 11158 APValue Src; 11159 APSInt Alignment; 11160 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11161 return false; 11162 if (!Src.isInt()) 11163 return Error(E); 11164 APSInt AlignedVal = 11165 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11166 Src.getInt().isUnsigned()); 11167 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11168 return Success(AlignedVal, E); 11169 } 11170 case Builtin::BI__builtin_align_down: { 11171 APValue Src; 11172 APSInt Alignment; 11173 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11174 return false; 11175 if (!Src.isInt()) 11176 return Error(E); 11177 APSInt AlignedVal = 11178 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11179 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11180 return Success(AlignedVal, E); 11181 } 11182 11183 case Builtin::BI__builtin_bswap16: 11184 case Builtin::BI__builtin_bswap32: 11185 case Builtin::BI__builtin_bswap64: { 11186 APSInt Val; 11187 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11188 return false; 11189 11190 return Success(Val.byteSwap(), E); 11191 } 11192 11193 case Builtin::BI__builtin_classify_type: 11194 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11195 11196 case Builtin::BI__builtin_clrsb: 11197 case Builtin::BI__builtin_clrsbl: 11198 case Builtin::BI__builtin_clrsbll: { 11199 APSInt Val; 11200 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11201 return false; 11202 11203 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11204 } 11205 11206 case Builtin::BI__builtin_clz: 11207 case Builtin::BI__builtin_clzl: 11208 case Builtin::BI__builtin_clzll: 11209 case Builtin::BI__builtin_clzs: { 11210 APSInt Val; 11211 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11212 return false; 11213 if (!Val) 11214 return Error(E); 11215 11216 return Success(Val.countLeadingZeros(), E); 11217 } 11218 11219 case Builtin::BI__builtin_constant_p: { 11220 const Expr *Arg = E->getArg(0); 11221 if (EvaluateBuiltinConstantP(Info, Arg)) 11222 return Success(true, E); 11223 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11224 // Outside a constant context, eagerly evaluate to false in the presence 11225 // of side-effects in order to avoid -Wunsequenced false-positives in 11226 // a branch on __builtin_constant_p(expr). 11227 return Success(false, E); 11228 } 11229 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11230 return false; 11231 } 11232 11233 case Builtin::BI__builtin_is_constant_evaluated: { 11234 const auto *Callee = Info.CurrentCall->getCallee(); 11235 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11236 (Info.CallStackDepth == 1 || 11237 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11238 Callee->getIdentifier() && 11239 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11240 // FIXME: Find a better way to avoid duplicated diagnostics. 11241 if (Info.EvalStatus.Diag) 11242 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11243 : Info.CurrentCall->CallLoc, 11244 diag::warn_is_constant_evaluated_always_true_constexpr) 11245 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11246 : "std::is_constant_evaluated"); 11247 } 11248 11249 return Success(Info.InConstantContext, E); 11250 } 11251 11252 case Builtin::BI__builtin_ctz: 11253 case Builtin::BI__builtin_ctzl: 11254 case Builtin::BI__builtin_ctzll: 11255 case Builtin::BI__builtin_ctzs: { 11256 APSInt Val; 11257 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11258 return false; 11259 if (!Val) 11260 return Error(E); 11261 11262 return Success(Val.countTrailingZeros(), E); 11263 } 11264 11265 case Builtin::BI__builtin_eh_return_data_regno: { 11266 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11267 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11268 return Success(Operand, E); 11269 } 11270 11271 case Builtin::BI__builtin_expect: 11272 case Builtin::BI__builtin_expect_with_probability: 11273 return Visit(E->getArg(0)); 11274 11275 case Builtin::BI__builtin_ffs: 11276 case Builtin::BI__builtin_ffsl: 11277 case Builtin::BI__builtin_ffsll: { 11278 APSInt Val; 11279 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11280 return false; 11281 11282 unsigned N = Val.countTrailingZeros(); 11283 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11284 } 11285 11286 case Builtin::BI__builtin_fpclassify: { 11287 APFloat Val(0.0); 11288 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11289 return false; 11290 unsigned Arg; 11291 switch (Val.getCategory()) { 11292 case APFloat::fcNaN: Arg = 0; break; 11293 case APFloat::fcInfinity: Arg = 1; break; 11294 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11295 case APFloat::fcZero: Arg = 4; break; 11296 } 11297 return Visit(E->getArg(Arg)); 11298 } 11299 11300 case Builtin::BI__builtin_isinf_sign: { 11301 APFloat Val(0.0); 11302 return EvaluateFloat(E->getArg(0), Val, Info) && 11303 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11304 } 11305 11306 case Builtin::BI__builtin_isinf: { 11307 APFloat Val(0.0); 11308 return EvaluateFloat(E->getArg(0), Val, Info) && 11309 Success(Val.isInfinity() ? 1 : 0, E); 11310 } 11311 11312 case Builtin::BI__builtin_isfinite: { 11313 APFloat Val(0.0); 11314 return EvaluateFloat(E->getArg(0), Val, Info) && 11315 Success(Val.isFinite() ? 1 : 0, E); 11316 } 11317 11318 case Builtin::BI__builtin_isnan: { 11319 APFloat Val(0.0); 11320 return EvaluateFloat(E->getArg(0), Val, Info) && 11321 Success(Val.isNaN() ? 1 : 0, E); 11322 } 11323 11324 case Builtin::BI__builtin_isnormal: { 11325 APFloat Val(0.0); 11326 return EvaluateFloat(E->getArg(0), Val, Info) && 11327 Success(Val.isNormal() ? 1 : 0, E); 11328 } 11329 11330 case Builtin::BI__builtin_parity: 11331 case Builtin::BI__builtin_parityl: 11332 case Builtin::BI__builtin_parityll: { 11333 APSInt Val; 11334 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11335 return false; 11336 11337 return Success(Val.countPopulation() % 2, E); 11338 } 11339 11340 case Builtin::BI__builtin_popcount: 11341 case Builtin::BI__builtin_popcountl: 11342 case Builtin::BI__builtin_popcountll: { 11343 APSInt Val; 11344 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11345 return false; 11346 11347 return Success(Val.countPopulation(), E); 11348 } 11349 11350 case Builtin::BIstrlen: 11351 case Builtin::BIwcslen: 11352 // A call to strlen is not a constant expression. 11353 if (Info.getLangOpts().CPlusPlus11) 11354 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11355 << /*isConstexpr*/0 << /*isConstructor*/0 11356 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11357 else 11358 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11359 LLVM_FALLTHROUGH; 11360 case Builtin::BI__builtin_strlen: 11361 case Builtin::BI__builtin_wcslen: { 11362 // As an extension, we support __builtin_strlen() as a constant expression, 11363 // and support folding strlen() to a constant. 11364 LValue String; 11365 if (!EvaluatePointer(E->getArg(0), String, Info)) 11366 return false; 11367 11368 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11369 11370 // Fast path: if it's a string literal, search the string value. 11371 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11372 String.getLValueBase().dyn_cast<const Expr *>())) { 11373 // The string literal may have embedded null characters. Find the first 11374 // one and truncate there. 11375 StringRef Str = S->getBytes(); 11376 int64_t Off = String.Offset.getQuantity(); 11377 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11378 S->getCharByteWidth() == 1 && 11379 // FIXME: Add fast-path for wchar_t too. 11380 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11381 Str = Str.substr(Off); 11382 11383 StringRef::size_type Pos = Str.find(0); 11384 if (Pos != StringRef::npos) 11385 Str = Str.substr(0, Pos); 11386 11387 return Success(Str.size(), E); 11388 } 11389 11390 // Fall through to slow path to issue appropriate diagnostic. 11391 } 11392 11393 // Slow path: scan the bytes of the string looking for the terminating 0. 11394 for (uint64_t Strlen = 0; /**/; ++Strlen) { 11395 APValue Char; 11396 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11397 !Char.isInt()) 11398 return false; 11399 if (!Char.getInt()) 11400 return Success(Strlen, E); 11401 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11402 return false; 11403 } 11404 } 11405 11406 case Builtin::BIstrcmp: 11407 case Builtin::BIwcscmp: 11408 case Builtin::BIstrncmp: 11409 case Builtin::BIwcsncmp: 11410 case Builtin::BImemcmp: 11411 case Builtin::BIbcmp: 11412 case Builtin::BIwmemcmp: 11413 // A call to strlen is not a constant expression. 11414 if (Info.getLangOpts().CPlusPlus11) 11415 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11416 << /*isConstexpr*/0 << /*isConstructor*/0 11417 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11418 else 11419 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11420 LLVM_FALLTHROUGH; 11421 case Builtin::BI__builtin_strcmp: 11422 case Builtin::BI__builtin_wcscmp: 11423 case Builtin::BI__builtin_strncmp: 11424 case Builtin::BI__builtin_wcsncmp: 11425 case Builtin::BI__builtin_memcmp: 11426 case Builtin::BI__builtin_bcmp: 11427 case Builtin::BI__builtin_wmemcmp: { 11428 LValue String1, String2; 11429 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11430 !EvaluatePointer(E->getArg(1), String2, Info)) 11431 return false; 11432 11433 uint64_t MaxLength = uint64_t(-1); 11434 if (BuiltinOp != Builtin::BIstrcmp && 11435 BuiltinOp != Builtin::BIwcscmp && 11436 BuiltinOp != Builtin::BI__builtin_strcmp && 11437 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11438 APSInt N; 11439 if (!EvaluateInteger(E->getArg(2), N, Info)) 11440 return false; 11441 MaxLength = N.getExtValue(); 11442 } 11443 11444 // Empty substrings compare equal by definition. 11445 if (MaxLength == 0u) 11446 return Success(0, E); 11447 11448 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11449 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11450 String1.Designator.Invalid || String2.Designator.Invalid) 11451 return false; 11452 11453 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11454 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11455 11456 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11457 BuiltinOp == Builtin::BIbcmp || 11458 BuiltinOp == Builtin::BI__builtin_memcmp || 11459 BuiltinOp == Builtin::BI__builtin_bcmp; 11460 11461 assert(IsRawByte || 11462 (Info.Ctx.hasSameUnqualifiedType( 11463 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11464 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11465 11466 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11467 // 'char8_t', but no other types. 11468 if (IsRawByte && 11469 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11470 // FIXME: Consider using our bit_cast implementation to support this. 11471 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11472 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11473 << CharTy1 << CharTy2; 11474 return false; 11475 } 11476 11477 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11478 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11479 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11480 Char1.isInt() && Char2.isInt(); 11481 }; 11482 const auto &AdvanceElems = [&] { 11483 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11484 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11485 }; 11486 11487 bool StopAtNull = 11488 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11489 BuiltinOp != Builtin::BIwmemcmp && 11490 BuiltinOp != Builtin::BI__builtin_memcmp && 11491 BuiltinOp != Builtin::BI__builtin_bcmp && 11492 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11493 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11494 BuiltinOp == Builtin::BIwcsncmp || 11495 BuiltinOp == Builtin::BIwmemcmp || 11496 BuiltinOp == Builtin::BI__builtin_wcscmp || 11497 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11498 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11499 11500 for (; MaxLength; --MaxLength) { 11501 APValue Char1, Char2; 11502 if (!ReadCurElems(Char1, Char2)) 11503 return false; 11504 if (Char1.getInt().ne(Char2.getInt())) { 11505 if (IsWide) // wmemcmp compares with wchar_t signedness. 11506 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11507 // memcmp always compares unsigned chars. 11508 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11509 } 11510 if (StopAtNull && !Char1.getInt()) 11511 return Success(0, E); 11512 assert(!(StopAtNull && !Char2.getInt())); 11513 if (!AdvanceElems()) 11514 return false; 11515 } 11516 // We hit the strncmp / memcmp limit. 11517 return Success(0, E); 11518 } 11519 11520 case Builtin::BI__atomic_always_lock_free: 11521 case Builtin::BI__atomic_is_lock_free: 11522 case Builtin::BI__c11_atomic_is_lock_free: { 11523 APSInt SizeVal; 11524 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11525 return false; 11526 11527 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11528 // of two less than or equal to the maximum inline atomic width, we know it 11529 // is lock-free. If the size isn't a power of two, or greater than the 11530 // maximum alignment where we promote atomics, we know it is not lock-free 11531 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11532 // the answer can only be determined at runtime; for example, 16-byte 11533 // atomics have lock-free implementations on some, but not all, 11534 // x86-64 processors. 11535 11536 // Check power-of-two. 11537 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11538 if (Size.isPowerOfTwo()) { 11539 // Check against inlining width. 11540 unsigned InlineWidthBits = 11541 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11542 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11543 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11544 Size == CharUnits::One() || 11545 E->getArg(1)->isNullPointerConstant(Info.Ctx, 11546 Expr::NPC_NeverValueDependent)) 11547 // OK, we will inline appropriately-aligned operations of this size, 11548 // and _Atomic(T) is appropriately-aligned. 11549 return Success(1, E); 11550 11551 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 11552 castAs<PointerType>()->getPointeeType(); 11553 if (!PointeeType->isIncompleteType() && 11554 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 11555 // OK, we will inline operations on this object. 11556 return Success(1, E); 11557 } 11558 } 11559 } 11560 11561 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 11562 Success(0, E) : Error(E); 11563 } 11564 case Builtin::BIomp_is_initial_device: 11565 // We can decide statically which value the runtime would return if called. 11566 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 11567 case Builtin::BI__builtin_add_overflow: 11568 case Builtin::BI__builtin_sub_overflow: 11569 case Builtin::BI__builtin_mul_overflow: 11570 case Builtin::BI__builtin_sadd_overflow: 11571 case Builtin::BI__builtin_uadd_overflow: 11572 case Builtin::BI__builtin_uaddl_overflow: 11573 case Builtin::BI__builtin_uaddll_overflow: 11574 case Builtin::BI__builtin_usub_overflow: 11575 case Builtin::BI__builtin_usubl_overflow: 11576 case Builtin::BI__builtin_usubll_overflow: 11577 case Builtin::BI__builtin_umul_overflow: 11578 case Builtin::BI__builtin_umull_overflow: 11579 case Builtin::BI__builtin_umulll_overflow: 11580 case Builtin::BI__builtin_saddl_overflow: 11581 case Builtin::BI__builtin_saddll_overflow: 11582 case Builtin::BI__builtin_ssub_overflow: 11583 case Builtin::BI__builtin_ssubl_overflow: 11584 case Builtin::BI__builtin_ssubll_overflow: 11585 case Builtin::BI__builtin_smul_overflow: 11586 case Builtin::BI__builtin_smull_overflow: 11587 case Builtin::BI__builtin_smulll_overflow: { 11588 LValue ResultLValue; 11589 APSInt LHS, RHS; 11590 11591 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 11592 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 11593 !EvaluateInteger(E->getArg(1), RHS, Info) || 11594 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 11595 return false; 11596 11597 APSInt Result; 11598 bool DidOverflow = false; 11599 11600 // If the types don't have to match, enlarge all 3 to the largest of them. 11601 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11602 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11603 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11604 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 11605 ResultType->isSignedIntegerOrEnumerationType(); 11606 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 11607 ResultType->isSignedIntegerOrEnumerationType(); 11608 uint64_t LHSSize = LHS.getBitWidth(); 11609 uint64_t RHSSize = RHS.getBitWidth(); 11610 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 11611 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 11612 11613 // Add an additional bit if the signedness isn't uniformly agreed to. We 11614 // could do this ONLY if there is a signed and an unsigned that both have 11615 // MaxBits, but the code to check that is pretty nasty. The issue will be 11616 // caught in the shrink-to-result later anyway. 11617 if (IsSigned && !AllSigned) 11618 ++MaxBits; 11619 11620 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 11621 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 11622 Result = APSInt(MaxBits, !IsSigned); 11623 } 11624 11625 // Find largest int. 11626 switch (BuiltinOp) { 11627 default: 11628 llvm_unreachable("Invalid value for BuiltinOp"); 11629 case Builtin::BI__builtin_add_overflow: 11630 case Builtin::BI__builtin_sadd_overflow: 11631 case Builtin::BI__builtin_saddl_overflow: 11632 case Builtin::BI__builtin_saddll_overflow: 11633 case Builtin::BI__builtin_uadd_overflow: 11634 case Builtin::BI__builtin_uaddl_overflow: 11635 case Builtin::BI__builtin_uaddll_overflow: 11636 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 11637 : LHS.uadd_ov(RHS, DidOverflow); 11638 break; 11639 case Builtin::BI__builtin_sub_overflow: 11640 case Builtin::BI__builtin_ssub_overflow: 11641 case Builtin::BI__builtin_ssubl_overflow: 11642 case Builtin::BI__builtin_ssubll_overflow: 11643 case Builtin::BI__builtin_usub_overflow: 11644 case Builtin::BI__builtin_usubl_overflow: 11645 case Builtin::BI__builtin_usubll_overflow: 11646 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 11647 : LHS.usub_ov(RHS, DidOverflow); 11648 break; 11649 case Builtin::BI__builtin_mul_overflow: 11650 case Builtin::BI__builtin_smul_overflow: 11651 case Builtin::BI__builtin_smull_overflow: 11652 case Builtin::BI__builtin_smulll_overflow: 11653 case Builtin::BI__builtin_umul_overflow: 11654 case Builtin::BI__builtin_umull_overflow: 11655 case Builtin::BI__builtin_umulll_overflow: 11656 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 11657 : LHS.umul_ov(RHS, DidOverflow); 11658 break; 11659 } 11660 11661 // In the case where multiple sizes are allowed, truncate and see if 11662 // the values are the same. 11663 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11664 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11665 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11666 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 11667 // since it will give us the behavior of a TruncOrSelf in the case where 11668 // its parameter <= its size. We previously set Result to be at least the 11669 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 11670 // will work exactly like TruncOrSelf. 11671 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 11672 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 11673 11674 if (!APSInt::isSameValue(Temp, Result)) 11675 DidOverflow = true; 11676 Result = Temp; 11677 } 11678 11679 APValue APV{Result}; 11680 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 11681 return false; 11682 return Success(DidOverflow, E); 11683 } 11684 } 11685 } 11686 11687 /// Determine whether this is a pointer past the end of the complete 11688 /// object referred to by the lvalue. 11689 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 11690 const LValue &LV) { 11691 // A null pointer can be viewed as being "past the end" but we don't 11692 // choose to look at it that way here. 11693 if (!LV.getLValueBase()) 11694 return false; 11695 11696 // If the designator is valid and refers to a subobject, we're not pointing 11697 // past the end. 11698 if (!LV.getLValueDesignator().Invalid && 11699 !LV.getLValueDesignator().isOnePastTheEnd()) 11700 return false; 11701 11702 // A pointer to an incomplete type might be past-the-end if the type's size is 11703 // zero. We cannot tell because the type is incomplete. 11704 QualType Ty = getType(LV.getLValueBase()); 11705 if (Ty->isIncompleteType()) 11706 return true; 11707 11708 // We're a past-the-end pointer if we point to the byte after the object, 11709 // no matter what our type or path is. 11710 auto Size = Ctx.getTypeSizeInChars(Ty); 11711 return LV.getLValueOffset() == Size; 11712 } 11713 11714 namespace { 11715 11716 /// Data recursive integer evaluator of certain binary operators. 11717 /// 11718 /// We use a data recursive algorithm for binary operators so that we are able 11719 /// to handle extreme cases of chained binary operators without causing stack 11720 /// overflow. 11721 class DataRecursiveIntBinOpEvaluator { 11722 struct EvalResult { 11723 APValue Val; 11724 bool Failed; 11725 11726 EvalResult() : Failed(false) { } 11727 11728 void swap(EvalResult &RHS) { 11729 Val.swap(RHS.Val); 11730 Failed = RHS.Failed; 11731 RHS.Failed = false; 11732 } 11733 }; 11734 11735 struct Job { 11736 const Expr *E; 11737 EvalResult LHSResult; // meaningful only for binary operator expression. 11738 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 11739 11740 Job() = default; 11741 Job(Job &&) = default; 11742 11743 void startSpeculativeEval(EvalInfo &Info) { 11744 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 11745 } 11746 11747 private: 11748 SpeculativeEvaluationRAII SpecEvalRAII; 11749 }; 11750 11751 SmallVector<Job, 16> Queue; 11752 11753 IntExprEvaluator &IntEval; 11754 EvalInfo &Info; 11755 APValue &FinalResult; 11756 11757 public: 11758 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 11759 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 11760 11761 /// True if \param E is a binary operator that we are going to handle 11762 /// data recursively. 11763 /// We handle binary operators that are comma, logical, or that have operands 11764 /// with integral or enumeration type. 11765 static bool shouldEnqueue(const BinaryOperator *E) { 11766 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 11767 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 11768 E->getLHS()->getType()->isIntegralOrEnumerationType() && 11769 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11770 } 11771 11772 bool Traverse(const BinaryOperator *E) { 11773 enqueue(E); 11774 EvalResult PrevResult; 11775 while (!Queue.empty()) 11776 process(PrevResult); 11777 11778 if (PrevResult.Failed) return false; 11779 11780 FinalResult.swap(PrevResult.Val); 11781 return true; 11782 } 11783 11784 private: 11785 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 11786 return IntEval.Success(Value, E, Result); 11787 } 11788 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 11789 return IntEval.Success(Value, E, Result); 11790 } 11791 bool Error(const Expr *E) { 11792 return IntEval.Error(E); 11793 } 11794 bool Error(const Expr *E, diag::kind D) { 11795 return IntEval.Error(E, D); 11796 } 11797 11798 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 11799 return Info.CCEDiag(E, D); 11800 } 11801 11802 // Returns true if visiting the RHS is necessary, false otherwise. 11803 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11804 bool &SuppressRHSDiags); 11805 11806 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 11807 const BinaryOperator *E, APValue &Result); 11808 11809 void EvaluateExpr(const Expr *E, EvalResult &Result) { 11810 Result.Failed = !Evaluate(Result.Val, Info, E); 11811 if (Result.Failed) 11812 Result.Val = APValue(); 11813 } 11814 11815 void process(EvalResult &Result); 11816 11817 void enqueue(const Expr *E) { 11818 E = E->IgnoreParens(); 11819 Queue.resize(Queue.size()+1); 11820 Queue.back().E = E; 11821 Queue.back().Kind = Job::AnyExprKind; 11822 } 11823 }; 11824 11825 } 11826 11827 bool DataRecursiveIntBinOpEvaluator:: 11828 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11829 bool &SuppressRHSDiags) { 11830 if (E->getOpcode() == BO_Comma) { 11831 // Ignore LHS but note if we could not evaluate it. 11832 if (LHSResult.Failed) 11833 return Info.noteSideEffect(); 11834 return true; 11835 } 11836 11837 if (E->isLogicalOp()) { 11838 bool LHSAsBool; 11839 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 11840 // We were able to evaluate the LHS, see if we can get away with not 11841 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 11842 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 11843 Success(LHSAsBool, E, LHSResult.Val); 11844 return false; // Ignore RHS 11845 } 11846 } else { 11847 LHSResult.Failed = true; 11848 11849 // Since we weren't able to evaluate the left hand side, it 11850 // might have had side effects. 11851 if (!Info.noteSideEffect()) 11852 return false; 11853 11854 // We can't evaluate the LHS; however, sometimes the result 11855 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 11856 // Don't ignore RHS and suppress diagnostics from this arm. 11857 SuppressRHSDiags = true; 11858 } 11859 11860 return true; 11861 } 11862 11863 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 11864 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11865 11866 if (LHSResult.Failed && !Info.noteFailure()) 11867 return false; // Ignore RHS; 11868 11869 return true; 11870 } 11871 11872 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 11873 bool IsSub) { 11874 // Compute the new offset in the appropriate width, wrapping at 64 bits. 11875 // FIXME: When compiling for a 32-bit target, we should use 32-bit 11876 // offsets. 11877 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 11878 CharUnits &Offset = LVal.getLValueOffset(); 11879 uint64_t Offset64 = Offset.getQuantity(); 11880 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 11881 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 11882 : Offset64 + Index64); 11883 } 11884 11885 bool DataRecursiveIntBinOpEvaluator:: 11886 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 11887 const BinaryOperator *E, APValue &Result) { 11888 if (E->getOpcode() == BO_Comma) { 11889 if (RHSResult.Failed) 11890 return false; 11891 Result = RHSResult.Val; 11892 return true; 11893 } 11894 11895 if (E->isLogicalOp()) { 11896 bool lhsResult, rhsResult; 11897 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 11898 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 11899 11900 if (LHSIsOK) { 11901 if (RHSIsOK) { 11902 if (E->getOpcode() == BO_LOr) 11903 return Success(lhsResult || rhsResult, E, Result); 11904 else 11905 return Success(lhsResult && rhsResult, E, Result); 11906 } 11907 } else { 11908 if (RHSIsOK) { 11909 // We can't evaluate the LHS; however, sometimes the result 11910 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 11911 if (rhsResult == (E->getOpcode() == BO_LOr)) 11912 return Success(rhsResult, E, Result); 11913 } 11914 } 11915 11916 return false; 11917 } 11918 11919 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 11920 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11921 11922 if (LHSResult.Failed || RHSResult.Failed) 11923 return false; 11924 11925 const APValue &LHSVal = LHSResult.Val; 11926 const APValue &RHSVal = RHSResult.Val; 11927 11928 // Handle cases like (unsigned long)&a + 4. 11929 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 11930 Result = LHSVal; 11931 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 11932 return true; 11933 } 11934 11935 // Handle cases like 4 + (unsigned long)&a 11936 if (E->getOpcode() == BO_Add && 11937 RHSVal.isLValue() && LHSVal.isInt()) { 11938 Result = RHSVal; 11939 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 11940 return true; 11941 } 11942 11943 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 11944 // Handle (intptr_t)&&A - (intptr_t)&&B. 11945 if (!LHSVal.getLValueOffset().isZero() || 11946 !RHSVal.getLValueOffset().isZero()) 11947 return false; 11948 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 11949 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 11950 if (!LHSExpr || !RHSExpr) 11951 return false; 11952 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 11953 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 11954 if (!LHSAddrExpr || !RHSAddrExpr) 11955 return false; 11956 // Make sure both labels come from the same function. 11957 if (LHSAddrExpr->getLabel()->getDeclContext() != 11958 RHSAddrExpr->getLabel()->getDeclContext()) 11959 return false; 11960 Result = APValue(LHSAddrExpr, RHSAddrExpr); 11961 return true; 11962 } 11963 11964 // All the remaining cases expect both operands to be an integer 11965 if (!LHSVal.isInt() || !RHSVal.isInt()) 11966 return Error(E); 11967 11968 // Set up the width and signedness manually, in case it can't be deduced 11969 // from the operation we're performing. 11970 // FIXME: Don't do this in the cases where we can deduce it. 11971 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 11972 E->getType()->isUnsignedIntegerOrEnumerationType()); 11973 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 11974 RHSVal.getInt(), Value)) 11975 return false; 11976 return Success(Value, E, Result); 11977 } 11978 11979 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 11980 Job &job = Queue.back(); 11981 11982 switch (job.Kind) { 11983 case Job::AnyExprKind: { 11984 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 11985 if (shouldEnqueue(Bop)) { 11986 job.Kind = Job::BinOpKind; 11987 enqueue(Bop->getLHS()); 11988 return; 11989 } 11990 } 11991 11992 EvaluateExpr(job.E, Result); 11993 Queue.pop_back(); 11994 return; 11995 } 11996 11997 case Job::BinOpKind: { 11998 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 11999 bool SuppressRHSDiags = false; 12000 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12001 Queue.pop_back(); 12002 return; 12003 } 12004 if (SuppressRHSDiags) 12005 job.startSpeculativeEval(Info); 12006 job.LHSResult.swap(Result); 12007 job.Kind = Job::BinOpVisitedLHSKind; 12008 enqueue(Bop->getRHS()); 12009 return; 12010 } 12011 12012 case Job::BinOpVisitedLHSKind: { 12013 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12014 EvalResult RHS; 12015 RHS.swap(Result); 12016 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12017 Queue.pop_back(); 12018 return; 12019 } 12020 } 12021 12022 llvm_unreachable("Invalid Job::Kind!"); 12023 } 12024 12025 namespace { 12026 /// Used when we determine that we should fail, but can keep evaluating prior to 12027 /// noting that we had a failure. 12028 class DelayedNoteFailureRAII { 12029 EvalInfo &Info; 12030 bool NoteFailure; 12031 12032 public: 12033 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 12034 : Info(Info), NoteFailure(NoteFailure) {} 12035 ~DelayedNoteFailureRAII() { 12036 if (NoteFailure) { 12037 bool ContinueAfterFailure = Info.noteFailure(); 12038 (void)ContinueAfterFailure; 12039 assert(ContinueAfterFailure && 12040 "Shouldn't have kept evaluating on failure."); 12041 } 12042 } 12043 }; 12044 12045 enum class CmpResult { 12046 Unequal, 12047 Less, 12048 Equal, 12049 Greater, 12050 Unordered, 12051 }; 12052 } 12053 12054 template <class SuccessCB, class AfterCB> 12055 static bool 12056 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12057 SuccessCB &&Success, AfterCB &&DoAfter) { 12058 assert(E->isComparisonOp() && "expected comparison operator"); 12059 assert((E->getOpcode() == BO_Cmp || 12060 E->getType()->isIntegralOrEnumerationType()) && 12061 "unsupported binary expression evaluation"); 12062 auto Error = [&](const Expr *E) { 12063 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12064 return false; 12065 }; 12066 12067 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12068 bool IsEquality = E->isEqualityOp(); 12069 12070 QualType LHSTy = E->getLHS()->getType(); 12071 QualType RHSTy = E->getRHS()->getType(); 12072 12073 if (LHSTy->isIntegralOrEnumerationType() && 12074 RHSTy->isIntegralOrEnumerationType()) { 12075 APSInt LHS, RHS; 12076 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12077 if (!LHSOK && !Info.noteFailure()) 12078 return false; 12079 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12080 return false; 12081 if (LHS < RHS) 12082 return Success(CmpResult::Less, E); 12083 if (LHS > RHS) 12084 return Success(CmpResult::Greater, E); 12085 return Success(CmpResult::Equal, E); 12086 } 12087 12088 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12089 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12090 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12091 12092 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12093 if (!LHSOK && !Info.noteFailure()) 12094 return false; 12095 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12096 return false; 12097 if (LHSFX < RHSFX) 12098 return Success(CmpResult::Less, E); 12099 if (LHSFX > RHSFX) 12100 return Success(CmpResult::Greater, E); 12101 return Success(CmpResult::Equal, E); 12102 } 12103 12104 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12105 ComplexValue LHS, RHS; 12106 bool LHSOK; 12107 if (E->isAssignmentOp()) { 12108 LValue LV; 12109 EvaluateLValue(E->getLHS(), LV, Info); 12110 LHSOK = false; 12111 } else if (LHSTy->isRealFloatingType()) { 12112 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12113 if (LHSOK) { 12114 LHS.makeComplexFloat(); 12115 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12116 } 12117 } else { 12118 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12119 } 12120 if (!LHSOK && !Info.noteFailure()) 12121 return false; 12122 12123 if (E->getRHS()->getType()->isRealFloatingType()) { 12124 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12125 return false; 12126 RHS.makeComplexFloat(); 12127 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12128 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12129 return false; 12130 12131 if (LHS.isComplexFloat()) { 12132 APFloat::cmpResult CR_r = 12133 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12134 APFloat::cmpResult CR_i = 12135 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12136 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12137 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12138 } else { 12139 assert(IsEquality && "invalid complex comparison"); 12140 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12141 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12142 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12143 } 12144 } 12145 12146 if (LHSTy->isRealFloatingType() && 12147 RHSTy->isRealFloatingType()) { 12148 APFloat RHS(0.0), LHS(0.0); 12149 12150 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12151 if (!LHSOK && !Info.noteFailure()) 12152 return false; 12153 12154 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12155 return false; 12156 12157 assert(E->isComparisonOp() && "Invalid binary operator!"); 12158 auto GetCmpRes = [&]() { 12159 switch (LHS.compare(RHS)) { 12160 case APFloat::cmpEqual: 12161 return CmpResult::Equal; 12162 case APFloat::cmpLessThan: 12163 return CmpResult::Less; 12164 case APFloat::cmpGreaterThan: 12165 return CmpResult::Greater; 12166 case APFloat::cmpUnordered: 12167 return CmpResult::Unordered; 12168 } 12169 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12170 }; 12171 return Success(GetCmpRes(), E); 12172 } 12173 12174 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12175 LValue LHSValue, RHSValue; 12176 12177 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12178 if (!LHSOK && !Info.noteFailure()) 12179 return false; 12180 12181 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12182 return false; 12183 12184 // Reject differing bases from the normal codepath; we special-case 12185 // comparisons to null. 12186 if (!HasSameBase(LHSValue, RHSValue)) { 12187 // Inequalities and subtractions between unrelated pointers have 12188 // unspecified or undefined behavior. 12189 if (!IsEquality) { 12190 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12191 return false; 12192 } 12193 // A constant address may compare equal to the address of a symbol. 12194 // The one exception is that address of an object cannot compare equal 12195 // to a null pointer constant. 12196 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12197 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12198 return Error(E); 12199 // It's implementation-defined whether distinct literals will have 12200 // distinct addresses. In clang, the result of such a comparison is 12201 // unspecified, so it is not a constant expression. However, we do know 12202 // that the address of a literal will be non-null. 12203 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12204 LHSValue.Base && RHSValue.Base) 12205 return Error(E); 12206 // We can't tell whether weak symbols will end up pointing to the same 12207 // object. 12208 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12209 return Error(E); 12210 // We can't compare the address of the start of one object with the 12211 // past-the-end address of another object, per C++ DR1652. 12212 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12213 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12214 (RHSValue.Base && RHSValue.Offset.isZero() && 12215 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12216 return Error(E); 12217 // We can't tell whether an object is at the same address as another 12218 // zero sized object. 12219 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12220 (LHSValue.Base && isZeroSized(RHSValue))) 12221 return Error(E); 12222 return Success(CmpResult::Unequal, E); 12223 } 12224 12225 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12226 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12227 12228 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12229 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12230 12231 // C++11 [expr.rel]p3: 12232 // Pointers to void (after pointer conversions) can be compared, with a 12233 // result defined as follows: If both pointers represent the same 12234 // address or are both the null pointer value, the result is true if the 12235 // operator is <= or >= and false otherwise; otherwise the result is 12236 // unspecified. 12237 // We interpret this as applying to pointers to *cv* void. 12238 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12239 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12240 12241 // C++11 [expr.rel]p2: 12242 // - If two pointers point to non-static data members of the same object, 12243 // or to subobjects or array elements fo such members, recursively, the 12244 // pointer to the later declared member compares greater provided the 12245 // two members have the same access control and provided their class is 12246 // not a union. 12247 // [...] 12248 // - Otherwise pointer comparisons are unspecified. 12249 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12250 bool WasArrayIndex; 12251 unsigned Mismatch = FindDesignatorMismatch( 12252 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12253 // At the point where the designators diverge, the comparison has a 12254 // specified value if: 12255 // - we are comparing array indices 12256 // - we are comparing fields of a union, or fields with the same access 12257 // Otherwise, the result is unspecified and thus the comparison is not a 12258 // constant expression. 12259 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12260 Mismatch < RHSDesignator.Entries.size()) { 12261 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12262 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12263 if (!LF && !RF) 12264 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12265 else if (!LF) 12266 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12267 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12268 << RF->getParent() << RF; 12269 else if (!RF) 12270 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12271 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12272 << LF->getParent() << LF; 12273 else if (!LF->getParent()->isUnion() && 12274 LF->getAccess() != RF->getAccess()) 12275 Info.CCEDiag(E, 12276 diag::note_constexpr_pointer_comparison_differing_access) 12277 << LF << LF->getAccess() << RF << RF->getAccess() 12278 << LF->getParent(); 12279 } 12280 } 12281 12282 // The comparison here must be unsigned, and performed with the same 12283 // width as the pointer. 12284 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12285 uint64_t CompareLHS = LHSOffset.getQuantity(); 12286 uint64_t CompareRHS = RHSOffset.getQuantity(); 12287 assert(PtrSize <= 64 && "Unexpected pointer width"); 12288 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12289 CompareLHS &= Mask; 12290 CompareRHS &= Mask; 12291 12292 // If there is a base and this is a relational operator, we can only 12293 // compare pointers within the object in question; otherwise, the result 12294 // depends on where the object is located in memory. 12295 if (!LHSValue.Base.isNull() && IsRelational) { 12296 QualType BaseTy = getType(LHSValue.Base); 12297 if (BaseTy->isIncompleteType()) 12298 return Error(E); 12299 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12300 uint64_t OffsetLimit = Size.getQuantity(); 12301 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12302 return Error(E); 12303 } 12304 12305 if (CompareLHS < CompareRHS) 12306 return Success(CmpResult::Less, E); 12307 if (CompareLHS > CompareRHS) 12308 return Success(CmpResult::Greater, E); 12309 return Success(CmpResult::Equal, E); 12310 } 12311 12312 if (LHSTy->isMemberPointerType()) { 12313 assert(IsEquality && "unexpected member pointer operation"); 12314 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12315 12316 MemberPtr LHSValue, RHSValue; 12317 12318 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12319 if (!LHSOK && !Info.noteFailure()) 12320 return false; 12321 12322 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12323 return false; 12324 12325 // C++11 [expr.eq]p2: 12326 // If both operands are null, they compare equal. Otherwise if only one is 12327 // null, they compare unequal. 12328 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12329 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12330 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12331 } 12332 12333 // Otherwise if either is a pointer to a virtual member function, the 12334 // result is unspecified. 12335 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12336 if (MD->isVirtual()) 12337 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12338 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12339 if (MD->isVirtual()) 12340 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12341 12342 // Otherwise they compare equal if and only if they would refer to the 12343 // same member of the same most derived object or the same subobject if 12344 // they were dereferenced with a hypothetical object of the associated 12345 // class type. 12346 bool Equal = LHSValue == RHSValue; 12347 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12348 } 12349 12350 if (LHSTy->isNullPtrType()) { 12351 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12352 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12353 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12354 // are compared, the result is true of the operator is <=, >= or ==, and 12355 // false otherwise. 12356 return Success(CmpResult::Equal, E); 12357 } 12358 12359 return DoAfter(); 12360 } 12361 12362 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12363 if (!CheckLiteralType(Info, E)) 12364 return false; 12365 12366 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12367 ComparisonCategoryResult CCR; 12368 switch (CR) { 12369 case CmpResult::Unequal: 12370 llvm_unreachable("should never produce Unequal for three-way comparison"); 12371 case CmpResult::Less: 12372 CCR = ComparisonCategoryResult::Less; 12373 break; 12374 case CmpResult::Equal: 12375 CCR = ComparisonCategoryResult::Equal; 12376 break; 12377 case CmpResult::Greater: 12378 CCR = ComparisonCategoryResult::Greater; 12379 break; 12380 case CmpResult::Unordered: 12381 CCR = ComparisonCategoryResult::Unordered; 12382 break; 12383 } 12384 // Evaluation succeeded. Lookup the information for the comparison category 12385 // type and fetch the VarDecl for the result. 12386 const ComparisonCategoryInfo &CmpInfo = 12387 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12388 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12389 // Check and evaluate the result as a constant expression. 12390 LValue LV; 12391 LV.set(VD); 12392 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12393 return false; 12394 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 12395 }; 12396 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12397 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12398 }); 12399 } 12400 12401 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12402 // We don't call noteFailure immediately because the assignment happens after 12403 // we evaluate LHS and RHS. 12404 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 12405 return Error(E); 12406 12407 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 12408 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12409 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12410 12411 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12412 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12413 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12414 12415 if (E->isComparisonOp()) { 12416 // Evaluate builtin binary comparisons by evaluating them as three-way 12417 // comparisons and then translating the result. 12418 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12419 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12420 "should only produce Unequal for equality comparisons"); 12421 bool IsEqual = CR == CmpResult::Equal, 12422 IsLess = CR == CmpResult::Less, 12423 IsGreater = CR == CmpResult::Greater; 12424 auto Op = E->getOpcode(); 12425 switch (Op) { 12426 default: 12427 llvm_unreachable("unsupported binary operator"); 12428 case BO_EQ: 12429 case BO_NE: 12430 return Success(IsEqual == (Op == BO_EQ), E); 12431 case BO_LT: 12432 return Success(IsLess, E); 12433 case BO_GT: 12434 return Success(IsGreater, E); 12435 case BO_LE: 12436 return Success(IsEqual || IsLess, E); 12437 case BO_GE: 12438 return Success(IsEqual || IsGreater, E); 12439 } 12440 }; 12441 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12442 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12443 }); 12444 } 12445 12446 QualType LHSTy = E->getLHS()->getType(); 12447 QualType RHSTy = E->getRHS()->getType(); 12448 12449 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12450 E->getOpcode() == BO_Sub) { 12451 LValue LHSValue, RHSValue; 12452 12453 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12454 if (!LHSOK && !Info.noteFailure()) 12455 return false; 12456 12457 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12458 return false; 12459 12460 // Reject differing bases from the normal codepath; we special-case 12461 // comparisons to null. 12462 if (!HasSameBase(LHSValue, RHSValue)) { 12463 // Handle &&A - &&B. 12464 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12465 return Error(E); 12466 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12467 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12468 if (!LHSExpr || !RHSExpr) 12469 return Error(E); 12470 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12471 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12472 if (!LHSAddrExpr || !RHSAddrExpr) 12473 return Error(E); 12474 // Make sure both labels come from the same function. 12475 if (LHSAddrExpr->getLabel()->getDeclContext() != 12476 RHSAddrExpr->getLabel()->getDeclContext()) 12477 return Error(E); 12478 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12479 } 12480 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12481 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12482 12483 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12484 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12485 12486 // C++11 [expr.add]p6: 12487 // Unless both pointers point to elements of the same array object, or 12488 // one past the last element of the array object, the behavior is 12489 // undefined. 12490 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12491 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12492 RHSDesignator)) 12493 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12494 12495 QualType Type = E->getLHS()->getType(); 12496 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12497 12498 CharUnits ElementSize; 12499 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12500 return false; 12501 12502 // As an extension, a type may have zero size (empty struct or union in 12503 // C, array of zero length). Pointer subtraction in such cases has 12504 // undefined behavior, so is not constant. 12505 if (ElementSize.isZero()) { 12506 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12507 << ElementType; 12508 return false; 12509 } 12510 12511 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12512 // and produce incorrect results when it overflows. Such behavior 12513 // appears to be non-conforming, but is common, so perhaps we should 12514 // assume the standard intended for such cases to be undefined behavior 12515 // and check for them. 12516 12517 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12518 // overflow in the final conversion to ptrdiff_t. 12519 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12520 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12521 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12522 false); 12523 APSInt TrueResult = (LHS - RHS) / ElemSize; 12524 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12525 12526 if (Result.extend(65) != TrueResult && 12527 !HandleOverflow(Info, E, TrueResult, E->getType())) 12528 return false; 12529 return Success(Result, E); 12530 } 12531 12532 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12533 } 12534 12535 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12536 /// a result as the expression's type. 12537 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12538 const UnaryExprOrTypeTraitExpr *E) { 12539 switch(E->getKind()) { 12540 case UETT_PreferredAlignOf: 12541 case UETT_AlignOf: { 12542 if (E->isArgumentType()) 12543 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 12544 E); 12545 else 12546 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 12547 E); 12548 } 12549 12550 case UETT_VecStep: { 12551 QualType Ty = E->getTypeOfArgument(); 12552 12553 if (Ty->isVectorType()) { 12554 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 12555 12556 // The vec_step built-in functions that take a 3-component 12557 // vector return 4. (OpenCL 1.1 spec 6.11.12) 12558 if (n == 3) 12559 n = 4; 12560 12561 return Success(n, E); 12562 } else 12563 return Success(1, E); 12564 } 12565 12566 case UETT_SizeOf: { 12567 QualType SrcTy = E->getTypeOfArgument(); 12568 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 12569 // the result is the size of the referenced type." 12570 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 12571 SrcTy = Ref->getPointeeType(); 12572 12573 CharUnits Sizeof; 12574 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 12575 return false; 12576 return Success(Sizeof, E); 12577 } 12578 case UETT_OpenMPRequiredSimdAlign: 12579 assert(E->isArgumentType()); 12580 return Success( 12581 Info.Ctx.toCharUnitsFromBits( 12582 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 12583 .getQuantity(), 12584 E); 12585 } 12586 12587 llvm_unreachable("unknown expr/type trait"); 12588 } 12589 12590 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 12591 CharUnits Result; 12592 unsigned n = OOE->getNumComponents(); 12593 if (n == 0) 12594 return Error(OOE); 12595 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 12596 for (unsigned i = 0; i != n; ++i) { 12597 OffsetOfNode ON = OOE->getComponent(i); 12598 switch (ON.getKind()) { 12599 case OffsetOfNode::Array: { 12600 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 12601 APSInt IdxResult; 12602 if (!EvaluateInteger(Idx, IdxResult, Info)) 12603 return false; 12604 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 12605 if (!AT) 12606 return Error(OOE); 12607 CurrentType = AT->getElementType(); 12608 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 12609 Result += IdxResult.getSExtValue() * ElementSize; 12610 break; 12611 } 12612 12613 case OffsetOfNode::Field: { 12614 FieldDecl *MemberDecl = ON.getField(); 12615 const RecordType *RT = CurrentType->getAs<RecordType>(); 12616 if (!RT) 12617 return Error(OOE); 12618 RecordDecl *RD = RT->getDecl(); 12619 if (RD->isInvalidDecl()) return false; 12620 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12621 unsigned i = MemberDecl->getFieldIndex(); 12622 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 12623 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 12624 CurrentType = MemberDecl->getType().getNonReferenceType(); 12625 break; 12626 } 12627 12628 case OffsetOfNode::Identifier: 12629 llvm_unreachable("dependent __builtin_offsetof"); 12630 12631 case OffsetOfNode::Base: { 12632 CXXBaseSpecifier *BaseSpec = ON.getBase(); 12633 if (BaseSpec->isVirtual()) 12634 return Error(OOE); 12635 12636 // Find the layout of the class whose base we are looking into. 12637 const RecordType *RT = CurrentType->getAs<RecordType>(); 12638 if (!RT) 12639 return Error(OOE); 12640 RecordDecl *RD = RT->getDecl(); 12641 if (RD->isInvalidDecl()) return false; 12642 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12643 12644 // Find the base class itself. 12645 CurrentType = BaseSpec->getType(); 12646 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 12647 if (!BaseRT) 12648 return Error(OOE); 12649 12650 // Add the offset to the base. 12651 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 12652 break; 12653 } 12654 } 12655 } 12656 return Success(Result, OOE); 12657 } 12658 12659 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12660 switch (E->getOpcode()) { 12661 default: 12662 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 12663 // See C99 6.6p3. 12664 return Error(E); 12665 case UO_Extension: 12666 // FIXME: Should extension allow i-c-e extension expressions in its scope? 12667 // If so, we could clear the diagnostic ID. 12668 return Visit(E->getSubExpr()); 12669 case UO_Plus: 12670 // The result is just the value. 12671 return Visit(E->getSubExpr()); 12672 case UO_Minus: { 12673 if (!Visit(E->getSubExpr())) 12674 return false; 12675 if (!Result.isInt()) return Error(E); 12676 const APSInt &Value = Result.getInt(); 12677 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 12678 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 12679 E->getType())) 12680 return false; 12681 return Success(-Value, E); 12682 } 12683 case UO_Not: { 12684 if (!Visit(E->getSubExpr())) 12685 return false; 12686 if (!Result.isInt()) return Error(E); 12687 return Success(~Result.getInt(), E); 12688 } 12689 case UO_LNot: { 12690 bool bres; 12691 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 12692 return false; 12693 return Success(!bres, E); 12694 } 12695 } 12696 } 12697 12698 /// HandleCast - This is used to evaluate implicit or explicit casts where the 12699 /// result type is integer. 12700 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 12701 const Expr *SubExpr = E->getSubExpr(); 12702 QualType DestType = E->getType(); 12703 QualType SrcType = SubExpr->getType(); 12704 12705 switch (E->getCastKind()) { 12706 case CK_BaseToDerived: 12707 case CK_DerivedToBase: 12708 case CK_UncheckedDerivedToBase: 12709 case CK_Dynamic: 12710 case CK_ToUnion: 12711 case CK_ArrayToPointerDecay: 12712 case CK_FunctionToPointerDecay: 12713 case CK_NullToPointer: 12714 case CK_NullToMemberPointer: 12715 case CK_BaseToDerivedMemberPointer: 12716 case CK_DerivedToBaseMemberPointer: 12717 case CK_ReinterpretMemberPointer: 12718 case CK_ConstructorConversion: 12719 case CK_IntegralToPointer: 12720 case CK_ToVoid: 12721 case CK_VectorSplat: 12722 case CK_IntegralToFloating: 12723 case CK_FloatingCast: 12724 case CK_CPointerToObjCPointerCast: 12725 case CK_BlockPointerToObjCPointerCast: 12726 case CK_AnyPointerToBlockPointerCast: 12727 case CK_ObjCObjectLValueCast: 12728 case CK_FloatingRealToComplex: 12729 case CK_FloatingComplexToReal: 12730 case CK_FloatingComplexCast: 12731 case CK_FloatingComplexToIntegralComplex: 12732 case CK_IntegralRealToComplex: 12733 case CK_IntegralComplexCast: 12734 case CK_IntegralComplexToFloatingComplex: 12735 case CK_BuiltinFnToFnPtr: 12736 case CK_ZeroToOCLOpaqueType: 12737 case CK_NonAtomicToAtomic: 12738 case CK_AddressSpaceConversion: 12739 case CK_IntToOCLSampler: 12740 case CK_FixedPointCast: 12741 case CK_IntegralToFixedPoint: 12742 llvm_unreachable("invalid cast kind for integral value"); 12743 12744 case CK_BitCast: 12745 case CK_Dependent: 12746 case CK_LValueBitCast: 12747 case CK_ARCProduceObject: 12748 case CK_ARCConsumeObject: 12749 case CK_ARCReclaimReturnedObject: 12750 case CK_ARCExtendBlockObject: 12751 case CK_CopyAndAutoreleaseBlockObject: 12752 return Error(E); 12753 12754 case CK_UserDefinedConversion: 12755 case CK_LValueToRValue: 12756 case CK_AtomicToNonAtomic: 12757 case CK_NoOp: 12758 case CK_LValueToRValueBitCast: 12759 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12760 12761 case CK_MemberPointerToBoolean: 12762 case CK_PointerToBoolean: 12763 case CK_IntegralToBoolean: 12764 case CK_FloatingToBoolean: 12765 case CK_BooleanToSignedIntegral: 12766 case CK_FloatingComplexToBoolean: 12767 case CK_IntegralComplexToBoolean: { 12768 bool BoolResult; 12769 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 12770 return false; 12771 uint64_t IntResult = BoolResult; 12772 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 12773 IntResult = (uint64_t)-1; 12774 return Success(IntResult, E); 12775 } 12776 12777 case CK_FixedPointToIntegral: { 12778 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 12779 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 12780 return false; 12781 bool Overflowed; 12782 llvm::APSInt Result = Src.convertToInt( 12783 Info.Ctx.getIntWidth(DestType), 12784 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 12785 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 12786 return false; 12787 return Success(Result, E); 12788 } 12789 12790 case CK_FixedPointToBoolean: { 12791 // Unsigned padding does not affect this. 12792 APValue Val; 12793 if (!Evaluate(Val, Info, SubExpr)) 12794 return false; 12795 return Success(Val.getFixedPoint().getBoolValue(), E); 12796 } 12797 12798 case CK_IntegralCast: { 12799 if (!Visit(SubExpr)) 12800 return false; 12801 12802 if (!Result.isInt()) { 12803 // Allow casts of address-of-label differences if they are no-ops 12804 // or narrowing. (The narrowing case isn't actually guaranteed to 12805 // be constant-evaluatable except in some narrow cases which are hard 12806 // to detect here. We let it through on the assumption the user knows 12807 // what they are doing.) 12808 if (Result.isAddrLabelDiff()) 12809 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 12810 // Only allow casts of lvalues if they are lossless. 12811 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 12812 } 12813 12814 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 12815 Result.getInt()), E); 12816 } 12817 12818 case CK_PointerToIntegral: { 12819 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 12820 12821 LValue LV; 12822 if (!EvaluatePointer(SubExpr, LV, Info)) 12823 return false; 12824 12825 if (LV.getLValueBase()) { 12826 // Only allow based lvalue casts if they are lossless. 12827 // FIXME: Allow a larger integer size than the pointer size, and allow 12828 // narrowing back down to pointer width in subsequent integral casts. 12829 // FIXME: Check integer type's active bits, not its type size. 12830 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 12831 return Error(E); 12832 12833 LV.Designator.setInvalid(); 12834 LV.moveInto(Result); 12835 return true; 12836 } 12837 12838 APSInt AsInt; 12839 APValue V; 12840 LV.moveInto(V); 12841 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 12842 llvm_unreachable("Can't cast this!"); 12843 12844 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 12845 } 12846 12847 case CK_IntegralComplexToReal: { 12848 ComplexValue C; 12849 if (!EvaluateComplex(SubExpr, C, Info)) 12850 return false; 12851 return Success(C.getComplexIntReal(), E); 12852 } 12853 12854 case CK_FloatingToIntegral: { 12855 APFloat F(0.0); 12856 if (!EvaluateFloat(SubExpr, F, Info)) 12857 return false; 12858 12859 APSInt Value; 12860 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 12861 return false; 12862 return Success(Value, E); 12863 } 12864 } 12865 12866 llvm_unreachable("unknown cast resulting in integral value"); 12867 } 12868 12869 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 12870 if (E->getSubExpr()->getType()->isAnyComplexType()) { 12871 ComplexValue LV; 12872 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 12873 return false; 12874 if (!LV.isComplexInt()) 12875 return Error(E); 12876 return Success(LV.getComplexIntReal(), E); 12877 } 12878 12879 return Visit(E->getSubExpr()); 12880 } 12881 12882 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 12883 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 12884 ComplexValue LV; 12885 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 12886 return false; 12887 if (!LV.isComplexInt()) 12888 return Error(E); 12889 return Success(LV.getComplexIntImag(), E); 12890 } 12891 12892 VisitIgnoredValue(E->getSubExpr()); 12893 return Success(0, E); 12894 } 12895 12896 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 12897 return Success(E->getPackLength(), E); 12898 } 12899 12900 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 12901 return Success(E->getValue(), E); 12902 } 12903 12904 bool IntExprEvaluator::VisitConceptSpecializationExpr( 12905 const ConceptSpecializationExpr *E) { 12906 return Success(E->isSatisfied(), E); 12907 } 12908 12909 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 12910 return Success(E->isSatisfied(), E); 12911 } 12912 12913 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12914 switch (E->getOpcode()) { 12915 default: 12916 // Invalid unary operators 12917 return Error(E); 12918 case UO_Plus: 12919 // The result is just the value. 12920 return Visit(E->getSubExpr()); 12921 case UO_Minus: { 12922 if (!Visit(E->getSubExpr())) return false; 12923 if (!Result.isFixedPoint()) 12924 return Error(E); 12925 bool Overflowed; 12926 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 12927 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 12928 return false; 12929 return Success(Negated, E); 12930 } 12931 case UO_LNot: { 12932 bool bres; 12933 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 12934 return false; 12935 return Success(!bres, E); 12936 } 12937 } 12938 } 12939 12940 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 12941 const Expr *SubExpr = E->getSubExpr(); 12942 QualType DestType = E->getType(); 12943 assert(DestType->isFixedPointType() && 12944 "Expected destination type to be a fixed point type"); 12945 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 12946 12947 switch (E->getCastKind()) { 12948 case CK_FixedPointCast: { 12949 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 12950 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 12951 return false; 12952 bool Overflowed; 12953 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 12954 if (Overflowed) { 12955 if (Info.checkingForUndefinedBehavior()) 12956 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 12957 diag::warn_fixedpoint_constant_overflow) 12958 << Result.toString() << E->getType(); 12959 else if (!HandleOverflow(Info, E, Result, E->getType())) 12960 return false; 12961 } 12962 return Success(Result, E); 12963 } 12964 case CK_IntegralToFixedPoint: { 12965 APSInt Src; 12966 if (!EvaluateInteger(SubExpr, Src, Info)) 12967 return false; 12968 12969 bool Overflowed; 12970 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 12971 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 12972 12973 if (Overflowed) { 12974 if (Info.checkingForUndefinedBehavior()) 12975 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 12976 diag::warn_fixedpoint_constant_overflow) 12977 << IntResult.toString() << E->getType(); 12978 else if (!HandleOverflow(Info, E, IntResult, E->getType())) 12979 return false; 12980 } 12981 12982 return Success(IntResult, E); 12983 } 12984 case CK_NoOp: 12985 case CK_LValueToRValue: 12986 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12987 default: 12988 return Error(E); 12989 } 12990 } 12991 12992 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12993 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 12994 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12995 12996 const Expr *LHS = E->getLHS(); 12997 const Expr *RHS = E->getRHS(); 12998 FixedPointSemantics ResultFXSema = 12999 Info.Ctx.getFixedPointSemantics(E->getType()); 13000 13001 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13002 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13003 return false; 13004 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13005 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13006 return false; 13007 13008 bool OpOverflow = false, ConversionOverflow = false; 13009 APFixedPoint Result(LHSFX.getSemantics()); 13010 switch (E->getOpcode()) { 13011 case BO_Add: { 13012 Result = LHSFX.add(RHSFX, &OpOverflow) 13013 .convert(ResultFXSema, &ConversionOverflow); 13014 break; 13015 } 13016 case BO_Sub: { 13017 Result = LHSFX.sub(RHSFX, &OpOverflow) 13018 .convert(ResultFXSema, &ConversionOverflow); 13019 break; 13020 } 13021 case BO_Mul: { 13022 Result = LHSFX.mul(RHSFX, &OpOverflow) 13023 .convert(ResultFXSema, &ConversionOverflow); 13024 break; 13025 } 13026 case BO_Div: { 13027 if (RHSFX.getValue() == 0) { 13028 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13029 return false; 13030 } 13031 Result = LHSFX.div(RHSFX, &OpOverflow) 13032 .convert(ResultFXSema, &ConversionOverflow); 13033 break; 13034 } 13035 case BO_Shl: 13036 case BO_Shr: { 13037 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13038 llvm::APSInt RHSVal = RHSFX.getValue(); 13039 13040 unsigned ShiftBW = 13041 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13042 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13043 // Embedded-C 4.1.6.2.2: 13044 // The right operand must be nonnegative and less than the total number 13045 // of (nonpadding) bits of the fixed-point operand ... 13046 if (RHSVal.isNegative()) 13047 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13048 else if (Amt != RHSVal) 13049 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13050 << RHSVal << E->getType() << ShiftBW; 13051 13052 if (E->getOpcode() == BO_Shl) 13053 Result = LHSFX.shl(Amt, &OpOverflow); 13054 else 13055 Result = LHSFX.shr(Amt, &OpOverflow); 13056 break; 13057 } 13058 default: 13059 return false; 13060 } 13061 if (OpOverflow || ConversionOverflow) { 13062 if (Info.checkingForUndefinedBehavior()) 13063 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13064 diag::warn_fixedpoint_constant_overflow) 13065 << Result.toString() << E->getType(); 13066 else if (!HandleOverflow(Info, E, Result, E->getType())) 13067 return false; 13068 } 13069 return Success(Result, E); 13070 } 13071 13072 //===----------------------------------------------------------------------===// 13073 // Float Evaluation 13074 //===----------------------------------------------------------------------===// 13075 13076 namespace { 13077 class FloatExprEvaluator 13078 : public ExprEvaluatorBase<FloatExprEvaluator> { 13079 APFloat &Result; 13080 public: 13081 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13082 : ExprEvaluatorBaseTy(info), Result(result) {} 13083 13084 bool Success(const APValue &V, const Expr *e) { 13085 Result = V.getFloat(); 13086 return true; 13087 } 13088 13089 bool ZeroInitialization(const Expr *E) { 13090 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13091 return true; 13092 } 13093 13094 bool VisitCallExpr(const CallExpr *E); 13095 13096 bool VisitUnaryOperator(const UnaryOperator *E); 13097 bool VisitBinaryOperator(const BinaryOperator *E); 13098 bool VisitFloatingLiteral(const FloatingLiteral *E); 13099 bool VisitCastExpr(const CastExpr *E); 13100 13101 bool VisitUnaryReal(const UnaryOperator *E); 13102 bool VisitUnaryImag(const UnaryOperator *E); 13103 13104 // FIXME: Missing: array subscript of vector, member of vector 13105 }; 13106 } // end anonymous namespace 13107 13108 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13109 assert(E->isRValue() && E->getType()->isRealFloatingType()); 13110 return FloatExprEvaluator(Info, Result).Visit(E); 13111 } 13112 13113 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13114 QualType ResultTy, 13115 const Expr *Arg, 13116 bool SNaN, 13117 llvm::APFloat &Result) { 13118 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13119 if (!S) return false; 13120 13121 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13122 13123 llvm::APInt fill; 13124 13125 // Treat empty strings as if they were zero. 13126 if (S->getString().empty()) 13127 fill = llvm::APInt(32, 0); 13128 else if (S->getString().getAsInteger(0, fill)) 13129 return false; 13130 13131 if (Context.getTargetInfo().isNan2008()) { 13132 if (SNaN) 13133 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13134 else 13135 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13136 } else { 13137 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13138 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13139 // a different encoding to what became a standard in 2008, and for pre- 13140 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13141 // sNaN. This is now known as "legacy NaN" encoding. 13142 if (SNaN) 13143 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13144 else 13145 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13146 } 13147 13148 return true; 13149 } 13150 13151 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13152 switch (E->getBuiltinCallee()) { 13153 default: 13154 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13155 13156 case Builtin::BI__builtin_huge_val: 13157 case Builtin::BI__builtin_huge_valf: 13158 case Builtin::BI__builtin_huge_vall: 13159 case Builtin::BI__builtin_huge_valf128: 13160 case Builtin::BI__builtin_inf: 13161 case Builtin::BI__builtin_inff: 13162 case Builtin::BI__builtin_infl: 13163 case Builtin::BI__builtin_inff128: { 13164 const llvm::fltSemantics &Sem = 13165 Info.Ctx.getFloatTypeSemantics(E->getType()); 13166 Result = llvm::APFloat::getInf(Sem); 13167 return true; 13168 } 13169 13170 case Builtin::BI__builtin_nans: 13171 case Builtin::BI__builtin_nansf: 13172 case Builtin::BI__builtin_nansl: 13173 case Builtin::BI__builtin_nansf128: 13174 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13175 true, Result)) 13176 return Error(E); 13177 return true; 13178 13179 case Builtin::BI__builtin_nan: 13180 case Builtin::BI__builtin_nanf: 13181 case Builtin::BI__builtin_nanl: 13182 case Builtin::BI__builtin_nanf128: 13183 // If this is __builtin_nan() turn this into a nan, otherwise we 13184 // can't constant fold it. 13185 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13186 false, Result)) 13187 return Error(E); 13188 return true; 13189 13190 case Builtin::BI__builtin_fabs: 13191 case Builtin::BI__builtin_fabsf: 13192 case Builtin::BI__builtin_fabsl: 13193 case Builtin::BI__builtin_fabsf128: 13194 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13195 return false; 13196 13197 if (Result.isNegative()) 13198 Result.changeSign(); 13199 return true; 13200 13201 // FIXME: Builtin::BI__builtin_powi 13202 // FIXME: Builtin::BI__builtin_powif 13203 // FIXME: Builtin::BI__builtin_powil 13204 13205 case Builtin::BI__builtin_copysign: 13206 case Builtin::BI__builtin_copysignf: 13207 case Builtin::BI__builtin_copysignl: 13208 case Builtin::BI__builtin_copysignf128: { 13209 APFloat RHS(0.); 13210 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13211 !EvaluateFloat(E->getArg(1), RHS, Info)) 13212 return false; 13213 Result.copySign(RHS); 13214 return true; 13215 } 13216 } 13217 } 13218 13219 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13220 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13221 ComplexValue CV; 13222 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13223 return false; 13224 Result = CV.FloatReal; 13225 return true; 13226 } 13227 13228 return Visit(E->getSubExpr()); 13229 } 13230 13231 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13232 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13233 ComplexValue CV; 13234 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13235 return false; 13236 Result = CV.FloatImag; 13237 return true; 13238 } 13239 13240 VisitIgnoredValue(E->getSubExpr()); 13241 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13242 Result = llvm::APFloat::getZero(Sem); 13243 return true; 13244 } 13245 13246 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13247 switch (E->getOpcode()) { 13248 default: return Error(E); 13249 case UO_Plus: 13250 return EvaluateFloat(E->getSubExpr(), Result, Info); 13251 case UO_Minus: 13252 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13253 return false; 13254 Result.changeSign(); 13255 return true; 13256 } 13257 } 13258 13259 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13260 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13261 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13262 13263 APFloat RHS(0.0); 13264 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13265 if (!LHSOK && !Info.noteFailure()) 13266 return false; 13267 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13268 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13269 } 13270 13271 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13272 Result = E->getValue(); 13273 return true; 13274 } 13275 13276 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13277 const Expr* SubExpr = E->getSubExpr(); 13278 13279 switch (E->getCastKind()) { 13280 default: 13281 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13282 13283 case CK_IntegralToFloating: { 13284 APSInt IntResult; 13285 return EvaluateInteger(SubExpr, IntResult, Info) && 13286 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 13287 E->getType(), Result); 13288 } 13289 13290 case CK_FloatingCast: { 13291 if (!Visit(SubExpr)) 13292 return false; 13293 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13294 Result); 13295 } 13296 13297 case CK_FloatingComplexToReal: { 13298 ComplexValue V; 13299 if (!EvaluateComplex(SubExpr, V, Info)) 13300 return false; 13301 Result = V.getComplexFloatReal(); 13302 return true; 13303 } 13304 } 13305 } 13306 13307 //===----------------------------------------------------------------------===// 13308 // Complex Evaluation (for float and integer) 13309 //===----------------------------------------------------------------------===// 13310 13311 namespace { 13312 class ComplexExprEvaluator 13313 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13314 ComplexValue &Result; 13315 13316 public: 13317 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13318 : ExprEvaluatorBaseTy(info), Result(Result) {} 13319 13320 bool Success(const APValue &V, const Expr *e) { 13321 Result.setFrom(V); 13322 return true; 13323 } 13324 13325 bool ZeroInitialization(const Expr *E); 13326 13327 //===--------------------------------------------------------------------===// 13328 // Visitor Methods 13329 //===--------------------------------------------------------------------===// 13330 13331 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13332 bool VisitCastExpr(const CastExpr *E); 13333 bool VisitBinaryOperator(const BinaryOperator *E); 13334 bool VisitUnaryOperator(const UnaryOperator *E); 13335 bool VisitInitListExpr(const InitListExpr *E); 13336 bool VisitCallExpr(const CallExpr *E); 13337 }; 13338 } // end anonymous namespace 13339 13340 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13341 EvalInfo &Info) { 13342 assert(E->isRValue() && E->getType()->isAnyComplexType()); 13343 return ComplexExprEvaluator(Info, Result).Visit(E); 13344 } 13345 13346 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13347 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13348 if (ElemTy->isRealFloatingType()) { 13349 Result.makeComplexFloat(); 13350 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13351 Result.FloatReal = Zero; 13352 Result.FloatImag = Zero; 13353 } else { 13354 Result.makeComplexInt(); 13355 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13356 Result.IntReal = Zero; 13357 Result.IntImag = Zero; 13358 } 13359 return true; 13360 } 13361 13362 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13363 const Expr* SubExpr = E->getSubExpr(); 13364 13365 if (SubExpr->getType()->isRealFloatingType()) { 13366 Result.makeComplexFloat(); 13367 APFloat &Imag = Result.FloatImag; 13368 if (!EvaluateFloat(SubExpr, Imag, Info)) 13369 return false; 13370 13371 Result.FloatReal = APFloat(Imag.getSemantics()); 13372 return true; 13373 } else { 13374 assert(SubExpr->getType()->isIntegerType() && 13375 "Unexpected imaginary literal."); 13376 13377 Result.makeComplexInt(); 13378 APSInt &Imag = Result.IntImag; 13379 if (!EvaluateInteger(SubExpr, Imag, Info)) 13380 return false; 13381 13382 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13383 return true; 13384 } 13385 } 13386 13387 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13388 13389 switch (E->getCastKind()) { 13390 case CK_BitCast: 13391 case CK_BaseToDerived: 13392 case CK_DerivedToBase: 13393 case CK_UncheckedDerivedToBase: 13394 case CK_Dynamic: 13395 case CK_ToUnion: 13396 case CK_ArrayToPointerDecay: 13397 case CK_FunctionToPointerDecay: 13398 case CK_NullToPointer: 13399 case CK_NullToMemberPointer: 13400 case CK_BaseToDerivedMemberPointer: 13401 case CK_DerivedToBaseMemberPointer: 13402 case CK_MemberPointerToBoolean: 13403 case CK_ReinterpretMemberPointer: 13404 case CK_ConstructorConversion: 13405 case CK_IntegralToPointer: 13406 case CK_PointerToIntegral: 13407 case CK_PointerToBoolean: 13408 case CK_ToVoid: 13409 case CK_VectorSplat: 13410 case CK_IntegralCast: 13411 case CK_BooleanToSignedIntegral: 13412 case CK_IntegralToBoolean: 13413 case CK_IntegralToFloating: 13414 case CK_FloatingToIntegral: 13415 case CK_FloatingToBoolean: 13416 case CK_FloatingCast: 13417 case CK_CPointerToObjCPointerCast: 13418 case CK_BlockPointerToObjCPointerCast: 13419 case CK_AnyPointerToBlockPointerCast: 13420 case CK_ObjCObjectLValueCast: 13421 case CK_FloatingComplexToReal: 13422 case CK_FloatingComplexToBoolean: 13423 case CK_IntegralComplexToReal: 13424 case CK_IntegralComplexToBoolean: 13425 case CK_ARCProduceObject: 13426 case CK_ARCConsumeObject: 13427 case CK_ARCReclaimReturnedObject: 13428 case CK_ARCExtendBlockObject: 13429 case CK_CopyAndAutoreleaseBlockObject: 13430 case CK_BuiltinFnToFnPtr: 13431 case CK_ZeroToOCLOpaqueType: 13432 case CK_NonAtomicToAtomic: 13433 case CK_AddressSpaceConversion: 13434 case CK_IntToOCLSampler: 13435 case CK_FixedPointCast: 13436 case CK_FixedPointToBoolean: 13437 case CK_FixedPointToIntegral: 13438 case CK_IntegralToFixedPoint: 13439 llvm_unreachable("invalid cast kind for complex value"); 13440 13441 case CK_LValueToRValue: 13442 case CK_AtomicToNonAtomic: 13443 case CK_NoOp: 13444 case CK_LValueToRValueBitCast: 13445 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13446 13447 case CK_Dependent: 13448 case CK_LValueBitCast: 13449 case CK_UserDefinedConversion: 13450 return Error(E); 13451 13452 case CK_FloatingRealToComplex: { 13453 APFloat &Real = Result.FloatReal; 13454 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13455 return false; 13456 13457 Result.makeComplexFloat(); 13458 Result.FloatImag = APFloat(Real.getSemantics()); 13459 return true; 13460 } 13461 13462 case CK_FloatingComplexCast: { 13463 if (!Visit(E->getSubExpr())) 13464 return false; 13465 13466 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13467 QualType From 13468 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13469 13470 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13471 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13472 } 13473 13474 case CK_FloatingComplexToIntegralComplex: { 13475 if (!Visit(E->getSubExpr())) 13476 return false; 13477 13478 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13479 QualType From 13480 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13481 Result.makeComplexInt(); 13482 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13483 To, Result.IntReal) && 13484 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13485 To, Result.IntImag); 13486 } 13487 13488 case CK_IntegralRealToComplex: { 13489 APSInt &Real = Result.IntReal; 13490 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13491 return false; 13492 13493 Result.makeComplexInt(); 13494 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13495 return true; 13496 } 13497 13498 case CK_IntegralComplexCast: { 13499 if (!Visit(E->getSubExpr())) 13500 return false; 13501 13502 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13503 QualType From 13504 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13505 13506 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 13507 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 13508 return true; 13509 } 13510 13511 case CK_IntegralComplexToFloatingComplex: { 13512 if (!Visit(E->getSubExpr())) 13513 return false; 13514 13515 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13516 QualType From 13517 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13518 Result.makeComplexFloat(); 13519 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 13520 To, Result.FloatReal) && 13521 HandleIntToFloatCast(Info, E, From, Result.IntImag, 13522 To, Result.FloatImag); 13523 } 13524 } 13525 13526 llvm_unreachable("unknown cast resulting in complex value"); 13527 } 13528 13529 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13530 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13531 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13532 13533 // Track whether the LHS or RHS is real at the type system level. When this is 13534 // the case we can simplify our evaluation strategy. 13535 bool LHSReal = false, RHSReal = false; 13536 13537 bool LHSOK; 13538 if (E->getLHS()->getType()->isRealFloatingType()) { 13539 LHSReal = true; 13540 APFloat &Real = Result.FloatReal; 13541 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 13542 if (LHSOK) { 13543 Result.makeComplexFloat(); 13544 Result.FloatImag = APFloat(Real.getSemantics()); 13545 } 13546 } else { 13547 LHSOK = Visit(E->getLHS()); 13548 } 13549 if (!LHSOK && !Info.noteFailure()) 13550 return false; 13551 13552 ComplexValue RHS; 13553 if (E->getRHS()->getType()->isRealFloatingType()) { 13554 RHSReal = true; 13555 APFloat &Real = RHS.FloatReal; 13556 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 13557 return false; 13558 RHS.makeComplexFloat(); 13559 RHS.FloatImag = APFloat(Real.getSemantics()); 13560 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 13561 return false; 13562 13563 assert(!(LHSReal && RHSReal) && 13564 "Cannot have both operands of a complex operation be real."); 13565 switch (E->getOpcode()) { 13566 default: return Error(E); 13567 case BO_Add: 13568 if (Result.isComplexFloat()) { 13569 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 13570 APFloat::rmNearestTiesToEven); 13571 if (LHSReal) 13572 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13573 else if (!RHSReal) 13574 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 13575 APFloat::rmNearestTiesToEven); 13576 } else { 13577 Result.getComplexIntReal() += RHS.getComplexIntReal(); 13578 Result.getComplexIntImag() += RHS.getComplexIntImag(); 13579 } 13580 break; 13581 case BO_Sub: 13582 if (Result.isComplexFloat()) { 13583 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 13584 APFloat::rmNearestTiesToEven); 13585 if (LHSReal) { 13586 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13587 Result.getComplexFloatImag().changeSign(); 13588 } else if (!RHSReal) { 13589 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 13590 APFloat::rmNearestTiesToEven); 13591 } 13592 } else { 13593 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 13594 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 13595 } 13596 break; 13597 case BO_Mul: 13598 if (Result.isComplexFloat()) { 13599 // This is an implementation of complex multiplication according to the 13600 // constraints laid out in C11 Annex G. The implementation uses the 13601 // following naming scheme: 13602 // (a + ib) * (c + id) 13603 ComplexValue LHS = Result; 13604 APFloat &A = LHS.getComplexFloatReal(); 13605 APFloat &B = LHS.getComplexFloatImag(); 13606 APFloat &C = RHS.getComplexFloatReal(); 13607 APFloat &D = RHS.getComplexFloatImag(); 13608 APFloat &ResR = Result.getComplexFloatReal(); 13609 APFloat &ResI = Result.getComplexFloatImag(); 13610 if (LHSReal) { 13611 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 13612 ResR = A * C; 13613 ResI = A * D; 13614 } else if (RHSReal) { 13615 ResR = C * A; 13616 ResI = C * B; 13617 } else { 13618 // In the fully general case, we need to handle NaNs and infinities 13619 // robustly. 13620 APFloat AC = A * C; 13621 APFloat BD = B * D; 13622 APFloat AD = A * D; 13623 APFloat BC = B * C; 13624 ResR = AC - BD; 13625 ResI = AD + BC; 13626 if (ResR.isNaN() && ResI.isNaN()) { 13627 bool Recalc = false; 13628 if (A.isInfinity() || B.isInfinity()) { 13629 A = APFloat::copySign( 13630 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13631 B = APFloat::copySign( 13632 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13633 if (C.isNaN()) 13634 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13635 if (D.isNaN()) 13636 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13637 Recalc = true; 13638 } 13639 if (C.isInfinity() || D.isInfinity()) { 13640 C = APFloat::copySign( 13641 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13642 D = APFloat::copySign( 13643 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13644 if (A.isNaN()) 13645 A = APFloat::copySign(APFloat(A.getSemantics()), A); 13646 if (B.isNaN()) 13647 B = APFloat::copySign(APFloat(B.getSemantics()), B); 13648 Recalc = true; 13649 } 13650 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 13651 AD.isInfinity() || BC.isInfinity())) { 13652 if (A.isNaN()) 13653 A = APFloat::copySign(APFloat(A.getSemantics()), A); 13654 if (B.isNaN()) 13655 B = APFloat::copySign(APFloat(B.getSemantics()), B); 13656 if (C.isNaN()) 13657 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13658 if (D.isNaN()) 13659 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13660 Recalc = true; 13661 } 13662 if (Recalc) { 13663 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 13664 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 13665 } 13666 } 13667 } 13668 } else { 13669 ComplexValue LHS = Result; 13670 Result.getComplexIntReal() = 13671 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 13672 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 13673 Result.getComplexIntImag() = 13674 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 13675 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 13676 } 13677 break; 13678 case BO_Div: 13679 if (Result.isComplexFloat()) { 13680 // This is an implementation of complex division 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 (RHSReal) { 13692 ResR = A / C; 13693 ResI = B / C; 13694 } else { 13695 if (LHSReal) { 13696 // No real optimizations we can do here, stub out with zero. 13697 B = APFloat::getZero(A.getSemantics()); 13698 } 13699 int DenomLogB = 0; 13700 APFloat MaxCD = maxnum(abs(C), abs(D)); 13701 if (MaxCD.isFinite()) { 13702 DenomLogB = ilogb(MaxCD); 13703 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 13704 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 13705 } 13706 APFloat Denom = C * C + D * D; 13707 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 13708 APFloat::rmNearestTiesToEven); 13709 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 13710 APFloat::rmNearestTiesToEven); 13711 if (ResR.isNaN() && ResI.isNaN()) { 13712 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 13713 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 13714 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 13715 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 13716 D.isFinite()) { 13717 A = APFloat::copySign( 13718 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13719 B = APFloat::copySign( 13720 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13721 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 13722 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 13723 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 13724 C = APFloat::copySign( 13725 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13726 D = APFloat::copySign( 13727 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13728 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 13729 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 13730 } 13731 } 13732 } 13733 } else { 13734 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 13735 return Error(E, diag::note_expr_divide_by_zero); 13736 13737 ComplexValue LHS = Result; 13738 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 13739 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 13740 Result.getComplexIntReal() = 13741 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 13742 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 13743 Result.getComplexIntImag() = 13744 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 13745 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 13746 } 13747 break; 13748 } 13749 13750 return true; 13751 } 13752 13753 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13754 // Get the operand value into 'Result'. 13755 if (!Visit(E->getSubExpr())) 13756 return false; 13757 13758 switch (E->getOpcode()) { 13759 default: 13760 return Error(E); 13761 case UO_Extension: 13762 return true; 13763 case UO_Plus: 13764 // The result is always just the subexpr. 13765 return true; 13766 case UO_Minus: 13767 if (Result.isComplexFloat()) { 13768 Result.getComplexFloatReal().changeSign(); 13769 Result.getComplexFloatImag().changeSign(); 13770 } 13771 else { 13772 Result.getComplexIntReal() = -Result.getComplexIntReal(); 13773 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13774 } 13775 return true; 13776 case UO_Not: 13777 if (Result.isComplexFloat()) 13778 Result.getComplexFloatImag().changeSign(); 13779 else 13780 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13781 return true; 13782 } 13783 } 13784 13785 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 13786 if (E->getNumInits() == 2) { 13787 if (E->getType()->isComplexType()) { 13788 Result.makeComplexFloat(); 13789 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 13790 return false; 13791 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 13792 return false; 13793 } else { 13794 Result.makeComplexInt(); 13795 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 13796 return false; 13797 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 13798 return false; 13799 } 13800 return true; 13801 } 13802 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 13803 } 13804 13805 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 13806 switch (E->getBuiltinCallee()) { 13807 case Builtin::BI__builtin_complex: 13808 Result.makeComplexFloat(); 13809 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 13810 return false; 13811 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 13812 return false; 13813 return true; 13814 13815 default: 13816 break; 13817 } 13818 13819 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13820 } 13821 13822 //===----------------------------------------------------------------------===// 13823 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 13824 // implicit conversion. 13825 //===----------------------------------------------------------------------===// 13826 13827 namespace { 13828 class AtomicExprEvaluator : 13829 public ExprEvaluatorBase<AtomicExprEvaluator> { 13830 const LValue *This; 13831 APValue &Result; 13832 public: 13833 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 13834 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 13835 13836 bool Success(const APValue &V, const Expr *E) { 13837 Result = V; 13838 return true; 13839 } 13840 13841 bool ZeroInitialization(const Expr *E) { 13842 ImplicitValueInitExpr VIE( 13843 E->getType()->castAs<AtomicType>()->getValueType()); 13844 // For atomic-qualified class (and array) types in C++, initialize the 13845 // _Atomic-wrapped subobject directly, in-place. 13846 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 13847 : Evaluate(Result, Info, &VIE); 13848 } 13849 13850 bool VisitCastExpr(const CastExpr *E) { 13851 switch (E->getCastKind()) { 13852 default: 13853 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13854 case CK_NonAtomicToAtomic: 13855 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 13856 : Evaluate(Result, Info, E->getSubExpr()); 13857 } 13858 } 13859 }; 13860 } // end anonymous namespace 13861 13862 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 13863 EvalInfo &Info) { 13864 assert(E->isRValue() && E->getType()->isAtomicType()); 13865 return AtomicExprEvaluator(Info, This, Result).Visit(E); 13866 } 13867 13868 //===----------------------------------------------------------------------===// 13869 // Void expression evaluation, primarily for a cast to void on the LHS of a 13870 // comma operator 13871 //===----------------------------------------------------------------------===// 13872 13873 namespace { 13874 class VoidExprEvaluator 13875 : public ExprEvaluatorBase<VoidExprEvaluator> { 13876 public: 13877 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 13878 13879 bool Success(const APValue &V, const Expr *e) { return true; } 13880 13881 bool ZeroInitialization(const Expr *E) { return true; } 13882 13883 bool VisitCastExpr(const CastExpr *E) { 13884 switch (E->getCastKind()) { 13885 default: 13886 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13887 case CK_ToVoid: 13888 VisitIgnoredValue(E->getSubExpr()); 13889 return true; 13890 } 13891 } 13892 13893 bool VisitCallExpr(const CallExpr *E) { 13894 switch (E->getBuiltinCallee()) { 13895 case Builtin::BI__assume: 13896 case Builtin::BI__builtin_assume: 13897 // The argument is not evaluated! 13898 return true; 13899 13900 case Builtin::BI__builtin_operator_delete: 13901 return HandleOperatorDeleteCall(Info, E); 13902 13903 default: 13904 break; 13905 } 13906 13907 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13908 } 13909 13910 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 13911 }; 13912 } // end anonymous namespace 13913 13914 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 13915 // We cannot speculatively evaluate a delete expression. 13916 if (Info.SpeculativeEvaluationDepth) 13917 return false; 13918 13919 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 13920 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 13921 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 13922 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 13923 return false; 13924 } 13925 13926 const Expr *Arg = E->getArgument(); 13927 13928 LValue Pointer; 13929 if (!EvaluatePointer(Arg, Pointer, Info)) 13930 return false; 13931 if (Pointer.Designator.Invalid) 13932 return false; 13933 13934 // Deleting a null pointer has no effect. 13935 if (Pointer.isNullPointer()) { 13936 // This is the only case where we need to produce an extension warning: 13937 // the only other way we can succeed is if we find a dynamic allocation, 13938 // and we will have warned when we allocated it in that case. 13939 if (!Info.getLangOpts().CPlusPlus20) 13940 Info.CCEDiag(E, diag::note_constexpr_new); 13941 return true; 13942 } 13943 13944 Optional<DynAlloc *> Alloc = CheckDeleteKind( 13945 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 13946 if (!Alloc) 13947 return false; 13948 QualType AllocType = Pointer.Base.getDynamicAllocType(); 13949 13950 // For the non-array case, the designator must be empty if the static type 13951 // does not have a virtual destructor. 13952 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 13953 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 13954 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 13955 << Arg->getType()->getPointeeType() << AllocType; 13956 return false; 13957 } 13958 13959 // For a class type with a virtual destructor, the selected operator delete 13960 // is the one looked up when building the destructor. 13961 if (!E->isArrayForm() && !E->isGlobalDelete()) { 13962 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 13963 if (VirtualDelete && 13964 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 13965 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 13966 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 13967 return false; 13968 } 13969 } 13970 13971 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 13972 (*Alloc)->Value, AllocType)) 13973 return false; 13974 13975 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 13976 // The element was already erased. This means the destructor call also 13977 // deleted the object. 13978 // FIXME: This probably results in undefined behavior before we get this 13979 // far, and should be diagnosed elsewhere first. 13980 Info.FFDiag(E, diag::note_constexpr_double_delete); 13981 return false; 13982 } 13983 13984 return true; 13985 } 13986 13987 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 13988 assert(E->isRValue() && E->getType()->isVoidType()); 13989 return VoidExprEvaluator(Info).Visit(E); 13990 } 13991 13992 //===----------------------------------------------------------------------===// 13993 // Top level Expr::EvaluateAsRValue method. 13994 //===----------------------------------------------------------------------===// 13995 13996 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 13997 // In C, function designators are not lvalues, but we evaluate them as if they 13998 // are. 13999 QualType T = E->getType(); 14000 if (E->isGLValue() || T->isFunctionType()) { 14001 LValue LV; 14002 if (!EvaluateLValue(E, LV, Info)) 14003 return false; 14004 LV.moveInto(Result); 14005 } else if (T->isVectorType()) { 14006 if (!EvaluateVector(E, Result, Info)) 14007 return false; 14008 } else if (T->isIntegralOrEnumerationType()) { 14009 if (!IntExprEvaluator(Info, Result).Visit(E)) 14010 return false; 14011 } else if (T->hasPointerRepresentation()) { 14012 LValue LV; 14013 if (!EvaluatePointer(E, LV, Info)) 14014 return false; 14015 LV.moveInto(Result); 14016 } else if (T->isRealFloatingType()) { 14017 llvm::APFloat F(0.0); 14018 if (!EvaluateFloat(E, F, Info)) 14019 return false; 14020 Result = APValue(F); 14021 } else if (T->isAnyComplexType()) { 14022 ComplexValue C; 14023 if (!EvaluateComplex(E, C, Info)) 14024 return false; 14025 C.moveInto(Result); 14026 } else if (T->isFixedPointType()) { 14027 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14028 } else if (T->isMemberPointerType()) { 14029 MemberPtr P; 14030 if (!EvaluateMemberPointer(E, P, Info)) 14031 return false; 14032 P.moveInto(Result); 14033 return true; 14034 } else if (T->isArrayType()) { 14035 LValue LV; 14036 APValue &Value = 14037 Info.CurrentCall->createTemporary(E, T, false, LV); 14038 if (!EvaluateArray(E, LV, Value, Info)) 14039 return false; 14040 Result = Value; 14041 } else if (T->isRecordType()) { 14042 LValue LV; 14043 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV); 14044 if (!EvaluateRecord(E, LV, Value, Info)) 14045 return false; 14046 Result = Value; 14047 } else if (T->isVoidType()) { 14048 if (!Info.getLangOpts().CPlusPlus11) 14049 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14050 << E->getType(); 14051 if (!EvaluateVoid(E, Info)) 14052 return false; 14053 } else if (T->isAtomicType()) { 14054 QualType Unqual = T.getAtomicUnqualifiedType(); 14055 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14056 LValue LV; 14057 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV); 14058 if (!EvaluateAtomic(E, &LV, Value, Info)) 14059 return false; 14060 } else { 14061 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14062 return false; 14063 } 14064 } else if (Info.getLangOpts().CPlusPlus11) { 14065 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14066 return false; 14067 } else { 14068 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14069 return false; 14070 } 14071 14072 return true; 14073 } 14074 14075 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14076 /// cases, the in-place evaluation is essential, since later initializers for 14077 /// an object can indirectly refer to subobjects which were initialized earlier. 14078 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14079 const Expr *E, bool AllowNonLiteralTypes) { 14080 assert(!E->isValueDependent()); 14081 14082 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14083 return false; 14084 14085 if (E->isRValue()) { 14086 // Evaluate arrays and record types in-place, so that later initializers can 14087 // refer to earlier-initialized members of the object. 14088 QualType T = E->getType(); 14089 if (T->isArrayType()) 14090 return EvaluateArray(E, This, Result, Info); 14091 else if (T->isRecordType()) 14092 return EvaluateRecord(E, This, Result, Info); 14093 else if (T->isAtomicType()) { 14094 QualType Unqual = T.getAtomicUnqualifiedType(); 14095 if (Unqual->isArrayType() || Unqual->isRecordType()) 14096 return EvaluateAtomic(E, &This, Result, Info); 14097 } 14098 } 14099 14100 // For any other type, in-place evaluation is unimportant. 14101 return Evaluate(Result, Info, E); 14102 } 14103 14104 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14105 /// lvalue-to-rvalue cast if it is an lvalue. 14106 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14107 if (Info.EnableNewConstInterp) { 14108 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14109 return false; 14110 } else { 14111 if (E->getType().isNull()) 14112 return false; 14113 14114 if (!CheckLiteralType(Info, E)) 14115 return false; 14116 14117 if (!::Evaluate(Result, Info, E)) 14118 return false; 14119 14120 if (E->isGLValue()) { 14121 LValue LV; 14122 LV.setFrom(Info.Ctx, Result); 14123 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14124 return false; 14125 } 14126 } 14127 14128 // Check this core constant expression is a constant expression. 14129 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) && 14130 CheckMemoryLeaks(Info); 14131 } 14132 14133 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14134 const ASTContext &Ctx, bool &IsConst) { 14135 // Fast-path evaluations of integer literals, since we sometimes see files 14136 // containing vast quantities of these. 14137 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14138 Result.Val = APValue(APSInt(L->getValue(), 14139 L->getType()->isUnsignedIntegerType())); 14140 IsConst = true; 14141 return true; 14142 } 14143 14144 // This case should be rare, but we need to check it before we check on 14145 // the type below. 14146 if (Exp->getType().isNull()) { 14147 IsConst = false; 14148 return true; 14149 } 14150 14151 // FIXME: Evaluating values of large array and record types can cause 14152 // performance problems. Only do so in C++11 for now. 14153 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 14154 Exp->getType()->isRecordType()) && 14155 !Ctx.getLangOpts().CPlusPlus11) { 14156 IsConst = false; 14157 return true; 14158 } 14159 return false; 14160 } 14161 14162 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14163 Expr::SideEffectsKind SEK) { 14164 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14165 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14166 } 14167 14168 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14169 const ASTContext &Ctx, EvalInfo &Info) { 14170 bool IsConst; 14171 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14172 return IsConst; 14173 14174 return EvaluateAsRValue(Info, E, Result.Val); 14175 } 14176 14177 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14178 const ASTContext &Ctx, 14179 Expr::SideEffectsKind AllowSideEffects, 14180 EvalInfo &Info) { 14181 if (!E->getType()->isIntegralOrEnumerationType()) 14182 return false; 14183 14184 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14185 !ExprResult.Val.isInt() || 14186 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14187 return false; 14188 14189 return true; 14190 } 14191 14192 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14193 const ASTContext &Ctx, 14194 Expr::SideEffectsKind AllowSideEffects, 14195 EvalInfo &Info) { 14196 if (!E->getType()->isFixedPointType()) 14197 return false; 14198 14199 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14200 return false; 14201 14202 if (!ExprResult.Val.isFixedPoint() || 14203 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14204 return false; 14205 14206 return true; 14207 } 14208 14209 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14210 /// any crazy technique (that has nothing to do with language standards) that 14211 /// we want to. If this function returns true, it returns the folded constant 14212 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14213 /// will be applied to the result. 14214 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14215 bool InConstantContext) const { 14216 assert(!isValueDependent() && 14217 "Expression evaluator can't be called on a dependent expression."); 14218 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14219 Info.InConstantContext = InConstantContext; 14220 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14221 } 14222 14223 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14224 bool InConstantContext) const { 14225 assert(!isValueDependent() && 14226 "Expression evaluator can't be called on a dependent expression."); 14227 EvalResult Scratch; 14228 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14229 HandleConversionToBool(Scratch.Val, Result); 14230 } 14231 14232 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14233 SideEffectsKind AllowSideEffects, 14234 bool InConstantContext) const { 14235 assert(!isValueDependent() && 14236 "Expression evaluator can't be called on a dependent expression."); 14237 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14238 Info.InConstantContext = InConstantContext; 14239 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14240 } 14241 14242 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14243 SideEffectsKind AllowSideEffects, 14244 bool InConstantContext) const { 14245 assert(!isValueDependent() && 14246 "Expression evaluator can't be called on a dependent expression."); 14247 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14248 Info.InConstantContext = InConstantContext; 14249 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14250 } 14251 14252 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14253 SideEffectsKind AllowSideEffects, 14254 bool InConstantContext) const { 14255 assert(!isValueDependent() && 14256 "Expression evaluator can't be called on a dependent expression."); 14257 14258 if (!getType()->isRealFloatingType()) 14259 return false; 14260 14261 EvalResult ExprResult; 14262 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14263 !ExprResult.Val.isFloat() || 14264 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14265 return false; 14266 14267 Result = ExprResult.Val.getFloat(); 14268 return true; 14269 } 14270 14271 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14272 bool InConstantContext) const { 14273 assert(!isValueDependent() && 14274 "Expression evaluator can't be called on a dependent expression."); 14275 14276 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14277 Info.InConstantContext = InConstantContext; 14278 LValue LV; 14279 CheckedTemporaries CheckedTemps; 14280 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14281 Result.HasSideEffects || 14282 !CheckLValueConstantExpression(Info, getExprLoc(), 14283 Ctx.getLValueReferenceType(getType()), LV, 14284 Expr::EvaluateForCodeGen, CheckedTemps)) 14285 return false; 14286 14287 LV.moveInto(Result.Val); 14288 return true; 14289 } 14290 14291 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 14292 const ASTContext &Ctx, bool InPlace) const { 14293 assert(!isValueDependent() && 14294 "Expression evaluator can't be called on a dependent expression."); 14295 14296 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14297 EvalInfo Info(Ctx, Result, EM); 14298 Info.InConstantContext = true; 14299 14300 if (InPlace) { 14301 Info.setEvaluatingDecl(this, Result.Val); 14302 LValue LVal; 14303 LVal.set(this); 14304 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || 14305 Result.HasSideEffects) 14306 return false; 14307 } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects) 14308 return false; 14309 14310 if (!Info.discardCleanups()) 14311 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14312 14313 return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14314 Result.Val, Usage) && 14315 CheckMemoryLeaks(Info); 14316 } 14317 14318 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14319 const VarDecl *VD, 14320 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14321 assert(!isValueDependent() && 14322 "Expression evaluator can't be called on a dependent expression."); 14323 14324 // FIXME: Evaluating initializers for large array and record types can cause 14325 // performance problems. Only do so in C++11 for now. 14326 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14327 !Ctx.getLangOpts().CPlusPlus11) 14328 return false; 14329 14330 Expr::EvalStatus EStatus; 14331 EStatus.Diag = &Notes; 14332 14333 EvalInfo Info(Ctx, EStatus, VD->isConstexpr() 14334 ? EvalInfo::EM_ConstantExpression 14335 : EvalInfo::EM_ConstantFold); 14336 Info.setEvaluatingDecl(VD, Value); 14337 Info.InConstantContext = true; 14338 14339 SourceLocation DeclLoc = VD->getLocation(); 14340 QualType DeclTy = VD->getType(); 14341 14342 if (Info.EnableNewConstInterp) { 14343 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14344 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14345 return false; 14346 } else { 14347 LValue LVal; 14348 LVal.set(VD); 14349 14350 if (!EvaluateInPlace(Value, Info, LVal, this, 14351 /*AllowNonLiteralTypes=*/true) || 14352 EStatus.HasSideEffects) 14353 return false; 14354 14355 // At this point, any lifetime-extended temporaries are completely 14356 // initialized. 14357 Info.performLifetimeExtension(); 14358 14359 if (!Info.discardCleanups()) 14360 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14361 } 14362 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) && 14363 CheckMemoryLeaks(Info); 14364 } 14365 14366 bool VarDecl::evaluateDestruction( 14367 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14368 Expr::EvalStatus EStatus; 14369 EStatus.Diag = &Notes; 14370 14371 // Make a copy of the value for the destructor to mutate, if we know it. 14372 // Otherwise, treat the value as default-initialized; if the destructor works 14373 // anyway, then the destruction is constant (and must be essentially empty). 14374 APValue DestroyedValue; 14375 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14376 DestroyedValue = *getEvaluatedValue(); 14377 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14378 return false; 14379 14380 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression); 14381 Info.setEvaluatingDecl(this, DestroyedValue, 14382 EvalInfo::EvaluatingDeclKind::Dtor); 14383 Info.InConstantContext = true; 14384 14385 SourceLocation DeclLoc = getLocation(); 14386 QualType DeclTy = getType(); 14387 14388 LValue LVal; 14389 LVal.set(this); 14390 14391 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) || 14392 EStatus.HasSideEffects) 14393 return false; 14394 14395 if (!Info.discardCleanups()) 14396 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14397 14398 ensureEvaluatedStmt()->HasConstantDestruction = true; 14399 return true; 14400 } 14401 14402 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14403 /// constant folded, but discard the result. 14404 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14405 assert(!isValueDependent() && 14406 "Expression evaluator can't be called on a dependent expression."); 14407 14408 EvalResult Result; 14409 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14410 !hasUnacceptableSideEffect(Result, SEK); 14411 } 14412 14413 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14414 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14415 assert(!isValueDependent() && 14416 "Expression evaluator can't be called on a dependent expression."); 14417 14418 EvalResult EVResult; 14419 EVResult.Diag = Diag; 14420 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14421 Info.InConstantContext = true; 14422 14423 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14424 (void)Result; 14425 assert(Result && "Could not evaluate expression"); 14426 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14427 14428 return EVResult.Val.getInt(); 14429 } 14430 14431 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14432 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14433 assert(!isValueDependent() && 14434 "Expression evaluator can't be called on a dependent expression."); 14435 14436 EvalResult EVResult; 14437 EVResult.Diag = Diag; 14438 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14439 Info.InConstantContext = true; 14440 Info.CheckingForUndefinedBehavior = true; 14441 14442 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 14443 (void)Result; 14444 assert(Result && "Could not evaluate expression"); 14445 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14446 14447 return EVResult.Val.getInt(); 14448 } 14449 14450 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 14451 assert(!isValueDependent() && 14452 "Expression evaluator can't be called on a dependent expression."); 14453 14454 bool IsConst; 14455 EvalResult EVResult; 14456 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 14457 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14458 Info.CheckingForUndefinedBehavior = true; 14459 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 14460 } 14461 } 14462 14463 bool Expr::EvalResult::isGlobalLValue() const { 14464 assert(Val.isLValue()); 14465 return IsGlobalLValue(Val.getLValueBase()); 14466 } 14467 14468 14469 /// isIntegerConstantExpr - this recursive routine will test if an expression is 14470 /// an integer constant expression. 14471 14472 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 14473 /// comma, etc 14474 14475 // CheckICE - This function does the fundamental ICE checking: the returned 14476 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 14477 // and a (possibly null) SourceLocation indicating the location of the problem. 14478 // 14479 // Note that to reduce code duplication, this helper does no evaluation 14480 // itself; the caller checks whether the expression is evaluatable, and 14481 // in the rare cases where CheckICE actually cares about the evaluated 14482 // value, it calls into Evaluate. 14483 14484 namespace { 14485 14486 enum ICEKind { 14487 /// This expression is an ICE. 14488 IK_ICE, 14489 /// This expression is not an ICE, but if it isn't evaluated, it's 14490 /// a legal subexpression for an ICE. This return value is used to handle 14491 /// the comma operator in C99 mode, and non-constant subexpressions. 14492 IK_ICEIfUnevaluated, 14493 /// This expression is not an ICE, and is not a legal subexpression for one. 14494 IK_NotICE 14495 }; 14496 14497 struct ICEDiag { 14498 ICEKind Kind; 14499 SourceLocation Loc; 14500 14501 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 14502 }; 14503 14504 } 14505 14506 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 14507 14508 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 14509 14510 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 14511 Expr::EvalResult EVResult; 14512 Expr::EvalStatus Status; 14513 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 14514 14515 Info.InConstantContext = true; 14516 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 14517 !EVResult.Val.isInt()) 14518 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14519 14520 return NoDiag(); 14521 } 14522 14523 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 14524 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 14525 if (!E->getType()->isIntegralOrEnumerationType()) 14526 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14527 14528 switch (E->getStmtClass()) { 14529 #define ABSTRACT_STMT(Node) 14530 #define STMT(Node, Base) case Expr::Node##Class: 14531 #define EXPR(Node, Base) 14532 #include "clang/AST/StmtNodes.inc" 14533 case Expr::PredefinedExprClass: 14534 case Expr::FloatingLiteralClass: 14535 case Expr::ImaginaryLiteralClass: 14536 case Expr::StringLiteralClass: 14537 case Expr::ArraySubscriptExprClass: 14538 case Expr::MatrixSubscriptExprClass: 14539 case Expr::OMPArraySectionExprClass: 14540 case Expr::OMPArrayShapingExprClass: 14541 case Expr::OMPIteratorExprClass: 14542 case Expr::MemberExprClass: 14543 case Expr::CompoundAssignOperatorClass: 14544 case Expr::CompoundLiteralExprClass: 14545 case Expr::ExtVectorElementExprClass: 14546 case Expr::DesignatedInitExprClass: 14547 case Expr::ArrayInitLoopExprClass: 14548 case Expr::ArrayInitIndexExprClass: 14549 case Expr::NoInitExprClass: 14550 case Expr::DesignatedInitUpdateExprClass: 14551 case Expr::ImplicitValueInitExprClass: 14552 case Expr::ParenListExprClass: 14553 case Expr::VAArgExprClass: 14554 case Expr::AddrLabelExprClass: 14555 case Expr::StmtExprClass: 14556 case Expr::CXXMemberCallExprClass: 14557 case Expr::CUDAKernelCallExprClass: 14558 case Expr::CXXAddrspaceCastExprClass: 14559 case Expr::CXXDynamicCastExprClass: 14560 case Expr::CXXTypeidExprClass: 14561 case Expr::CXXUuidofExprClass: 14562 case Expr::MSPropertyRefExprClass: 14563 case Expr::MSPropertySubscriptExprClass: 14564 case Expr::CXXNullPtrLiteralExprClass: 14565 case Expr::UserDefinedLiteralClass: 14566 case Expr::CXXThisExprClass: 14567 case Expr::CXXThrowExprClass: 14568 case Expr::CXXNewExprClass: 14569 case Expr::CXXDeleteExprClass: 14570 case Expr::CXXPseudoDestructorExprClass: 14571 case Expr::UnresolvedLookupExprClass: 14572 case Expr::TypoExprClass: 14573 case Expr::RecoveryExprClass: 14574 case Expr::DependentScopeDeclRefExprClass: 14575 case Expr::CXXConstructExprClass: 14576 case Expr::CXXInheritedCtorInitExprClass: 14577 case Expr::CXXStdInitializerListExprClass: 14578 case Expr::CXXBindTemporaryExprClass: 14579 case Expr::ExprWithCleanupsClass: 14580 case Expr::CXXTemporaryObjectExprClass: 14581 case Expr::CXXUnresolvedConstructExprClass: 14582 case Expr::CXXDependentScopeMemberExprClass: 14583 case Expr::UnresolvedMemberExprClass: 14584 case Expr::ObjCStringLiteralClass: 14585 case Expr::ObjCBoxedExprClass: 14586 case Expr::ObjCArrayLiteralClass: 14587 case Expr::ObjCDictionaryLiteralClass: 14588 case Expr::ObjCEncodeExprClass: 14589 case Expr::ObjCMessageExprClass: 14590 case Expr::ObjCSelectorExprClass: 14591 case Expr::ObjCProtocolExprClass: 14592 case Expr::ObjCIvarRefExprClass: 14593 case Expr::ObjCPropertyRefExprClass: 14594 case Expr::ObjCSubscriptRefExprClass: 14595 case Expr::ObjCIsaExprClass: 14596 case Expr::ObjCAvailabilityCheckExprClass: 14597 case Expr::ShuffleVectorExprClass: 14598 case Expr::ConvertVectorExprClass: 14599 case Expr::BlockExprClass: 14600 case Expr::NoStmtClass: 14601 case Expr::OpaqueValueExprClass: 14602 case Expr::PackExpansionExprClass: 14603 case Expr::SubstNonTypeTemplateParmPackExprClass: 14604 case Expr::FunctionParmPackExprClass: 14605 case Expr::AsTypeExprClass: 14606 case Expr::ObjCIndirectCopyRestoreExprClass: 14607 case Expr::MaterializeTemporaryExprClass: 14608 case Expr::PseudoObjectExprClass: 14609 case Expr::AtomicExprClass: 14610 case Expr::LambdaExprClass: 14611 case Expr::CXXFoldExprClass: 14612 case Expr::CoawaitExprClass: 14613 case Expr::DependentCoawaitExprClass: 14614 case Expr::CoyieldExprClass: 14615 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14616 14617 case Expr::InitListExprClass: { 14618 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 14619 // form "T x = { a };" is equivalent to "T x = a;". 14620 // Unless we're initializing a reference, T is a scalar as it is known to be 14621 // of integral or enumeration type. 14622 if (E->isRValue()) 14623 if (cast<InitListExpr>(E)->getNumInits() == 1) 14624 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 14625 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14626 } 14627 14628 case Expr::SizeOfPackExprClass: 14629 case Expr::GNUNullExprClass: 14630 case Expr::SourceLocExprClass: 14631 return NoDiag(); 14632 14633 case Expr::SubstNonTypeTemplateParmExprClass: 14634 return 14635 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 14636 14637 case Expr::ConstantExprClass: 14638 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 14639 14640 case Expr::ParenExprClass: 14641 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 14642 case Expr::GenericSelectionExprClass: 14643 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 14644 case Expr::IntegerLiteralClass: 14645 case Expr::FixedPointLiteralClass: 14646 case Expr::CharacterLiteralClass: 14647 case Expr::ObjCBoolLiteralExprClass: 14648 case Expr::CXXBoolLiteralExprClass: 14649 case Expr::CXXScalarValueInitExprClass: 14650 case Expr::TypeTraitExprClass: 14651 case Expr::ConceptSpecializationExprClass: 14652 case Expr::RequiresExprClass: 14653 case Expr::ArrayTypeTraitExprClass: 14654 case Expr::ExpressionTraitExprClass: 14655 case Expr::CXXNoexceptExprClass: 14656 return NoDiag(); 14657 case Expr::CallExprClass: 14658 case Expr::CXXOperatorCallExprClass: { 14659 // C99 6.6/3 allows function calls within unevaluated subexpressions of 14660 // constant expressions, but they can never be ICEs because an ICE cannot 14661 // contain an operand of (pointer to) function type. 14662 const CallExpr *CE = cast<CallExpr>(E); 14663 if (CE->getBuiltinCallee()) 14664 return CheckEvalInICE(E, Ctx); 14665 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14666 } 14667 case Expr::CXXRewrittenBinaryOperatorClass: 14668 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 14669 Ctx); 14670 case Expr::DeclRefExprClass: { 14671 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 14672 return NoDiag(); 14673 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 14674 if (Ctx.getLangOpts().CPlusPlus && 14675 D && IsConstNonVolatile(D->getType())) { 14676 // Parameter variables are never constants. Without this check, 14677 // getAnyInitializer() can find a default argument, which leads 14678 // to chaos. 14679 if (isa<ParmVarDecl>(D)) 14680 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14681 14682 // C++ 7.1.5.1p2 14683 // A variable of non-volatile const-qualified integral or enumeration 14684 // type initialized by an ICE can be used in ICEs. 14685 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 14686 if (!Dcl->getType()->isIntegralOrEnumerationType()) 14687 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14688 14689 const VarDecl *VD; 14690 // Look for a declaration of this variable that has an initializer, and 14691 // check whether it is an ICE. 14692 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 14693 return NoDiag(); 14694 else 14695 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14696 } 14697 } 14698 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14699 } 14700 case Expr::UnaryOperatorClass: { 14701 const UnaryOperator *Exp = cast<UnaryOperator>(E); 14702 switch (Exp->getOpcode()) { 14703 case UO_PostInc: 14704 case UO_PostDec: 14705 case UO_PreInc: 14706 case UO_PreDec: 14707 case UO_AddrOf: 14708 case UO_Deref: 14709 case UO_Coawait: 14710 // C99 6.6/3 allows increment and decrement within unevaluated 14711 // subexpressions of constant expressions, but they can never be ICEs 14712 // because an ICE cannot contain an lvalue operand. 14713 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14714 case UO_Extension: 14715 case UO_LNot: 14716 case UO_Plus: 14717 case UO_Minus: 14718 case UO_Not: 14719 case UO_Real: 14720 case UO_Imag: 14721 return CheckICE(Exp->getSubExpr(), Ctx); 14722 } 14723 llvm_unreachable("invalid unary operator class"); 14724 } 14725 case Expr::OffsetOfExprClass: { 14726 // Note that per C99, offsetof must be an ICE. And AFAIK, using 14727 // EvaluateAsRValue matches the proposed gcc behavior for cases like 14728 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 14729 // compliance: we should warn earlier for offsetof expressions with 14730 // array subscripts that aren't ICEs, and if the array subscripts 14731 // are ICEs, the value of the offsetof must be an integer constant. 14732 return CheckEvalInICE(E, Ctx); 14733 } 14734 case Expr::UnaryExprOrTypeTraitExprClass: { 14735 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 14736 if ((Exp->getKind() == UETT_SizeOf) && 14737 Exp->getTypeOfArgument()->isVariableArrayType()) 14738 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14739 return NoDiag(); 14740 } 14741 case Expr::BinaryOperatorClass: { 14742 const BinaryOperator *Exp = cast<BinaryOperator>(E); 14743 switch (Exp->getOpcode()) { 14744 case BO_PtrMemD: 14745 case BO_PtrMemI: 14746 case BO_Assign: 14747 case BO_MulAssign: 14748 case BO_DivAssign: 14749 case BO_RemAssign: 14750 case BO_AddAssign: 14751 case BO_SubAssign: 14752 case BO_ShlAssign: 14753 case BO_ShrAssign: 14754 case BO_AndAssign: 14755 case BO_XorAssign: 14756 case BO_OrAssign: 14757 // C99 6.6/3 allows assignments within unevaluated subexpressions of 14758 // constant expressions, but they can never be ICEs because an ICE cannot 14759 // contain an lvalue operand. 14760 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14761 14762 case BO_Mul: 14763 case BO_Div: 14764 case BO_Rem: 14765 case BO_Add: 14766 case BO_Sub: 14767 case BO_Shl: 14768 case BO_Shr: 14769 case BO_LT: 14770 case BO_GT: 14771 case BO_LE: 14772 case BO_GE: 14773 case BO_EQ: 14774 case BO_NE: 14775 case BO_And: 14776 case BO_Xor: 14777 case BO_Or: 14778 case BO_Comma: 14779 case BO_Cmp: { 14780 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14781 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14782 if (Exp->getOpcode() == BO_Div || 14783 Exp->getOpcode() == BO_Rem) { 14784 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 14785 // we don't evaluate one. 14786 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 14787 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 14788 if (REval == 0) 14789 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14790 if (REval.isSigned() && REval.isAllOnesValue()) { 14791 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 14792 if (LEval.isMinSignedValue()) 14793 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14794 } 14795 } 14796 } 14797 if (Exp->getOpcode() == BO_Comma) { 14798 if (Ctx.getLangOpts().C99) { 14799 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 14800 // if it isn't evaluated. 14801 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 14802 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14803 } else { 14804 // In both C89 and C++, commas in ICEs are illegal. 14805 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14806 } 14807 } 14808 return Worst(LHSResult, RHSResult); 14809 } 14810 case BO_LAnd: 14811 case BO_LOr: { 14812 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14813 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14814 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 14815 // Rare case where the RHS has a comma "side-effect"; we need 14816 // to actually check the condition to see whether the side 14817 // with the comma is evaluated. 14818 if ((Exp->getOpcode() == BO_LAnd) != 14819 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 14820 return RHSResult; 14821 return NoDiag(); 14822 } 14823 14824 return Worst(LHSResult, RHSResult); 14825 } 14826 } 14827 llvm_unreachable("invalid binary operator kind"); 14828 } 14829 case Expr::ImplicitCastExprClass: 14830 case Expr::CStyleCastExprClass: 14831 case Expr::CXXFunctionalCastExprClass: 14832 case Expr::CXXStaticCastExprClass: 14833 case Expr::CXXReinterpretCastExprClass: 14834 case Expr::CXXConstCastExprClass: 14835 case Expr::ObjCBridgedCastExprClass: { 14836 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 14837 if (isa<ExplicitCastExpr>(E)) { 14838 if (const FloatingLiteral *FL 14839 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 14840 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 14841 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 14842 APSInt IgnoredVal(DestWidth, !DestSigned); 14843 bool Ignored; 14844 // If the value does not fit in the destination type, the behavior is 14845 // undefined, so we are not required to treat it as a constant 14846 // expression. 14847 if (FL->getValue().convertToInteger(IgnoredVal, 14848 llvm::APFloat::rmTowardZero, 14849 &Ignored) & APFloat::opInvalidOp) 14850 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14851 return NoDiag(); 14852 } 14853 } 14854 switch (cast<CastExpr>(E)->getCastKind()) { 14855 case CK_LValueToRValue: 14856 case CK_AtomicToNonAtomic: 14857 case CK_NonAtomicToAtomic: 14858 case CK_NoOp: 14859 case CK_IntegralToBoolean: 14860 case CK_IntegralCast: 14861 return CheckICE(SubExpr, Ctx); 14862 default: 14863 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14864 } 14865 } 14866 case Expr::BinaryConditionalOperatorClass: { 14867 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 14868 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 14869 if (CommonResult.Kind == IK_NotICE) return CommonResult; 14870 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 14871 if (FalseResult.Kind == IK_NotICE) return FalseResult; 14872 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 14873 if (FalseResult.Kind == IK_ICEIfUnevaluated && 14874 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 14875 return FalseResult; 14876 } 14877 case Expr::ConditionalOperatorClass: { 14878 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 14879 // If the condition (ignoring parens) is a __builtin_constant_p call, 14880 // then only the true side is actually considered in an integer constant 14881 // expression, and it is fully evaluated. This is an important GNU 14882 // extension. See GCC PR38377 for discussion. 14883 if (const CallExpr *CallCE 14884 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 14885 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 14886 return CheckEvalInICE(E, Ctx); 14887 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 14888 if (CondResult.Kind == IK_NotICE) 14889 return CondResult; 14890 14891 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 14892 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 14893 14894 if (TrueResult.Kind == IK_NotICE) 14895 return TrueResult; 14896 if (FalseResult.Kind == IK_NotICE) 14897 return FalseResult; 14898 if (CondResult.Kind == IK_ICEIfUnevaluated) 14899 return CondResult; 14900 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 14901 return NoDiag(); 14902 // Rare case where the diagnostics depend on which side is evaluated 14903 // Note that if we get here, CondResult is 0, and at least one of 14904 // TrueResult and FalseResult is non-zero. 14905 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 14906 return FalseResult; 14907 return TrueResult; 14908 } 14909 case Expr::CXXDefaultArgExprClass: 14910 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 14911 case Expr::CXXDefaultInitExprClass: 14912 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 14913 case Expr::ChooseExprClass: { 14914 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 14915 } 14916 case Expr::BuiltinBitCastExprClass: { 14917 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 14918 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14919 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 14920 } 14921 } 14922 14923 llvm_unreachable("Invalid StmtClass!"); 14924 } 14925 14926 /// Evaluate an expression as a C++11 integral constant expression. 14927 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 14928 const Expr *E, 14929 llvm::APSInt *Value, 14930 SourceLocation *Loc) { 14931 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14932 if (Loc) *Loc = E->getExprLoc(); 14933 return false; 14934 } 14935 14936 APValue Result; 14937 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 14938 return false; 14939 14940 if (!Result.isInt()) { 14941 if (Loc) *Loc = E->getExprLoc(); 14942 return false; 14943 } 14944 14945 if (Value) *Value = Result.getInt(); 14946 return true; 14947 } 14948 14949 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 14950 SourceLocation *Loc) const { 14951 assert(!isValueDependent() && 14952 "Expression evaluator can't be called on a dependent expression."); 14953 14954 if (Ctx.getLangOpts().CPlusPlus11) 14955 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 14956 14957 ICEDiag D = CheckICE(this, Ctx); 14958 if (D.Kind != IK_ICE) { 14959 if (Loc) *Loc = D.Loc; 14960 return false; 14961 } 14962 return true; 14963 } 14964 14965 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 14966 SourceLocation *Loc, 14967 bool isEvaluated) const { 14968 assert(!isValueDependent() && 14969 "Expression evaluator can't be called on a dependent expression."); 14970 14971 APSInt Value; 14972 14973 if (Ctx.getLangOpts().CPlusPlus11) { 14974 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 14975 return Value; 14976 return None; 14977 } 14978 14979 if (!isIntegerConstantExpr(Ctx, Loc)) 14980 return None; 14981 14982 // The only possible side-effects here are due to UB discovered in the 14983 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 14984 // required to treat the expression as an ICE, so we produce the folded 14985 // value. 14986 EvalResult ExprResult; 14987 Expr::EvalStatus Status; 14988 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 14989 Info.InConstantContext = true; 14990 14991 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 14992 llvm_unreachable("ICE cannot be evaluated!"); 14993 14994 return ExprResult.Val.getInt(); 14995 } 14996 14997 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 14998 assert(!isValueDependent() && 14999 "Expression evaluator can't be called on a dependent expression."); 15000 15001 return CheckICE(this, Ctx).Kind == IK_ICE; 15002 } 15003 15004 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15005 SourceLocation *Loc) const { 15006 assert(!isValueDependent() && 15007 "Expression evaluator can't be called on a dependent expression."); 15008 15009 // We support this checking in C++98 mode in order to diagnose compatibility 15010 // issues. 15011 assert(Ctx.getLangOpts().CPlusPlus); 15012 15013 // Build evaluation settings. 15014 Expr::EvalStatus Status; 15015 SmallVector<PartialDiagnosticAt, 8> Diags; 15016 Status.Diag = &Diags; 15017 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15018 15019 APValue Scratch; 15020 bool IsConstExpr = 15021 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15022 // FIXME: We don't produce a diagnostic for this, but the callers that 15023 // call us on arbitrary full-expressions should generally not care. 15024 Info.discardCleanups() && !Status.HasSideEffects; 15025 15026 if (!Diags.empty()) { 15027 IsConstExpr = false; 15028 if (Loc) *Loc = Diags[0].first; 15029 } else if (!IsConstExpr) { 15030 // FIXME: This shouldn't happen. 15031 if (Loc) *Loc = getExprLoc(); 15032 } 15033 15034 return IsConstExpr; 15035 } 15036 15037 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15038 const FunctionDecl *Callee, 15039 ArrayRef<const Expr*> Args, 15040 const Expr *This) const { 15041 assert(!isValueDependent() && 15042 "Expression evaluator can't be called on a dependent expression."); 15043 15044 Expr::EvalStatus Status; 15045 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15046 Info.InConstantContext = true; 15047 15048 LValue ThisVal; 15049 const LValue *ThisPtr = nullptr; 15050 if (This) { 15051 #ifndef NDEBUG 15052 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15053 assert(MD && "Don't provide `this` for non-methods."); 15054 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15055 #endif 15056 if (!This->isValueDependent() && 15057 EvaluateObjectArgument(Info, This, ThisVal) && 15058 !Info.EvalStatus.HasSideEffects) 15059 ThisPtr = &ThisVal; 15060 15061 // Ignore any side-effects from a failed evaluation. This is safe because 15062 // they can't interfere with any other argument evaluation. 15063 Info.EvalStatus.HasSideEffects = false; 15064 } 15065 15066 ArgVector ArgValues(Args.size()); 15067 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15068 I != E; ++I) { 15069 if ((*I)->isValueDependent() || 15070 !Evaluate(ArgValues[I - Args.begin()], Info, *I) || 15071 Info.EvalStatus.HasSideEffects) 15072 // If evaluation fails, throw away the argument entirely. 15073 ArgValues[I - Args.begin()] = APValue(); 15074 15075 // Ignore any side-effects from a failed evaluation. This is safe because 15076 // they can't interfere with any other argument evaluation. 15077 Info.EvalStatus.HasSideEffects = false; 15078 } 15079 15080 // Parameter cleanups happen in the caller and are not part of this 15081 // evaluation. 15082 Info.discardCleanups(); 15083 Info.EvalStatus.HasSideEffects = false; 15084 15085 // Build fake call to Callee. 15086 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 15087 ArgValues.data()); 15088 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15089 FullExpressionRAII Scope(Info); 15090 return Evaluate(Value, Info, this) && Scope.destroy() && 15091 !Info.EvalStatus.HasSideEffects; 15092 } 15093 15094 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15095 SmallVectorImpl< 15096 PartialDiagnosticAt> &Diags) { 15097 // FIXME: It would be useful to check constexpr function templates, but at the 15098 // moment the constant expression evaluator cannot cope with the non-rigorous 15099 // ASTs which we build for dependent expressions. 15100 if (FD->isDependentContext()) 15101 return true; 15102 15103 // Bail out if a constexpr constructor has an initializer that contains an 15104 // error. We deliberately don't produce a diagnostic, as we have produced a 15105 // relevant diagnostic when parsing the error initializer. 15106 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 15107 for (const auto *InitExpr : Ctor->inits()) { 15108 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 15109 return false; 15110 } 15111 } 15112 Expr::EvalStatus Status; 15113 Status.Diag = &Diags; 15114 15115 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15116 Info.InConstantContext = true; 15117 Info.CheckingPotentialConstantExpression = true; 15118 15119 // The constexpr VM attempts to compile all methods to bytecode here. 15120 if (Info.EnableNewConstInterp) { 15121 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15122 return Diags.empty(); 15123 } 15124 15125 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15126 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15127 15128 // Fabricate an arbitrary expression on the stack and pretend that it 15129 // is a temporary being used as the 'this' pointer. 15130 LValue This; 15131 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15132 This.set({&VIE, Info.CurrentCall->Index}); 15133 15134 ArrayRef<const Expr*> Args; 15135 15136 APValue Scratch; 15137 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15138 // Evaluate the call as a constant initializer, to allow the construction 15139 // of objects of non-literal types. 15140 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15141 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15142 } else { 15143 SourceLocation Loc = FD->getLocation(); 15144 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15145 Args, FD->getBody(), Info, Scratch, nullptr); 15146 } 15147 15148 return Diags.empty(); 15149 } 15150 15151 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15152 const FunctionDecl *FD, 15153 SmallVectorImpl< 15154 PartialDiagnosticAt> &Diags) { 15155 assert(!E->isValueDependent() && 15156 "Expression evaluator can't be called on a dependent expression."); 15157 15158 Expr::EvalStatus Status; 15159 Status.Diag = &Diags; 15160 15161 EvalInfo Info(FD->getASTContext(), Status, 15162 EvalInfo::EM_ConstantExpressionUnevaluated); 15163 Info.InConstantContext = true; 15164 Info.CheckingPotentialConstantExpression = true; 15165 15166 // Fabricate a call stack frame to give the arguments a plausible cover story. 15167 ArrayRef<const Expr*> Args; 15168 ArgVector ArgValues(0); 15169 bool Success = EvaluateArgs(Args, ArgValues, Info, FD); 15170 (void)Success; 15171 assert(Success && 15172 "Failed to set up arguments for potential constant evaluation"); 15173 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 15174 15175 APValue ResultScratch; 15176 Evaluate(ResultScratch, Info, E); 15177 return Diags.empty(); 15178 } 15179 15180 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15181 unsigned Type) const { 15182 if (!getType()->isPointerType()) 15183 return false; 15184 15185 Expr::EvalStatus Status; 15186 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15187 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15188 } 15189