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 CheckedTemporaries CheckedTemps; 2303 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2304 Info, DiagLoc, Type, Value, Usage, 2305 SourceLocation(), CheckedTemps); 2306 } 2307 2308 /// Check that this evaluated value is fully-initialized and can be loaded by 2309 /// an lvalue-to-rvalue conversion. 2310 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2311 QualType Type, const APValue &Value) { 2312 CheckedTemporaries CheckedTemps; 2313 return CheckEvaluationResult( 2314 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2315 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps); 2316 } 2317 2318 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2319 /// "the allocated storage is deallocated within the evaluation". 2320 static bool CheckMemoryLeaks(EvalInfo &Info) { 2321 if (!Info.HeapAllocs.empty()) { 2322 // We can still fold to a constant despite a compile-time memory leak, 2323 // so long as the heap allocation isn't referenced in the result (we check 2324 // that in CheckConstantExpression). 2325 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2326 diag::note_constexpr_memory_leak) 2327 << unsigned(Info.HeapAllocs.size() - 1); 2328 } 2329 return true; 2330 } 2331 2332 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2333 // A null base expression indicates a null pointer. These are always 2334 // evaluatable, and they are false unless the offset is zero. 2335 if (!Value.getLValueBase()) { 2336 Result = !Value.getLValueOffset().isZero(); 2337 return true; 2338 } 2339 2340 // We have a non-null base. These are generally known to be true, but if it's 2341 // a weak declaration it can be null at runtime. 2342 Result = true; 2343 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2344 return !Decl || !Decl->isWeak(); 2345 } 2346 2347 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2348 switch (Val.getKind()) { 2349 case APValue::None: 2350 case APValue::Indeterminate: 2351 return false; 2352 case APValue::Int: 2353 Result = Val.getInt().getBoolValue(); 2354 return true; 2355 case APValue::FixedPoint: 2356 Result = Val.getFixedPoint().getBoolValue(); 2357 return true; 2358 case APValue::Float: 2359 Result = !Val.getFloat().isZero(); 2360 return true; 2361 case APValue::ComplexInt: 2362 Result = Val.getComplexIntReal().getBoolValue() || 2363 Val.getComplexIntImag().getBoolValue(); 2364 return true; 2365 case APValue::ComplexFloat: 2366 Result = !Val.getComplexFloatReal().isZero() || 2367 !Val.getComplexFloatImag().isZero(); 2368 return true; 2369 case APValue::LValue: 2370 return EvalPointerValueAsBool(Val, Result); 2371 case APValue::MemberPointer: 2372 Result = Val.getMemberPointerDecl(); 2373 return true; 2374 case APValue::Vector: 2375 case APValue::Array: 2376 case APValue::Struct: 2377 case APValue::Union: 2378 case APValue::AddrLabelDiff: 2379 return false; 2380 } 2381 2382 llvm_unreachable("unknown APValue kind"); 2383 } 2384 2385 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2386 EvalInfo &Info) { 2387 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2388 APValue Val; 2389 if (!Evaluate(Val, Info, E)) 2390 return false; 2391 return HandleConversionToBool(Val, Result); 2392 } 2393 2394 template<typename T> 2395 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2396 const T &SrcValue, QualType DestType) { 2397 Info.CCEDiag(E, diag::note_constexpr_overflow) 2398 << SrcValue << DestType; 2399 return Info.noteUndefinedBehavior(); 2400 } 2401 2402 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2403 QualType SrcType, const APFloat &Value, 2404 QualType DestType, APSInt &Result) { 2405 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2406 // Determine whether we are converting to unsigned or signed. 2407 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2408 2409 Result = APSInt(DestWidth, !DestSigned); 2410 bool ignored; 2411 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2412 & APFloat::opInvalidOp) 2413 return HandleOverflow(Info, E, Value, DestType); 2414 return true; 2415 } 2416 2417 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2418 QualType SrcType, QualType DestType, 2419 APFloat &Result) { 2420 APFloat Value = Result; 2421 bool ignored; 2422 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 2423 APFloat::rmNearestTiesToEven, &ignored); 2424 return true; 2425 } 2426 2427 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2428 QualType DestType, QualType SrcType, 2429 const APSInt &Value) { 2430 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2431 // Figure out if this is a truncate, extend or noop cast. 2432 // If the input is signed, do a sign extend, noop, or truncate. 2433 APSInt Result = Value.extOrTrunc(DestWidth); 2434 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2435 if (DestType->isBooleanType()) 2436 Result = Value.getBoolValue(); 2437 return Result; 2438 } 2439 2440 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2441 QualType SrcType, const APSInt &Value, 2442 QualType DestType, APFloat &Result) { 2443 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2444 Result.convertFromAPInt(Value, Value.isSigned(), 2445 APFloat::rmNearestTiesToEven); 2446 return true; 2447 } 2448 2449 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2450 APValue &Value, const FieldDecl *FD) { 2451 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2452 2453 if (!Value.isInt()) { 2454 // Trying to store a pointer-cast-to-integer into a bitfield. 2455 // FIXME: In this case, we should provide the diagnostic for casting 2456 // a pointer to an integer. 2457 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2458 Info.FFDiag(E); 2459 return false; 2460 } 2461 2462 APSInt &Int = Value.getInt(); 2463 unsigned OldBitWidth = Int.getBitWidth(); 2464 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2465 if (NewBitWidth < OldBitWidth) 2466 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2467 return true; 2468 } 2469 2470 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2471 llvm::APInt &Res) { 2472 APValue SVal; 2473 if (!Evaluate(SVal, Info, E)) 2474 return false; 2475 if (SVal.isInt()) { 2476 Res = SVal.getInt(); 2477 return true; 2478 } 2479 if (SVal.isFloat()) { 2480 Res = SVal.getFloat().bitcastToAPInt(); 2481 return true; 2482 } 2483 if (SVal.isVector()) { 2484 QualType VecTy = E->getType(); 2485 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2486 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2487 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2488 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2489 Res = llvm::APInt::getNullValue(VecSize); 2490 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2491 APValue &Elt = SVal.getVectorElt(i); 2492 llvm::APInt EltAsInt; 2493 if (Elt.isInt()) { 2494 EltAsInt = Elt.getInt(); 2495 } else if (Elt.isFloat()) { 2496 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2497 } else { 2498 // Don't try to handle vectors of anything other than int or float 2499 // (not sure if it's possible to hit this case). 2500 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2501 return false; 2502 } 2503 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2504 if (BigEndian) 2505 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2506 else 2507 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2508 } 2509 return true; 2510 } 2511 // Give up if the input isn't an int, float, or vector. For example, we 2512 // reject "(v4i16)(intptr_t)&a". 2513 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2514 return false; 2515 } 2516 2517 /// Perform the given integer operation, which is known to need at most BitWidth 2518 /// bits, and check for overflow in the original type (if that type was not an 2519 /// unsigned type). 2520 template<typename Operation> 2521 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2522 const APSInt &LHS, const APSInt &RHS, 2523 unsigned BitWidth, Operation Op, 2524 APSInt &Result) { 2525 if (LHS.isUnsigned()) { 2526 Result = Op(LHS, RHS); 2527 return true; 2528 } 2529 2530 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2531 Result = Value.trunc(LHS.getBitWidth()); 2532 if (Result.extend(BitWidth) != Value) { 2533 if (Info.checkingForUndefinedBehavior()) 2534 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2535 diag::warn_integer_constant_overflow) 2536 << Result.toString(10) << E->getType(); 2537 else 2538 return HandleOverflow(Info, E, Value, E->getType()); 2539 } 2540 return true; 2541 } 2542 2543 /// Perform the given binary integer operation. 2544 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2545 BinaryOperatorKind Opcode, APSInt RHS, 2546 APSInt &Result) { 2547 switch (Opcode) { 2548 default: 2549 Info.FFDiag(E); 2550 return false; 2551 case BO_Mul: 2552 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2553 std::multiplies<APSInt>(), Result); 2554 case BO_Add: 2555 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2556 std::plus<APSInt>(), Result); 2557 case BO_Sub: 2558 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2559 std::minus<APSInt>(), Result); 2560 case BO_And: Result = LHS & RHS; return true; 2561 case BO_Xor: Result = LHS ^ RHS; return true; 2562 case BO_Or: Result = LHS | RHS; return true; 2563 case BO_Div: 2564 case BO_Rem: 2565 if (RHS == 0) { 2566 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2567 return false; 2568 } 2569 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2570 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2571 // this operation and gives the two's complement result. 2572 if (RHS.isNegative() && RHS.isAllOnesValue() && 2573 LHS.isSigned() && LHS.isMinSignedValue()) 2574 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2575 E->getType()); 2576 return true; 2577 case BO_Shl: { 2578 if (Info.getLangOpts().OpenCL) 2579 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2580 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2581 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2582 RHS.isUnsigned()); 2583 else if (RHS.isSigned() && RHS.isNegative()) { 2584 // During constant-folding, a negative shift is an opposite shift. Such 2585 // a shift is not a constant expression. 2586 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2587 RHS = -RHS; 2588 goto shift_right; 2589 } 2590 shift_left: 2591 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2592 // the shifted type. 2593 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2594 if (SA != RHS) { 2595 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2596 << RHS << E->getType() << LHS.getBitWidth(); 2597 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2598 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2599 // operand, and must not overflow the corresponding unsigned type. 2600 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2601 // E1 x 2^E2 module 2^N. 2602 if (LHS.isNegative()) 2603 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2604 else if (LHS.countLeadingZeros() < SA) 2605 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2606 } 2607 Result = LHS << SA; 2608 return true; 2609 } 2610 case BO_Shr: { 2611 if (Info.getLangOpts().OpenCL) 2612 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2613 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2614 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2615 RHS.isUnsigned()); 2616 else if (RHS.isSigned() && RHS.isNegative()) { 2617 // During constant-folding, a negative shift is an opposite shift. Such a 2618 // shift is not a constant expression. 2619 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2620 RHS = -RHS; 2621 goto shift_left; 2622 } 2623 shift_right: 2624 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2625 // shifted type. 2626 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2627 if (SA != RHS) 2628 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2629 << RHS << E->getType() << LHS.getBitWidth(); 2630 Result = LHS >> SA; 2631 return true; 2632 } 2633 2634 case BO_LT: Result = LHS < RHS; return true; 2635 case BO_GT: Result = LHS > RHS; return true; 2636 case BO_LE: Result = LHS <= RHS; return true; 2637 case BO_GE: Result = LHS >= RHS; return true; 2638 case BO_EQ: Result = LHS == RHS; return true; 2639 case BO_NE: Result = LHS != RHS; return true; 2640 case BO_Cmp: 2641 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2642 } 2643 } 2644 2645 /// Perform the given binary floating-point operation, in-place, on LHS. 2646 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2647 APFloat &LHS, BinaryOperatorKind Opcode, 2648 const APFloat &RHS) { 2649 switch (Opcode) { 2650 default: 2651 Info.FFDiag(E); 2652 return false; 2653 case BO_Mul: 2654 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2655 break; 2656 case BO_Add: 2657 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2658 break; 2659 case BO_Sub: 2660 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2661 break; 2662 case BO_Div: 2663 // [expr.mul]p4: 2664 // If the second operand of / or % is zero the behavior is undefined. 2665 if (RHS.isZero()) 2666 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2667 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2668 break; 2669 } 2670 2671 // [expr.pre]p4: 2672 // If during the evaluation of an expression, the result is not 2673 // mathematically defined [...], the behavior is undefined. 2674 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2675 if (LHS.isNaN()) { 2676 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2677 return Info.noteUndefinedBehavior(); 2678 } 2679 return true; 2680 } 2681 2682 static bool handleLogicalOpForVector(const APInt &LHSValue, 2683 BinaryOperatorKind Opcode, 2684 const APInt &RHSValue, APInt &Result) { 2685 bool LHS = (LHSValue != 0); 2686 bool RHS = (RHSValue != 0); 2687 2688 if (Opcode == BO_LAnd) 2689 Result = LHS && RHS; 2690 else 2691 Result = LHS || RHS; 2692 return true; 2693 } 2694 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2695 BinaryOperatorKind Opcode, 2696 const APFloat &RHSValue, APInt &Result) { 2697 bool LHS = !LHSValue.isZero(); 2698 bool RHS = !RHSValue.isZero(); 2699 2700 if (Opcode == BO_LAnd) 2701 Result = LHS && RHS; 2702 else 2703 Result = LHS || RHS; 2704 return true; 2705 } 2706 2707 static bool handleLogicalOpForVector(const APValue &LHSValue, 2708 BinaryOperatorKind Opcode, 2709 const APValue &RHSValue, APInt &Result) { 2710 // The result is always an int type, however operands match the first. 2711 if (LHSValue.getKind() == APValue::Int) 2712 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2713 RHSValue.getInt(), Result); 2714 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2715 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2716 RHSValue.getFloat(), Result); 2717 } 2718 2719 template <typename APTy> 2720 static bool 2721 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2722 const APTy &RHSValue, APInt &Result) { 2723 switch (Opcode) { 2724 default: 2725 llvm_unreachable("unsupported binary operator"); 2726 case BO_EQ: 2727 Result = (LHSValue == RHSValue); 2728 break; 2729 case BO_NE: 2730 Result = (LHSValue != RHSValue); 2731 break; 2732 case BO_LT: 2733 Result = (LHSValue < RHSValue); 2734 break; 2735 case BO_GT: 2736 Result = (LHSValue > RHSValue); 2737 break; 2738 case BO_LE: 2739 Result = (LHSValue <= RHSValue); 2740 break; 2741 case BO_GE: 2742 Result = (LHSValue >= RHSValue); 2743 break; 2744 } 2745 2746 return true; 2747 } 2748 2749 static bool handleCompareOpForVector(const APValue &LHSValue, 2750 BinaryOperatorKind Opcode, 2751 const APValue &RHSValue, APInt &Result) { 2752 // The result is always an int type, however operands match the first. 2753 if (LHSValue.getKind() == APValue::Int) 2754 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2755 RHSValue.getInt(), Result); 2756 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2757 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2758 RHSValue.getFloat(), Result); 2759 } 2760 2761 // Perform binary operations for vector types, in place on the LHS. 2762 static bool handleVectorVectorBinOp(EvalInfo &Info, const Expr *E, 2763 BinaryOperatorKind Opcode, 2764 APValue &LHSValue, 2765 const APValue &RHSValue) { 2766 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2767 "Operation not supported on vector types"); 2768 2769 const auto *VT = E->getType()->castAs<VectorType>(); 2770 unsigned NumElements = VT->getNumElements(); 2771 QualType EltTy = VT->getElementType(); 2772 2773 // In the cases (typically C as I've observed) where we aren't evaluating 2774 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2775 // just give up. 2776 if (!LHSValue.isVector()) { 2777 assert(LHSValue.isLValue() && 2778 "A vector result that isn't a vector OR uncalculated LValue"); 2779 Info.FFDiag(E); 2780 return false; 2781 } 2782 2783 assert(LHSValue.getVectorLength() == NumElements && 2784 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2785 2786 SmallVector<APValue, 4> ResultElements; 2787 2788 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2789 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2790 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2791 2792 if (EltTy->isIntegerType()) { 2793 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2794 EltTy->isUnsignedIntegerType()}; 2795 bool Success = true; 2796 2797 if (BinaryOperator::isLogicalOp(Opcode)) 2798 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2799 else if (BinaryOperator::isComparisonOp(Opcode)) 2800 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2801 else 2802 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2803 RHSElt.getInt(), EltResult); 2804 2805 if (!Success) { 2806 Info.FFDiag(E); 2807 return false; 2808 } 2809 ResultElements.emplace_back(EltResult); 2810 2811 } else if (EltTy->isFloatingType()) { 2812 assert(LHSElt.getKind() == APValue::Float && 2813 RHSElt.getKind() == APValue::Float && 2814 "Mismatched LHS/RHS/Result Type"); 2815 APFloat LHSFloat = LHSElt.getFloat(); 2816 2817 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 2818 RHSElt.getFloat())) { 2819 Info.FFDiag(E); 2820 return false; 2821 } 2822 2823 ResultElements.emplace_back(LHSFloat); 2824 } 2825 } 2826 2827 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 2828 return true; 2829 } 2830 2831 /// Cast an lvalue referring to a base subobject to a derived class, by 2832 /// truncating the lvalue's path to the given length. 2833 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2834 const RecordDecl *TruncatedType, 2835 unsigned TruncatedElements) { 2836 SubobjectDesignator &D = Result.Designator; 2837 2838 // Check we actually point to a derived class object. 2839 if (TruncatedElements == D.Entries.size()) 2840 return true; 2841 assert(TruncatedElements >= D.MostDerivedPathLength && 2842 "not casting to a derived class"); 2843 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2844 return false; 2845 2846 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2847 const RecordDecl *RD = TruncatedType; 2848 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2849 if (RD->isInvalidDecl()) return false; 2850 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2851 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2852 if (isVirtualBaseClass(D.Entries[I])) 2853 Result.Offset -= Layout.getVBaseClassOffset(Base); 2854 else 2855 Result.Offset -= Layout.getBaseClassOffset(Base); 2856 RD = Base; 2857 } 2858 D.Entries.resize(TruncatedElements); 2859 return true; 2860 } 2861 2862 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2863 const CXXRecordDecl *Derived, 2864 const CXXRecordDecl *Base, 2865 const ASTRecordLayout *RL = nullptr) { 2866 if (!RL) { 2867 if (Derived->isInvalidDecl()) return false; 2868 RL = &Info.Ctx.getASTRecordLayout(Derived); 2869 } 2870 2871 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2872 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2873 return true; 2874 } 2875 2876 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2877 const CXXRecordDecl *DerivedDecl, 2878 const CXXBaseSpecifier *Base) { 2879 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2880 2881 if (!Base->isVirtual()) 2882 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2883 2884 SubobjectDesignator &D = Obj.Designator; 2885 if (D.Invalid) 2886 return false; 2887 2888 // Extract most-derived object and corresponding type. 2889 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2890 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2891 return false; 2892 2893 // Find the virtual base class. 2894 if (DerivedDecl->isInvalidDecl()) return false; 2895 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2896 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2897 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2898 return true; 2899 } 2900 2901 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2902 QualType Type, LValue &Result) { 2903 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2904 PathE = E->path_end(); 2905 PathI != PathE; ++PathI) { 2906 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2907 *PathI)) 2908 return false; 2909 Type = (*PathI)->getType(); 2910 } 2911 return true; 2912 } 2913 2914 /// Cast an lvalue referring to a derived class to a known base subobject. 2915 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 2916 const CXXRecordDecl *DerivedRD, 2917 const CXXRecordDecl *BaseRD) { 2918 CXXBasePaths Paths(/*FindAmbiguities=*/false, 2919 /*RecordPaths=*/true, /*DetectVirtual=*/false); 2920 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 2921 llvm_unreachable("Class must be derived from the passed in base class!"); 2922 2923 for (CXXBasePathElement &Elem : Paths.front()) 2924 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 2925 return false; 2926 return true; 2927 } 2928 2929 /// Update LVal to refer to the given field, which must be a member of the type 2930 /// currently described by LVal. 2931 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2932 const FieldDecl *FD, 2933 const ASTRecordLayout *RL = nullptr) { 2934 if (!RL) { 2935 if (FD->getParent()->isInvalidDecl()) return false; 2936 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2937 } 2938 2939 unsigned I = FD->getFieldIndex(); 2940 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2941 LVal.addDecl(Info, E, FD); 2942 return true; 2943 } 2944 2945 /// Update LVal to refer to the given indirect field. 2946 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2947 LValue &LVal, 2948 const IndirectFieldDecl *IFD) { 2949 for (const auto *C : IFD->chain()) 2950 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2951 return false; 2952 return true; 2953 } 2954 2955 /// Get the size of the given type in char units. 2956 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2957 QualType Type, CharUnits &Size) { 2958 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2959 // extension. 2960 if (Type->isVoidType() || Type->isFunctionType()) { 2961 Size = CharUnits::One(); 2962 return true; 2963 } 2964 2965 if (Type->isDependentType()) { 2966 Info.FFDiag(Loc); 2967 return false; 2968 } 2969 2970 if (!Type->isConstantSizeType()) { 2971 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2972 // FIXME: Better diagnostic. 2973 Info.FFDiag(Loc); 2974 return false; 2975 } 2976 2977 Size = Info.Ctx.getTypeSizeInChars(Type); 2978 return true; 2979 } 2980 2981 /// Update a pointer value to model pointer arithmetic. 2982 /// \param Info - Information about the ongoing evaluation. 2983 /// \param E - The expression being evaluated, for diagnostic purposes. 2984 /// \param LVal - The pointer value to be updated. 2985 /// \param EltTy - The pointee type represented by LVal. 2986 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2987 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2988 LValue &LVal, QualType EltTy, 2989 APSInt Adjustment) { 2990 CharUnits SizeOfPointee; 2991 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2992 return false; 2993 2994 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2995 return true; 2996 } 2997 2998 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2999 LValue &LVal, QualType EltTy, 3000 int64_t Adjustment) { 3001 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3002 APSInt::get(Adjustment)); 3003 } 3004 3005 /// Update an lvalue to refer to a component of a complex number. 3006 /// \param Info - Information about the ongoing evaluation. 3007 /// \param LVal - The lvalue to be updated. 3008 /// \param EltTy - The complex number's component type. 3009 /// \param Imag - False for the real component, true for the imaginary. 3010 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3011 LValue &LVal, QualType EltTy, 3012 bool Imag) { 3013 if (Imag) { 3014 CharUnits SizeOfComponent; 3015 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3016 return false; 3017 LVal.Offset += SizeOfComponent; 3018 } 3019 LVal.addComplex(Info, E, EltTy, Imag); 3020 return true; 3021 } 3022 3023 /// Try to evaluate the initializer for a variable declaration. 3024 /// 3025 /// \param Info Information about the ongoing evaluation. 3026 /// \param E An expression to be used when printing diagnostics. 3027 /// \param VD The variable whose initializer should be obtained. 3028 /// \param Frame The frame in which the variable was created. Must be null 3029 /// if this variable is not local to the evaluation. 3030 /// \param Result Filled in with a pointer to the value of the variable. 3031 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3032 const VarDecl *VD, CallStackFrame *Frame, 3033 APValue *&Result, const LValue *LVal) { 3034 3035 // If this is a parameter to an active constexpr function call, perform 3036 // argument substitution. 3037 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 3038 // Assume arguments of a potential constant expression are unknown 3039 // constant expressions. 3040 if (Info.checkingPotentialConstantExpression()) 3041 return false; 3042 if (!Frame || !Frame->Arguments) { 3043 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) << VD; 3044 return false; 3045 } 3046 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 3047 return true; 3048 } 3049 3050 // If this is a local variable, dig out its value. 3051 if (Frame) { 3052 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 3053 : Frame->getCurrentTemporary(VD); 3054 if (!Result) { 3055 // Assume variables referenced within a lambda's call operator that were 3056 // not declared within the call operator are captures and during checking 3057 // of a potential constant expression, assume they are unknown constant 3058 // expressions. 3059 assert(isLambdaCallOperator(Frame->Callee) && 3060 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3061 "missing value for local variable"); 3062 if (Info.checkingPotentialConstantExpression()) 3063 return false; 3064 // FIXME: implement capture evaluation during constant expr evaluation. 3065 Info.FFDiag(E->getBeginLoc(), 3066 diag::note_unimplemented_constexpr_lambda_feature_ast) 3067 << "captures not currently allowed"; 3068 return false; 3069 } 3070 return true; 3071 } 3072 3073 // Dig out the initializer, and use the declaration which it's attached to. 3074 // FIXME: We should eventually check whether the variable has a reachable 3075 // initializing declaration. 3076 const Expr *Init = VD->getAnyInitializer(VD); 3077 if (!Init) { 3078 // Don't diagnose during potential constant expression checking; an 3079 // initializer might be added later. 3080 if (!Info.checkingPotentialConstantExpression()) { 3081 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3082 << VD; 3083 Info.Note(VD->getLocation(), diag::note_declared_at); 3084 } 3085 return false; 3086 } 3087 3088 if (Init->isValueDependent()) { 3089 // The DeclRefExpr is not value-dependent, but the variable it refers to 3090 // has a value-dependent initializer. This should only happen in 3091 // constant-folding cases, where the variable is not actually of a suitable 3092 // type for use in a constant expression (otherwise the DeclRefExpr would 3093 // have been value-dependent too), so diagnose that. 3094 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3095 if (!Info.checkingPotentialConstantExpression()) { 3096 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3097 ? diag::note_constexpr_ltor_non_constexpr 3098 : diag::note_constexpr_ltor_non_integral, 1) 3099 << VD << VD->getType(); 3100 Info.Note(VD->getLocation(), diag::note_declared_at); 3101 } 3102 return false; 3103 } 3104 3105 // If we're currently evaluating the initializer of this declaration, use that 3106 // in-flight value. 3107 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 3108 Result = Info.EvaluatingDeclValue; 3109 return true; 3110 } 3111 3112 // Check that we can fold the initializer. In C++, we will have already done 3113 // this in the cases where it matters for conformance. 3114 SmallVector<PartialDiagnosticAt, 8> Notes; 3115 if (!VD->evaluateValue(Notes)) { 3116 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 3117 Notes.size() + 1) << VD; 3118 Info.Note(VD->getLocation(), diag::note_declared_at); 3119 Info.addNotes(Notes); 3120 return false; 3121 } 3122 3123 // Check that the variable is actually usable in constant expressions. 3124 if (!VD->checkInitIsICE()) { 3125 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 3126 Notes.size() + 1) << VD; 3127 Info.Note(VD->getLocation(), diag::note_declared_at); 3128 Info.addNotes(Notes); 3129 } 3130 3131 // Never use the initializer of a weak variable, not even for constant 3132 // folding. We can't be sure that this is the definition that will be used. 3133 if (VD->isWeak()) { 3134 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3135 Info.Note(VD->getLocation(), diag::note_declared_at); 3136 return false; 3137 } 3138 3139 Result = VD->getEvaluatedValue(); 3140 return true; 3141 } 3142 3143 static bool IsConstNonVolatile(QualType T) { 3144 Qualifiers Quals = T.getQualifiers(); 3145 return Quals.hasConst() && !Quals.hasVolatile(); 3146 } 3147 3148 /// Get the base index of the given base class within an APValue representing 3149 /// the given derived class. 3150 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3151 const CXXRecordDecl *Base) { 3152 Base = Base->getCanonicalDecl(); 3153 unsigned Index = 0; 3154 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3155 E = Derived->bases_end(); I != E; ++I, ++Index) { 3156 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3157 return Index; 3158 } 3159 3160 llvm_unreachable("base class missing from derived class's bases list"); 3161 } 3162 3163 /// Extract the value of a character from a string literal. 3164 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3165 uint64_t Index) { 3166 assert(!isa<SourceLocExpr>(Lit) && 3167 "SourceLocExpr should have already been converted to a StringLiteral"); 3168 3169 // FIXME: Support MakeStringConstant 3170 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3171 std::string Str; 3172 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3173 assert(Index <= Str.size() && "Index too large"); 3174 return APSInt::getUnsigned(Str.c_str()[Index]); 3175 } 3176 3177 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3178 Lit = PE->getFunctionName(); 3179 const StringLiteral *S = cast<StringLiteral>(Lit); 3180 const ConstantArrayType *CAT = 3181 Info.Ctx.getAsConstantArrayType(S->getType()); 3182 assert(CAT && "string literal isn't an array"); 3183 QualType CharType = CAT->getElementType(); 3184 assert(CharType->isIntegerType() && "unexpected character type"); 3185 3186 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3187 CharType->isUnsignedIntegerType()); 3188 if (Index < S->getLength()) 3189 Value = S->getCodeUnit(Index); 3190 return Value; 3191 } 3192 3193 // Expand a string literal into an array of characters. 3194 // 3195 // FIXME: This is inefficient; we should probably introduce something similar 3196 // to the LLVM ConstantDataArray to make this cheaper. 3197 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3198 APValue &Result, 3199 QualType AllocType = QualType()) { 3200 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3201 AllocType.isNull() ? S->getType() : AllocType); 3202 assert(CAT && "string literal isn't an array"); 3203 QualType CharType = CAT->getElementType(); 3204 assert(CharType->isIntegerType() && "unexpected character type"); 3205 3206 unsigned Elts = CAT->getSize().getZExtValue(); 3207 Result = APValue(APValue::UninitArray(), 3208 std::min(S->getLength(), Elts), Elts); 3209 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3210 CharType->isUnsignedIntegerType()); 3211 if (Result.hasArrayFiller()) 3212 Result.getArrayFiller() = APValue(Value); 3213 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3214 Value = S->getCodeUnit(I); 3215 Result.getArrayInitializedElt(I) = APValue(Value); 3216 } 3217 } 3218 3219 // Expand an array so that it has more than Index filled elements. 3220 static void expandArray(APValue &Array, unsigned Index) { 3221 unsigned Size = Array.getArraySize(); 3222 assert(Index < Size); 3223 3224 // Always at least double the number of elements for which we store a value. 3225 unsigned OldElts = Array.getArrayInitializedElts(); 3226 unsigned NewElts = std::max(Index+1, OldElts * 2); 3227 NewElts = std::min(Size, std::max(NewElts, 8u)); 3228 3229 // Copy the data across. 3230 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3231 for (unsigned I = 0; I != OldElts; ++I) 3232 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3233 for (unsigned I = OldElts; I != NewElts; ++I) 3234 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3235 if (NewValue.hasArrayFiller()) 3236 NewValue.getArrayFiller() = Array.getArrayFiller(); 3237 Array.swap(NewValue); 3238 } 3239 3240 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3241 /// conversion. If it's of class type, we may assume that the copy operation 3242 /// is trivial. Note that this is never true for a union type with fields 3243 /// (because the copy always "reads" the active member) and always true for 3244 /// a non-class type. 3245 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3246 static bool isReadByLvalueToRvalueConversion(QualType T) { 3247 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3248 return !RD || isReadByLvalueToRvalueConversion(RD); 3249 } 3250 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3251 // FIXME: A trivial copy of a union copies the object representation, even if 3252 // the union is empty. 3253 if (RD->isUnion()) 3254 return !RD->field_empty(); 3255 if (RD->isEmpty()) 3256 return false; 3257 3258 for (auto *Field : RD->fields()) 3259 if (!Field->isUnnamedBitfield() && 3260 isReadByLvalueToRvalueConversion(Field->getType())) 3261 return true; 3262 3263 for (auto &BaseSpec : RD->bases()) 3264 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3265 return true; 3266 3267 return false; 3268 } 3269 3270 /// Diagnose an attempt to read from any unreadable field within the specified 3271 /// type, which might be a class type. 3272 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3273 QualType T) { 3274 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3275 if (!RD) 3276 return false; 3277 3278 if (!RD->hasMutableFields()) 3279 return false; 3280 3281 for (auto *Field : RD->fields()) { 3282 // If we're actually going to read this field in some way, then it can't 3283 // be mutable. If we're in a union, then assigning to a mutable field 3284 // (even an empty one) can change the active member, so that's not OK. 3285 // FIXME: Add core issue number for the union case. 3286 if (Field->isMutable() && 3287 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3288 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3289 Info.Note(Field->getLocation(), diag::note_declared_at); 3290 return true; 3291 } 3292 3293 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3294 return true; 3295 } 3296 3297 for (auto &BaseSpec : RD->bases()) 3298 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3299 return true; 3300 3301 // All mutable fields were empty, and thus not actually read. 3302 return false; 3303 } 3304 3305 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3306 APValue::LValueBase Base, 3307 bool MutableSubobject = false) { 3308 // A temporary we created. 3309 if (Base.getCallIndex()) 3310 return true; 3311 3312 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3313 if (!Evaluating) 3314 return false; 3315 3316 auto *BaseD = Base.dyn_cast<const ValueDecl*>(); 3317 3318 switch (Info.IsEvaluatingDecl) { 3319 case EvalInfo::EvaluatingDeclKind::None: 3320 return false; 3321 3322 case EvalInfo::EvaluatingDeclKind::Ctor: 3323 // The variable whose initializer we're evaluating. 3324 if (BaseD) 3325 return declaresSameEntity(Evaluating, BaseD); 3326 3327 // A temporary lifetime-extended by the variable whose initializer we're 3328 // evaluating. 3329 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3330 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3331 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating); 3332 return false; 3333 3334 case EvalInfo::EvaluatingDeclKind::Dtor: 3335 // C++2a [expr.const]p6: 3336 // [during constant destruction] the lifetime of a and its non-mutable 3337 // subobjects (but not its mutable subobjects) [are] considered to start 3338 // within e. 3339 // 3340 // FIXME: We can meaningfully extend this to cover non-const objects, but 3341 // we will need special handling: we should be able to access only 3342 // subobjects of such objects that are themselves declared const. 3343 if (!BaseD || 3344 !(BaseD->getType().isConstQualified() || 3345 BaseD->getType()->isReferenceType()) || 3346 MutableSubobject) 3347 return false; 3348 return declaresSameEntity(Evaluating, BaseD); 3349 } 3350 3351 llvm_unreachable("unknown evaluating decl kind"); 3352 } 3353 3354 namespace { 3355 /// A handle to a complete object (an object that is not a subobject of 3356 /// another object). 3357 struct CompleteObject { 3358 /// The identity of the object. 3359 APValue::LValueBase Base; 3360 /// The value of the complete object. 3361 APValue *Value; 3362 /// The type of the complete object. 3363 QualType Type; 3364 3365 CompleteObject() : Value(nullptr) {} 3366 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3367 : Base(Base), Value(Value), Type(Type) {} 3368 3369 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3370 // If this isn't a "real" access (eg, if it's just accessing the type 3371 // info), allow it. We assume the type doesn't change dynamically for 3372 // subobjects of constexpr objects (even though we'd hit UB here if it 3373 // did). FIXME: Is this right? 3374 if (!isAnyAccess(AK)) 3375 return true; 3376 3377 // In C++14 onwards, it is permitted to read a mutable member whose 3378 // lifetime began within the evaluation. 3379 // FIXME: Should we also allow this in C++11? 3380 if (!Info.getLangOpts().CPlusPlus14) 3381 return false; 3382 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3383 } 3384 3385 explicit operator bool() const { return !Type.isNull(); } 3386 }; 3387 } // end anonymous namespace 3388 3389 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3390 bool IsMutable = false) { 3391 // C++ [basic.type.qualifier]p1: 3392 // - A const object is an object of type const T or a non-mutable subobject 3393 // of a const object. 3394 if (ObjType.isConstQualified() && !IsMutable) 3395 SubobjType.addConst(); 3396 // - A volatile object is an object of type const T or a subobject of a 3397 // volatile object. 3398 if (ObjType.isVolatileQualified()) 3399 SubobjType.addVolatile(); 3400 return SubobjType; 3401 } 3402 3403 /// Find the designated sub-object of an rvalue. 3404 template<typename SubobjectHandler> 3405 typename SubobjectHandler::result_type 3406 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3407 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3408 if (Sub.Invalid) 3409 // A diagnostic will have already been produced. 3410 return handler.failed(); 3411 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3412 if (Info.getLangOpts().CPlusPlus11) 3413 Info.FFDiag(E, Sub.isOnePastTheEnd() 3414 ? diag::note_constexpr_access_past_end 3415 : diag::note_constexpr_access_unsized_array) 3416 << handler.AccessKind; 3417 else 3418 Info.FFDiag(E); 3419 return handler.failed(); 3420 } 3421 3422 APValue *O = Obj.Value; 3423 QualType ObjType = Obj.Type; 3424 const FieldDecl *LastField = nullptr; 3425 const FieldDecl *VolatileField = nullptr; 3426 3427 // Walk the designator's path to find the subobject. 3428 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3429 // Reading an indeterminate value is undefined, but assigning over one is OK. 3430 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3431 (O->isIndeterminate() && 3432 !isValidIndeterminateAccess(handler.AccessKind))) { 3433 if (!Info.checkingPotentialConstantExpression()) 3434 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3435 << handler.AccessKind << O->isIndeterminate(); 3436 return handler.failed(); 3437 } 3438 3439 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3440 // const and volatile semantics are not applied on an object under 3441 // {con,de}struction. 3442 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3443 ObjType->isRecordType() && 3444 Info.isEvaluatingCtorDtor( 3445 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3446 Sub.Entries.begin() + I)) != 3447 ConstructionPhase::None) { 3448 ObjType = Info.Ctx.getCanonicalType(ObjType); 3449 ObjType.removeLocalConst(); 3450 ObjType.removeLocalVolatile(); 3451 } 3452 3453 // If this is our last pass, check that the final object type is OK. 3454 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3455 // Accesses to volatile objects are prohibited. 3456 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3457 if (Info.getLangOpts().CPlusPlus) { 3458 int DiagKind; 3459 SourceLocation Loc; 3460 const NamedDecl *Decl = nullptr; 3461 if (VolatileField) { 3462 DiagKind = 2; 3463 Loc = VolatileField->getLocation(); 3464 Decl = VolatileField; 3465 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3466 DiagKind = 1; 3467 Loc = VD->getLocation(); 3468 Decl = VD; 3469 } else { 3470 DiagKind = 0; 3471 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3472 Loc = E->getExprLoc(); 3473 } 3474 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3475 << handler.AccessKind << DiagKind << Decl; 3476 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3477 } else { 3478 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3479 } 3480 return handler.failed(); 3481 } 3482 3483 // If we are reading an object of class type, there may still be more 3484 // things we need to check: if there are any mutable subobjects, we 3485 // cannot perform this read. (This only happens when performing a trivial 3486 // copy or assignment.) 3487 if (ObjType->isRecordType() && 3488 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3489 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3490 return handler.failed(); 3491 } 3492 3493 if (I == N) { 3494 if (!handler.found(*O, ObjType)) 3495 return false; 3496 3497 // If we modified a bit-field, truncate it to the right width. 3498 if (isModification(handler.AccessKind) && 3499 LastField && LastField->isBitField() && 3500 !truncateBitfieldValue(Info, E, *O, LastField)) 3501 return false; 3502 3503 return true; 3504 } 3505 3506 LastField = nullptr; 3507 if (ObjType->isArrayType()) { 3508 // Next subobject is an array element. 3509 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3510 assert(CAT && "vla in literal type?"); 3511 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3512 if (CAT->getSize().ule(Index)) { 3513 // Note, it should not be possible to form a pointer with a valid 3514 // designator which points more than one past the end of the array. 3515 if (Info.getLangOpts().CPlusPlus11) 3516 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3517 << handler.AccessKind; 3518 else 3519 Info.FFDiag(E); 3520 return handler.failed(); 3521 } 3522 3523 ObjType = CAT->getElementType(); 3524 3525 if (O->getArrayInitializedElts() > Index) 3526 O = &O->getArrayInitializedElt(Index); 3527 else if (!isRead(handler.AccessKind)) { 3528 expandArray(*O, Index); 3529 O = &O->getArrayInitializedElt(Index); 3530 } else 3531 O = &O->getArrayFiller(); 3532 } else if (ObjType->isAnyComplexType()) { 3533 // Next subobject is a complex number. 3534 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3535 if (Index > 1) { 3536 if (Info.getLangOpts().CPlusPlus11) 3537 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3538 << handler.AccessKind; 3539 else 3540 Info.FFDiag(E); 3541 return handler.failed(); 3542 } 3543 3544 ObjType = getSubobjectType( 3545 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3546 3547 assert(I == N - 1 && "extracting subobject of scalar?"); 3548 if (O->isComplexInt()) { 3549 return handler.found(Index ? O->getComplexIntImag() 3550 : O->getComplexIntReal(), ObjType); 3551 } else { 3552 assert(O->isComplexFloat()); 3553 return handler.found(Index ? O->getComplexFloatImag() 3554 : O->getComplexFloatReal(), ObjType); 3555 } 3556 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3557 if (Field->isMutable() && 3558 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3559 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3560 << handler.AccessKind << Field; 3561 Info.Note(Field->getLocation(), diag::note_declared_at); 3562 return handler.failed(); 3563 } 3564 3565 // Next subobject is a class, struct or union field. 3566 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3567 if (RD->isUnion()) { 3568 const FieldDecl *UnionField = O->getUnionField(); 3569 if (!UnionField || 3570 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3571 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3572 // Placement new onto an inactive union member makes it active. 3573 O->setUnion(Field, APValue()); 3574 } else { 3575 // FIXME: If O->getUnionValue() is absent, report that there's no 3576 // active union member rather than reporting the prior active union 3577 // member. We'll need to fix nullptr_t to not use APValue() as its 3578 // representation first. 3579 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3580 << handler.AccessKind << Field << !UnionField << UnionField; 3581 return handler.failed(); 3582 } 3583 } 3584 O = &O->getUnionValue(); 3585 } else 3586 O = &O->getStructField(Field->getFieldIndex()); 3587 3588 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3589 LastField = Field; 3590 if (Field->getType().isVolatileQualified()) 3591 VolatileField = Field; 3592 } else { 3593 // Next subobject is a base class. 3594 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3595 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3596 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3597 3598 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3599 } 3600 } 3601 } 3602 3603 namespace { 3604 struct ExtractSubobjectHandler { 3605 EvalInfo &Info; 3606 const Expr *E; 3607 APValue &Result; 3608 const AccessKinds AccessKind; 3609 3610 typedef bool result_type; 3611 bool failed() { return false; } 3612 bool found(APValue &Subobj, QualType SubobjType) { 3613 Result = Subobj; 3614 if (AccessKind == AK_ReadObjectRepresentation) 3615 return true; 3616 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3617 } 3618 bool found(APSInt &Value, QualType SubobjType) { 3619 Result = APValue(Value); 3620 return true; 3621 } 3622 bool found(APFloat &Value, QualType SubobjType) { 3623 Result = APValue(Value); 3624 return true; 3625 } 3626 }; 3627 } // end anonymous namespace 3628 3629 /// Extract the designated sub-object of an rvalue. 3630 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3631 const CompleteObject &Obj, 3632 const SubobjectDesignator &Sub, APValue &Result, 3633 AccessKinds AK = AK_Read) { 3634 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3635 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3636 return findSubobject(Info, E, Obj, Sub, Handler); 3637 } 3638 3639 namespace { 3640 struct ModifySubobjectHandler { 3641 EvalInfo &Info; 3642 APValue &NewVal; 3643 const Expr *E; 3644 3645 typedef bool result_type; 3646 static const AccessKinds AccessKind = AK_Assign; 3647 3648 bool checkConst(QualType QT) { 3649 // Assigning to a const object has undefined behavior. 3650 if (QT.isConstQualified()) { 3651 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3652 return false; 3653 } 3654 return true; 3655 } 3656 3657 bool failed() { return false; } 3658 bool found(APValue &Subobj, QualType SubobjType) { 3659 if (!checkConst(SubobjType)) 3660 return false; 3661 // We've been given ownership of NewVal, so just swap it in. 3662 Subobj.swap(NewVal); 3663 return true; 3664 } 3665 bool found(APSInt &Value, QualType SubobjType) { 3666 if (!checkConst(SubobjType)) 3667 return false; 3668 if (!NewVal.isInt()) { 3669 // Maybe trying to write a cast pointer value into a complex? 3670 Info.FFDiag(E); 3671 return false; 3672 } 3673 Value = NewVal.getInt(); 3674 return true; 3675 } 3676 bool found(APFloat &Value, QualType SubobjType) { 3677 if (!checkConst(SubobjType)) 3678 return false; 3679 Value = NewVal.getFloat(); 3680 return true; 3681 } 3682 }; 3683 } // end anonymous namespace 3684 3685 const AccessKinds ModifySubobjectHandler::AccessKind; 3686 3687 /// Update the designated sub-object of an rvalue to the given value. 3688 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3689 const CompleteObject &Obj, 3690 const SubobjectDesignator &Sub, 3691 APValue &NewVal) { 3692 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3693 return findSubobject(Info, E, Obj, Sub, Handler); 3694 } 3695 3696 /// Find the position where two subobject designators diverge, or equivalently 3697 /// the length of the common initial subsequence. 3698 static unsigned FindDesignatorMismatch(QualType ObjType, 3699 const SubobjectDesignator &A, 3700 const SubobjectDesignator &B, 3701 bool &WasArrayIndex) { 3702 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3703 for (/**/; I != N; ++I) { 3704 if (!ObjType.isNull() && 3705 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3706 // Next subobject is an array element. 3707 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3708 WasArrayIndex = true; 3709 return I; 3710 } 3711 if (ObjType->isAnyComplexType()) 3712 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3713 else 3714 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3715 } else { 3716 if (A.Entries[I].getAsBaseOrMember() != 3717 B.Entries[I].getAsBaseOrMember()) { 3718 WasArrayIndex = false; 3719 return I; 3720 } 3721 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3722 // Next subobject is a field. 3723 ObjType = FD->getType(); 3724 else 3725 // Next subobject is a base class. 3726 ObjType = QualType(); 3727 } 3728 } 3729 WasArrayIndex = false; 3730 return I; 3731 } 3732 3733 /// Determine whether the given subobject designators refer to elements of the 3734 /// same array object. 3735 static bool AreElementsOfSameArray(QualType ObjType, 3736 const SubobjectDesignator &A, 3737 const SubobjectDesignator &B) { 3738 if (A.Entries.size() != B.Entries.size()) 3739 return false; 3740 3741 bool IsArray = A.MostDerivedIsArrayElement; 3742 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3743 // A is a subobject of the array element. 3744 return false; 3745 3746 // If A (and B) designates an array element, the last entry will be the array 3747 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3748 // of length 1' case, and the entire path must match. 3749 bool WasArrayIndex; 3750 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3751 return CommonLength >= A.Entries.size() - IsArray; 3752 } 3753 3754 /// Find the complete object to which an LValue refers. 3755 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3756 AccessKinds AK, const LValue &LVal, 3757 QualType LValType) { 3758 if (LVal.InvalidBase) { 3759 Info.FFDiag(E); 3760 return CompleteObject(); 3761 } 3762 3763 if (!LVal.Base) { 3764 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3765 return CompleteObject(); 3766 } 3767 3768 CallStackFrame *Frame = nullptr; 3769 unsigned Depth = 0; 3770 if (LVal.getLValueCallIndex()) { 3771 std::tie(Frame, Depth) = 3772 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3773 if (!Frame) { 3774 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3775 << AK << LVal.Base.is<const ValueDecl*>(); 3776 NoteLValueLocation(Info, LVal.Base); 3777 return CompleteObject(); 3778 } 3779 } 3780 3781 bool IsAccess = isAnyAccess(AK); 3782 3783 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3784 // is not a constant expression (even if the object is non-volatile). We also 3785 // apply this rule to C++98, in order to conform to the expected 'volatile' 3786 // semantics. 3787 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3788 if (Info.getLangOpts().CPlusPlus) 3789 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3790 << AK << LValType; 3791 else 3792 Info.FFDiag(E); 3793 return CompleteObject(); 3794 } 3795 3796 // Compute value storage location and type of base object. 3797 APValue *BaseVal = nullptr; 3798 QualType BaseType = getType(LVal.Base); 3799 3800 if (const ConstantExpr *CE = 3801 dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) { 3802 /// Nested immediate invocation have been previously removed so if we found 3803 /// a ConstantExpr it can only be the EvaluatingDecl. 3804 assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl); 3805 (void)CE; 3806 BaseVal = Info.EvaluatingDeclValue; 3807 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3808 // Allow reading from a GUID declaration. 3809 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 3810 if (isModification(AK)) { 3811 // All the remaining cases do not permit modification of the object. 3812 Info.FFDiag(E, diag::note_constexpr_modify_global); 3813 return CompleteObject(); 3814 } 3815 APValue &V = GD->getAsAPValue(); 3816 if (V.isAbsent()) { 3817 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 3818 << GD->getType(); 3819 return CompleteObject(); 3820 } 3821 return CompleteObject(LVal.Base, &V, GD->getType()); 3822 } 3823 3824 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3825 // In C++11, constexpr, non-volatile variables initialized with constant 3826 // expressions are constant expressions too. Inside constexpr functions, 3827 // parameters are constant expressions even if they're non-const. 3828 // In C++1y, objects local to a constant expression (those with a Frame) are 3829 // both readable and writable inside constant expressions. 3830 // In C, such things can also be folded, although they are not ICEs. 3831 const VarDecl *VD = dyn_cast<VarDecl>(D); 3832 if (VD) { 3833 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3834 VD = VDef; 3835 } 3836 if (!VD || VD->isInvalidDecl()) { 3837 Info.FFDiag(E); 3838 return CompleteObject(); 3839 } 3840 3841 // In OpenCL if a variable is in constant address space it is a const value. 3842 bool IsConstant = BaseType.isConstQualified() || 3843 (Info.getLangOpts().OpenCL && 3844 BaseType.getAddressSpace() == LangAS::opencl_constant); 3845 3846 // Unless we're looking at a local variable or argument in a constexpr call, 3847 // the variable we're reading must be const. 3848 if (!Frame) { 3849 if (Info.getLangOpts().CPlusPlus14 && 3850 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3851 // OK, we can read and modify an object if we're in the process of 3852 // evaluating its initializer, because its lifetime began in this 3853 // evaluation. 3854 } else if (isModification(AK)) { 3855 // All the remaining cases do not permit modification of the object. 3856 Info.FFDiag(E, diag::note_constexpr_modify_global); 3857 return CompleteObject(); 3858 } else if (VD->isConstexpr()) { 3859 // OK, we can read this variable. 3860 } else if (BaseType->isIntegralOrEnumerationType()) { 3861 // In OpenCL if a variable is in constant address space it is a const 3862 // value. 3863 if (!IsConstant) { 3864 if (!IsAccess) 3865 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3866 if (Info.getLangOpts().CPlusPlus) { 3867 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3868 Info.Note(VD->getLocation(), diag::note_declared_at); 3869 } else { 3870 Info.FFDiag(E); 3871 } 3872 return CompleteObject(); 3873 } 3874 } else if (!IsAccess) { 3875 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3876 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 3877 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 3878 // This variable might end up being constexpr. Don't diagnose it yet. 3879 } else if (IsConstant) { 3880 // Keep evaluating to see what we can do. In particular, we support 3881 // folding of const floating-point types, in order to make static const 3882 // data members of such types (supported as an extension) more useful. 3883 if (Info.getLangOpts().CPlusPlus) { 3884 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 3885 ? diag::note_constexpr_ltor_non_constexpr 3886 : diag::note_constexpr_ltor_non_integral, 1) 3887 << VD << BaseType; 3888 Info.Note(VD->getLocation(), diag::note_declared_at); 3889 } else { 3890 Info.CCEDiag(E); 3891 } 3892 } else { 3893 // Never allow reading a non-const value. 3894 if (Info.getLangOpts().CPlusPlus) { 3895 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3896 ? diag::note_constexpr_ltor_non_constexpr 3897 : diag::note_constexpr_ltor_non_integral, 1) 3898 << VD << BaseType; 3899 Info.Note(VD->getLocation(), diag::note_declared_at); 3900 } else { 3901 Info.FFDiag(E); 3902 } 3903 return CompleteObject(); 3904 } 3905 } 3906 3907 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3908 return CompleteObject(); 3909 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 3910 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 3911 if (!Alloc) { 3912 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 3913 return CompleteObject(); 3914 } 3915 return CompleteObject(LVal.Base, &(*Alloc)->Value, 3916 LVal.Base.getDynamicAllocType()); 3917 } else { 3918 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3919 3920 if (!Frame) { 3921 if (const MaterializeTemporaryExpr *MTE = 3922 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 3923 assert(MTE->getStorageDuration() == SD_Static && 3924 "should have a frame for a non-global materialized temporary"); 3925 3926 // Per C++1y [expr.const]p2: 3927 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3928 // - a [...] glvalue of integral or enumeration type that refers to 3929 // a non-volatile const object [...] 3930 // [...] 3931 // - a [...] glvalue of literal type that refers to a non-volatile 3932 // object whose lifetime began within the evaluation of e. 3933 // 3934 // C++11 misses the 'began within the evaluation of e' check and 3935 // instead allows all temporaries, including things like: 3936 // int &&r = 1; 3937 // int x = ++r; 3938 // constexpr int k = r; 3939 // Therefore we use the C++14 rules in C++11 too. 3940 // 3941 // Note that temporaries whose lifetimes began while evaluating a 3942 // variable's constructor are not usable while evaluating the 3943 // corresponding destructor, not even if they're of const-qualified 3944 // types. 3945 if (!(BaseType.isConstQualified() && 3946 BaseType->isIntegralOrEnumerationType()) && 3947 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 3948 if (!IsAccess) 3949 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3950 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3951 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3952 return CompleteObject(); 3953 } 3954 3955 BaseVal = MTE->getOrCreateValue(false); 3956 assert(BaseVal && "got reference to unevaluated temporary"); 3957 } else { 3958 if (!IsAccess) 3959 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3960 APValue Val; 3961 LVal.moveInto(Val); 3962 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 3963 << AK 3964 << Val.getAsString(Info.Ctx, 3965 Info.Ctx.getLValueReferenceType(LValType)); 3966 NoteLValueLocation(Info, LVal.Base); 3967 return CompleteObject(); 3968 } 3969 } else { 3970 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 3971 assert(BaseVal && "missing value for temporary"); 3972 } 3973 } 3974 3975 // In C++14, we can't safely access any mutable state when we might be 3976 // evaluating after an unmodeled side effect. 3977 // 3978 // FIXME: Not all local state is mutable. Allow local constant subobjects 3979 // to be read here (but take care with 'mutable' fields). 3980 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3981 Info.EvalStatus.HasSideEffects) || 3982 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth)) 3983 return CompleteObject(); 3984 3985 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 3986 } 3987 3988 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 3989 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3990 /// glvalue referred to by an entity of reference type. 3991 /// 3992 /// \param Info - Information about the ongoing evaluation. 3993 /// \param Conv - The expression for which we are performing the conversion. 3994 /// Used for diagnostics. 3995 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 3996 /// case of a non-class type). 3997 /// \param LVal - The glvalue on which we are attempting to perform this action. 3998 /// \param RVal - The produced value will be placed here. 3999 /// \param WantObjectRepresentation - If true, we're looking for the object 4000 /// representation rather than the value, and in particular, 4001 /// there is no requirement that the result be fully initialized. 4002 static bool 4003 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4004 const LValue &LVal, APValue &RVal, 4005 bool WantObjectRepresentation = false) { 4006 if (LVal.Designator.Invalid) 4007 return false; 4008 4009 // Check for special cases where there is no existing APValue to look at. 4010 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4011 4012 AccessKinds AK = 4013 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4014 4015 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4016 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4017 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4018 // initializer until now for such expressions. Such an expression can't be 4019 // an ICE in C, so this only matters for fold. 4020 if (Type.isVolatileQualified()) { 4021 Info.FFDiag(Conv); 4022 return false; 4023 } 4024 APValue Lit; 4025 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4026 return false; 4027 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4028 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4029 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4030 // Special-case character extraction so we don't have to construct an 4031 // APValue for the whole string. 4032 assert(LVal.Designator.Entries.size() <= 1 && 4033 "Can only read characters from string literals"); 4034 if (LVal.Designator.Entries.empty()) { 4035 // Fail for now for LValue to RValue conversion of an array. 4036 // (This shouldn't show up in C/C++, but it could be triggered by a 4037 // weird EvaluateAsRValue call from a tool.) 4038 Info.FFDiag(Conv); 4039 return false; 4040 } 4041 if (LVal.Designator.isOnePastTheEnd()) { 4042 if (Info.getLangOpts().CPlusPlus11) 4043 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4044 else 4045 Info.FFDiag(Conv); 4046 return false; 4047 } 4048 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4049 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4050 return true; 4051 } 4052 } 4053 4054 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4055 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4056 } 4057 4058 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4059 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4060 QualType LValType, APValue &Val) { 4061 if (LVal.Designator.Invalid) 4062 return false; 4063 4064 if (!Info.getLangOpts().CPlusPlus14) { 4065 Info.FFDiag(E); 4066 return false; 4067 } 4068 4069 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4070 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4071 } 4072 4073 namespace { 4074 struct CompoundAssignSubobjectHandler { 4075 EvalInfo &Info; 4076 const Expr *E; 4077 QualType PromotedLHSType; 4078 BinaryOperatorKind Opcode; 4079 const APValue &RHS; 4080 4081 static const AccessKinds AccessKind = AK_Assign; 4082 4083 typedef bool result_type; 4084 4085 bool checkConst(QualType QT) { 4086 // Assigning to a const object has undefined behavior. 4087 if (QT.isConstQualified()) { 4088 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4089 return false; 4090 } 4091 return true; 4092 } 4093 4094 bool failed() { return false; } 4095 bool found(APValue &Subobj, QualType SubobjType) { 4096 switch (Subobj.getKind()) { 4097 case APValue::Int: 4098 return found(Subobj.getInt(), SubobjType); 4099 case APValue::Float: 4100 return found(Subobj.getFloat(), SubobjType); 4101 case APValue::ComplexInt: 4102 case APValue::ComplexFloat: 4103 // FIXME: Implement complex compound assignment. 4104 Info.FFDiag(E); 4105 return false; 4106 case APValue::LValue: 4107 return foundPointer(Subobj, SubobjType); 4108 case APValue::Vector: 4109 return foundVector(Subobj, SubobjType); 4110 default: 4111 // FIXME: can this happen? 4112 Info.FFDiag(E); 4113 return false; 4114 } 4115 } 4116 4117 bool foundVector(APValue &Value, QualType SubobjType) { 4118 if (!checkConst(SubobjType)) 4119 return false; 4120 4121 if (!SubobjType->isVectorType()) { 4122 Info.FFDiag(E); 4123 return false; 4124 } 4125 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4126 } 4127 4128 bool found(APSInt &Value, QualType SubobjType) { 4129 if (!checkConst(SubobjType)) 4130 return false; 4131 4132 if (!SubobjType->isIntegerType()) { 4133 // We don't support compound assignment on integer-cast-to-pointer 4134 // values. 4135 Info.FFDiag(E); 4136 return false; 4137 } 4138 4139 if (RHS.isInt()) { 4140 APSInt LHS = 4141 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4142 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4143 return false; 4144 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4145 return true; 4146 } else if (RHS.isFloat()) { 4147 APFloat FValue(0.0); 4148 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, 4149 FValue) && 4150 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4151 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4152 Value); 4153 } 4154 4155 Info.FFDiag(E); 4156 return false; 4157 } 4158 bool found(APFloat &Value, QualType SubobjType) { 4159 return checkConst(SubobjType) && 4160 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4161 Value) && 4162 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4163 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4164 } 4165 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4166 if (!checkConst(SubobjType)) 4167 return false; 4168 4169 QualType PointeeType; 4170 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4171 PointeeType = PT->getPointeeType(); 4172 4173 if (PointeeType.isNull() || !RHS.isInt() || 4174 (Opcode != BO_Add && Opcode != BO_Sub)) { 4175 Info.FFDiag(E); 4176 return false; 4177 } 4178 4179 APSInt Offset = RHS.getInt(); 4180 if (Opcode == BO_Sub) 4181 negateAsSigned(Offset); 4182 4183 LValue LVal; 4184 LVal.setFrom(Info.Ctx, Subobj); 4185 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4186 return false; 4187 LVal.moveInto(Subobj); 4188 return true; 4189 } 4190 }; 4191 } // end anonymous namespace 4192 4193 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4194 4195 /// Perform a compound assignment of LVal <op>= RVal. 4196 static bool handleCompoundAssignment( 4197 EvalInfo &Info, const Expr *E, 4198 const LValue &LVal, QualType LValType, QualType PromotedLValType, 4199 BinaryOperatorKind Opcode, const APValue &RVal) { 4200 if (LVal.Designator.Invalid) 4201 return false; 4202 4203 if (!Info.getLangOpts().CPlusPlus14) { 4204 Info.FFDiag(E); 4205 return false; 4206 } 4207 4208 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4209 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4210 RVal }; 4211 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4212 } 4213 4214 namespace { 4215 struct IncDecSubobjectHandler { 4216 EvalInfo &Info; 4217 const UnaryOperator *E; 4218 AccessKinds AccessKind; 4219 APValue *Old; 4220 4221 typedef bool result_type; 4222 4223 bool checkConst(QualType QT) { 4224 // Assigning to a const object has undefined behavior. 4225 if (QT.isConstQualified()) { 4226 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4227 return false; 4228 } 4229 return true; 4230 } 4231 4232 bool failed() { return false; } 4233 bool found(APValue &Subobj, QualType SubobjType) { 4234 // Stash the old value. Also clear Old, so we don't clobber it later 4235 // if we're post-incrementing a complex. 4236 if (Old) { 4237 *Old = Subobj; 4238 Old = nullptr; 4239 } 4240 4241 switch (Subobj.getKind()) { 4242 case APValue::Int: 4243 return found(Subobj.getInt(), SubobjType); 4244 case APValue::Float: 4245 return found(Subobj.getFloat(), SubobjType); 4246 case APValue::ComplexInt: 4247 return found(Subobj.getComplexIntReal(), 4248 SubobjType->castAs<ComplexType>()->getElementType() 4249 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4250 case APValue::ComplexFloat: 4251 return found(Subobj.getComplexFloatReal(), 4252 SubobjType->castAs<ComplexType>()->getElementType() 4253 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4254 case APValue::LValue: 4255 return foundPointer(Subobj, SubobjType); 4256 default: 4257 // FIXME: can this happen? 4258 Info.FFDiag(E); 4259 return false; 4260 } 4261 } 4262 bool found(APSInt &Value, QualType SubobjType) { 4263 if (!checkConst(SubobjType)) 4264 return false; 4265 4266 if (!SubobjType->isIntegerType()) { 4267 // We don't support increment / decrement on integer-cast-to-pointer 4268 // values. 4269 Info.FFDiag(E); 4270 return false; 4271 } 4272 4273 if (Old) *Old = APValue(Value); 4274 4275 // bool arithmetic promotes to int, and the conversion back to bool 4276 // doesn't reduce mod 2^n, so special-case it. 4277 if (SubobjType->isBooleanType()) { 4278 if (AccessKind == AK_Increment) 4279 Value = 1; 4280 else 4281 Value = !Value; 4282 return true; 4283 } 4284 4285 bool WasNegative = Value.isNegative(); 4286 if (AccessKind == AK_Increment) { 4287 ++Value; 4288 4289 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4290 APSInt ActualValue(Value, /*IsUnsigned*/true); 4291 return HandleOverflow(Info, E, ActualValue, SubobjType); 4292 } 4293 } else { 4294 --Value; 4295 4296 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4297 unsigned BitWidth = Value.getBitWidth(); 4298 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4299 ActualValue.setBit(BitWidth); 4300 return HandleOverflow(Info, E, ActualValue, SubobjType); 4301 } 4302 } 4303 return true; 4304 } 4305 bool found(APFloat &Value, QualType SubobjType) { 4306 if (!checkConst(SubobjType)) 4307 return false; 4308 4309 if (Old) *Old = APValue(Value); 4310 4311 APFloat One(Value.getSemantics(), 1); 4312 if (AccessKind == AK_Increment) 4313 Value.add(One, APFloat::rmNearestTiesToEven); 4314 else 4315 Value.subtract(One, APFloat::rmNearestTiesToEven); 4316 return true; 4317 } 4318 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4319 if (!checkConst(SubobjType)) 4320 return false; 4321 4322 QualType PointeeType; 4323 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4324 PointeeType = PT->getPointeeType(); 4325 else { 4326 Info.FFDiag(E); 4327 return false; 4328 } 4329 4330 LValue LVal; 4331 LVal.setFrom(Info.Ctx, Subobj); 4332 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4333 AccessKind == AK_Increment ? 1 : -1)) 4334 return false; 4335 LVal.moveInto(Subobj); 4336 return true; 4337 } 4338 }; 4339 } // end anonymous namespace 4340 4341 /// Perform an increment or decrement on LVal. 4342 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4343 QualType LValType, bool IsIncrement, APValue *Old) { 4344 if (LVal.Designator.Invalid) 4345 return false; 4346 4347 if (!Info.getLangOpts().CPlusPlus14) { 4348 Info.FFDiag(E); 4349 return false; 4350 } 4351 4352 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4353 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4354 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4355 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4356 } 4357 4358 /// Build an lvalue for the object argument of a member function call. 4359 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4360 LValue &This) { 4361 if (Object->getType()->isPointerType() && Object->isRValue()) 4362 return EvaluatePointer(Object, This, Info); 4363 4364 if (Object->isGLValue()) 4365 return EvaluateLValue(Object, This, Info); 4366 4367 if (Object->getType()->isLiteralType(Info.Ctx)) 4368 return EvaluateTemporary(Object, This, Info); 4369 4370 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4371 return false; 4372 } 4373 4374 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4375 /// lvalue referring to the result. 4376 /// 4377 /// \param Info - Information about the ongoing evaluation. 4378 /// \param LV - An lvalue referring to the base of the member pointer. 4379 /// \param RHS - The member pointer expression. 4380 /// \param IncludeMember - Specifies whether the member itself is included in 4381 /// the resulting LValue subobject designator. This is not possible when 4382 /// creating a bound member function. 4383 /// \return The field or method declaration to which the member pointer refers, 4384 /// or 0 if evaluation fails. 4385 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4386 QualType LVType, 4387 LValue &LV, 4388 const Expr *RHS, 4389 bool IncludeMember = true) { 4390 MemberPtr MemPtr; 4391 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4392 return nullptr; 4393 4394 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4395 // member value, the behavior is undefined. 4396 if (!MemPtr.getDecl()) { 4397 // FIXME: Specific diagnostic. 4398 Info.FFDiag(RHS); 4399 return nullptr; 4400 } 4401 4402 if (MemPtr.isDerivedMember()) { 4403 // This is a member of some derived class. Truncate LV appropriately. 4404 // The end of the derived-to-base path for the base object must match the 4405 // derived-to-base path for the member pointer. 4406 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4407 LV.Designator.Entries.size()) { 4408 Info.FFDiag(RHS); 4409 return nullptr; 4410 } 4411 unsigned PathLengthToMember = 4412 LV.Designator.Entries.size() - MemPtr.Path.size(); 4413 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4414 const CXXRecordDecl *LVDecl = getAsBaseClass( 4415 LV.Designator.Entries[PathLengthToMember + I]); 4416 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4417 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4418 Info.FFDiag(RHS); 4419 return nullptr; 4420 } 4421 } 4422 4423 // Truncate the lvalue to the appropriate derived class. 4424 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4425 PathLengthToMember)) 4426 return nullptr; 4427 } else if (!MemPtr.Path.empty()) { 4428 // Extend the LValue path with the member pointer's path. 4429 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4430 MemPtr.Path.size() + IncludeMember); 4431 4432 // Walk down to the appropriate base class. 4433 if (const PointerType *PT = LVType->getAs<PointerType>()) 4434 LVType = PT->getPointeeType(); 4435 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4436 assert(RD && "member pointer access on non-class-type expression"); 4437 // The first class in the path is that of the lvalue. 4438 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4439 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4440 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4441 return nullptr; 4442 RD = Base; 4443 } 4444 // Finally cast to the class containing the member. 4445 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4446 MemPtr.getContainingRecord())) 4447 return nullptr; 4448 } 4449 4450 // Add the member. Note that we cannot build bound member functions here. 4451 if (IncludeMember) { 4452 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4453 if (!HandleLValueMember(Info, RHS, LV, FD)) 4454 return nullptr; 4455 } else if (const IndirectFieldDecl *IFD = 4456 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4457 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4458 return nullptr; 4459 } else { 4460 llvm_unreachable("can't construct reference to bound member function"); 4461 } 4462 } 4463 4464 return MemPtr.getDecl(); 4465 } 4466 4467 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4468 const BinaryOperator *BO, 4469 LValue &LV, 4470 bool IncludeMember = true) { 4471 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4472 4473 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4474 if (Info.noteFailure()) { 4475 MemberPtr MemPtr; 4476 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4477 } 4478 return nullptr; 4479 } 4480 4481 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4482 BO->getRHS(), IncludeMember); 4483 } 4484 4485 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4486 /// the provided lvalue, which currently refers to the base object. 4487 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4488 LValue &Result) { 4489 SubobjectDesignator &D = Result.Designator; 4490 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4491 return false; 4492 4493 QualType TargetQT = E->getType(); 4494 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4495 TargetQT = PT->getPointeeType(); 4496 4497 // Check this cast lands within the final derived-to-base subobject path. 4498 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4499 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4500 << D.MostDerivedType << TargetQT; 4501 return false; 4502 } 4503 4504 // Check the type of the final cast. We don't need to check the path, 4505 // since a cast can only be formed if the path is unique. 4506 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4507 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4508 const CXXRecordDecl *FinalType; 4509 if (NewEntriesSize == D.MostDerivedPathLength) 4510 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4511 else 4512 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4513 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4514 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4515 << D.MostDerivedType << TargetQT; 4516 return false; 4517 } 4518 4519 // Truncate the lvalue to the appropriate derived class. 4520 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4521 } 4522 4523 /// Get the value to use for a default-initialized object of type T. 4524 /// Return false if it encounters something invalid. 4525 static bool getDefaultInitValue(QualType T, APValue &Result) { 4526 bool Success = true; 4527 if (auto *RD = T->getAsCXXRecordDecl()) { 4528 if (RD->isInvalidDecl()) { 4529 Result = APValue(); 4530 return false; 4531 } 4532 if (RD->isUnion()) { 4533 Result = APValue((const FieldDecl *)nullptr); 4534 return true; 4535 } 4536 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4537 std::distance(RD->field_begin(), RD->field_end())); 4538 4539 unsigned Index = 0; 4540 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4541 End = RD->bases_end(); 4542 I != End; ++I, ++Index) 4543 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4544 4545 for (const auto *I : RD->fields()) { 4546 if (I->isUnnamedBitfield()) 4547 continue; 4548 Success &= getDefaultInitValue(I->getType(), 4549 Result.getStructField(I->getFieldIndex())); 4550 } 4551 return Success; 4552 } 4553 4554 if (auto *AT = 4555 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4556 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4557 if (Result.hasArrayFiller()) 4558 Success &= 4559 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4560 4561 return Success; 4562 } 4563 4564 Result = APValue::IndeterminateValue(); 4565 return true; 4566 } 4567 4568 namespace { 4569 enum EvalStmtResult { 4570 /// Evaluation failed. 4571 ESR_Failed, 4572 /// Hit a 'return' statement. 4573 ESR_Returned, 4574 /// Evaluation succeeded. 4575 ESR_Succeeded, 4576 /// Hit a 'continue' statement. 4577 ESR_Continue, 4578 /// Hit a 'break' statement. 4579 ESR_Break, 4580 /// Still scanning for 'case' or 'default' statement. 4581 ESR_CaseNotFound 4582 }; 4583 } 4584 4585 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4586 // We don't need to evaluate the initializer for a static local. 4587 if (!VD->hasLocalStorage()) 4588 return true; 4589 4590 LValue Result; 4591 APValue &Val = 4592 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result); 4593 4594 const Expr *InitE = VD->getInit(); 4595 if (!InitE) 4596 return getDefaultInitValue(VD->getType(), Val); 4597 4598 if (InitE->isValueDependent()) 4599 return false; 4600 4601 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4602 // Wipe out any partially-computed value, to allow tracking that this 4603 // evaluation failed. 4604 Val = APValue(); 4605 return false; 4606 } 4607 4608 return true; 4609 } 4610 4611 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4612 bool OK = true; 4613 4614 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4615 OK &= EvaluateVarDecl(Info, VD); 4616 4617 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4618 for (auto *BD : DD->bindings()) 4619 if (auto *VD = BD->getHoldingVar()) 4620 OK &= EvaluateDecl(Info, VD); 4621 4622 return OK; 4623 } 4624 4625 4626 /// Evaluate a condition (either a variable declaration or an expression). 4627 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4628 const Expr *Cond, bool &Result) { 4629 FullExpressionRAII Scope(Info); 4630 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4631 return false; 4632 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4633 return false; 4634 return Scope.destroy(); 4635 } 4636 4637 namespace { 4638 /// A location where the result (returned value) of evaluating a 4639 /// statement should be stored. 4640 struct StmtResult { 4641 /// The APValue that should be filled in with the returned value. 4642 APValue &Value; 4643 /// The location containing the result, if any (used to support RVO). 4644 const LValue *Slot; 4645 }; 4646 4647 struct TempVersionRAII { 4648 CallStackFrame &Frame; 4649 4650 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4651 Frame.pushTempVersion(); 4652 } 4653 4654 ~TempVersionRAII() { 4655 Frame.popTempVersion(); 4656 } 4657 }; 4658 4659 } 4660 4661 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4662 const Stmt *S, 4663 const SwitchCase *SC = nullptr); 4664 4665 /// Evaluate the body of a loop, and translate the result as appropriate. 4666 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4667 const Stmt *Body, 4668 const SwitchCase *Case = nullptr) { 4669 BlockScopeRAII Scope(Info); 4670 4671 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4672 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4673 ESR = ESR_Failed; 4674 4675 switch (ESR) { 4676 case ESR_Break: 4677 return ESR_Succeeded; 4678 case ESR_Succeeded: 4679 case ESR_Continue: 4680 return ESR_Continue; 4681 case ESR_Failed: 4682 case ESR_Returned: 4683 case ESR_CaseNotFound: 4684 return ESR; 4685 } 4686 llvm_unreachable("Invalid EvalStmtResult!"); 4687 } 4688 4689 /// Evaluate a switch statement. 4690 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4691 const SwitchStmt *SS) { 4692 BlockScopeRAII Scope(Info); 4693 4694 // Evaluate the switch condition. 4695 APSInt Value; 4696 { 4697 if (const Stmt *Init = SS->getInit()) { 4698 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4699 if (ESR != ESR_Succeeded) { 4700 if (ESR != ESR_Failed && !Scope.destroy()) 4701 ESR = ESR_Failed; 4702 return ESR; 4703 } 4704 } 4705 4706 FullExpressionRAII CondScope(Info); 4707 if (SS->getConditionVariable() && 4708 !EvaluateDecl(Info, SS->getConditionVariable())) 4709 return ESR_Failed; 4710 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4711 return ESR_Failed; 4712 if (!CondScope.destroy()) 4713 return ESR_Failed; 4714 } 4715 4716 // Find the switch case corresponding to the value of the condition. 4717 // FIXME: Cache this lookup. 4718 const SwitchCase *Found = nullptr; 4719 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4720 SC = SC->getNextSwitchCase()) { 4721 if (isa<DefaultStmt>(SC)) { 4722 Found = SC; 4723 continue; 4724 } 4725 4726 const CaseStmt *CS = cast<CaseStmt>(SC); 4727 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4728 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4729 : LHS; 4730 if (LHS <= Value && Value <= RHS) { 4731 Found = SC; 4732 break; 4733 } 4734 } 4735 4736 if (!Found) 4737 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4738 4739 // Search the switch body for the switch case and evaluate it from there. 4740 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4741 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4742 return ESR_Failed; 4743 4744 switch (ESR) { 4745 case ESR_Break: 4746 return ESR_Succeeded; 4747 case ESR_Succeeded: 4748 case ESR_Continue: 4749 case ESR_Failed: 4750 case ESR_Returned: 4751 return ESR; 4752 case ESR_CaseNotFound: 4753 // This can only happen if the switch case is nested within a statement 4754 // expression. We have no intention of supporting that. 4755 Info.FFDiag(Found->getBeginLoc(), 4756 diag::note_constexpr_stmt_expr_unsupported); 4757 return ESR_Failed; 4758 } 4759 llvm_unreachable("Invalid EvalStmtResult!"); 4760 } 4761 4762 // Evaluate a statement. 4763 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4764 const Stmt *S, const SwitchCase *Case) { 4765 if (!Info.nextStep(S)) 4766 return ESR_Failed; 4767 4768 // If we're hunting down a 'case' or 'default' label, recurse through 4769 // substatements until we hit the label. 4770 if (Case) { 4771 switch (S->getStmtClass()) { 4772 case Stmt::CompoundStmtClass: 4773 // FIXME: Precompute which substatement of a compound statement we 4774 // would jump to, and go straight there rather than performing a 4775 // linear scan each time. 4776 case Stmt::LabelStmtClass: 4777 case Stmt::AttributedStmtClass: 4778 case Stmt::DoStmtClass: 4779 break; 4780 4781 case Stmt::CaseStmtClass: 4782 case Stmt::DefaultStmtClass: 4783 if (Case == S) 4784 Case = nullptr; 4785 break; 4786 4787 case Stmt::IfStmtClass: { 4788 // FIXME: Precompute which side of an 'if' we would jump to, and go 4789 // straight there rather than scanning both sides. 4790 const IfStmt *IS = cast<IfStmt>(S); 4791 4792 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4793 // preceded by our switch label. 4794 BlockScopeRAII Scope(Info); 4795 4796 // Step into the init statement in case it brings an (uninitialized) 4797 // variable into scope. 4798 if (const Stmt *Init = IS->getInit()) { 4799 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4800 if (ESR != ESR_CaseNotFound) { 4801 assert(ESR != ESR_Succeeded); 4802 return ESR; 4803 } 4804 } 4805 4806 // Condition variable must be initialized if it exists. 4807 // FIXME: We can skip evaluating the body if there's a condition 4808 // variable, as there can't be any case labels within it. 4809 // (The same is true for 'for' statements.) 4810 4811 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4812 if (ESR == ESR_Failed) 4813 return ESR; 4814 if (ESR != ESR_CaseNotFound) 4815 return Scope.destroy() ? ESR : ESR_Failed; 4816 if (!IS->getElse()) 4817 return ESR_CaseNotFound; 4818 4819 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 4820 if (ESR == ESR_Failed) 4821 return ESR; 4822 if (ESR != ESR_CaseNotFound) 4823 return Scope.destroy() ? ESR : ESR_Failed; 4824 return ESR_CaseNotFound; 4825 } 4826 4827 case Stmt::WhileStmtClass: { 4828 EvalStmtResult ESR = 4829 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4830 if (ESR != ESR_Continue) 4831 return ESR; 4832 break; 4833 } 4834 4835 case Stmt::ForStmtClass: { 4836 const ForStmt *FS = cast<ForStmt>(S); 4837 BlockScopeRAII Scope(Info); 4838 4839 // Step into the init statement in case it brings an (uninitialized) 4840 // variable into scope. 4841 if (const Stmt *Init = FS->getInit()) { 4842 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4843 if (ESR != ESR_CaseNotFound) { 4844 assert(ESR != ESR_Succeeded); 4845 return ESR; 4846 } 4847 } 4848 4849 EvalStmtResult ESR = 4850 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4851 if (ESR != ESR_Continue) 4852 return ESR; 4853 if (FS->getInc()) { 4854 FullExpressionRAII IncScope(Info); 4855 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 4856 return ESR_Failed; 4857 } 4858 break; 4859 } 4860 4861 case Stmt::DeclStmtClass: { 4862 // Start the lifetime of any uninitialized variables we encounter. They 4863 // might be used by the selected branch of the switch. 4864 const DeclStmt *DS = cast<DeclStmt>(S); 4865 for (const auto *D : DS->decls()) { 4866 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4867 if (VD->hasLocalStorage() && !VD->getInit()) 4868 if (!EvaluateVarDecl(Info, VD)) 4869 return ESR_Failed; 4870 // FIXME: If the variable has initialization that can't be jumped 4871 // over, bail out of any immediately-surrounding compound-statement 4872 // too. There can't be any case labels here. 4873 } 4874 } 4875 return ESR_CaseNotFound; 4876 } 4877 4878 default: 4879 return ESR_CaseNotFound; 4880 } 4881 } 4882 4883 switch (S->getStmtClass()) { 4884 default: 4885 if (const Expr *E = dyn_cast<Expr>(S)) { 4886 // Don't bother evaluating beyond an expression-statement which couldn't 4887 // be evaluated. 4888 // FIXME: Do we need the FullExpressionRAII object here? 4889 // VisitExprWithCleanups should create one when necessary. 4890 FullExpressionRAII Scope(Info); 4891 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 4892 return ESR_Failed; 4893 return ESR_Succeeded; 4894 } 4895 4896 Info.FFDiag(S->getBeginLoc()); 4897 return ESR_Failed; 4898 4899 case Stmt::NullStmtClass: 4900 return ESR_Succeeded; 4901 4902 case Stmt::DeclStmtClass: { 4903 const DeclStmt *DS = cast<DeclStmt>(S); 4904 for (const auto *D : DS->decls()) { 4905 // Each declaration initialization is its own full-expression. 4906 FullExpressionRAII Scope(Info); 4907 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 4908 return ESR_Failed; 4909 if (!Scope.destroy()) 4910 return ESR_Failed; 4911 } 4912 return ESR_Succeeded; 4913 } 4914 4915 case Stmt::ReturnStmtClass: { 4916 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4917 FullExpressionRAII Scope(Info); 4918 if (RetExpr && 4919 !(Result.Slot 4920 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4921 : Evaluate(Result.Value, Info, RetExpr))) 4922 return ESR_Failed; 4923 return Scope.destroy() ? ESR_Returned : ESR_Failed; 4924 } 4925 4926 case Stmt::CompoundStmtClass: { 4927 BlockScopeRAII Scope(Info); 4928 4929 const CompoundStmt *CS = cast<CompoundStmt>(S); 4930 for (const auto *BI : CS->body()) { 4931 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4932 if (ESR == ESR_Succeeded) 4933 Case = nullptr; 4934 else if (ESR != ESR_CaseNotFound) { 4935 if (ESR != ESR_Failed && !Scope.destroy()) 4936 return ESR_Failed; 4937 return ESR; 4938 } 4939 } 4940 if (Case) 4941 return ESR_CaseNotFound; 4942 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4943 } 4944 4945 case Stmt::IfStmtClass: { 4946 const IfStmt *IS = cast<IfStmt>(S); 4947 4948 // Evaluate the condition, as either a var decl or as an expression. 4949 BlockScopeRAII Scope(Info); 4950 if (const Stmt *Init = IS->getInit()) { 4951 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4952 if (ESR != ESR_Succeeded) { 4953 if (ESR != ESR_Failed && !Scope.destroy()) 4954 return ESR_Failed; 4955 return ESR; 4956 } 4957 } 4958 bool Cond; 4959 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 4960 return ESR_Failed; 4961 4962 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 4963 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 4964 if (ESR != ESR_Succeeded) { 4965 if (ESR != ESR_Failed && !Scope.destroy()) 4966 return ESR_Failed; 4967 return ESR; 4968 } 4969 } 4970 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4971 } 4972 4973 case Stmt::WhileStmtClass: { 4974 const WhileStmt *WS = cast<WhileStmt>(S); 4975 while (true) { 4976 BlockScopeRAII Scope(Info); 4977 bool Continue; 4978 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 4979 Continue)) 4980 return ESR_Failed; 4981 if (!Continue) 4982 break; 4983 4984 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 4985 if (ESR != ESR_Continue) { 4986 if (ESR != ESR_Failed && !Scope.destroy()) 4987 return ESR_Failed; 4988 return ESR; 4989 } 4990 if (!Scope.destroy()) 4991 return ESR_Failed; 4992 } 4993 return ESR_Succeeded; 4994 } 4995 4996 case Stmt::DoStmtClass: { 4997 const DoStmt *DS = cast<DoStmt>(S); 4998 bool Continue; 4999 do { 5000 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5001 if (ESR != ESR_Continue) 5002 return ESR; 5003 Case = nullptr; 5004 5005 FullExpressionRAII CondScope(Info); 5006 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5007 !CondScope.destroy()) 5008 return ESR_Failed; 5009 } while (Continue); 5010 return ESR_Succeeded; 5011 } 5012 5013 case Stmt::ForStmtClass: { 5014 const ForStmt *FS = cast<ForStmt>(S); 5015 BlockScopeRAII ForScope(Info); 5016 if (FS->getInit()) { 5017 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5018 if (ESR != ESR_Succeeded) { 5019 if (ESR != ESR_Failed && !ForScope.destroy()) 5020 return ESR_Failed; 5021 return ESR; 5022 } 5023 } 5024 while (true) { 5025 BlockScopeRAII IterScope(Info); 5026 bool Continue = true; 5027 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5028 FS->getCond(), Continue)) 5029 return ESR_Failed; 5030 if (!Continue) 5031 break; 5032 5033 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5034 if (ESR != ESR_Continue) { 5035 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5036 return ESR_Failed; 5037 return ESR; 5038 } 5039 5040 if (FS->getInc()) { 5041 FullExpressionRAII IncScope(Info); 5042 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 5043 return ESR_Failed; 5044 } 5045 5046 if (!IterScope.destroy()) 5047 return ESR_Failed; 5048 } 5049 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5050 } 5051 5052 case Stmt::CXXForRangeStmtClass: { 5053 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5054 BlockScopeRAII Scope(Info); 5055 5056 // Evaluate the init-statement if present. 5057 if (FS->getInit()) { 5058 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5059 if (ESR != ESR_Succeeded) { 5060 if (ESR != ESR_Failed && !Scope.destroy()) 5061 return ESR_Failed; 5062 return ESR; 5063 } 5064 } 5065 5066 // Initialize the __range variable. 5067 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5068 if (ESR != ESR_Succeeded) { 5069 if (ESR != ESR_Failed && !Scope.destroy()) 5070 return ESR_Failed; 5071 return ESR; 5072 } 5073 5074 // Create the __begin and __end iterators. 5075 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5076 if (ESR != ESR_Succeeded) { 5077 if (ESR != ESR_Failed && !Scope.destroy()) 5078 return ESR_Failed; 5079 return ESR; 5080 } 5081 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5082 if (ESR != ESR_Succeeded) { 5083 if (ESR != ESR_Failed && !Scope.destroy()) 5084 return ESR_Failed; 5085 return ESR; 5086 } 5087 5088 while (true) { 5089 // Condition: __begin != __end. 5090 { 5091 bool Continue = true; 5092 FullExpressionRAII CondExpr(Info); 5093 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5094 return ESR_Failed; 5095 if (!Continue) 5096 break; 5097 } 5098 5099 // User's variable declaration, initialized by *__begin. 5100 BlockScopeRAII InnerScope(Info); 5101 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5102 if (ESR != ESR_Succeeded) { 5103 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5104 return ESR_Failed; 5105 return ESR; 5106 } 5107 5108 // Loop body. 5109 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5110 if (ESR != ESR_Continue) { 5111 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5112 return ESR_Failed; 5113 return ESR; 5114 } 5115 5116 // Increment: ++__begin 5117 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5118 return ESR_Failed; 5119 5120 if (!InnerScope.destroy()) 5121 return ESR_Failed; 5122 } 5123 5124 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5125 } 5126 5127 case Stmt::SwitchStmtClass: 5128 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5129 5130 case Stmt::ContinueStmtClass: 5131 return ESR_Continue; 5132 5133 case Stmt::BreakStmtClass: 5134 return ESR_Break; 5135 5136 case Stmt::LabelStmtClass: 5137 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5138 5139 case Stmt::AttributedStmtClass: 5140 // As a general principle, C++11 attributes can be ignored without 5141 // any semantic impact. 5142 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5143 Case); 5144 5145 case Stmt::CaseStmtClass: 5146 case Stmt::DefaultStmtClass: 5147 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5148 case Stmt::CXXTryStmtClass: 5149 // Evaluate try blocks by evaluating all sub statements. 5150 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5151 } 5152 } 5153 5154 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5155 /// default constructor. If so, we'll fold it whether or not it's marked as 5156 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5157 /// so we need special handling. 5158 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5159 const CXXConstructorDecl *CD, 5160 bool IsValueInitialization) { 5161 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5162 return false; 5163 5164 // Value-initialization does not call a trivial default constructor, so such a 5165 // call is a core constant expression whether or not the constructor is 5166 // constexpr. 5167 if (!CD->isConstexpr() && !IsValueInitialization) { 5168 if (Info.getLangOpts().CPlusPlus11) { 5169 // FIXME: If DiagDecl is an implicitly-declared special member function, 5170 // we should be much more explicit about why it's not constexpr. 5171 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5172 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5173 Info.Note(CD->getLocation(), diag::note_declared_at); 5174 } else { 5175 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5176 } 5177 } 5178 return true; 5179 } 5180 5181 /// CheckConstexprFunction - Check that a function can be called in a constant 5182 /// expression. 5183 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5184 const FunctionDecl *Declaration, 5185 const FunctionDecl *Definition, 5186 const Stmt *Body) { 5187 // Potential constant expressions can contain calls to declared, but not yet 5188 // defined, constexpr functions. 5189 if (Info.checkingPotentialConstantExpression() && !Definition && 5190 Declaration->isConstexpr()) 5191 return false; 5192 5193 // Bail out if the function declaration itself is invalid. We will 5194 // have produced a relevant diagnostic while parsing it, so just 5195 // note the problematic sub-expression. 5196 if (Declaration->isInvalidDecl()) { 5197 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5198 return false; 5199 } 5200 5201 // DR1872: An instantiated virtual constexpr function can't be called in a 5202 // constant expression (prior to C++20). We can still constant-fold such a 5203 // call. 5204 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5205 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5206 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5207 5208 if (Definition && Definition->isInvalidDecl()) { 5209 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5210 return false; 5211 } 5212 5213 if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) { 5214 for (const auto *InitExpr : CtorDecl->inits()) { 5215 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 5216 return false; 5217 } 5218 } 5219 5220 // Can we evaluate this function call? 5221 if (Definition && Definition->isConstexpr() && Body) 5222 return true; 5223 5224 if (Info.getLangOpts().CPlusPlus11) { 5225 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5226 5227 // If this function is not constexpr because it is an inherited 5228 // non-constexpr constructor, diagnose that directly. 5229 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5230 if (CD && CD->isInheritingConstructor()) { 5231 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5232 if (!Inherited->isConstexpr()) 5233 DiagDecl = CD = Inherited; 5234 } 5235 5236 // FIXME: If DiagDecl is an implicitly-declared special member function 5237 // or an inheriting constructor, we should be much more explicit about why 5238 // it's not constexpr. 5239 if (CD && CD->isInheritingConstructor()) 5240 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5241 << CD->getInheritedConstructor().getConstructor()->getParent(); 5242 else 5243 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5244 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5245 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5246 } else { 5247 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5248 } 5249 return false; 5250 } 5251 5252 namespace { 5253 struct CheckDynamicTypeHandler { 5254 AccessKinds AccessKind; 5255 typedef bool result_type; 5256 bool failed() { return false; } 5257 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5258 bool found(APSInt &Value, QualType SubobjType) { return true; } 5259 bool found(APFloat &Value, QualType SubobjType) { return true; } 5260 }; 5261 } // end anonymous namespace 5262 5263 /// Check that we can access the notional vptr of an object / determine its 5264 /// dynamic type. 5265 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5266 AccessKinds AK, bool Polymorphic) { 5267 if (This.Designator.Invalid) 5268 return false; 5269 5270 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5271 5272 if (!Obj) 5273 return false; 5274 5275 if (!Obj.Value) { 5276 // The object is not usable in constant expressions, so we can't inspect 5277 // its value to see if it's in-lifetime or what the active union members 5278 // are. We can still check for a one-past-the-end lvalue. 5279 if (This.Designator.isOnePastTheEnd() || 5280 This.Designator.isMostDerivedAnUnsizedArray()) { 5281 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5282 ? diag::note_constexpr_access_past_end 5283 : diag::note_constexpr_access_unsized_array) 5284 << AK; 5285 return false; 5286 } else if (Polymorphic) { 5287 // Conservatively refuse to perform a polymorphic operation if we would 5288 // not be able to read a notional 'vptr' value. 5289 APValue Val; 5290 This.moveInto(Val); 5291 QualType StarThisType = 5292 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5293 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5294 << AK << Val.getAsString(Info.Ctx, StarThisType); 5295 return false; 5296 } 5297 return true; 5298 } 5299 5300 CheckDynamicTypeHandler Handler{AK}; 5301 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5302 } 5303 5304 /// Check that the pointee of the 'this' pointer in a member function call is 5305 /// either within its lifetime or in its period of construction or destruction. 5306 static bool 5307 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5308 const LValue &This, 5309 const CXXMethodDecl *NamedMember) { 5310 return checkDynamicType( 5311 Info, E, This, 5312 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5313 } 5314 5315 struct DynamicType { 5316 /// The dynamic class type of the object. 5317 const CXXRecordDecl *Type; 5318 /// The corresponding path length in the lvalue. 5319 unsigned PathLength; 5320 }; 5321 5322 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5323 unsigned PathLength) { 5324 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5325 Designator.Entries.size() && "invalid path length"); 5326 return (PathLength == Designator.MostDerivedPathLength) 5327 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5328 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5329 } 5330 5331 /// Determine the dynamic type of an object. 5332 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5333 LValue &This, AccessKinds AK) { 5334 // If we don't have an lvalue denoting an object of class type, there is no 5335 // meaningful dynamic type. (We consider objects of non-class type to have no 5336 // dynamic type.) 5337 if (!checkDynamicType(Info, E, This, AK, true)) 5338 return None; 5339 5340 // Refuse to compute a dynamic type in the presence of virtual bases. This 5341 // shouldn't happen other than in constant-folding situations, since literal 5342 // types can't have virtual bases. 5343 // 5344 // Note that consumers of DynamicType assume that the type has no virtual 5345 // bases, and will need modifications if this restriction is relaxed. 5346 const CXXRecordDecl *Class = 5347 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5348 if (!Class || Class->getNumVBases()) { 5349 Info.FFDiag(E); 5350 return None; 5351 } 5352 5353 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5354 // binary search here instead. But the overwhelmingly common case is that 5355 // we're not in the middle of a constructor, so it probably doesn't matter 5356 // in practice. 5357 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5358 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5359 PathLength <= Path.size(); ++PathLength) { 5360 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5361 Path.slice(0, PathLength))) { 5362 case ConstructionPhase::Bases: 5363 case ConstructionPhase::DestroyingBases: 5364 // We're constructing or destroying a base class. This is not the dynamic 5365 // type. 5366 break; 5367 5368 case ConstructionPhase::None: 5369 case ConstructionPhase::AfterBases: 5370 case ConstructionPhase::AfterFields: 5371 case ConstructionPhase::Destroying: 5372 // We've finished constructing the base classes and not yet started 5373 // destroying them again, so this is the dynamic type. 5374 return DynamicType{getBaseClassType(This.Designator, PathLength), 5375 PathLength}; 5376 } 5377 } 5378 5379 // CWG issue 1517: we're constructing a base class of the object described by 5380 // 'This', so that object has not yet begun its period of construction and 5381 // any polymorphic operation on it results in undefined behavior. 5382 Info.FFDiag(E); 5383 return None; 5384 } 5385 5386 /// Perform virtual dispatch. 5387 static const CXXMethodDecl *HandleVirtualDispatch( 5388 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5389 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5390 Optional<DynamicType> DynType = ComputeDynamicType( 5391 Info, E, This, 5392 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5393 if (!DynType) 5394 return nullptr; 5395 5396 // Find the final overrider. It must be declared in one of the classes on the 5397 // path from the dynamic type to the static type. 5398 // FIXME: If we ever allow literal types to have virtual base classes, that 5399 // won't be true. 5400 const CXXMethodDecl *Callee = Found; 5401 unsigned PathLength = DynType->PathLength; 5402 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5403 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5404 const CXXMethodDecl *Overrider = 5405 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5406 if (Overrider) { 5407 Callee = Overrider; 5408 break; 5409 } 5410 } 5411 5412 // C++2a [class.abstract]p6: 5413 // the effect of making a virtual call to a pure virtual function [...] is 5414 // undefined 5415 if (Callee->isPure()) { 5416 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5417 Info.Note(Callee->getLocation(), diag::note_declared_at); 5418 return nullptr; 5419 } 5420 5421 // If necessary, walk the rest of the path to determine the sequence of 5422 // covariant adjustment steps to apply. 5423 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5424 Found->getReturnType())) { 5425 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5426 for (unsigned CovariantPathLength = PathLength + 1; 5427 CovariantPathLength != This.Designator.Entries.size(); 5428 ++CovariantPathLength) { 5429 const CXXRecordDecl *NextClass = 5430 getBaseClassType(This.Designator, CovariantPathLength); 5431 const CXXMethodDecl *Next = 5432 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5433 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5434 Next->getReturnType(), CovariantAdjustmentPath.back())) 5435 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5436 } 5437 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5438 CovariantAdjustmentPath.back())) 5439 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5440 } 5441 5442 // Perform 'this' adjustment. 5443 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5444 return nullptr; 5445 5446 return Callee; 5447 } 5448 5449 /// Perform the adjustment from a value returned by a virtual function to 5450 /// a value of the statically expected type, which may be a pointer or 5451 /// reference to a base class of the returned type. 5452 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5453 APValue &Result, 5454 ArrayRef<QualType> Path) { 5455 assert(Result.isLValue() && 5456 "unexpected kind of APValue for covariant return"); 5457 if (Result.isNullPointer()) 5458 return true; 5459 5460 LValue LVal; 5461 LVal.setFrom(Info.Ctx, Result); 5462 5463 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5464 for (unsigned I = 1; I != Path.size(); ++I) { 5465 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5466 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5467 if (OldClass != NewClass && 5468 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5469 return false; 5470 OldClass = NewClass; 5471 } 5472 5473 LVal.moveInto(Result); 5474 return true; 5475 } 5476 5477 /// Determine whether \p Base, which is known to be a direct base class of 5478 /// \p Derived, is a public base class. 5479 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5480 const CXXRecordDecl *Base) { 5481 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5482 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5483 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5484 return BaseSpec.getAccessSpecifier() == AS_public; 5485 } 5486 llvm_unreachable("Base is not a direct base of Derived"); 5487 } 5488 5489 /// Apply the given dynamic cast operation on the provided lvalue. 5490 /// 5491 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5492 /// to find a suitable target subobject. 5493 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5494 LValue &Ptr) { 5495 // We can't do anything with a non-symbolic pointer value. 5496 SubobjectDesignator &D = Ptr.Designator; 5497 if (D.Invalid) 5498 return false; 5499 5500 // C++ [expr.dynamic.cast]p6: 5501 // If v is a null pointer value, the result is a null pointer value. 5502 if (Ptr.isNullPointer() && !E->isGLValue()) 5503 return true; 5504 5505 // For all the other cases, we need the pointer to point to an object within 5506 // its lifetime / period of construction / destruction, and we need to know 5507 // its dynamic type. 5508 Optional<DynamicType> DynType = 5509 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5510 if (!DynType) 5511 return false; 5512 5513 // C++ [expr.dynamic.cast]p7: 5514 // If T is "pointer to cv void", then the result is a pointer to the most 5515 // derived object 5516 if (E->getType()->isVoidPointerType()) 5517 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5518 5519 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5520 assert(C && "dynamic_cast target is not void pointer nor class"); 5521 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5522 5523 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5524 // C++ [expr.dynamic.cast]p9: 5525 if (!E->isGLValue()) { 5526 // The value of a failed cast to pointer type is the null pointer value 5527 // of the required result type. 5528 Ptr.setNull(Info.Ctx, E->getType()); 5529 return true; 5530 } 5531 5532 // A failed cast to reference type throws [...] std::bad_cast. 5533 unsigned DiagKind; 5534 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5535 DynType->Type->isDerivedFrom(C))) 5536 DiagKind = 0; 5537 else if (!Paths || Paths->begin() == Paths->end()) 5538 DiagKind = 1; 5539 else if (Paths->isAmbiguous(CQT)) 5540 DiagKind = 2; 5541 else { 5542 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5543 DiagKind = 3; 5544 } 5545 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5546 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5547 << Info.Ctx.getRecordType(DynType->Type) 5548 << E->getType().getUnqualifiedType(); 5549 return false; 5550 }; 5551 5552 // Runtime check, phase 1: 5553 // Walk from the base subobject towards the derived object looking for the 5554 // target type. 5555 for (int PathLength = Ptr.Designator.Entries.size(); 5556 PathLength >= (int)DynType->PathLength; --PathLength) { 5557 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5558 if (declaresSameEntity(Class, C)) 5559 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5560 // We can only walk across public inheritance edges. 5561 if (PathLength > (int)DynType->PathLength && 5562 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5563 Class)) 5564 return RuntimeCheckFailed(nullptr); 5565 } 5566 5567 // Runtime check, phase 2: 5568 // Search the dynamic type for an unambiguous public base of type C. 5569 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5570 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5571 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5572 Paths.front().Access == AS_public) { 5573 // Downcast to the dynamic type... 5574 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5575 return false; 5576 // ... then upcast to the chosen base class subobject. 5577 for (CXXBasePathElement &Elem : Paths.front()) 5578 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5579 return false; 5580 return true; 5581 } 5582 5583 // Otherwise, the runtime check fails. 5584 return RuntimeCheckFailed(&Paths); 5585 } 5586 5587 namespace { 5588 struct StartLifetimeOfUnionMemberHandler { 5589 EvalInfo &Info; 5590 const Expr *LHSExpr; 5591 const FieldDecl *Field; 5592 bool DuringInit; 5593 bool Failed = false; 5594 static const AccessKinds AccessKind = AK_Assign; 5595 5596 typedef bool result_type; 5597 bool failed() { return Failed; } 5598 bool found(APValue &Subobj, QualType SubobjType) { 5599 // We are supposed to perform no initialization but begin the lifetime of 5600 // the object. We interpret that as meaning to do what default 5601 // initialization of the object would do if all constructors involved were 5602 // trivial: 5603 // * All base, non-variant member, and array element subobjects' lifetimes 5604 // begin 5605 // * No variant members' lifetimes begin 5606 // * All scalar subobjects whose lifetimes begin have indeterminate values 5607 assert(SubobjType->isUnionType()); 5608 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5609 // This union member is already active. If it's also in-lifetime, there's 5610 // nothing to do. 5611 if (Subobj.getUnionValue().hasValue()) 5612 return true; 5613 } else if (DuringInit) { 5614 // We're currently in the process of initializing a different union 5615 // member. If we carried on, that initialization would attempt to 5616 // store to an inactive union member, resulting in undefined behavior. 5617 Info.FFDiag(LHSExpr, 5618 diag::note_constexpr_union_member_change_during_init); 5619 return false; 5620 } 5621 APValue Result; 5622 Failed = !getDefaultInitValue(Field->getType(), Result); 5623 Subobj.setUnion(Field, Result); 5624 return true; 5625 } 5626 bool found(APSInt &Value, QualType SubobjType) { 5627 llvm_unreachable("wrong value kind for union object"); 5628 } 5629 bool found(APFloat &Value, QualType SubobjType) { 5630 llvm_unreachable("wrong value kind for union object"); 5631 } 5632 }; 5633 } // end anonymous namespace 5634 5635 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5636 5637 /// Handle a builtin simple-assignment or a call to a trivial assignment 5638 /// operator whose left-hand side might involve a union member access. If it 5639 /// does, implicitly start the lifetime of any accessed union elements per 5640 /// C++20 [class.union]5. 5641 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5642 const LValue &LHS) { 5643 if (LHS.InvalidBase || LHS.Designator.Invalid) 5644 return false; 5645 5646 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5647 // C++ [class.union]p5: 5648 // define the set S(E) of subexpressions of E as follows: 5649 unsigned PathLength = LHS.Designator.Entries.size(); 5650 for (const Expr *E = LHSExpr; E != nullptr;) { 5651 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5652 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5653 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5654 // Note that we can't implicitly start the lifetime of a reference, 5655 // so we don't need to proceed any further if we reach one. 5656 if (!FD || FD->getType()->isReferenceType()) 5657 break; 5658 5659 // ... and also contains A.B if B names a union member ... 5660 if (FD->getParent()->isUnion()) { 5661 // ... of a non-class, non-array type, or of a class type with a 5662 // trivial default constructor that is not deleted, or an array of 5663 // such types. 5664 auto *RD = 5665 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5666 if (!RD || RD->hasTrivialDefaultConstructor()) 5667 UnionPathLengths.push_back({PathLength - 1, FD}); 5668 } 5669 5670 E = ME->getBase(); 5671 --PathLength; 5672 assert(declaresSameEntity(FD, 5673 LHS.Designator.Entries[PathLength] 5674 .getAsBaseOrMember().getPointer())); 5675 5676 // -- If E is of the form A[B] and is interpreted as a built-in array 5677 // subscripting operator, S(E) is [S(the array operand, if any)]. 5678 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5679 // Step over an ArrayToPointerDecay implicit cast. 5680 auto *Base = ASE->getBase()->IgnoreImplicit(); 5681 if (!Base->getType()->isArrayType()) 5682 break; 5683 5684 E = Base; 5685 --PathLength; 5686 5687 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5688 // Step over a derived-to-base conversion. 5689 E = ICE->getSubExpr(); 5690 if (ICE->getCastKind() == CK_NoOp) 5691 continue; 5692 if (ICE->getCastKind() != CK_DerivedToBase && 5693 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5694 break; 5695 // Walk path backwards as we walk up from the base to the derived class. 5696 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5697 --PathLength; 5698 (void)Elt; 5699 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5700 LHS.Designator.Entries[PathLength] 5701 .getAsBaseOrMember().getPointer())); 5702 } 5703 5704 // -- Otherwise, S(E) is empty. 5705 } else { 5706 break; 5707 } 5708 } 5709 5710 // Common case: no unions' lifetimes are started. 5711 if (UnionPathLengths.empty()) 5712 return true; 5713 5714 // if modification of X [would access an inactive union member], an object 5715 // of the type of X is implicitly created 5716 CompleteObject Obj = 5717 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5718 if (!Obj) 5719 return false; 5720 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5721 llvm::reverse(UnionPathLengths)) { 5722 // Form a designator for the union object. 5723 SubobjectDesignator D = LHS.Designator; 5724 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5725 5726 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5727 ConstructionPhase::AfterBases; 5728 StartLifetimeOfUnionMemberHandler StartLifetime{ 5729 Info, LHSExpr, LengthAndField.second, DuringInit}; 5730 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5731 return false; 5732 } 5733 5734 return true; 5735 } 5736 5737 namespace { 5738 typedef SmallVector<APValue, 8> ArgVector; 5739 } 5740 5741 /// EvaluateArgs - Evaluate the arguments to a function call. 5742 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues, 5743 EvalInfo &Info, const FunctionDecl *Callee) { 5744 bool Success = true; 5745 llvm::SmallBitVector ForbiddenNullArgs; 5746 if (Callee->hasAttr<NonNullAttr>()) { 5747 ForbiddenNullArgs.resize(Args.size()); 5748 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 5749 if (!Attr->args_size()) { 5750 ForbiddenNullArgs.set(); 5751 break; 5752 } else 5753 for (auto Idx : Attr->args()) { 5754 unsigned ASTIdx = Idx.getASTIndex(); 5755 if (ASTIdx >= Args.size()) 5756 continue; 5757 ForbiddenNullArgs[ASTIdx] = 1; 5758 } 5759 } 5760 } 5761 // FIXME: This is the wrong evaluation order for an assignment operator 5762 // called via operator syntax. 5763 for (unsigned Idx = 0; Idx < Args.size(); Idx++) { 5764 if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) { 5765 // If we're checking for a potential constant expression, evaluate all 5766 // initializers even if some of them fail. 5767 if (!Info.noteFailure()) 5768 return false; 5769 Success = false; 5770 } else if (!ForbiddenNullArgs.empty() && 5771 ForbiddenNullArgs[Idx] && 5772 ArgValues[Idx].isLValue() && 5773 ArgValues[Idx].isNullPointer()) { 5774 Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed); 5775 if (!Info.noteFailure()) 5776 return false; 5777 Success = false; 5778 } 5779 } 5780 return Success; 5781 } 5782 5783 /// Evaluate a function call. 5784 static bool HandleFunctionCall(SourceLocation CallLoc, 5785 const FunctionDecl *Callee, const LValue *This, 5786 ArrayRef<const Expr*> Args, const Stmt *Body, 5787 EvalInfo &Info, APValue &Result, 5788 const LValue *ResultSlot) { 5789 ArgVector ArgValues(Args.size()); 5790 if (!EvaluateArgs(Args, ArgValues, Info, Callee)) 5791 return false; 5792 5793 if (!Info.CheckCallLimit(CallLoc)) 5794 return false; 5795 5796 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 5797 5798 // For a trivial copy or move assignment, perform an APValue copy. This is 5799 // essential for unions, where the operations performed by the assignment 5800 // operator cannot be represented as statements. 5801 // 5802 // Skip this for non-union classes with no fields; in that case, the defaulted 5803 // copy/move does not actually read the object. 5804 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 5805 if (MD && MD->isDefaulted() && 5806 (MD->getParent()->isUnion() || 5807 (MD->isTrivial() && 5808 isReadByLvalueToRvalueConversion(MD->getParent())))) { 5809 assert(This && 5810 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 5811 LValue RHS; 5812 RHS.setFrom(Info.Ctx, ArgValues[0]); 5813 APValue RHSValue; 5814 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS, 5815 RHSValue, MD->getParent()->isUnion())) 5816 return false; 5817 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 5818 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 5819 return false; 5820 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 5821 RHSValue)) 5822 return false; 5823 This->moveInto(Result); 5824 return true; 5825 } else if (MD && isLambdaCallOperator(MD)) { 5826 // We're in a lambda; determine the lambda capture field maps unless we're 5827 // just constexpr checking a lambda's call operator. constexpr checking is 5828 // done before the captures have been added to the closure object (unless 5829 // we're inferring constexpr-ness), so we don't have access to them in this 5830 // case. But since we don't need the captures to constexpr check, we can 5831 // just ignore them. 5832 if (!Info.checkingPotentialConstantExpression()) 5833 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 5834 Frame.LambdaThisCaptureField); 5835 } 5836 5837 StmtResult Ret = {Result, ResultSlot}; 5838 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 5839 if (ESR == ESR_Succeeded) { 5840 if (Callee->getReturnType()->isVoidType()) 5841 return true; 5842 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 5843 } 5844 return ESR == ESR_Returned; 5845 } 5846 5847 /// Evaluate a constructor call. 5848 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5849 APValue *ArgValues, 5850 const CXXConstructorDecl *Definition, 5851 EvalInfo &Info, APValue &Result) { 5852 SourceLocation CallLoc = E->getExprLoc(); 5853 if (!Info.CheckCallLimit(CallLoc)) 5854 return false; 5855 5856 const CXXRecordDecl *RD = Definition->getParent(); 5857 if (RD->getNumVBases()) { 5858 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 5859 return false; 5860 } 5861 5862 EvalInfo::EvaluatingConstructorRAII EvalObj( 5863 Info, 5864 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 5865 RD->getNumBases()); 5866 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 5867 5868 // FIXME: Creating an APValue just to hold a nonexistent return value is 5869 // wasteful. 5870 APValue RetVal; 5871 StmtResult Ret = {RetVal, nullptr}; 5872 5873 // If it's a delegating constructor, delegate. 5874 if (Definition->isDelegatingConstructor()) { 5875 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 5876 { 5877 FullExpressionRAII InitScope(Info); 5878 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 5879 !InitScope.destroy()) 5880 return false; 5881 } 5882 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5883 } 5884 5885 // For a trivial copy or move constructor, perform an APValue copy. This is 5886 // essential for unions (or classes with anonymous union members), where the 5887 // operations performed by the constructor cannot be represented by 5888 // ctor-initializers. 5889 // 5890 // Skip this for empty non-union classes; we should not perform an 5891 // lvalue-to-rvalue conversion on them because their copy constructor does not 5892 // actually read them. 5893 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 5894 (Definition->getParent()->isUnion() || 5895 (Definition->isTrivial() && 5896 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 5897 LValue RHS; 5898 RHS.setFrom(Info.Ctx, ArgValues[0]); 5899 return handleLValueToRValueConversion( 5900 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 5901 RHS, Result, Definition->getParent()->isUnion()); 5902 } 5903 5904 // Reserve space for the struct members. 5905 if (!Result.hasValue()) { 5906 if (!RD->isUnion()) 5907 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 5908 std::distance(RD->field_begin(), RD->field_end())); 5909 else 5910 // A union starts with no active member. 5911 Result = APValue((const FieldDecl*)nullptr); 5912 } 5913 5914 if (RD->isInvalidDecl()) return false; 5915 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5916 5917 // A scope for temporaries lifetime-extended by reference members. 5918 BlockScopeRAII LifetimeExtendedScope(Info); 5919 5920 bool Success = true; 5921 unsigned BasesSeen = 0; 5922 #ifndef NDEBUG 5923 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 5924 #endif 5925 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 5926 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 5927 // We might be initializing the same field again if this is an indirect 5928 // field initialization. 5929 if (FieldIt == RD->field_end() || 5930 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 5931 assert(Indirect && "fields out of order?"); 5932 return; 5933 } 5934 5935 // Default-initialize any fields with no explicit initializer. 5936 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 5937 assert(FieldIt != RD->field_end() && "missing field?"); 5938 if (!FieldIt->isUnnamedBitfield()) 5939 Success &= getDefaultInitValue( 5940 FieldIt->getType(), 5941 Result.getStructField(FieldIt->getFieldIndex())); 5942 } 5943 ++FieldIt; 5944 }; 5945 for (const auto *I : Definition->inits()) { 5946 LValue Subobject = This; 5947 LValue SubobjectParent = This; 5948 APValue *Value = &Result; 5949 5950 // Determine the subobject to initialize. 5951 FieldDecl *FD = nullptr; 5952 if (I->isBaseInitializer()) { 5953 QualType BaseType(I->getBaseClass(), 0); 5954 #ifndef NDEBUG 5955 // Non-virtual base classes are initialized in the order in the class 5956 // definition. We have already checked for virtual base classes. 5957 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 5958 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 5959 "base class initializers not in expected order"); 5960 ++BaseIt; 5961 #endif 5962 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 5963 BaseType->getAsCXXRecordDecl(), &Layout)) 5964 return false; 5965 Value = &Result.getStructBase(BasesSeen++); 5966 } else if ((FD = I->getMember())) { 5967 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 5968 return false; 5969 if (RD->isUnion()) { 5970 Result = APValue(FD); 5971 Value = &Result.getUnionValue(); 5972 } else { 5973 SkipToField(FD, false); 5974 Value = &Result.getStructField(FD->getFieldIndex()); 5975 } 5976 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 5977 // Walk the indirect field decl's chain to find the object to initialize, 5978 // and make sure we've initialized every step along it. 5979 auto IndirectFieldChain = IFD->chain(); 5980 for (auto *C : IndirectFieldChain) { 5981 FD = cast<FieldDecl>(C); 5982 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 5983 // Switch the union field if it differs. This happens if we had 5984 // preceding zero-initialization, and we're now initializing a union 5985 // subobject other than the first. 5986 // FIXME: In this case, the values of the other subobjects are 5987 // specified, since zero-initialization sets all padding bits to zero. 5988 if (!Value->hasValue() || 5989 (Value->isUnion() && Value->getUnionField() != FD)) { 5990 if (CD->isUnion()) 5991 *Value = APValue(FD); 5992 else 5993 // FIXME: This immediately starts the lifetime of all members of 5994 // an anonymous struct. It would be preferable to strictly start 5995 // member lifetime in initialization order. 5996 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 5997 } 5998 // Store Subobject as its parent before updating it for the last element 5999 // in the chain. 6000 if (C == IndirectFieldChain.back()) 6001 SubobjectParent = Subobject; 6002 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6003 return false; 6004 if (CD->isUnion()) 6005 Value = &Value->getUnionValue(); 6006 else { 6007 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6008 SkipToField(FD, true); 6009 Value = &Value->getStructField(FD->getFieldIndex()); 6010 } 6011 } 6012 } else { 6013 llvm_unreachable("unknown base initializer kind"); 6014 } 6015 6016 // Need to override This for implicit field initializers as in this case 6017 // This refers to innermost anonymous struct/union containing initializer, 6018 // not to currently constructed class. 6019 const Expr *Init = I->getInit(); 6020 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6021 isa<CXXDefaultInitExpr>(Init)); 6022 FullExpressionRAII InitScope(Info); 6023 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6024 (FD && FD->isBitField() && 6025 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6026 // If we're checking for a potential constant expression, evaluate all 6027 // initializers even if some of them fail. 6028 if (!Info.noteFailure()) 6029 return false; 6030 Success = false; 6031 } 6032 6033 // This is the point at which the dynamic type of the object becomes this 6034 // class type. 6035 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6036 EvalObj.finishedConstructingBases(); 6037 } 6038 6039 // Default-initialize any remaining fields. 6040 if (!RD->isUnion()) { 6041 for (; FieldIt != RD->field_end(); ++FieldIt) { 6042 if (!FieldIt->isUnnamedBitfield()) 6043 Success &= getDefaultInitValue( 6044 FieldIt->getType(), 6045 Result.getStructField(FieldIt->getFieldIndex())); 6046 } 6047 } 6048 6049 EvalObj.finishedConstructingFields(); 6050 6051 return Success && 6052 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6053 LifetimeExtendedScope.destroy(); 6054 } 6055 6056 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6057 ArrayRef<const Expr*> Args, 6058 const CXXConstructorDecl *Definition, 6059 EvalInfo &Info, APValue &Result) { 6060 ArgVector ArgValues(Args.size()); 6061 if (!EvaluateArgs(Args, ArgValues, Info, Definition)) 6062 return false; 6063 6064 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 6065 Info, Result); 6066 } 6067 6068 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6069 const LValue &This, APValue &Value, 6070 QualType T) { 6071 // Objects can only be destroyed while they're within their lifetimes. 6072 // FIXME: We have no representation for whether an object of type nullptr_t 6073 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6074 // as indeterminate instead? 6075 if (Value.isAbsent() && !T->isNullPtrType()) { 6076 APValue Printable; 6077 This.moveInto(Printable); 6078 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6079 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6080 return false; 6081 } 6082 6083 // Invent an expression for location purposes. 6084 // FIXME: We shouldn't need to do this. 6085 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 6086 6087 // For arrays, destroy elements right-to-left. 6088 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6089 uint64_t Size = CAT->getSize().getZExtValue(); 6090 QualType ElemT = CAT->getElementType(); 6091 6092 LValue ElemLV = This; 6093 ElemLV.addArray(Info, &LocE, CAT); 6094 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6095 return false; 6096 6097 // Ensure that we have actual array elements available to destroy; the 6098 // destructors might mutate the value, so we can't run them on the array 6099 // filler. 6100 if (Size && Size > Value.getArrayInitializedElts()) 6101 expandArray(Value, Value.getArraySize() - 1); 6102 6103 for (; Size != 0; --Size) { 6104 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6105 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6106 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6107 return false; 6108 } 6109 6110 // End the lifetime of this array now. 6111 Value = APValue(); 6112 return true; 6113 } 6114 6115 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6116 if (!RD) { 6117 if (T.isDestructedType()) { 6118 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6119 return false; 6120 } 6121 6122 Value = APValue(); 6123 return true; 6124 } 6125 6126 if (RD->getNumVBases()) { 6127 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6128 return false; 6129 } 6130 6131 const CXXDestructorDecl *DD = RD->getDestructor(); 6132 if (!DD && !RD->hasTrivialDestructor()) { 6133 Info.FFDiag(CallLoc); 6134 return false; 6135 } 6136 6137 if (!DD || DD->isTrivial() || 6138 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6139 // A trivial destructor just ends the lifetime of the object. Check for 6140 // this case before checking for a body, because we might not bother 6141 // building a body for a trivial destructor. Note that it doesn't matter 6142 // whether the destructor is constexpr in this case; all trivial 6143 // destructors are constexpr. 6144 // 6145 // If an anonymous union would be destroyed, some enclosing destructor must 6146 // have been explicitly defined, and the anonymous union destruction should 6147 // have no effect. 6148 Value = APValue(); 6149 return true; 6150 } 6151 6152 if (!Info.CheckCallLimit(CallLoc)) 6153 return false; 6154 6155 const FunctionDecl *Definition = nullptr; 6156 const Stmt *Body = DD->getBody(Definition); 6157 6158 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6159 return false; 6160 6161 CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr); 6162 6163 // We're now in the period of destruction of this object. 6164 unsigned BasesLeft = RD->getNumBases(); 6165 EvalInfo::EvaluatingDestructorRAII EvalObj( 6166 Info, 6167 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6168 if (!EvalObj.DidInsert) { 6169 // C++2a [class.dtor]p19: 6170 // the behavior is undefined if the destructor is invoked for an object 6171 // whose lifetime has ended 6172 // (Note that formally the lifetime ends when the period of destruction 6173 // begins, even though certain uses of the object remain valid until the 6174 // period of destruction ends.) 6175 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6176 return false; 6177 } 6178 6179 // FIXME: Creating an APValue just to hold a nonexistent return value is 6180 // wasteful. 6181 APValue RetVal; 6182 StmtResult Ret = {RetVal, nullptr}; 6183 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6184 return false; 6185 6186 // A union destructor does not implicitly destroy its members. 6187 if (RD->isUnion()) 6188 return true; 6189 6190 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6191 6192 // We don't have a good way to iterate fields in reverse, so collect all the 6193 // fields first and then walk them backwards. 6194 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6195 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6196 if (FD->isUnnamedBitfield()) 6197 continue; 6198 6199 LValue Subobject = This; 6200 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6201 return false; 6202 6203 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6204 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6205 FD->getType())) 6206 return false; 6207 } 6208 6209 if (BasesLeft != 0) 6210 EvalObj.startedDestroyingBases(); 6211 6212 // Destroy base classes in reverse order. 6213 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6214 --BasesLeft; 6215 6216 QualType BaseType = Base.getType(); 6217 LValue Subobject = This; 6218 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6219 BaseType->getAsCXXRecordDecl(), &Layout)) 6220 return false; 6221 6222 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6223 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6224 BaseType)) 6225 return false; 6226 } 6227 assert(BasesLeft == 0 && "NumBases was wrong?"); 6228 6229 // The period of destruction ends now. The object is gone. 6230 Value = APValue(); 6231 return true; 6232 } 6233 6234 namespace { 6235 struct DestroyObjectHandler { 6236 EvalInfo &Info; 6237 const Expr *E; 6238 const LValue &This; 6239 const AccessKinds AccessKind; 6240 6241 typedef bool result_type; 6242 bool failed() { return false; } 6243 bool found(APValue &Subobj, QualType SubobjType) { 6244 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6245 SubobjType); 6246 } 6247 bool found(APSInt &Value, QualType SubobjType) { 6248 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6249 return false; 6250 } 6251 bool found(APFloat &Value, QualType SubobjType) { 6252 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6253 return false; 6254 } 6255 }; 6256 } 6257 6258 /// Perform a destructor or pseudo-destructor call on the given object, which 6259 /// might in general not be a complete object. 6260 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6261 const LValue &This, QualType ThisType) { 6262 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6263 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6264 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6265 } 6266 6267 /// Destroy and end the lifetime of the given complete object. 6268 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6269 APValue::LValueBase LVBase, APValue &Value, 6270 QualType T) { 6271 // If we've had an unmodeled side-effect, we can't rely on mutable state 6272 // (such as the object we're about to destroy) being correct. 6273 if (Info.EvalStatus.HasSideEffects) 6274 return false; 6275 6276 LValue LV; 6277 LV.set({LVBase}); 6278 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6279 } 6280 6281 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6282 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6283 LValue &Result) { 6284 if (Info.checkingPotentialConstantExpression() || 6285 Info.SpeculativeEvaluationDepth) 6286 return false; 6287 6288 // This is permitted only within a call to std::allocator<T>::allocate. 6289 auto Caller = Info.getStdAllocatorCaller("allocate"); 6290 if (!Caller) { 6291 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6292 ? diag::note_constexpr_new_untyped 6293 : diag::note_constexpr_new); 6294 return false; 6295 } 6296 6297 QualType ElemType = Caller.ElemType; 6298 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6299 Info.FFDiag(E->getExprLoc(), 6300 diag::note_constexpr_new_not_complete_object_type) 6301 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6302 return false; 6303 } 6304 6305 APSInt ByteSize; 6306 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6307 return false; 6308 bool IsNothrow = false; 6309 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6310 EvaluateIgnoredValue(Info, E->getArg(I)); 6311 IsNothrow |= E->getType()->isNothrowT(); 6312 } 6313 6314 CharUnits ElemSize; 6315 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6316 return false; 6317 APInt Size, Remainder; 6318 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6319 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6320 if (Remainder != 0) { 6321 // This likely indicates a bug in the implementation of 'std::allocator'. 6322 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6323 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6324 return false; 6325 } 6326 6327 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6328 if (IsNothrow) { 6329 Result.setNull(Info.Ctx, E->getType()); 6330 return true; 6331 } 6332 6333 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6334 return false; 6335 } 6336 6337 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6338 ArrayType::Normal, 0); 6339 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6340 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6341 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6342 return true; 6343 } 6344 6345 static bool hasVirtualDestructor(QualType T) { 6346 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6347 if (CXXDestructorDecl *DD = RD->getDestructor()) 6348 return DD->isVirtual(); 6349 return false; 6350 } 6351 6352 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6353 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6354 if (CXXDestructorDecl *DD = RD->getDestructor()) 6355 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6356 return nullptr; 6357 } 6358 6359 /// Check that the given object is a suitable pointer to a heap allocation that 6360 /// still exists and is of the right kind for the purpose of a deletion. 6361 /// 6362 /// On success, returns the heap allocation to deallocate. On failure, produces 6363 /// a diagnostic and returns None. 6364 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6365 const LValue &Pointer, 6366 DynAlloc::Kind DeallocKind) { 6367 auto PointerAsString = [&] { 6368 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6369 }; 6370 6371 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6372 if (!DA) { 6373 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6374 << PointerAsString(); 6375 if (Pointer.Base) 6376 NoteLValueLocation(Info, Pointer.Base); 6377 return None; 6378 } 6379 6380 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6381 if (!Alloc) { 6382 Info.FFDiag(E, diag::note_constexpr_double_delete); 6383 return None; 6384 } 6385 6386 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6387 if (DeallocKind != (*Alloc)->getKind()) { 6388 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6389 << DeallocKind << (*Alloc)->getKind() << AllocType; 6390 NoteLValueLocation(Info, Pointer.Base); 6391 return None; 6392 } 6393 6394 bool Subobject = false; 6395 if (DeallocKind == DynAlloc::New) { 6396 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6397 Pointer.Designator.isOnePastTheEnd(); 6398 } else { 6399 Subobject = Pointer.Designator.Entries.size() != 1 || 6400 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6401 } 6402 if (Subobject) { 6403 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6404 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6405 return None; 6406 } 6407 6408 return Alloc; 6409 } 6410 6411 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6412 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6413 if (Info.checkingPotentialConstantExpression() || 6414 Info.SpeculativeEvaluationDepth) 6415 return false; 6416 6417 // This is permitted only within a call to std::allocator<T>::deallocate. 6418 if (!Info.getStdAllocatorCaller("deallocate")) { 6419 Info.FFDiag(E->getExprLoc()); 6420 return true; 6421 } 6422 6423 LValue Pointer; 6424 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6425 return false; 6426 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6427 EvaluateIgnoredValue(Info, E->getArg(I)); 6428 6429 if (Pointer.Designator.Invalid) 6430 return false; 6431 6432 // Deleting a null pointer has no effect. 6433 if (Pointer.isNullPointer()) 6434 return true; 6435 6436 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6437 return false; 6438 6439 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6440 return true; 6441 } 6442 6443 //===----------------------------------------------------------------------===// 6444 // Generic Evaluation 6445 //===----------------------------------------------------------------------===// 6446 namespace { 6447 6448 class BitCastBuffer { 6449 // FIXME: We're going to need bit-level granularity when we support 6450 // bit-fields. 6451 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6452 // we don't support a host or target where that is the case. Still, we should 6453 // use a more generic type in case we ever do. 6454 SmallVector<Optional<unsigned char>, 32> Bytes; 6455 6456 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6457 "Need at least 8 bit unsigned char"); 6458 6459 bool TargetIsLittleEndian; 6460 6461 public: 6462 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6463 : Bytes(Width.getQuantity()), 6464 TargetIsLittleEndian(TargetIsLittleEndian) {} 6465 6466 LLVM_NODISCARD 6467 bool readObject(CharUnits Offset, CharUnits Width, 6468 SmallVectorImpl<unsigned char> &Output) const { 6469 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6470 // If a byte of an integer is uninitialized, then the whole integer is 6471 // uninitalized. 6472 if (!Bytes[I.getQuantity()]) 6473 return false; 6474 Output.push_back(*Bytes[I.getQuantity()]); 6475 } 6476 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6477 std::reverse(Output.begin(), Output.end()); 6478 return true; 6479 } 6480 6481 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6482 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6483 std::reverse(Input.begin(), Input.end()); 6484 6485 size_t Index = 0; 6486 for (unsigned char Byte : Input) { 6487 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6488 Bytes[Offset.getQuantity() + Index] = Byte; 6489 ++Index; 6490 } 6491 } 6492 6493 size_t size() { return Bytes.size(); } 6494 }; 6495 6496 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6497 /// target would represent the value at runtime. 6498 class APValueToBufferConverter { 6499 EvalInfo &Info; 6500 BitCastBuffer Buffer; 6501 const CastExpr *BCE; 6502 6503 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6504 const CastExpr *BCE) 6505 : Info(Info), 6506 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6507 BCE(BCE) {} 6508 6509 bool visit(const APValue &Val, QualType Ty) { 6510 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6511 } 6512 6513 // Write out Val with type Ty into Buffer starting at Offset. 6514 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6515 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6516 6517 // As a special case, nullptr_t has an indeterminate value. 6518 if (Ty->isNullPtrType()) 6519 return true; 6520 6521 // Dig through Src to find the byte at SrcOffset. 6522 switch (Val.getKind()) { 6523 case APValue::Indeterminate: 6524 case APValue::None: 6525 return true; 6526 6527 case APValue::Int: 6528 return visitInt(Val.getInt(), Ty, Offset); 6529 case APValue::Float: 6530 return visitFloat(Val.getFloat(), Ty, Offset); 6531 case APValue::Array: 6532 return visitArray(Val, Ty, Offset); 6533 case APValue::Struct: 6534 return visitRecord(Val, Ty, Offset); 6535 6536 case APValue::ComplexInt: 6537 case APValue::ComplexFloat: 6538 case APValue::Vector: 6539 case APValue::FixedPoint: 6540 // FIXME: We should support these. 6541 6542 case APValue::Union: 6543 case APValue::MemberPointer: 6544 case APValue::AddrLabelDiff: { 6545 Info.FFDiag(BCE->getBeginLoc(), 6546 diag::note_constexpr_bit_cast_unsupported_type) 6547 << Ty; 6548 return false; 6549 } 6550 6551 case APValue::LValue: 6552 llvm_unreachable("LValue subobject in bit_cast?"); 6553 } 6554 llvm_unreachable("Unhandled APValue::ValueKind"); 6555 } 6556 6557 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6558 const RecordDecl *RD = Ty->getAsRecordDecl(); 6559 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6560 6561 // Visit the base classes. 6562 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6563 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6564 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6565 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6566 6567 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6568 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6569 return false; 6570 } 6571 } 6572 6573 // Visit the fields. 6574 unsigned FieldIdx = 0; 6575 for (FieldDecl *FD : RD->fields()) { 6576 if (FD->isBitField()) { 6577 Info.FFDiag(BCE->getBeginLoc(), 6578 diag::note_constexpr_bit_cast_unsupported_bitfield); 6579 return false; 6580 } 6581 6582 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6583 6584 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6585 "only bit-fields can have sub-char alignment"); 6586 CharUnits FieldOffset = 6587 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6588 QualType FieldTy = FD->getType(); 6589 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6590 return false; 6591 ++FieldIdx; 6592 } 6593 6594 return true; 6595 } 6596 6597 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6598 const auto *CAT = 6599 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6600 if (!CAT) 6601 return false; 6602 6603 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6604 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6605 unsigned ArraySize = Val.getArraySize(); 6606 // First, initialize the initialized elements. 6607 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6608 const APValue &SubObj = Val.getArrayInitializedElt(I); 6609 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6610 return false; 6611 } 6612 6613 // Next, initialize the rest of the array using the filler. 6614 if (Val.hasArrayFiller()) { 6615 const APValue &Filler = Val.getArrayFiller(); 6616 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6617 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6618 return false; 6619 } 6620 } 6621 6622 return true; 6623 } 6624 6625 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6626 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty); 6627 SmallVector<unsigned char, 8> Bytes(Width.getQuantity()); 6628 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity()); 6629 Buffer.writeObject(Offset, Bytes); 6630 return true; 6631 } 6632 6633 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6634 APSInt AsInt(Val.bitcastToAPInt()); 6635 return visitInt(AsInt, Ty, Offset); 6636 } 6637 6638 public: 6639 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6640 const CastExpr *BCE) { 6641 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6642 APValueToBufferConverter Converter(Info, DstSize, BCE); 6643 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6644 return None; 6645 return Converter.Buffer; 6646 } 6647 }; 6648 6649 /// Write an BitCastBuffer into an APValue. 6650 class BufferToAPValueConverter { 6651 EvalInfo &Info; 6652 const BitCastBuffer &Buffer; 6653 const CastExpr *BCE; 6654 6655 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6656 const CastExpr *BCE) 6657 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6658 6659 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6660 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6661 // Ideally this will be unreachable. 6662 llvm::NoneType unsupportedType(QualType Ty) { 6663 Info.FFDiag(BCE->getBeginLoc(), 6664 diag::note_constexpr_bit_cast_unsupported_type) 6665 << Ty; 6666 return None; 6667 } 6668 6669 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6670 const EnumType *EnumSugar = nullptr) { 6671 if (T->isNullPtrType()) { 6672 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6673 return APValue((Expr *)nullptr, 6674 /*Offset=*/CharUnits::fromQuantity(NullValue), 6675 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6676 } 6677 6678 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6679 SmallVector<uint8_t, 8> Bytes; 6680 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6681 // If this is std::byte or unsigned char, then its okay to store an 6682 // indeterminate value. 6683 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 6684 bool IsUChar = 6685 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 6686 T->isSpecificBuiltinType(BuiltinType::Char_U)); 6687 if (!IsStdByte && !IsUChar) { 6688 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 6689 Info.FFDiag(BCE->getExprLoc(), 6690 diag::note_constexpr_bit_cast_indet_dest) 6691 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 6692 return None; 6693 } 6694 6695 return APValue::IndeterminateValue(); 6696 } 6697 6698 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 6699 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 6700 6701 if (T->isIntegralOrEnumerationType()) { 6702 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 6703 return APValue(Val); 6704 } 6705 6706 if (T->isRealFloatingType()) { 6707 const llvm::fltSemantics &Semantics = 6708 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6709 return APValue(APFloat(Semantics, Val)); 6710 } 6711 6712 return unsupportedType(QualType(T, 0)); 6713 } 6714 6715 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 6716 const RecordDecl *RD = RTy->getAsRecordDecl(); 6717 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6718 6719 unsigned NumBases = 0; 6720 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6721 NumBases = CXXRD->getNumBases(); 6722 6723 APValue ResultVal(APValue::UninitStruct(), NumBases, 6724 std::distance(RD->field_begin(), RD->field_end())); 6725 6726 // Visit the base classes. 6727 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6728 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6729 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6730 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6731 if (BaseDecl->isEmpty() || 6732 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 6733 continue; 6734 6735 Optional<APValue> SubObj = visitType( 6736 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 6737 if (!SubObj) 6738 return None; 6739 ResultVal.getStructBase(I) = *SubObj; 6740 } 6741 } 6742 6743 // Visit the fields. 6744 unsigned FieldIdx = 0; 6745 for (FieldDecl *FD : RD->fields()) { 6746 // FIXME: We don't currently support bit-fields. A lot of the logic for 6747 // this is in CodeGen, so we need to factor it around. 6748 if (FD->isBitField()) { 6749 Info.FFDiag(BCE->getBeginLoc(), 6750 diag::note_constexpr_bit_cast_unsupported_bitfield); 6751 return None; 6752 } 6753 6754 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6755 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 6756 6757 CharUnits FieldOffset = 6758 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 6759 Offset; 6760 QualType FieldTy = FD->getType(); 6761 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 6762 if (!SubObj) 6763 return None; 6764 ResultVal.getStructField(FieldIdx) = *SubObj; 6765 ++FieldIdx; 6766 } 6767 6768 return ResultVal; 6769 } 6770 6771 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 6772 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 6773 assert(!RepresentationType.isNull() && 6774 "enum forward decl should be caught by Sema"); 6775 const auto *AsBuiltin = 6776 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 6777 // Recurse into the underlying type. Treat std::byte transparently as 6778 // unsigned char. 6779 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 6780 } 6781 6782 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 6783 size_t Size = Ty->getSize().getLimitedValue(); 6784 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 6785 6786 APValue ArrayValue(APValue::UninitArray(), Size, Size); 6787 for (size_t I = 0; I != Size; ++I) { 6788 Optional<APValue> ElementValue = 6789 visitType(Ty->getElementType(), Offset + I * ElementWidth); 6790 if (!ElementValue) 6791 return None; 6792 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 6793 } 6794 6795 return ArrayValue; 6796 } 6797 6798 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 6799 return unsupportedType(QualType(Ty, 0)); 6800 } 6801 6802 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 6803 QualType Can = Ty.getCanonicalType(); 6804 6805 switch (Can->getTypeClass()) { 6806 #define TYPE(Class, Base) \ 6807 case Type::Class: \ 6808 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 6809 #define ABSTRACT_TYPE(Class, Base) 6810 #define NON_CANONICAL_TYPE(Class, Base) \ 6811 case Type::Class: \ 6812 llvm_unreachable("non-canonical type should be impossible!"); 6813 #define DEPENDENT_TYPE(Class, Base) \ 6814 case Type::Class: \ 6815 llvm_unreachable( \ 6816 "dependent types aren't supported in the constant evaluator!"); 6817 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 6818 case Type::Class: \ 6819 llvm_unreachable("either dependent or not canonical!"); 6820 #include "clang/AST/TypeNodes.inc" 6821 } 6822 llvm_unreachable("Unhandled Type::TypeClass"); 6823 } 6824 6825 public: 6826 // Pull out a full value of type DstType. 6827 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 6828 const CastExpr *BCE) { 6829 BufferToAPValueConverter Converter(Info, Buffer, BCE); 6830 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 6831 } 6832 }; 6833 6834 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 6835 QualType Ty, EvalInfo *Info, 6836 const ASTContext &Ctx, 6837 bool CheckingDest) { 6838 Ty = Ty.getCanonicalType(); 6839 6840 auto diag = [&](int Reason) { 6841 if (Info) 6842 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 6843 << CheckingDest << (Reason == 4) << Reason; 6844 return false; 6845 }; 6846 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 6847 if (Info) 6848 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 6849 << NoteTy << Construct << Ty; 6850 return false; 6851 }; 6852 6853 if (Ty->isUnionType()) 6854 return diag(0); 6855 if (Ty->isPointerType()) 6856 return diag(1); 6857 if (Ty->isMemberPointerType()) 6858 return diag(2); 6859 if (Ty.isVolatileQualified()) 6860 return diag(3); 6861 6862 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 6863 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 6864 for (CXXBaseSpecifier &BS : CXXRD->bases()) 6865 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 6866 CheckingDest)) 6867 return note(1, BS.getType(), BS.getBeginLoc()); 6868 } 6869 for (FieldDecl *FD : Record->fields()) { 6870 if (FD->getType()->isReferenceType()) 6871 return diag(4); 6872 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 6873 CheckingDest)) 6874 return note(0, FD->getType(), FD->getBeginLoc()); 6875 } 6876 } 6877 6878 if (Ty->isArrayType() && 6879 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 6880 Info, Ctx, CheckingDest)) 6881 return false; 6882 6883 return true; 6884 } 6885 6886 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 6887 const ASTContext &Ctx, 6888 const CastExpr *BCE) { 6889 bool DestOK = checkBitCastConstexprEligibilityType( 6890 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 6891 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 6892 BCE->getBeginLoc(), 6893 BCE->getSubExpr()->getType(), Info, Ctx, false); 6894 return SourceOK; 6895 } 6896 6897 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 6898 APValue &SourceValue, 6899 const CastExpr *BCE) { 6900 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 6901 "no host or target supports non 8-bit chars"); 6902 assert(SourceValue.isLValue() && 6903 "LValueToRValueBitcast requires an lvalue operand!"); 6904 6905 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 6906 return false; 6907 6908 LValue SourceLValue; 6909 APValue SourceRValue; 6910 SourceLValue.setFrom(Info.Ctx, SourceValue); 6911 if (!handleLValueToRValueConversion( 6912 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 6913 SourceRValue, /*WantObjectRepresentation=*/true)) 6914 return false; 6915 6916 // Read out SourceValue into a char buffer. 6917 Optional<BitCastBuffer> Buffer = 6918 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 6919 if (!Buffer) 6920 return false; 6921 6922 // Write out the buffer into a new APValue. 6923 Optional<APValue> MaybeDestValue = 6924 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 6925 if (!MaybeDestValue) 6926 return false; 6927 6928 DestValue = std::move(*MaybeDestValue); 6929 return true; 6930 } 6931 6932 template <class Derived> 6933 class ExprEvaluatorBase 6934 : public ConstStmtVisitor<Derived, bool> { 6935 private: 6936 Derived &getDerived() { return static_cast<Derived&>(*this); } 6937 bool DerivedSuccess(const APValue &V, const Expr *E) { 6938 return getDerived().Success(V, E); 6939 } 6940 bool DerivedZeroInitialization(const Expr *E) { 6941 return getDerived().ZeroInitialization(E); 6942 } 6943 6944 // Check whether a conditional operator with a non-constant condition is a 6945 // potential constant expression. If neither arm is a potential constant 6946 // expression, then the conditional operator is not either. 6947 template<typename ConditionalOperator> 6948 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 6949 assert(Info.checkingPotentialConstantExpression()); 6950 6951 // Speculatively evaluate both arms. 6952 SmallVector<PartialDiagnosticAt, 8> Diag; 6953 { 6954 SpeculativeEvaluationRAII Speculate(Info, &Diag); 6955 StmtVisitorTy::Visit(E->getFalseExpr()); 6956 if (Diag.empty()) 6957 return; 6958 } 6959 6960 { 6961 SpeculativeEvaluationRAII Speculate(Info, &Diag); 6962 Diag.clear(); 6963 StmtVisitorTy::Visit(E->getTrueExpr()); 6964 if (Diag.empty()) 6965 return; 6966 } 6967 6968 Error(E, diag::note_constexpr_conditional_never_const); 6969 } 6970 6971 6972 template<typename ConditionalOperator> 6973 bool HandleConditionalOperator(const ConditionalOperator *E) { 6974 bool BoolResult; 6975 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 6976 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 6977 CheckPotentialConstantConditional(E); 6978 return false; 6979 } 6980 if (Info.noteFailure()) { 6981 StmtVisitorTy::Visit(E->getTrueExpr()); 6982 StmtVisitorTy::Visit(E->getFalseExpr()); 6983 } 6984 return false; 6985 } 6986 6987 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 6988 return StmtVisitorTy::Visit(EvalExpr); 6989 } 6990 6991 protected: 6992 EvalInfo &Info; 6993 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 6994 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 6995 6996 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 6997 return Info.CCEDiag(E, D); 6998 } 6999 7000 bool ZeroInitialization(const Expr *E) { return Error(E); } 7001 7002 public: 7003 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7004 7005 EvalInfo &getEvalInfo() { return Info; } 7006 7007 /// Report an evaluation error. This should only be called when an error is 7008 /// first discovered. When propagating an error, just return false. 7009 bool Error(const Expr *E, diag::kind D) { 7010 Info.FFDiag(E, D); 7011 return false; 7012 } 7013 bool Error(const Expr *E) { 7014 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7015 } 7016 7017 bool VisitStmt(const Stmt *) { 7018 llvm_unreachable("Expression evaluator should not be called on stmts"); 7019 } 7020 bool VisitExpr(const Expr *E) { 7021 return Error(E); 7022 } 7023 7024 bool VisitConstantExpr(const ConstantExpr *E) { 7025 if (E->hasAPValueResult()) 7026 return DerivedSuccess(E->getAPValueResult(), E); 7027 7028 return StmtVisitorTy::Visit(E->getSubExpr()); 7029 } 7030 7031 bool VisitParenExpr(const ParenExpr *E) 7032 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7033 bool VisitUnaryExtension(const UnaryOperator *E) 7034 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7035 bool VisitUnaryPlus(const UnaryOperator *E) 7036 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7037 bool VisitChooseExpr(const ChooseExpr *E) 7038 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7039 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7040 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7041 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7042 { return StmtVisitorTy::Visit(E->getReplacement()); } 7043 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7044 TempVersionRAII RAII(*Info.CurrentCall); 7045 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7046 return StmtVisitorTy::Visit(E->getExpr()); 7047 } 7048 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7049 TempVersionRAII RAII(*Info.CurrentCall); 7050 // The initializer may not have been parsed yet, or might be erroneous. 7051 if (!E->getExpr()) 7052 return Error(E); 7053 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7054 return StmtVisitorTy::Visit(E->getExpr()); 7055 } 7056 7057 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7058 FullExpressionRAII Scope(Info); 7059 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7060 } 7061 7062 // Temporaries are registered when created, so we don't care about 7063 // CXXBindTemporaryExpr. 7064 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7065 return StmtVisitorTy::Visit(E->getSubExpr()); 7066 } 7067 7068 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7069 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7070 return static_cast<Derived*>(this)->VisitCastExpr(E); 7071 } 7072 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7073 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7074 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7075 return static_cast<Derived*>(this)->VisitCastExpr(E); 7076 } 7077 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7078 return static_cast<Derived*>(this)->VisitCastExpr(E); 7079 } 7080 7081 bool VisitBinaryOperator(const BinaryOperator *E) { 7082 switch (E->getOpcode()) { 7083 default: 7084 return Error(E); 7085 7086 case BO_Comma: 7087 VisitIgnoredValue(E->getLHS()); 7088 return StmtVisitorTy::Visit(E->getRHS()); 7089 7090 case BO_PtrMemD: 7091 case BO_PtrMemI: { 7092 LValue Obj; 7093 if (!HandleMemberPointerAccess(Info, E, Obj)) 7094 return false; 7095 APValue Result; 7096 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7097 return false; 7098 return DerivedSuccess(Result, E); 7099 } 7100 } 7101 } 7102 7103 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7104 return StmtVisitorTy::Visit(E->getSemanticForm()); 7105 } 7106 7107 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7108 // Evaluate and cache the common expression. We treat it as a temporary, 7109 // even though it's not quite the same thing. 7110 LValue CommonLV; 7111 if (!Evaluate(Info.CurrentCall->createTemporary( 7112 E->getOpaqueValue(), 7113 getStorageType(Info.Ctx, E->getOpaqueValue()), false, 7114 CommonLV), 7115 Info, E->getCommon())) 7116 return false; 7117 7118 return HandleConditionalOperator(E); 7119 } 7120 7121 bool VisitConditionalOperator(const ConditionalOperator *E) { 7122 bool IsBcpCall = false; 7123 // If the condition (ignoring parens) is a __builtin_constant_p call, 7124 // the result is a constant expression if it can be folded without 7125 // side-effects. This is an important GNU extension. See GCC PR38377 7126 // for discussion. 7127 if (const CallExpr *CallCE = 7128 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7129 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7130 IsBcpCall = true; 7131 7132 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7133 // constant expression; we can't check whether it's potentially foldable. 7134 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7135 // it would return 'false' in this mode. 7136 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7137 return false; 7138 7139 FoldConstant Fold(Info, IsBcpCall); 7140 if (!HandleConditionalOperator(E)) { 7141 Fold.keepDiagnostics(); 7142 return false; 7143 } 7144 7145 return true; 7146 } 7147 7148 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7149 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7150 return DerivedSuccess(*Value, E); 7151 7152 const Expr *Source = E->getSourceExpr(); 7153 if (!Source) 7154 return Error(E); 7155 if (Source == E) { // sanity checking. 7156 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7157 return Error(E); 7158 } 7159 return StmtVisitorTy::Visit(Source); 7160 } 7161 7162 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7163 for (const Expr *SemE : E->semantics()) { 7164 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7165 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7166 // result expression: there could be two different LValues that would 7167 // refer to the same object in that case, and we can't model that. 7168 if (SemE == E->getResultExpr()) 7169 return Error(E); 7170 7171 // Unique OVEs get evaluated if and when we encounter them when 7172 // emitting the rest of the semantic form, rather than eagerly. 7173 if (OVE->isUnique()) 7174 continue; 7175 7176 LValue LV; 7177 if (!Evaluate(Info.CurrentCall->createTemporary( 7178 OVE, getStorageType(Info.Ctx, OVE), false, LV), 7179 Info, OVE->getSourceExpr())) 7180 return false; 7181 } else if (SemE == E->getResultExpr()) { 7182 if (!StmtVisitorTy::Visit(SemE)) 7183 return false; 7184 } else { 7185 if (!EvaluateIgnoredValue(Info, SemE)) 7186 return false; 7187 } 7188 } 7189 return true; 7190 } 7191 7192 bool VisitCallExpr(const CallExpr *E) { 7193 APValue Result; 7194 if (!handleCallExpr(E, Result, nullptr)) 7195 return false; 7196 return DerivedSuccess(Result, E); 7197 } 7198 7199 bool handleCallExpr(const CallExpr *E, APValue &Result, 7200 const LValue *ResultSlot) { 7201 const Expr *Callee = E->getCallee()->IgnoreParens(); 7202 QualType CalleeType = Callee->getType(); 7203 7204 const FunctionDecl *FD = nullptr; 7205 LValue *This = nullptr, ThisVal; 7206 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7207 bool HasQualifier = false; 7208 7209 // Extract function decl and 'this' pointer from the callee. 7210 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7211 const CXXMethodDecl *Member = nullptr; 7212 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7213 // Explicit bound member calls, such as x.f() or p->g(); 7214 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7215 return false; 7216 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7217 if (!Member) 7218 return Error(Callee); 7219 This = &ThisVal; 7220 HasQualifier = ME->hasQualifier(); 7221 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7222 // Indirect bound member calls ('.*' or '->*'). 7223 const ValueDecl *D = 7224 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7225 if (!D) 7226 return false; 7227 Member = dyn_cast<CXXMethodDecl>(D); 7228 if (!Member) 7229 return Error(Callee); 7230 This = &ThisVal; 7231 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7232 if (!Info.getLangOpts().CPlusPlus20) 7233 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7234 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7235 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7236 } else 7237 return Error(Callee); 7238 FD = Member; 7239 } else if (CalleeType->isFunctionPointerType()) { 7240 LValue Call; 7241 if (!EvaluatePointer(Callee, Call, Info)) 7242 return false; 7243 7244 if (!Call.getLValueOffset().isZero()) 7245 return Error(Callee); 7246 FD = dyn_cast_or_null<FunctionDecl>( 7247 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 7248 if (!FD) 7249 return Error(Callee); 7250 // Don't call function pointers which have been cast to some other type. 7251 // Per DR (no number yet), the caller and callee can differ in noexcept. 7252 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7253 CalleeType->getPointeeType(), FD->getType())) { 7254 return Error(E); 7255 } 7256 7257 // Overloaded operator calls to member functions are represented as normal 7258 // calls with '*this' as the first argument. 7259 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7260 if (MD && !MD->isStatic()) { 7261 // FIXME: When selecting an implicit conversion for an overloaded 7262 // operator delete, we sometimes try to evaluate calls to conversion 7263 // operators without a 'this' parameter! 7264 if (Args.empty()) 7265 return Error(E); 7266 7267 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7268 return false; 7269 This = &ThisVal; 7270 Args = Args.slice(1); 7271 } else if (MD && MD->isLambdaStaticInvoker()) { 7272 // Map the static invoker for the lambda back to the call operator. 7273 // Conveniently, we don't have to slice out the 'this' argument (as is 7274 // being done for the non-static case), since a static member function 7275 // doesn't have an implicit argument passed in. 7276 const CXXRecordDecl *ClosureClass = MD->getParent(); 7277 assert( 7278 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7279 "Number of captures must be zero for conversion to function-ptr"); 7280 7281 const CXXMethodDecl *LambdaCallOp = 7282 ClosureClass->getLambdaCallOperator(); 7283 7284 // Set 'FD', the function that will be called below, to the call 7285 // operator. If the closure object represents a generic lambda, find 7286 // the corresponding specialization of the call operator. 7287 7288 if (ClosureClass->isGenericLambda()) { 7289 assert(MD->isFunctionTemplateSpecialization() && 7290 "A generic lambda's static-invoker function must be a " 7291 "template specialization"); 7292 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7293 FunctionTemplateDecl *CallOpTemplate = 7294 LambdaCallOp->getDescribedFunctionTemplate(); 7295 void *InsertPos = nullptr; 7296 FunctionDecl *CorrespondingCallOpSpecialization = 7297 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7298 assert(CorrespondingCallOpSpecialization && 7299 "We must always have a function call operator specialization " 7300 "that corresponds to our static invoker specialization"); 7301 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7302 } else 7303 FD = LambdaCallOp; 7304 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7305 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7306 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7307 LValue Ptr; 7308 if (!HandleOperatorNewCall(Info, E, Ptr)) 7309 return false; 7310 Ptr.moveInto(Result); 7311 return true; 7312 } else { 7313 return HandleOperatorDeleteCall(Info, E); 7314 } 7315 } 7316 } else 7317 return Error(E); 7318 7319 SmallVector<QualType, 4> CovariantAdjustmentPath; 7320 if (This) { 7321 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7322 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7323 // Perform virtual dispatch, if necessary. 7324 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7325 CovariantAdjustmentPath); 7326 if (!FD) 7327 return false; 7328 } else { 7329 // Check that the 'this' pointer points to an object of the right type. 7330 // FIXME: If this is an assignment operator call, we may need to change 7331 // the active union member before we check this. 7332 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7333 return false; 7334 } 7335 } 7336 7337 // Destructor calls are different enough that they have their own codepath. 7338 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7339 assert(This && "no 'this' pointer for destructor call"); 7340 return HandleDestruction(Info, E, *This, 7341 Info.Ctx.getRecordType(DD->getParent())); 7342 } 7343 7344 const FunctionDecl *Definition = nullptr; 7345 Stmt *Body = FD->getBody(Definition); 7346 7347 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7348 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 7349 Result, ResultSlot)) 7350 return false; 7351 7352 if (!CovariantAdjustmentPath.empty() && 7353 !HandleCovariantReturnAdjustment(Info, E, Result, 7354 CovariantAdjustmentPath)) 7355 return false; 7356 7357 return true; 7358 } 7359 7360 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7361 return StmtVisitorTy::Visit(E->getInitializer()); 7362 } 7363 bool VisitInitListExpr(const InitListExpr *E) { 7364 if (E->getNumInits() == 0) 7365 return DerivedZeroInitialization(E); 7366 if (E->getNumInits() == 1) 7367 return StmtVisitorTy::Visit(E->getInit(0)); 7368 return Error(E); 7369 } 7370 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7371 return DerivedZeroInitialization(E); 7372 } 7373 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7374 return DerivedZeroInitialization(E); 7375 } 7376 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7377 return DerivedZeroInitialization(E); 7378 } 7379 7380 /// A member expression where the object is a prvalue is itself a prvalue. 7381 bool VisitMemberExpr(const MemberExpr *E) { 7382 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7383 "missing temporary materialization conversion"); 7384 assert(!E->isArrow() && "missing call to bound member function?"); 7385 7386 APValue Val; 7387 if (!Evaluate(Val, Info, E->getBase())) 7388 return false; 7389 7390 QualType BaseTy = E->getBase()->getType(); 7391 7392 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7393 if (!FD) return Error(E); 7394 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7395 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7396 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7397 7398 // Note: there is no lvalue base here. But this case should only ever 7399 // happen in C or in C++98, where we cannot be evaluating a constexpr 7400 // constructor, which is the only case the base matters. 7401 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7402 SubobjectDesignator Designator(BaseTy); 7403 Designator.addDeclUnchecked(FD); 7404 7405 APValue Result; 7406 return extractSubobject(Info, E, Obj, Designator, Result) && 7407 DerivedSuccess(Result, E); 7408 } 7409 7410 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7411 APValue Val; 7412 if (!Evaluate(Val, Info, E->getBase())) 7413 return false; 7414 7415 if (Val.isVector()) { 7416 SmallVector<uint32_t, 4> Indices; 7417 E->getEncodedElementAccess(Indices); 7418 if (Indices.size() == 1) { 7419 // Return scalar. 7420 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7421 } else { 7422 // Construct new APValue vector. 7423 SmallVector<APValue, 4> Elts; 7424 for (unsigned I = 0; I < Indices.size(); ++I) { 7425 Elts.push_back(Val.getVectorElt(Indices[I])); 7426 } 7427 APValue VecResult(Elts.data(), Indices.size()); 7428 return DerivedSuccess(VecResult, E); 7429 } 7430 } 7431 7432 return false; 7433 } 7434 7435 bool VisitCastExpr(const CastExpr *E) { 7436 switch (E->getCastKind()) { 7437 default: 7438 break; 7439 7440 case CK_AtomicToNonAtomic: { 7441 APValue AtomicVal; 7442 // This does not need to be done in place even for class/array types: 7443 // atomic-to-non-atomic conversion implies copying the object 7444 // representation. 7445 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7446 return false; 7447 return DerivedSuccess(AtomicVal, E); 7448 } 7449 7450 case CK_NoOp: 7451 case CK_UserDefinedConversion: 7452 return StmtVisitorTy::Visit(E->getSubExpr()); 7453 7454 case CK_LValueToRValue: { 7455 LValue LVal; 7456 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7457 return false; 7458 APValue RVal; 7459 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7460 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7461 LVal, RVal)) 7462 return false; 7463 return DerivedSuccess(RVal, E); 7464 } 7465 case CK_LValueToRValueBitCast: { 7466 APValue DestValue, SourceValue; 7467 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7468 return false; 7469 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7470 return false; 7471 return DerivedSuccess(DestValue, E); 7472 } 7473 7474 case CK_AddressSpaceConversion: { 7475 APValue Value; 7476 if (!Evaluate(Value, Info, E->getSubExpr())) 7477 return false; 7478 return DerivedSuccess(Value, E); 7479 } 7480 } 7481 7482 return Error(E); 7483 } 7484 7485 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7486 return VisitUnaryPostIncDec(UO); 7487 } 7488 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7489 return VisitUnaryPostIncDec(UO); 7490 } 7491 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7492 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7493 return Error(UO); 7494 7495 LValue LVal; 7496 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7497 return false; 7498 APValue RVal; 7499 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7500 UO->isIncrementOp(), &RVal)) 7501 return false; 7502 return DerivedSuccess(RVal, UO); 7503 } 7504 7505 bool VisitStmtExpr(const StmtExpr *E) { 7506 // We will have checked the full-expressions inside the statement expression 7507 // when they were completed, and don't need to check them again now. 7508 if (Info.checkingForUndefinedBehavior()) 7509 return Error(E); 7510 7511 const CompoundStmt *CS = E->getSubStmt(); 7512 if (CS->body_empty()) 7513 return true; 7514 7515 BlockScopeRAII Scope(Info); 7516 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7517 BE = CS->body_end(); 7518 /**/; ++BI) { 7519 if (BI + 1 == BE) { 7520 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7521 if (!FinalExpr) { 7522 Info.FFDiag((*BI)->getBeginLoc(), 7523 diag::note_constexpr_stmt_expr_unsupported); 7524 return false; 7525 } 7526 return this->Visit(FinalExpr) && Scope.destroy(); 7527 } 7528 7529 APValue ReturnValue; 7530 StmtResult Result = { ReturnValue, nullptr }; 7531 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7532 if (ESR != ESR_Succeeded) { 7533 // FIXME: If the statement-expression terminated due to 'return', 7534 // 'break', or 'continue', it would be nice to propagate that to 7535 // the outer statement evaluation rather than bailing out. 7536 if (ESR != ESR_Failed) 7537 Info.FFDiag((*BI)->getBeginLoc(), 7538 diag::note_constexpr_stmt_expr_unsupported); 7539 return false; 7540 } 7541 } 7542 7543 llvm_unreachable("Return from function from the loop above."); 7544 } 7545 7546 /// Visit a value which is evaluated, but whose value is ignored. 7547 void VisitIgnoredValue(const Expr *E) { 7548 EvaluateIgnoredValue(Info, E); 7549 } 7550 7551 /// Potentially visit a MemberExpr's base expression. 7552 void VisitIgnoredBaseExpression(const Expr *E) { 7553 // While MSVC doesn't evaluate the base expression, it does diagnose the 7554 // presence of side-effecting behavior. 7555 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7556 return; 7557 VisitIgnoredValue(E); 7558 } 7559 }; 7560 7561 } // namespace 7562 7563 //===----------------------------------------------------------------------===// 7564 // Common base class for lvalue and temporary evaluation. 7565 //===----------------------------------------------------------------------===// 7566 namespace { 7567 template<class Derived> 7568 class LValueExprEvaluatorBase 7569 : public ExprEvaluatorBase<Derived> { 7570 protected: 7571 LValue &Result; 7572 bool InvalidBaseOK; 7573 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7574 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7575 7576 bool Success(APValue::LValueBase B) { 7577 Result.set(B); 7578 return true; 7579 } 7580 7581 bool evaluatePointer(const Expr *E, LValue &Result) { 7582 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7583 } 7584 7585 public: 7586 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7587 : ExprEvaluatorBaseTy(Info), Result(Result), 7588 InvalidBaseOK(InvalidBaseOK) {} 7589 7590 bool Success(const APValue &V, const Expr *E) { 7591 Result.setFrom(this->Info.Ctx, V); 7592 return true; 7593 } 7594 7595 bool VisitMemberExpr(const MemberExpr *E) { 7596 // Handle non-static data members. 7597 QualType BaseTy; 7598 bool EvalOK; 7599 if (E->isArrow()) { 7600 EvalOK = evaluatePointer(E->getBase(), Result); 7601 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7602 } else if (E->getBase()->isRValue()) { 7603 assert(E->getBase()->getType()->isRecordType()); 7604 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7605 BaseTy = E->getBase()->getType(); 7606 } else { 7607 EvalOK = this->Visit(E->getBase()); 7608 BaseTy = E->getBase()->getType(); 7609 } 7610 if (!EvalOK) { 7611 if (!InvalidBaseOK) 7612 return false; 7613 Result.setInvalid(E); 7614 return true; 7615 } 7616 7617 const ValueDecl *MD = E->getMemberDecl(); 7618 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7619 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7620 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7621 (void)BaseTy; 7622 if (!HandleLValueMember(this->Info, E, Result, FD)) 7623 return false; 7624 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7625 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7626 return false; 7627 } else 7628 return this->Error(E); 7629 7630 if (MD->getType()->isReferenceType()) { 7631 APValue RefValue; 7632 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7633 RefValue)) 7634 return false; 7635 return Success(RefValue, E); 7636 } 7637 return true; 7638 } 7639 7640 bool VisitBinaryOperator(const BinaryOperator *E) { 7641 switch (E->getOpcode()) { 7642 default: 7643 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7644 7645 case BO_PtrMemD: 7646 case BO_PtrMemI: 7647 return HandleMemberPointerAccess(this->Info, E, Result); 7648 } 7649 } 7650 7651 bool VisitCastExpr(const CastExpr *E) { 7652 switch (E->getCastKind()) { 7653 default: 7654 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7655 7656 case CK_DerivedToBase: 7657 case CK_UncheckedDerivedToBase: 7658 if (!this->Visit(E->getSubExpr())) 7659 return false; 7660 7661 // Now figure out the necessary offset to add to the base LV to get from 7662 // the derived class to the base class. 7663 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 7664 Result); 7665 } 7666 } 7667 }; 7668 } 7669 7670 //===----------------------------------------------------------------------===// 7671 // LValue Evaluation 7672 // 7673 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 7674 // function designators (in C), decl references to void objects (in C), and 7675 // temporaries (if building with -Wno-address-of-temporary). 7676 // 7677 // LValue evaluation produces values comprising a base expression of one of the 7678 // following types: 7679 // - Declarations 7680 // * VarDecl 7681 // * FunctionDecl 7682 // - Literals 7683 // * CompoundLiteralExpr in C (and in global scope in C++) 7684 // * StringLiteral 7685 // * PredefinedExpr 7686 // * ObjCStringLiteralExpr 7687 // * ObjCEncodeExpr 7688 // * AddrLabelExpr 7689 // * BlockExpr 7690 // * CallExpr for a MakeStringConstant builtin 7691 // - typeid(T) expressions, as TypeInfoLValues 7692 // - Locals and temporaries 7693 // * MaterializeTemporaryExpr 7694 // * Any Expr, with a CallIndex indicating the function in which the temporary 7695 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 7696 // from the AST (FIXME). 7697 // * A MaterializeTemporaryExpr that has static storage duration, with no 7698 // CallIndex, for a lifetime-extended temporary. 7699 // * The ConstantExpr that is currently being evaluated during evaluation of an 7700 // immediate invocation. 7701 // plus an offset in bytes. 7702 //===----------------------------------------------------------------------===// 7703 namespace { 7704 class LValueExprEvaluator 7705 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 7706 public: 7707 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 7708 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 7709 7710 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 7711 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 7712 7713 bool VisitDeclRefExpr(const DeclRefExpr *E); 7714 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 7715 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 7716 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 7717 bool VisitMemberExpr(const MemberExpr *E); 7718 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 7719 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 7720 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 7721 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 7722 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 7723 bool VisitUnaryDeref(const UnaryOperator *E); 7724 bool VisitUnaryReal(const UnaryOperator *E); 7725 bool VisitUnaryImag(const UnaryOperator *E); 7726 bool VisitUnaryPreInc(const UnaryOperator *UO) { 7727 return VisitUnaryPreIncDec(UO); 7728 } 7729 bool VisitUnaryPreDec(const UnaryOperator *UO) { 7730 return VisitUnaryPreIncDec(UO); 7731 } 7732 bool VisitBinAssign(const BinaryOperator *BO); 7733 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 7734 7735 bool VisitCastExpr(const CastExpr *E) { 7736 switch (E->getCastKind()) { 7737 default: 7738 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 7739 7740 case CK_LValueBitCast: 7741 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7742 if (!Visit(E->getSubExpr())) 7743 return false; 7744 Result.Designator.setInvalid(); 7745 return true; 7746 7747 case CK_BaseToDerived: 7748 if (!Visit(E->getSubExpr())) 7749 return false; 7750 return HandleBaseToDerivedCast(Info, E, Result); 7751 7752 case CK_Dynamic: 7753 if (!Visit(E->getSubExpr())) 7754 return false; 7755 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 7756 } 7757 } 7758 }; 7759 } // end anonymous namespace 7760 7761 /// Evaluate an expression as an lvalue. This can be legitimately called on 7762 /// expressions which are not glvalues, in three cases: 7763 /// * function designators in C, and 7764 /// * "extern void" objects 7765 /// * @selector() expressions in Objective-C 7766 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 7767 bool InvalidBaseOK) { 7768 assert(E->isGLValue() || E->getType()->isFunctionType() || 7769 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 7770 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 7771 } 7772 7773 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 7774 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 7775 return Success(FD); 7776 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 7777 return VisitVarDecl(E, VD); 7778 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 7779 return Visit(BD->getBinding()); 7780 if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(E->getDecl())) 7781 return Success(GD); 7782 return Error(E); 7783 } 7784 7785 7786 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 7787 7788 // If we are within a lambda's call operator, check whether the 'VD' referred 7789 // to within 'E' actually represents a lambda-capture that maps to a 7790 // data-member/field within the closure object, and if so, evaluate to the 7791 // field or what the field refers to. 7792 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 7793 isa<DeclRefExpr>(E) && 7794 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 7795 // We don't always have a complete capture-map when checking or inferring if 7796 // the function call operator meets the requirements of a constexpr function 7797 // - but we don't need to evaluate the captures to determine constexprness 7798 // (dcl.constexpr C++17). 7799 if (Info.checkingPotentialConstantExpression()) 7800 return false; 7801 7802 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 7803 // Start with 'Result' referring to the complete closure object... 7804 Result = *Info.CurrentCall->This; 7805 // ... then update it to refer to the field of the closure object 7806 // that represents the capture. 7807 if (!HandleLValueMember(Info, E, Result, FD)) 7808 return false; 7809 // And if the field is of reference type, update 'Result' to refer to what 7810 // the field refers to. 7811 if (FD->getType()->isReferenceType()) { 7812 APValue RVal; 7813 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 7814 RVal)) 7815 return false; 7816 Result.setFrom(Info.Ctx, RVal); 7817 } 7818 return true; 7819 } 7820 } 7821 CallStackFrame *Frame = nullptr; 7822 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 7823 // Only if a local variable was declared in the function currently being 7824 // evaluated, do we expect to be able to find its value in the current 7825 // frame. (Otherwise it was likely declared in an enclosing context and 7826 // could either have a valid evaluatable value (for e.g. a constexpr 7827 // variable) or be ill-formed (and trigger an appropriate evaluation 7828 // diagnostic)). 7829 if (Info.CurrentCall->Callee && 7830 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 7831 Frame = Info.CurrentCall; 7832 } 7833 } 7834 7835 if (!VD->getType()->isReferenceType()) { 7836 if (Frame) { 7837 Result.set({VD, Frame->Index, 7838 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 7839 return true; 7840 } 7841 return Success(VD); 7842 } 7843 7844 APValue *V; 7845 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 7846 return false; 7847 if (!V->hasValue()) { 7848 // FIXME: Is it possible for V to be indeterminate here? If so, we should 7849 // adjust the diagnostic to say that. 7850 if (!Info.checkingPotentialConstantExpression()) 7851 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 7852 return false; 7853 } 7854 return Success(*V, E); 7855 } 7856 7857 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 7858 const MaterializeTemporaryExpr *E) { 7859 // Walk through the expression to find the materialized temporary itself. 7860 SmallVector<const Expr *, 2> CommaLHSs; 7861 SmallVector<SubobjectAdjustment, 2> Adjustments; 7862 const Expr *Inner = 7863 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 7864 7865 // If we passed any comma operators, evaluate their LHSs. 7866 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 7867 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 7868 return false; 7869 7870 // A materialized temporary with static storage duration can appear within the 7871 // result of a constant expression evaluation, so we need to preserve its 7872 // value for use outside this evaluation. 7873 APValue *Value; 7874 if (E->getStorageDuration() == SD_Static) { 7875 Value = E->getOrCreateValue(true); 7876 *Value = APValue(); 7877 Result.set(E); 7878 } else { 7879 Value = &Info.CurrentCall->createTemporary( 7880 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result); 7881 } 7882 7883 QualType Type = Inner->getType(); 7884 7885 // Materialize the temporary itself. 7886 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 7887 *Value = APValue(); 7888 return false; 7889 } 7890 7891 // Adjust our lvalue to refer to the desired subobject. 7892 for (unsigned I = Adjustments.size(); I != 0; /**/) { 7893 --I; 7894 switch (Adjustments[I].Kind) { 7895 case SubobjectAdjustment::DerivedToBaseAdjustment: 7896 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 7897 Type, Result)) 7898 return false; 7899 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 7900 break; 7901 7902 case SubobjectAdjustment::FieldAdjustment: 7903 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 7904 return false; 7905 Type = Adjustments[I].Field->getType(); 7906 break; 7907 7908 case SubobjectAdjustment::MemberPointerAdjustment: 7909 if (!HandleMemberPointerAccess(this->Info, Type, Result, 7910 Adjustments[I].Ptr.RHS)) 7911 return false; 7912 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 7913 break; 7914 } 7915 } 7916 7917 return true; 7918 } 7919 7920 bool 7921 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7922 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 7923 "lvalue compound literal in c++?"); 7924 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 7925 // only see this when folding in C, so there's no standard to follow here. 7926 return Success(E); 7927 } 7928 7929 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 7930 TypeInfoLValue TypeInfo; 7931 7932 if (!E->isPotentiallyEvaluated()) { 7933 if (E->isTypeOperand()) 7934 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 7935 else 7936 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 7937 } else { 7938 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 7939 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 7940 << E->getExprOperand()->getType() 7941 << E->getExprOperand()->getSourceRange(); 7942 } 7943 7944 if (!Visit(E->getExprOperand())) 7945 return false; 7946 7947 Optional<DynamicType> DynType = 7948 ComputeDynamicType(Info, E, Result, AK_TypeId); 7949 if (!DynType) 7950 return false; 7951 7952 TypeInfo = 7953 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 7954 } 7955 7956 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 7957 } 7958 7959 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 7960 return Success(E->getGuidDecl()); 7961 } 7962 7963 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 7964 // Handle static data members. 7965 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 7966 VisitIgnoredBaseExpression(E->getBase()); 7967 return VisitVarDecl(E, VD); 7968 } 7969 7970 // Handle static member functions. 7971 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 7972 if (MD->isStatic()) { 7973 VisitIgnoredBaseExpression(E->getBase()); 7974 return Success(MD); 7975 } 7976 } 7977 7978 // Handle non-static data members. 7979 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 7980 } 7981 7982 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 7983 // FIXME: Deal with vectors as array subscript bases. 7984 if (E->getBase()->getType()->isVectorType()) 7985 return Error(E); 7986 7987 bool Success = true; 7988 if (!evaluatePointer(E->getBase(), Result)) { 7989 if (!Info.noteFailure()) 7990 return false; 7991 Success = false; 7992 } 7993 7994 APSInt Index; 7995 if (!EvaluateInteger(E->getIdx(), Index, Info)) 7996 return false; 7997 7998 return Success && 7999 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8000 } 8001 8002 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8003 return evaluatePointer(E->getSubExpr(), Result); 8004 } 8005 8006 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8007 if (!Visit(E->getSubExpr())) 8008 return false; 8009 // __real is a no-op on scalar lvalues. 8010 if (E->getSubExpr()->getType()->isAnyComplexType()) 8011 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8012 return true; 8013 } 8014 8015 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8016 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8017 "lvalue __imag__ on scalar?"); 8018 if (!Visit(E->getSubExpr())) 8019 return false; 8020 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8021 return true; 8022 } 8023 8024 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8025 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8026 return Error(UO); 8027 8028 if (!this->Visit(UO->getSubExpr())) 8029 return false; 8030 8031 return handleIncDec( 8032 this->Info, UO, Result, UO->getSubExpr()->getType(), 8033 UO->isIncrementOp(), nullptr); 8034 } 8035 8036 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8037 const CompoundAssignOperator *CAO) { 8038 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8039 return Error(CAO); 8040 8041 APValue RHS; 8042 8043 // The overall lvalue result is the result of evaluating the LHS. 8044 if (!this->Visit(CAO->getLHS())) { 8045 if (Info.noteFailure()) 8046 Evaluate(RHS, this->Info, CAO->getRHS()); 8047 return false; 8048 } 8049 8050 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 8051 return false; 8052 8053 return handleCompoundAssignment( 8054 this->Info, CAO, 8055 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8056 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8057 } 8058 8059 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8060 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8061 return Error(E); 8062 8063 APValue NewVal; 8064 8065 if (!this->Visit(E->getLHS())) { 8066 if (Info.noteFailure()) 8067 Evaluate(NewVal, this->Info, E->getRHS()); 8068 return false; 8069 } 8070 8071 if (!Evaluate(NewVal, this->Info, E->getRHS())) 8072 return false; 8073 8074 if (Info.getLangOpts().CPlusPlus20 && 8075 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8076 return false; 8077 8078 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8079 NewVal); 8080 } 8081 8082 //===----------------------------------------------------------------------===// 8083 // Pointer Evaluation 8084 //===----------------------------------------------------------------------===// 8085 8086 /// Attempts to compute the number of bytes available at the pointer 8087 /// returned by a function with the alloc_size attribute. Returns true if we 8088 /// were successful. Places an unsigned number into `Result`. 8089 /// 8090 /// This expects the given CallExpr to be a call to a function with an 8091 /// alloc_size attribute. 8092 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8093 const CallExpr *Call, 8094 llvm::APInt &Result) { 8095 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8096 8097 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8098 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8099 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8100 if (Call->getNumArgs() <= SizeArgNo) 8101 return false; 8102 8103 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8104 Expr::EvalResult ExprResult; 8105 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8106 return false; 8107 Into = ExprResult.Val.getInt(); 8108 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8109 return false; 8110 Into = Into.zextOrSelf(BitsInSizeT); 8111 return true; 8112 }; 8113 8114 APSInt SizeOfElem; 8115 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8116 return false; 8117 8118 if (!AllocSize->getNumElemsParam().isValid()) { 8119 Result = std::move(SizeOfElem); 8120 return true; 8121 } 8122 8123 APSInt NumberOfElems; 8124 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8125 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8126 return false; 8127 8128 bool Overflow; 8129 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8130 if (Overflow) 8131 return false; 8132 8133 Result = std::move(BytesAvailable); 8134 return true; 8135 } 8136 8137 /// Convenience function. LVal's base must be a call to an alloc_size 8138 /// function. 8139 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8140 const LValue &LVal, 8141 llvm::APInt &Result) { 8142 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8143 "Can't get the size of a non alloc_size function"); 8144 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8145 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8146 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8147 } 8148 8149 /// Attempts to evaluate the given LValueBase as the result of a call to 8150 /// a function with the alloc_size attribute. If it was possible to do so, this 8151 /// function will return true, make Result's Base point to said function call, 8152 /// and mark Result's Base as invalid. 8153 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8154 LValue &Result) { 8155 if (Base.isNull()) 8156 return false; 8157 8158 // Because we do no form of static analysis, we only support const variables. 8159 // 8160 // Additionally, we can't support parameters, nor can we support static 8161 // variables (in the latter case, use-before-assign isn't UB; in the former, 8162 // we have no clue what they'll be assigned to). 8163 const auto *VD = 8164 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8165 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8166 return false; 8167 8168 const Expr *Init = VD->getAnyInitializer(); 8169 if (!Init) 8170 return false; 8171 8172 const Expr *E = Init->IgnoreParens(); 8173 if (!tryUnwrapAllocSizeCall(E)) 8174 return false; 8175 8176 // Store E instead of E unwrapped so that the type of the LValue's base is 8177 // what the user wanted. 8178 Result.setInvalid(E); 8179 8180 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8181 Result.addUnsizedArray(Info, E, Pointee); 8182 return true; 8183 } 8184 8185 namespace { 8186 class PointerExprEvaluator 8187 : public ExprEvaluatorBase<PointerExprEvaluator> { 8188 LValue &Result; 8189 bool InvalidBaseOK; 8190 8191 bool Success(const Expr *E) { 8192 Result.set(E); 8193 return true; 8194 } 8195 8196 bool evaluateLValue(const Expr *E, LValue &Result) { 8197 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8198 } 8199 8200 bool evaluatePointer(const Expr *E, LValue &Result) { 8201 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8202 } 8203 8204 bool visitNonBuiltinCallExpr(const CallExpr *E); 8205 public: 8206 8207 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8208 : ExprEvaluatorBaseTy(info), Result(Result), 8209 InvalidBaseOK(InvalidBaseOK) {} 8210 8211 bool Success(const APValue &V, const Expr *E) { 8212 Result.setFrom(Info.Ctx, V); 8213 return true; 8214 } 8215 bool ZeroInitialization(const Expr *E) { 8216 Result.setNull(Info.Ctx, E->getType()); 8217 return true; 8218 } 8219 8220 bool VisitBinaryOperator(const BinaryOperator *E); 8221 bool VisitCastExpr(const CastExpr* E); 8222 bool VisitUnaryAddrOf(const UnaryOperator *E); 8223 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8224 { return Success(E); } 8225 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8226 if (E->isExpressibleAsConstantInitializer()) 8227 return Success(E); 8228 if (Info.noteFailure()) 8229 EvaluateIgnoredValue(Info, E->getSubExpr()); 8230 return Error(E); 8231 } 8232 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8233 { return Success(E); } 8234 bool VisitCallExpr(const CallExpr *E); 8235 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8236 bool VisitBlockExpr(const BlockExpr *E) { 8237 if (!E->getBlockDecl()->hasCaptures()) 8238 return Success(E); 8239 return Error(E); 8240 } 8241 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8242 // Can't look at 'this' when checking a potential constant expression. 8243 if (Info.checkingPotentialConstantExpression()) 8244 return false; 8245 if (!Info.CurrentCall->This) { 8246 if (Info.getLangOpts().CPlusPlus11) 8247 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8248 else 8249 Info.FFDiag(E); 8250 return false; 8251 } 8252 Result = *Info.CurrentCall->This; 8253 // If we are inside a lambda's call operator, the 'this' expression refers 8254 // to the enclosing '*this' object (either by value or reference) which is 8255 // either copied into the closure object's field that represents the '*this' 8256 // or refers to '*this'. 8257 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8258 // Ensure we actually have captured 'this'. (an error will have 8259 // been previously reported if not). 8260 if (!Info.CurrentCall->LambdaThisCaptureField) 8261 return false; 8262 8263 // Update 'Result' to refer to the data member/field of the closure object 8264 // that represents the '*this' capture. 8265 if (!HandleLValueMember(Info, E, Result, 8266 Info.CurrentCall->LambdaThisCaptureField)) 8267 return false; 8268 // If we captured '*this' by reference, replace the field with its referent. 8269 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8270 ->isPointerType()) { 8271 APValue RVal; 8272 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8273 RVal)) 8274 return false; 8275 8276 Result.setFrom(Info.Ctx, RVal); 8277 } 8278 } 8279 return true; 8280 } 8281 8282 bool VisitCXXNewExpr(const CXXNewExpr *E); 8283 8284 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8285 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8286 APValue LValResult = E->EvaluateInContext( 8287 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8288 Result.setFrom(Info.Ctx, LValResult); 8289 return true; 8290 } 8291 8292 // FIXME: Missing: @protocol, @selector 8293 }; 8294 } // end anonymous namespace 8295 8296 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8297 bool InvalidBaseOK) { 8298 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8299 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8300 } 8301 8302 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8303 if (E->getOpcode() != BO_Add && 8304 E->getOpcode() != BO_Sub) 8305 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8306 8307 const Expr *PExp = E->getLHS(); 8308 const Expr *IExp = E->getRHS(); 8309 if (IExp->getType()->isPointerType()) 8310 std::swap(PExp, IExp); 8311 8312 bool EvalPtrOK = evaluatePointer(PExp, Result); 8313 if (!EvalPtrOK && !Info.noteFailure()) 8314 return false; 8315 8316 llvm::APSInt Offset; 8317 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8318 return false; 8319 8320 if (E->getOpcode() == BO_Sub) 8321 negateAsSigned(Offset); 8322 8323 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8324 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8325 } 8326 8327 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8328 return evaluateLValue(E->getSubExpr(), Result); 8329 } 8330 8331 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8332 const Expr *SubExpr = E->getSubExpr(); 8333 8334 switch (E->getCastKind()) { 8335 default: 8336 break; 8337 case CK_BitCast: 8338 case CK_CPointerToObjCPointerCast: 8339 case CK_BlockPointerToObjCPointerCast: 8340 case CK_AnyPointerToBlockPointerCast: 8341 case CK_AddressSpaceConversion: 8342 if (!Visit(SubExpr)) 8343 return false; 8344 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8345 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8346 // also static_casts, but we disallow them as a resolution to DR1312. 8347 if (!E->getType()->isVoidPointerType()) { 8348 if (!Result.InvalidBase && !Result.Designator.Invalid && 8349 !Result.IsNullPtr && 8350 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8351 E->getType()->getPointeeType()) && 8352 Info.getStdAllocatorCaller("allocate")) { 8353 // Inside a call to std::allocator::allocate and friends, we permit 8354 // casting from void* back to cv1 T* for a pointer that points to a 8355 // cv2 T. 8356 } else { 8357 Result.Designator.setInvalid(); 8358 if (SubExpr->getType()->isVoidPointerType()) 8359 CCEDiag(E, diag::note_constexpr_invalid_cast) 8360 << 3 << SubExpr->getType(); 8361 else 8362 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8363 } 8364 } 8365 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8366 ZeroInitialization(E); 8367 return true; 8368 8369 case CK_DerivedToBase: 8370 case CK_UncheckedDerivedToBase: 8371 if (!evaluatePointer(E->getSubExpr(), Result)) 8372 return false; 8373 if (!Result.Base && Result.Offset.isZero()) 8374 return true; 8375 8376 // Now figure out the necessary offset to add to the base LV to get from 8377 // the derived class to the base class. 8378 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8379 castAs<PointerType>()->getPointeeType(), 8380 Result); 8381 8382 case CK_BaseToDerived: 8383 if (!Visit(E->getSubExpr())) 8384 return false; 8385 if (!Result.Base && Result.Offset.isZero()) 8386 return true; 8387 return HandleBaseToDerivedCast(Info, E, Result); 8388 8389 case CK_Dynamic: 8390 if (!Visit(E->getSubExpr())) 8391 return false; 8392 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8393 8394 case CK_NullToPointer: 8395 VisitIgnoredValue(E->getSubExpr()); 8396 return ZeroInitialization(E); 8397 8398 case CK_IntegralToPointer: { 8399 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8400 8401 APValue Value; 8402 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8403 break; 8404 8405 if (Value.isInt()) { 8406 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8407 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8408 Result.Base = (Expr*)nullptr; 8409 Result.InvalidBase = false; 8410 Result.Offset = CharUnits::fromQuantity(N); 8411 Result.Designator.setInvalid(); 8412 Result.IsNullPtr = false; 8413 return true; 8414 } else { 8415 // Cast is of an lvalue, no need to change value. 8416 Result.setFrom(Info.Ctx, Value); 8417 return true; 8418 } 8419 } 8420 8421 case CK_ArrayToPointerDecay: { 8422 if (SubExpr->isGLValue()) { 8423 if (!evaluateLValue(SubExpr, Result)) 8424 return false; 8425 } else { 8426 APValue &Value = Info.CurrentCall->createTemporary( 8427 SubExpr, SubExpr->getType(), false, Result); 8428 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8429 return false; 8430 } 8431 // The result is a pointer to the first element of the array. 8432 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8433 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8434 Result.addArray(Info, E, CAT); 8435 else 8436 Result.addUnsizedArray(Info, E, AT->getElementType()); 8437 return true; 8438 } 8439 8440 case CK_FunctionToPointerDecay: 8441 return evaluateLValue(SubExpr, Result); 8442 8443 case CK_LValueToRValue: { 8444 LValue LVal; 8445 if (!evaluateLValue(E->getSubExpr(), LVal)) 8446 return false; 8447 8448 APValue RVal; 8449 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8450 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8451 LVal, RVal)) 8452 return InvalidBaseOK && 8453 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8454 return Success(RVal, E); 8455 } 8456 } 8457 8458 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8459 } 8460 8461 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8462 UnaryExprOrTypeTrait ExprKind) { 8463 // C++ [expr.alignof]p3: 8464 // When alignof is applied to a reference type, the result is the 8465 // alignment of the referenced type. 8466 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8467 T = Ref->getPointeeType(); 8468 8469 if (T.getQualifiers().hasUnaligned()) 8470 return CharUnits::One(); 8471 8472 const bool AlignOfReturnsPreferred = 8473 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8474 8475 // __alignof is defined to return the preferred alignment. 8476 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8477 // as well. 8478 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8479 return Info.Ctx.toCharUnitsFromBits( 8480 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8481 // alignof and _Alignof are defined to return the ABI alignment. 8482 else if (ExprKind == UETT_AlignOf) 8483 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8484 else 8485 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8486 } 8487 8488 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8489 UnaryExprOrTypeTrait ExprKind) { 8490 E = E->IgnoreParens(); 8491 8492 // The kinds of expressions that we have special-case logic here for 8493 // should be kept up to date with the special checks for those 8494 // expressions in Sema. 8495 8496 // alignof decl is always accepted, even if it doesn't make sense: we default 8497 // to 1 in those cases. 8498 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8499 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8500 /*RefAsPointee*/true); 8501 8502 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8503 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8504 /*RefAsPointee*/true); 8505 8506 return GetAlignOfType(Info, E->getType(), ExprKind); 8507 } 8508 8509 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8510 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8511 return Info.Ctx.getDeclAlign(VD); 8512 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8513 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8514 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8515 } 8516 8517 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8518 /// __builtin_is_aligned and __builtin_assume_aligned. 8519 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8520 EvalInfo &Info, APSInt &Alignment) { 8521 if (!EvaluateInteger(E, Alignment, Info)) 8522 return false; 8523 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8524 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8525 return false; 8526 } 8527 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8528 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8529 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8530 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8531 << MaxValue << ForType << Alignment; 8532 return false; 8533 } 8534 // Ensure both alignment and source value have the same bit width so that we 8535 // don't assert when computing the resulting value. 8536 APSInt ExtAlignment = 8537 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8538 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8539 "Alignment should not be changed by ext/trunc"); 8540 Alignment = ExtAlignment; 8541 assert(Alignment.getBitWidth() == SrcWidth); 8542 return true; 8543 } 8544 8545 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8546 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8547 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8548 return true; 8549 8550 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8551 return false; 8552 8553 Result.setInvalid(E); 8554 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8555 Result.addUnsizedArray(Info, E, PointeeTy); 8556 return true; 8557 } 8558 8559 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8560 if (IsStringLiteralCall(E)) 8561 return Success(E); 8562 8563 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8564 return VisitBuiltinCallExpr(E, BuiltinOp); 8565 8566 return visitNonBuiltinCallExpr(E); 8567 } 8568 8569 // Determine if T is a character type for which we guarantee that 8570 // sizeof(T) == 1. 8571 static bool isOneByteCharacterType(QualType T) { 8572 return T->isCharType() || T->isChar8Type(); 8573 } 8574 8575 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8576 unsigned BuiltinOp) { 8577 switch (BuiltinOp) { 8578 case Builtin::BI__builtin_addressof: 8579 return evaluateLValue(E->getArg(0), Result); 8580 case Builtin::BI__builtin_assume_aligned: { 8581 // We need to be very careful here because: if the pointer does not have the 8582 // asserted alignment, then the behavior is undefined, and undefined 8583 // behavior is non-constant. 8584 if (!evaluatePointer(E->getArg(0), Result)) 8585 return false; 8586 8587 LValue OffsetResult(Result); 8588 APSInt Alignment; 8589 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8590 Alignment)) 8591 return false; 8592 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8593 8594 if (E->getNumArgs() > 2) { 8595 APSInt Offset; 8596 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8597 return false; 8598 8599 int64_t AdditionalOffset = -Offset.getZExtValue(); 8600 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8601 } 8602 8603 // If there is a base object, then it must have the correct alignment. 8604 if (OffsetResult.Base) { 8605 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 8606 8607 if (BaseAlignment < Align) { 8608 Result.Designator.setInvalid(); 8609 // FIXME: Add support to Diagnostic for long / long long. 8610 CCEDiag(E->getArg(0), 8611 diag::note_constexpr_baa_insufficient_alignment) << 0 8612 << (unsigned)BaseAlignment.getQuantity() 8613 << (unsigned)Align.getQuantity(); 8614 return false; 8615 } 8616 } 8617 8618 // The offset must also have the correct alignment. 8619 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 8620 Result.Designator.setInvalid(); 8621 8622 (OffsetResult.Base 8623 ? CCEDiag(E->getArg(0), 8624 diag::note_constexpr_baa_insufficient_alignment) << 1 8625 : CCEDiag(E->getArg(0), 8626 diag::note_constexpr_baa_value_insufficient_alignment)) 8627 << (int)OffsetResult.Offset.getQuantity() 8628 << (unsigned)Align.getQuantity(); 8629 return false; 8630 } 8631 8632 return true; 8633 } 8634 case Builtin::BI__builtin_align_up: 8635 case Builtin::BI__builtin_align_down: { 8636 if (!evaluatePointer(E->getArg(0), Result)) 8637 return false; 8638 APSInt Alignment; 8639 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8640 Alignment)) 8641 return false; 8642 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 8643 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 8644 // For align_up/align_down, we can return the same value if the alignment 8645 // is known to be greater or equal to the requested value. 8646 if (PtrAlign.getQuantity() >= Alignment) 8647 return true; 8648 8649 // The alignment could be greater than the minimum at run-time, so we cannot 8650 // infer much about the resulting pointer value. One case is possible: 8651 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 8652 // can infer the correct index if the requested alignment is smaller than 8653 // the base alignment so we can perform the computation on the offset. 8654 if (BaseAlignment.getQuantity() >= Alignment) { 8655 assert(Alignment.getBitWidth() <= 64 && 8656 "Cannot handle > 64-bit address-space"); 8657 uint64_t Alignment64 = Alignment.getZExtValue(); 8658 CharUnits NewOffset = CharUnits::fromQuantity( 8659 BuiltinOp == Builtin::BI__builtin_align_down 8660 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 8661 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 8662 Result.adjustOffset(NewOffset - Result.Offset); 8663 // TODO: diagnose out-of-bounds values/only allow for arrays? 8664 return true; 8665 } 8666 // Otherwise, we cannot constant-evaluate the result. 8667 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 8668 << Alignment; 8669 return false; 8670 } 8671 case Builtin::BI__builtin_operator_new: 8672 return HandleOperatorNewCall(Info, E, Result); 8673 case Builtin::BI__builtin_launder: 8674 return evaluatePointer(E->getArg(0), Result); 8675 case Builtin::BIstrchr: 8676 case Builtin::BIwcschr: 8677 case Builtin::BImemchr: 8678 case Builtin::BIwmemchr: 8679 if (Info.getLangOpts().CPlusPlus11) 8680 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8681 << /*isConstexpr*/0 << /*isConstructor*/0 8682 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8683 else 8684 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8685 LLVM_FALLTHROUGH; 8686 case Builtin::BI__builtin_strchr: 8687 case Builtin::BI__builtin_wcschr: 8688 case Builtin::BI__builtin_memchr: 8689 case Builtin::BI__builtin_char_memchr: 8690 case Builtin::BI__builtin_wmemchr: { 8691 if (!Visit(E->getArg(0))) 8692 return false; 8693 APSInt Desired; 8694 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 8695 return false; 8696 uint64_t MaxLength = uint64_t(-1); 8697 if (BuiltinOp != Builtin::BIstrchr && 8698 BuiltinOp != Builtin::BIwcschr && 8699 BuiltinOp != Builtin::BI__builtin_strchr && 8700 BuiltinOp != Builtin::BI__builtin_wcschr) { 8701 APSInt N; 8702 if (!EvaluateInteger(E->getArg(2), N, Info)) 8703 return false; 8704 MaxLength = N.getExtValue(); 8705 } 8706 // We cannot find the value if there are no candidates to match against. 8707 if (MaxLength == 0u) 8708 return ZeroInitialization(E); 8709 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 8710 Result.Designator.Invalid) 8711 return false; 8712 QualType CharTy = Result.Designator.getType(Info.Ctx); 8713 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 8714 BuiltinOp == Builtin::BI__builtin_memchr; 8715 assert(IsRawByte || 8716 Info.Ctx.hasSameUnqualifiedType( 8717 CharTy, E->getArg(0)->getType()->getPointeeType())); 8718 // Pointers to const void may point to objects of incomplete type. 8719 if (IsRawByte && CharTy->isIncompleteType()) { 8720 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 8721 return false; 8722 } 8723 // Give up on byte-oriented matching against multibyte elements. 8724 // FIXME: We can compare the bytes in the correct order. 8725 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 8726 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 8727 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 8728 << CharTy; 8729 return false; 8730 } 8731 // Figure out what value we're actually looking for (after converting to 8732 // the corresponding unsigned type if necessary). 8733 uint64_t DesiredVal; 8734 bool StopAtNull = false; 8735 switch (BuiltinOp) { 8736 case Builtin::BIstrchr: 8737 case Builtin::BI__builtin_strchr: 8738 // strchr compares directly to the passed integer, and therefore 8739 // always fails if given an int that is not a char. 8740 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 8741 E->getArg(1)->getType(), 8742 Desired), 8743 Desired)) 8744 return ZeroInitialization(E); 8745 StopAtNull = true; 8746 LLVM_FALLTHROUGH; 8747 case Builtin::BImemchr: 8748 case Builtin::BI__builtin_memchr: 8749 case Builtin::BI__builtin_char_memchr: 8750 // memchr compares by converting both sides to unsigned char. That's also 8751 // correct for strchr if we get this far (to cope with plain char being 8752 // unsigned in the strchr case). 8753 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 8754 break; 8755 8756 case Builtin::BIwcschr: 8757 case Builtin::BI__builtin_wcschr: 8758 StopAtNull = true; 8759 LLVM_FALLTHROUGH; 8760 case Builtin::BIwmemchr: 8761 case Builtin::BI__builtin_wmemchr: 8762 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 8763 DesiredVal = Desired.getZExtValue(); 8764 break; 8765 } 8766 8767 for (; MaxLength; --MaxLength) { 8768 APValue Char; 8769 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 8770 !Char.isInt()) 8771 return false; 8772 if (Char.getInt().getZExtValue() == DesiredVal) 8773 return true; 8774 if (StopAtNull && !Char.getInt()) 8775 break; 8776 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 8777 return false; 8778 } 8779 // Not found: return nullptr. 8780 return ZeroInitialization(E); 8781 } 8782 8783 case Builtin::BImemcpy: 8784 case Builtin::BImemmove: 8785 case Builtin::BIwmemcpy: 8786 case Builtin::BIwmemmove: 8787 if (Info.getLangOpts().CPlusPlus11) 8788 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8789 << /*isConstexpr*/0 << /*isConstructor*/0 8790 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8791 else 8792 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8793 LLVM_FALLTHROUGH; 8794 case Builtin::BI__builtin_memcpy: 8795 case Builtin::BI__builtin_memmove: 8796 case Builtin::BI__builtin_wmemcpy: 8797 case Builtin::BI__builtin_wmemmove: { 8798 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 8799 BuiltinOp == Builtin::BIwmemmove || 8800 BuiltinOp == Builtin::BI__builtin_wmemcpy || 8801 BuiltinOp == Builtin::BI__builtin_wmemmove; 8802 bool Move = BuiltinOp == Builtin::BImemmove || 8803 BuiltinOp == Builtin::BIwmemmove || 8804 BuiltinOp == Builtin::BI__builtin_memmove || 8805 BuiltinOp == Builtin::BI__builtin_wmemmove; 8806 8807 // The result of mem* is the first argument. 8808 if (!Visit(E->getArg(0))) 8809 return false; 8810 LValue Dest = Result; 8811 8812 LValue Src; 8813 if (!EvaluatePointer(E->getArg(1), Src, Info)) 8814 return false; 8815 8816 APSInt N; 8817 if (!EvaluateInteger(E->getArg(2), N, Info)) 8818 return false; 8819 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 8820 8821 // If the size is zero, we treat this as always being a valid no-op. 8822 // (Even if one of the src and dest pointers is null.) 8823 if (!N) 8824 return true; 8825 8826 // Otherwise, if either of the operands is null, we can't proceed. Don't 8827 // try to determine the type of the copied objects, because there aren't 8828 // any. 8829 if (!Src.Base || !Dest.Base) { 8830 APValue Val; 8831 (!Src.Base ? Src : Dest).moveInto(Val); 8832 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 8833 << Move << WChar << !!Src.Base 8834 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 8835 return false; 8836 } 8837 if (Src.Designator.Invalid || Dest.Designator.Invalid) 8838 return false; 8839 8840 // We require that Src and Dest are both pointers to arrays of 8841 // trivially-copyable type. (For the wide version, the designator will be 8842 // invalid if the designated object is not a wchar_t.) 8843 QualType T = Dest.Designator.getType(Info.Ctx); 8844 QualType SrcT = Src.Designator.getType(Info.Ctx); 8845 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 8846 // FIXME: Consider using our bit_cast implementation to support this. 8847 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 8848 return false; 8849 } 8850 if (T->isIncompleteType()) { 8851 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 8852 return false; 8853 } 8854 if (!T.isTriviallyCopyableType(Info.Ctx)) { 8855 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 8856 return false; 8857 } 8858 8859 // Figure out how many T's we're copying. 8860 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 8861 if (!WChar) { 8862 uint64_t Remainder; 8863 llvm::APInt OrigN = N; 8864 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 8865 if (Remainder) { 8866 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8867 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 8868 << (unsigned)TSize; 8869 return false; 8870 } 8871 } 8872 8873 // Check that the copying will remain within the arrays, just so that we 8874 // can give a more meaningful diagnostic. This implicitly also checks that 8875 // N fits into 64 bits. 8876 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 8877 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 8878 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 8879 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8880 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 8881 << N.toString(10, /*Signed*/false); 8882 return false; 8883 } 8884 uint64_t NElems = N.getZExtValue(); 8885 uint64_t NBytes = NElems * TSize; 8886 8887 // Check for overlap. 8888 int Direction = 1; 8889 if (HasSameBase(Src, Dest)) { 8890 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 8891 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 8892 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 8893 // Dest is inside the source region. 8894 if (!Move) { 8895 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 8896 return false; 8897 } 8898 // For memmove and friends, copy backwards. 8899 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 8900 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 8901 return false; 8902 Direction = -1; 8903 } else if (!Move && SrcOffset >= DestOffset && 8904 SrcOffset - DestOffset < NBytes) { 8905 // Src is inside the destination region for memcpy: invalid. 8906 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 8907 return false; 8908 } 8909 } 8910 8911 while (true) { 8912 APValue Val; 8913 // FIXME: Set WantObjectRepresentation to true if we're copying a 8914 // char-like type? 8915 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 8916 !handleAssignment(Info, E, Dest, T, Val)) 8917 return false; 8918 // Do not iterate past the last element; if we're copying backwards, that 8919 // might take us off the start of the array. 8920 if (--NElems == 0) 8921 return true; 8922 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 8923 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 8924 return false; 8925 } 8926 } 8927 8928 default: 8929 break; 8930 } 8931 8932 return visitNonBuiltinCallExpr(E); 8933 } 8934 8935 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 8936 APValue &Result, const InitListExpr *ILE, 8937 QualType AllocType); 8938 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 8939 APValue &Result, 8940 const CXXConstructExpr *CCE, 8941 QualType AllocType); 8942 8943 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 8944 if (!Info.getLangOpts().CPlusPlus20) 8945 Info.CCEDiag(E, diag::note_constexpr_new); 8946 8947 // We cannot speculatively evaluate a delete expression. 8948 if (Info.SpeculativeEvaluationDepth) 8949 return false; 8950 8951 FunctionDecl *OperatorNew = E->getOperatorNew(); 8952 8953 bool IsNothrow = false; 8954 bool IsPlacement = false; 8955 if (OperatorNew->isReservedGlobalPlacementOperator() && 8956 Info.CurrentCall->isStdFunction() && !E->isArray()) { 8957 // FIXME Support array placement new. 8958 assert(E->getNumPlacementArgs() == 1); 8959 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 8960 return false; 8961 if (Result.Designator.Invalid) 8962 return false; 8963 IsPlacement = true; 8964 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 8965 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 8966 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 8967 return false; 8968 } else if (E->getNumPlacementArgs()) { 8969 // The only new-placement list we support is of the form (std::nothrow). 8970 // 8971 // FIXME: There is no restriction on this, but it's not clear that any 8972 // other form makes any sense. We get here for cases such as: 8973 // 8974 // new (std::align_val_t{N}) X(int) 8975 // 8976 // (which should presumably be valid only if N is a multiple of 8977 // alignof(int), and in any case can't be deallocated unless N is 8978 // alignof(X) and X has new-extended alignment). 8979 if (E->getNumPlacementArgs() != 1 || 8980 !E->getPlacementArg(0)->getType()->isNothrowT()) 8981 return Error(E, diag::note_constexpr_new_placement); 8982 8983 LValue Nothrow; 8984 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 8985 return false; 8986 IsNothrow = true; 8987 } 8988 8989 const Expr *Init = E->getInitializer(); 8990 const InitListExpr *ResizedArrayILE = nullptr; 8991 const CXXConstructExpr *ResizedArrayCCE = nullptr; 8992 bool ValueInit = false; 8993 8994 QualType AllocType = E->getAllocatedType(); 8995 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 8996 const Expr *Stripped = *ArraySize; 8997 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 8998 Stripped = ICE->getSubExpr()) 8999 if (ICE->getCastKind() != CK_NoOp && 9000 ICE->getCastKind() != CK_IntegralCast) 9001 break; 9002 9003 llvm::APSInt ArrayBound; 9004 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9005 return false; 9006 9007 // C++ [expr.new]p9: 9008 // The expression is erroneous if: 9009 // -- [...] its value before converting to size_t [or] applying the 9010 // second standard conversion sequence is less than zero 9011 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9012 if (IsNothrow) 9013 return ZeroInitialization(E); 9014 9015 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9016 << ArrayBound << (*ArraySize)->getSourceRange(); 9017 return false; 9018 } 9019 9020 // -- its value is such that the size of the allocated object would 9021 // exceed the implementation-defined limit 9022 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9023 ArrayBound) > 9024 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9025 if (IsNothrow) 9026 return ZeroInitialization(E); 9027 9028 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9029 << ArrayBound << (*ArraySize)->getSourceRange(); 9030 return false; 9031 } 9032 9033 // -- the new-initializer is a braced-init-list and the number of 9034 // array elements for which initializers are provided [...] 9035 // exceeds the number of elements to initialize 9036 if (!Init) { 9037 // No initialization is performed. 9038 } else if (isa<CXXScalarValueInitExpr>(Init) || 9039 isa<ImplicitValueInitExpr>(Init)) { 9040 ValueInit = true; 9041 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9042 ResizedArrayCCE = CCE; 9043 } else { 9044 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9045 assert(CAT && "unexpected type for array initializer"); 9046 9047 unsigned Bits = 9048 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9049 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9050 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9051 if (InitBound.ugt(AllocBound)) { 9052 if (IsNothrow) 9053 return ZeroInitialization(E); 9054 9055 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9056 << AllocBound.toString(10, /*Signed=*/false) 9057 << InitBound.toString(10, /*Signed=*/false) 9058 << (*ArraySize)->getSourceRange(); 9059 return false; 9060 } 9061 9062 // If the sizes differ, we must have an initializer list, and we need 9063 // special handling for this case when we initialize. 9064 if (InitBound != AllocBound) 9065 ResizedArrayILE = cast<InitListExpr>(Init); 9066 } 9067 9068 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9069 ArrayType::Normal, 0); 9070 } else { 9071 assert(!AllocType->isArrayType() && 9072 "array allocation with non-array new"); 9073 } 9074 9075 APValue *Val; 9076 if (IsPlacement) { 9077 AccessKinds AK = AK_Construct; 9078 struct FindObjectHandler { 9079 EvalInfo &Info; 9080 const Expr *E; 9081 QualType AllocType; 9082 const AccessKinds AccessKind; 9083 APValue *Value; 9084 9085 typedef bool result_type; 9086 bool failed() { return false; } 9087 bool found(APValue &Subobj, QualType SubobjType) { 9088 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9089 // old name of the object to be used to name the new object. 9090 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9091 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9092 SubobjType << AllocType; 9093 return false; 9094 } 9095 Value = &Subobj; 9096 return true; 9097 } 9098 bool found(APSInt &Value, QualType SubobjType) { 9099 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9100 return false; 9101 } 9102 bool found(APFloat &Value, QualType SubobjType) { 9103 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9104 return false; 9105 } 9106 } Handler = {Info, E, AllocType, AK, nullptr}; 9107 9108 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9109 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9110 return false; 9111 9112 Val = Handler.Value; 9113 9114 // [basic.life]p1: 9115 // The lifetime of an object o of type T ends when [...] the storage 9116 // which the object occupies is [...] reused by an object that is not 9117 // nested within o (6.6.2). 9118 *Val = APValue(); 9119 } else { 9120 // Perform the allocation and obtain a pointer to the resulting object. 9121 Val = Info.createHeapAlloc(E, AllocType, Result); 9122 if (!Val) 9123 return false; 9124 } 9125 9126 if (ValueInit) { 9127 ImplicitValueInitExpr VIE(AllocType); 9128 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9129 return false; 9130 } else if (ResizedArrayILE) { 9131 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9132 AllocType)) 9133 return false; 9134 } else if (ResizedArrayCCE) { 9135 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9136 AllocType)) 9137 return false; 9138 } else if (Init) { 9139 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9140 return false; 9141 } else if (!getDefaultInitValue(AllocType, *Val)) { 9142 return false; 9143 } 9144 9145 // Array new returns a pointer to the first element, not a pointer to the 9146 // array. 9147 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9148 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9149 9150 return true; 9151 } 9152 //===----------------------------------------------------------------------===// 9153 // Member Pointer Evaluation 9154 //===----------------------------------------------------------------------===// 9155 9156 namespace { 9157 class MemberPointerExprEvaluator 9158 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9159 MemberPtr &Result; 9160 9161 bool Success(const ValueDecl *D) { 9162 Result = MemberPtr(D); 9163 return true; 9164 } 9165 public: 9166 9167 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9168 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9169 9170 bool Success(const APValue &V, const Expr *E) { 9171 Result.setFrom(V); 9172 return true; 9173 } 9174 bool ZeroInitialization(const Expr *E) { 9175 return Success((const ValueDecl*)nullptr); 9176 } 9177 9178 bool VisitCastExpr(const CastExpr *E); 9179 bool VisitUnaryAddrOf(const UnaryOperator *E); 9180 }; 9181 } // end anonymous namespace 9182 9183 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9184 EvalInfo &Info) { 9185 assert(E->isRValue() && E->getType()->isMemberPointerType()); 9186 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9187 } 9188 9189 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9190 switch (E->getCastKind()) { 9191 default: 9192 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9193 9194 case CK_NullToMemberPointer: 9195 VisitIgnoredValue(E->getSubExpr()); 9196 return ZeroInitialization(E); 9197 9198 case CK_BaseToDerivedMemberPointer: { 9199 if (!Visit(E->getSubExpr())) 9200 return false; 9201 if (E->path_empty()) 9202 return true; 9203 // Base-to-derived member pointer casts store the path in derived-to-base 9204 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9205 // the wrong end of the derived->base arc, so stagger the path by one class. 9206 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9207 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9208 PathI != PathE; ++PathI) { 9209 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9210 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9211 if (!Result.castToDerived(Derived)) 9212 return Error(E); 9213 } 9214 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9215 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9216 return Error(E); 9217 return true; 9218 } 9219 9220 case CK_DerivedToBaseMemberPointer: 9221 if (!Visit(E->getSubExpr())) 9222 return false; 9223 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9224 PathE = E->path_end(); PathI != PathE; ++PathI) { 9225 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9226 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9227 if (!Result.castToBase(Base)) 9228 return Error(E); 9229 } 9230 return true; 9231 } 9232 } 9233 9234 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9235 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9236 // member can be formed. 9237 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9238 } 9239 9240 //===----------------------------------------------------------------------===// 9241 // Record Evaluation 9242 //===----------------------------------------------------------------------===// 9243 9244 namespace { 9245 class RecordExprEvaluator 9246 : public ExprEvaluatorBase<RecordExprEvaluator> { 9247 const LValue &This; 9248 APValue &Result; 9249 public: 9250 9251 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9252 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9253 9254 bool Success(const APValue &V, const Expr *E) { 9255 Result = V; 9256 return true; 9257 } 9258 bool ZeroInitialization(const Expr *E) { 9259 return ZeroInitialization(E, E->getType()); 9260 } 9261 bool ZeroInitialization(const Expr *E, QualType T); 9262 9263 bool VisitCallExpr(const CallExpr *E) { 9264 return handleCallExpr(E, Result, &This); 9265 } 9266 bool VisitCastExpr(const CastExpr *E); 9267 bool VisitInitListExpr(const InitListExpr *E); 9268 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9269 return VisitCXXConstructExpr(E, E->getType()); 9270 } 9271 bool VisitLambdaExpr(const LambdaExpr *E); 9272 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9273 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9274 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9275 bool VisitBinCmp(const BinaryOperator *E); 9276 }; 9277 } 9278 9279 /// Perform zero-initialization on an object of non-union class type. 9280 /// C++11 [dcl.init]p5: 9281 /// To zero-initialize an object or reference of type T means: 9282 /// [...] 9283 /// -- if T is a (possibly cv-qualified) non-union class type, 9284 /// each non-static data member and each base-class subobject is 9285 /// zero-initialized 9286 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9287 const RecordDecl *RD, 9288 const LValue &This, APValue &Result) { 9289 assert(!RD->isUnion() && "Expected non-union class type"); 9290 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9291 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9292 std::distance(RD->field_begin(), RD->field_end())); 9293 9294 if (RD->isInvalidDecl()) return false; 9295 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9296 9297 if (CD) { 9298 unsigned Index = 0; 9299 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9300 End = CD->bases_end(); I != End; ++I, ++Index) { 9301 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9302 LValue Subobject = This; 9303 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9304 return false; 9305 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9306 Result.getStructBase(Index))) 9307 return false; 9308 } 9309 } 9310 9311 for (const auto *I : RD->fields()) { 9312 // -- if T is a reference type, no initialization is performed. 9313 if (I->getType()->isReferenceType()) 9314 continue; 9315 9316 LValue Subobject = This; 9317 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9318 return false; 9319 9320 ImplicitValueInitExpr VIE(I->getType()); 9321 if (!EvaluateInPlace( 9322 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9323 return false; 9324 } 9325 9326 return true; 9327 } 9328 9329 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9330 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9331 if (RD->isInvalidDecl()) return false; 9332 if (RD->isUnion()) { 9333 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9334 // object's first non-static named data member is zero-initialized 9335 RecordDecl::field_iterator I = RD->field_begin(); 9336 if (I == RD->field_end()) { 9337 Result = APValue((const FieldDecl*)nullptr); 9338 return true; 9339 } 9340 9341 LValue Subobject = This; 9342 if (!HandleLValueMember(Info, E, Subobject, *I)) 9343 return false; 9344 Result = APValue(*I); 9345 ImplicitValueInitExpr VIE(I->getType()); 9346 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9347 } 9348 9349 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9350 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9351 return false; 9352 } 9353 9354 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9355 } 9356 9357 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9358 switch (E->getCastKind()) { 9359 default: 9360 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9361 9362 case CK_ConstructorConversion: 9363 return Visit(E->getSubExpr()); 9364 9365 case CK_DerivedToBase: 9366 case CK_UncheckedDerivedToBase: { 9367 APValue DerivedObject; 9368 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9369 return false; 9370 if (!DerivedObject.isStruct()) 9371 return Error(E->getSubExpr()); 9372 9373 // Derived-to-base rvalue conversion: just slice off the derived part. 9374 APValue *Value = &DerivedObject; 9375 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9376 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9377 PathE = E->path_end(); PathI != PathE; ++PathI) { 9378 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9379 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9380 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9381 RD = Base; 9382 } 9383 Result = *Value; 9384 return true; 9385 } 9386 } 9387 } 9388 9389 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9390 if (E->isTransparent()) 9391 return Visit(E->getInit(0)); 9392 9393 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9394 if (RD->isInvalidDecl()) return false; 9395 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9396 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9397 9398 EvalInfo::EvaluatingConstructorRAII EvalObj( 9399 Info, 9400 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9401 CXXRD && CXXRD->getNumBases()); 9402 9403 if (RD->isUnion()) { 9404 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9405 Result = APValue(Field); 9406 if (!Field) 9407 return true; 9408 9409 // If the initializer list for a union does not contain any elements, the 9410 // first element of the union is value-initialized. 9411 // FIXME: The element should be initialized from an initializer list. 9412 // Is this difference ever observable for initializer lists which 9413 // we don't build? 9414 ImplicitValueInitExpr VIE(Field->getType()); 9415 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9416 9417 LValue Subobject = This; 9418 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9419 return false; 9420 9421 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9422 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9423 isa<CXXDefaultInitExpr>(InitExpr)); 9424 9425 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 9426 } 9427 9428 if (!Result.hasValue()) 9429 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9430 std::distance(RD->field_begin(), RD->field_end())); 9431 unsigned ElementNo = 0; 9432 bool Success = true; 9433 9434 // Initialize base classes. 9435 if (CXXRD && CXXRD->getNumBases()) { 9436 for (const auto &Base : CXXRD->bases()) { 9437 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9438 const Expr *Init = E->getInit(ElementNo); 9439 9440 LValue Subobject = This; 9441 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9442 return false; 9443 9444 APValue &FieldVal = Result.getStructBase(ElementNo); 9445 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9446 if (!Info.noteFailure()) 9447 return false; 9448 Success = false; 9449 } 9450 ++ElementNo; 9451 } 9452 9453 EvalObj.finishedConstructingBases(); 9454 } 9455 9456 // Initialize members. 9457 for (const auto *Field : RD->fields()) { 9458 // Anonymous bit-fields are not considered members of the class for 9459 // purposes of aggregate initialization. 9460 if (Field->isUnnamedBitfield()) 9461 continue; 9462 9463 LValue Subobject = This; 9464 9465 bool HaveInit = ElementNo < E->getNumInits(); 9466 9467 // FIXME: Diagnostics here should point to the end of the initializer 9468 // list, not the start. 9469 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9470 Subobject, Field, &Layout)) 9471 return false; 9472 9473 // Perform an implicit value-initialization for members beyond the end of 9474 // the initializer list. 9475 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9476 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9477 9478 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9479 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9480 isa<CXXDefaultInitExpr>(Init)); 9481 9482 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9483 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9484 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9485 FieldVal, Field))) { 9486 if (!Info.noteFailure()) 9487 return false; 9488 Success = false; 9489 } 9490 } 9491 9492 EvalObj.finishedConstructingFields(); 9493 9494 return Success; 9495 } 9496 9497 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9498 QualType T) { 9499 // Note that E's type is not necessarily the type of our class here; we might 9500 // be initializing an array element instead. 9501 const CXXConstructorDecl *FD = E->getConstructor(); 9502 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9503 9504 bool ZeroInit = E->requiresZeroInitialization(); 9505 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9506 // If we've already performed zero-initialization, we're already done. 9507 if (Result.hasValue()) 9508 return true; 9509 9510 if (ZeroInit) 9511 return ZeroInitialization(E, T); 9512 9513 return getDefaultInitValue(T, Result); 9514 } 9515 9516 const FunctionDecl *Definition = nullptr; 9517 auto Body = FD->getBody(Definition); 9518 9519 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9520 return false; 9521 9522 // Avoid materializing a temporary for an elidable copy/move constructor. 9523 if (E->isElidable() && !ZeroInit) 9524 if (const MaterializeTemporaryExpr *ME 9525 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9526 return Visit(ME->getSubExpr()); 9527 9528 if (ZeroInit && !ZeroInitialization(E, T)) 9529 return false; 9530 9531 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9532 return HandleConstructorCall(E, This, Args, 9533 cast<CXXConstructorDecl>(Definition), Info, 9534 Result); 9535 } 9536 9537 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9538 const CXXInheritedCtorInitExpr *E) { 9539 if (!Info.CurrentCall) { 9540 assert(Info.checkingPotentialConstantExpression()); 9541 return false; 9542 } 9543 9544 const CXXConstructorDecl *FD = E->getConstructor(); 9545 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9546 return false; 9547 9548 const FunctionDecl *Definition = nullptr; 9549 auto Body = FD->getBody(Definition); 9550 9551 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9552 return false; 9553 9554 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9555 cast<CXXConstructorDecl>(Definition), Info, 9556 Result); 9557 } 9558 9559 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9560 const CXXStdInitializerListExpr *E) { 9561 const ConstantArrayType *ArrayType = 9562 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9563 9564 LValue Array; 9565 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9566 return false; 9567 9568 // Get a pointer to the first element of the array. 9569 Array.addArray(Info, E, ArrayType); 9570 9571 auto InvalidType = [&] { 9572 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9573 << E->getType(); 9574 return false; 9575 }; 9576 9577 // FIXME: Perform the checks on the field types in SemaInit. 9578 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9579 RecordDecl::field_iterator Field = Record->field_begin(); 9580 if (Field == Record->field_end()) 9581 return InvalidType(); 9582 9583 // Start pointer. 9584 if (!Field->getType()->isPointerType() || 9585 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9586 ArrayType->getElementType())) 9587 return InvalidType(); 9588 9589 // FIXME: What if the initializer_list type has base classes, etc? 9590 Result = APValue(APValue::UninitStruct(), 0, 2); 9591 Array.moveInto(Result.getStructField(0)); 9592 9593 if (++Field == Record->field_end()) 9594 return InvalidType(); 9595 9596 if (Field->getType()->isPointerType() && 9597 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9598 ArrayType->getElementType())) { 9599 // End pointer. 9600 if (!HandleLValueArrayAdjustment(Info, E, Array, 9601 ArrayType->getElementType(), 9602 ArrayType->getSize().getZExtValue())) 9603 return false; 9604 Array.moveInto(Result.getStructField(1)); 9605 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9606 // Length. 9607 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9608 else 9609 return InvalidType(); 9610 9611 if (++Field != Record->field_end()) 9612 return InvalidType(); 9613 9614 return true; 9615 } 9616 9617 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 9618 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 9619 if (ClosureClass->isInvalidDecl()) 9620 return false; 9621 9622 const size_t NumFields = 9623 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 9624 9625 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 9626 E->capture_init_end()) && 9627 "The number of lambda capture initializers should equal the number of " 9628 "fields within the closure type"); 9629 9630 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 9631 // Iterate through all the lambda's closure object's fields and initialize 9632 // them. 9633 auto *CaptureInitIt = E->capture_init_begin(); 9634 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 9635 bool Success = true; 9636 for (const auto *Field : ClosureClass->fields()) { 9637 assert(CaptureInitIt != E->capture_init_end()); 9638 // Get the initializer for this field 9639 Expr *const CurFieldInit = *CaptureInitIt++; 9640 9641 // If there is no initializer, either this is a VLA or an error has 9642 // occurred. 9643 if (!CurFieldInit) 9644 return Error(E); 9645 9646 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9647 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 9648 if (!Info.keepEvaluatingAfterFailure()) 9649 return false; 9650 Success = false; 9651 } 9652 ++CaptureIt; 9653 } 9654 return Success; 9655 } 9656 9657 static bool EvaluateRecord(const Expr *E, const LValue &This, 9658 APValue &Result, EvalInfo &Info) { 9659 assert(E->isRValue() && E->getType()->isRecordType() && 9660 "can't evaluate expression as a record rvalue"); 9661 return RecordExprEvaluator(Info, This, Result).Visit(E); 9662 } 9663 9664 //===----------------------------------------------------------------------===// 9665 // Temporary Evaluation 9666 // 9667 // Temporaries are represented in the AST as rvalues, but generally behave like 9668 // lvalues. The full-object of which the temporary is a subobject is implicitly 9669 // materialized so that a reference can bind to it. 9670 //===----------------------------------------------------------------------===// 9671 namespace { 9672 class TemporaryExprEvaluator 9673 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 9674 public: 9675 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 9676 LValueExprEvaluatorBaseTy(Info, Result, false) {} 9677 9678 /// Visit an expression which constructs the value of this temporary. 9679 bool VisitConstructExpr(const Expr *E) { 9680 APValue &Value = 9681 Info.CurrentCall->createTemporary(E, E->getType(), false, Result); 9682 return EvaluateInPlace(Value, Info, Result, E); 9683 } 9684 9685 bool VisitCastExpr(const CastExpr *E) { 9686 switch (E->getCastKind()) { 9687 default: 9688 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 9689 9690 case CK_ConstructorConversion: 9691 return VisitConstructExpr(E->getSubExpr()); 9692 } 9693 } 9694 bool VisitInitListExpr(const InitListExpr *E) { 9695 return VisitConstructExpr(E); 9696 } 9697 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9698 return VisitConstructExpr(E); 9699 } 9700 bool VisitCallExpr(const CallExpr *E) { 9701 return VisitConstructExpr(E); 9702 } 9703 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 9704 return VisitConstructExpr(E); 9705 } 9706 bool VisitLambdaExpr(const LambdaExpr *E) { 9707 return VisitConstructExpr(E); 9708 } 9709 }; 9710 } // end anonymous namespace 9711 9712 /// Evaluate an expression of record type as a temporary. 9713 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 9714 assert(E->isRValue() && E->getType()->isRecordType()); 9715 return TemporaryExprEvaluator(Info, Result).Visit(E); 9716 } 9717 9718 //===----------------------------------------------------------------------===// 9719 // Vector Evaluation 9720 //===----------------------------------------------------------------------===// 9721 9722 namespace { 9723 class VectorExprEvaluator 9724 : public ExprEvaluatorBase<VectorExprEvaluator> { 9725 APValue &Result; 9726 public: 9727 9728 VectorExprEvaluator(EvalInfo &info, APValue &Result) 9729 : ExprEvaluatorBaseTy(info), Result(Result) {} 9730 9731 bool Success(ArrayRef<APValue> V, const Expr *E) { 9732 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 9733 // FIXME: remove this APValue copy. 9734 Result = APValue(V.data(), V.size()); 9735 return true; 9736 } 9737 bool Success(const APValue &V, const Expr *E) { 9738 assert(V.isVector()); 9739 Result = V; 9740 return true; 9741 } 9742 bool ZeroInitialization(const Expr *E); 9743 9744 bool VisitUnaryReal(const UnaryOperator *E) 9745 { return Visit(E->getSubExpr()); } 9746 bool VisitCastExpr(const CastExpr* E); 9747 bool VisitInitListExpr(const InitListExpr *E); 9748 bool VisitUnaryImag(const UnaryOperator *E); 9749 bool VisitBinaryOperator(const BinaryOperator *E); 9750 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 9751 // conditional select), shufflevector, ExtVectorElementExpr 9752 }; 9753 } // end anonymous namespace 9754 9755 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 9756 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 9757 return VectorExprEvaluator(Info, Result).Visit(E); 9758 } 9759 9760 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 9761 const VectorType *VTy = E->getType()->castAs<VectorType>(); 9762 unsigned NElts = VTy->getNumElements(); 9763 9764 const Expr *SE = E->getSubExpr(); 9765 QualType SETy = SE->getType(); 9766 9767 switch (E->getCastKind()) { 9768 case CK_VectorSplat: { 9769 APValue Val = APValue(); 9770 if (SETy->isIntegerType()) { 9771 APSInt IntResult; 9772 if (!EvaluateInteger(SE, IntResult, Info)) 9773 return false; 9774 Val = APValue(std::move(IntResult)); 9775 } else if (SETy->isRealFloatingType()) { 9776 APFloat FloatResult(0.0); 9777 if (!EvaluateFloat(SE, FloatResult, Info)) 9778 return false; 9779 Val = APValue(std::move(FloatResult)); 9780 } else { 9781 return Error(E); 9782 } 9783 9784 // Splat and create vector APValue. 9785 SmallVector<APValue, 4> Elts(NElts, Val); 9786 return Success(Elts, E); 9787 } 9788 case CK_BitCast: { 9789 // Evaluate the operand into an APInt we can extract from. 9790 llvm::APInt SValInt; 9791 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 9792 return false; 9793 // Extract the elements 9794 QualType EltTy = VTy->getElementType(); 9795 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 9796 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 9797 SmallVector<APValue, 4> Elts; 9798 if (EltTy->isRealFloatingType()) { 9799 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 9800 unsigned FloatEltSize = EltSize; 9801 if (&Sem == &APFloat::x87DoubleExtended()) 9802 FloatEltSize = 80; 9803 for (unsigned i = 0; i < NElts; i++) { 9804 llvm::APInt Elt; 9805 if (BigEndian) 9806 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 9807 else 9808 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 9809 Elts.push_back(APValue(APFloat(Sem, Elt))); 9810 } 9811 } else if (EltTy->isIntegerType()) { 9812 for (unsigned i = 0; i < NElts; i++) { 9813 llvm::APInt Elt; 9814 if (BigEndian) 9815 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 9816 else 9817 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 9818 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 9819 } 9820 } else { 9821 return Error(E); 9822 } 9823 return Success(Elts, E); 9824 } 9825 default: 9826 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9827 } 9828 } 9829 9830 bool 9831 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9832 const VectorType *VT = E->getType()->castAs<VectorType>(); 9833 unsigned NumInits = E->getNumInits(); 9834 unsigned NumElements = VT->getNumElements(); 9835 9836 QualType EltTy = VT->getElementType(); 9837 SmallVector<APValue, 4> Elements; 9838 9839 // The number of initializers can be less than the number of 9840 // vector elements. For OpenCL, this can be due to nested vector 9841 // initialization. For GCC compatibility, missing trailing elements 9842 // should be initialized with zeroes. 9843 unsigned CountInits = 0, CountElts = 0; 9844 while (CountElts < NumElements) { 9845 // Handle nested vector initialization. 9846 if (CountInits < NumInits 9847 && E->getInit(CountInits)->getType()->isVectorType()) { 9848 APValue v; 9849 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 9850 return Error(E); 9851 unsigned vlen = v.getVectorLength(); 9852 for (unsigned j = 0; j < vlen; j++) 9853 Elements.push_back(v.getVectorElt(j)); 9854 CountElts += vlen; 9855 } else if (EltTy->isIntegerType()) { 9856 llvm::APSInt sInt(32); 9857 if (CountInits < NumInits) { 9858 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 9859 return false; 9860 } else // trailing integer zero. 9861 sInt = Info.Ctx.MakeIntValue(0, EltTy); 9862 Elements.push_back(APValue(sInt)); 9863 CountElts++; 9864 } else { 9865 llvm::APFloat f(0.0); 9866 if (CountInits < NumInits) { 9867 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 9868 return false; 9869 } else // trailing float zero. 9870 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 9871 Elements.push_back(APValue(f)); 9872 CountElts++; 9873 } 9874 CountInits++; 9875 } 9876 return Success(Elements, E); 9877 } 9878 9879 bool 9880 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 9881 const auto *VT = E->getType()->castAs<VectorType>(); 9882 QualType EltTy = VT->getElementType(); 9883 APValue ZeroElement; 9884 if (EltTy->isIntegerType()) 9885 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 9886 else 9887 ZeroElement = 9888 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 9889 9890 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 9891 return Success(Elements, E); 9892 } 9893 9894 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9895 VisitIgnoredValue(E->getSubExpr()); 9896 return ZeroInitialization(E); 9897 } 9898 9899 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9900 BinaryOperatorKind Op = E->getOpcode(); 9901 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 9902 "Operation not supported on vector types"); 9903 9904 if (Op == BO_Comma) 9905 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9906 9907 Expr *LHS = E->getLHS(); 9908 Expr *RHS = E->getRHS(); 9909 9910 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 9911 "Must both be vector types"); 9912 // Checking JUST the types are the same would be fine, except shifts don't 9913 // need to have their types be the same (since you always shift by an int). 9914 assert(LHS->getType()->getAs<VectorType>()->getNumElements() == 9915 E->getType()->getAs<VectorType>()->getNumElements() && 9916 RHS->getType()->getAs<VectorType>()->getNumElements() == 9917 E->getType()->getAs<VectorType>()->getNumElements() && 9918 "All operands must be the same size."); 9919 9920 APValue LHSValue; 9921 APValue RHSValue; 9922 bool LHSOK = Evaluate(LHSValue, Info, LHS); 9923 if (!LHSOK && !Info.noteFailure()) 9924 return false; 9925 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 9926 return false; 9927 9928 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 9929 return false; 9930 9931 return Success(LHSValue, E); 9932 } 9933 9934 //===----------------------------------------------------------------------===// 9935 // Array Evaluation 9936 //===----------------------------------------------------------------------===// 9937 9938 namespace { 9939 class ArrayExprEvaluator 9940 : public ExprEvaluatorBase<ArrayExprEvaluator> { 9941 const LValue &This; 9942 APValue &Result; 9943 public: 9944 9945 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 9946 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 9947 9948 bool Success(const APValue &V, const Expr *E) { 9949 assert(V.isArray() && "expected array"); 9950 Result = V; 9951 return true; 9952 } 9953 9954 bool ZeroInitialization(const Expr *E) { 9955 const ConstantArrayType *CAT = 9956 Info.Ctx.getAsConstantArrayType(E->getType()); 9957 if (!CAT) { 9958 if (E->getType()->isIncompleteArrayType()) { 9959 // We can be asked to zero-initialize a flexible array member; this 9960 // is represented as an ImplicitValueInitExpr of incomplete array 9961 // type. In this case, the array has zero elements. 9962 Result = APValue(APValue::UninitArray(), 0, 0); 9963 return true; 9964 } 9965 // FIXME: We could handle VLAs here. 9966 return Error(E); 9967 } 9968 9969 Result = APValue(APValue::UninitArray(), 0, 9970 CAT->getSize().getZExtValue()); 9971 if (!Result.hasArrayFiller()) return true; 9972 9973 // Zero-initialize all elements. 9974 LValue Subobject = This; 9975 Subobject.addArray(Info, E, CAT); 9976 ImplicitValueInitExpr VIE(CAT->getElementType()); 9977 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 9978 } 9979 9980 bool VisitCallExpr(const CallExpr *E) { 9981 return handleCallExpr(E, Result, &This); 9982 } 9983 bool VisitInitListExpr(const InitListExpr *E, 9984 QualType AllocType = QualType()); 9985 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 9986 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 9987 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 9988 const LValue &Subobject, 9989 APValue *Value, QualType Type); 9990 bool VisitStringLiteral(const StringLiteral *E, 9991 QualType AllocType = QualType()) { 9992 expandStringLiteral(Info, E, Result, AllocType); 9993 return true; 9994 } 9995 }; 9996 } // end anonymous namespace 9997 9998 static bool EvaluateArray(const Expr *E, const LValue &This, 9999 APValue &Result, EvalInfo &Info) { 10000 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 10001 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10002 } 10003 10004 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10005 APValue &Result, const InitListExpr *ILE, 10006 QualType AllocType) { 10007 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 10008 "not an array rvalue"); 10009 return ArrayExprEvaluator(Info, This, Result) 10010 .VisitInitListExpr(ILE, AllocType); 10011 } 10012 10013 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10014 APValue &Result, 10015 const CXXConstructExpr *CCE, 10016 QualType AllocType) { 10017 assert(CCE->isRValue() && CCE->getType()->isArrayType() && 10018 "not an array rvalue"); 10019 return ArrayExprEvaluator(Info, This, Result) 10020 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10021 } 10022 10023 // Return true iff the given array filler may depend on the element index. 10024 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10025 // For now, just allow non-class value-initialization and initialization 10026 // lists comprised of them. 10027 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10028 return false; 10029 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10030 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10031 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10032 return true; 10033 } 10034 return false; 10035 } 10036 return true; 10037 } 10038 10039 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10040 QualType AllocType) { 10041 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10042 AllocType.isNull() ? E->getType() : AllocType); 10043 if (!CAT) 10044 return Error(E); 10045 10046 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10047 // an appropriately-typed string literal enclosed in braces. 10048 if (E->isStringLiteralInit()) { 10049 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 10050 // FIXME: Support ObjCEncodeExpr here once we support it in 10051 // ArrayExprEvaluator generally. 10052 if (!SL) 10053 return Error(E); 10054 return VisitStringLiteral(SL, AllocType); 10055 } 10056 10057 bool Success = true; 10058 10059 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10060 "zero-initialized array shouldn't have any initialized elts"); 10061 APValue Filler; 10062 if (Result.isArray() && Result.hasArrayFiller()) 10063 Filler = Result.getArrayFiller(); 10064 10065 unsigned NumEltsToInit = E->getNumInits(); 10066 unsigned NumElts = CAT->getSize().getZExtValue(); 10067 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10068 10069 // If the initializer might depend on the array index, run it for each 10070 // array element. 10071 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10072 NumEltsToInit = NumElts; 10073 10074 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10075 << NumEltsToInit << ".\n"); 10076 10077 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10078 10079 // If the array was previously zero-initialized, preserve the 10080 // zero-initialized values. 10081 if (Filler.hasValue()) { 10082 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10083 Result.getArrayInitializedElt(I) = Filler; 10084 if (Result.hasArrayFiller()) 10085 Result.getArrayFiller() = Filler; 10086 } 10087 10088 LValue Subobject = This; 10089 Subobject.addArray(Info, E, CAT); 10090 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10091 const Expr *Init = 10092 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10093 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10094 Info, Subobject, Init) || 10095 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10096 CAT->getElementType(), 1)) { 10097 if (!Info.noteFailure()) 10098 return false; 10099 Success = false; 10100 } 10101 } 10102 10103 if (!Result.hasArrayFiller()) 10104 return Success; 10105 10106 // If we get here, we have a trivial filler, which we can just evaluate 10107 // once and splat over the rest of the array elements. 10108 assert(FillerExpr && "no array filler for incomplete init list"); 10109 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10110 FillerExpr) && Success; 10111 } 10112 10113 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10114 LValue CommonLV; 10115 if (E->getCommonExpr() && 10116 !Evaluate(Info.CurrentCall->createTemporary( 10117 E->getCommonExpr(), 10118 getStorageType(Info.Ctx, E->getCommonExpr()), false, 10119 CommonLV), 10120 Info, E->getCommonExpr()->getSourceExpr())) 10121 return false; 10122 10123 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10124 10125 uint64_t Elements = CAT->getSize().getZExtValue(); 10126 Result = APValue(APValue::UninitArray(), Elements, Elements); 10127 10128 LValue Subobject = This; 10129 Subobject.addArray(Info, E, CAT); 10130 10131 bool Success = true; 10132 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10133 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10134 Info, Subobject, E->getSubExpr()) || 10135 !HandleLValueArrayAdjustment(Info, E, Subobject, 10136 CAT->getElementType(), 1)) { 10137 if (!Info.noteFailure()) 10138 return false; 10139 Success = false; 10140 } 10141 } 10142 10143 return Success; 10144 } 10145 10146 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10147 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10148 } 10149 10150 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10151 const LValue &Subobject, 10152 APValue *Value, 10153 QualType Type) { 10154 bool HadZeroInit = Value->hasValue(); 10155 10156 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10157 unsigned N = CAT->getSize().getZExtValue(); 10158 10159 // Preserve the array filler if we had prior zero-initialization. 10160 APValue Filler = 10161 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10162 : APValue(); 10163 10164 *Value = APValue(APValue::UninitArray(), N, N); 10165 10166 if (HadZeroInit) 10167 for (unsigned I = 0; I != N; ++I) 10168 Value->getArrayInitializedElt(I) = Filler; 10169 10170 // Initialize the elements. 10171 LValue ArrayElt = Subobject; 10172 ArrayElt.addArray(Info, E, CAT); 10173 for (unsigned I = 0; I != N; ++I) 10174 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10175 CAT->getElementType()) || 10176 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10177 CAT->getElementType(), 1)) 10178 return false; 10179 10180 return true; 10181 } 10182 10183 if (!Type->isRecordType()) 10184 return Error(E); 10185 10186 return RecordExprEvaluator(Info, Subobject, *Value) 10187 .VisitCXXConstructExpr(E, Type); 10188 } 10189 10190 //===----------------------------------------------------------------------===// 10191 // Integer Evaluation 10192 // 10193 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10194 // types and back in constant folding. Integer values are thus represented 10195 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10196 //===----------------------------------------------------------------------===// 10197 10198 namespace { 10199 class IntExprEvaluator 10200 : public ExprEvaluatorBase<IntExprEvaluator> { 10201 APValue &Result; 10202 public: 10203 IntExprEvaluator(EvalInfo &info, APValue &result) 10204 : ExprEvaluatorBaseTy(info), Result(result) {} 10205 10206 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10207 assert(E->getType()->isIntegralOrEnumerationType() && 10208 "Invalid evaluation result."); 10209 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10210 "Invalid evaluation result."); 10211 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10212 "Invalid evaluation result."); 10213 Result = APValue(SI); 10214 return true; 10215 } 10216 bool Success(const llvm::APSInt &SI, const Expr *E) { 10217 return Success(SI, E, Result); 10218 } 10219 10220 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10221 assert(E->getType()->isIntegralOrEnumerationType() && 10222 "Invalid evaluation result."); 10223 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10224 "Invalid evaluation result."); 10225 Result = APValue(APSInt(I)); 10226 Result.getInt().setIsUnsigned( 10227 E->getType()->isUnsignedIntegerOrEnumerationType()); 10228 return true; 10229 } 10230 bool Success(const llvm::APInt &I, const Expr *E) { 10231 return Success(I, E, Result); 10232 } 10233 10234 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10235 assert(E->getType()->isIntegralOrEnumerationType() && 10236 "Invalid evaluation result."); 10237 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10238 return true; 10239 } 10240 bool Success(uint64_t Value, const Expr *E) { 10241 return Success(Value, E, Result); 10242 } 10243 10244 bool Success(CharUnits Size, const Expr *E) { 10245 return Success(Size.getQuantity(), E); 10246 } 10247 10248 bool Success(const APValue &V, const Expr *E) { 10249 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10250 Result = V; 10251 return true; 10252 } 10253 return Success(V.getInt(), E); 10254 } 10255 10256 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10257 10258 //===--------------------------------------------------------------------===// 10259 // Visitor Methods 10260 //===--------------------------------------------------------------------===// 10261 10262 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10263 return Success(E->getValue(), E); 10264 } 10265 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10266 return Success(E->getValue(), E); 10267 } 10268 10269 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10270 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10271 if (CheckReferencedDecl(E, E->getDecl())) 10272 return true; 10273 10274 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10275 } 10276 bool VisitMemberExpr(const MemberExpr *E) { 10277 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10278 VisitIgnoredBaseExpression(E->getBase()); 10279 return true; 10280 } 10281 10282 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10283 } 10284 10285 bool VisitCallExpr(const CallExpr *E); 10286 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10287 bool VisitBinaryOperator(const BinaryOperator *E); 10288 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10289 bool VisitUnaryOperator(const UnaryOperator *E); 10290 10291 bool VisitCastExpr(const CastExpr* E); 10292 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10293 10294 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10295 return Success(E->getValue(), E); 10296 } 10297 10298 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10299 return Success(E->getValue(), E); 10300 } 10301 10302 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10303 if (Info.ArrayInitIndex == uint64_t(-1)) { 10304 // We were asked to evaluate this subexpression independent of the 10305 // enclosing ArrayInitLoopExpr. We can't do that. 10306 Info.FFDiag(E); 10307 return false; 10308 } 10309 return Success(Info.ArrayInitIndex, E); 10310 } 10311 10312 // Note, GNU defines __null as an integer, not a pointer. 10313 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10314 return ZeroInitialization(E); 10315 } 10316 10317 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10318 return Success(E->getValue(), E); 10319 } 10320 10321 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10322 return Success(E->getValue(), E); 10323 } 10324 10325 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10326 return Success(E->getValue(), E); 10327 } 10328 10329 bool VisitUnaryReal(const UnaryOperator *E); 10330 bool VisitUnaryImag(const UnaryOperator *E); 10331 10332 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10333 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10334 bool VisitSourceLocExpr(const SourceLocExpr *E); 10335 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10336 bool VisitRequiresExpr(const RequiresExpr *E); 10337 // FIXME: Missing: array subscript of vector, member of vector 10338 }; 10339 10340 class FixedPointExprEvaluator 10341 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10342 APValue &Result; 10343 10344 public: 10345 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10346 : ExprEvaluatorBaseTy(info), Result(result) {} 10347 10348 bool Success(const llvm::APInt &I, const Expr *E) { 10349 return Success( 10350 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10351 } 10352 10353 bool Success(uint64_t Value, const Expr *E) { 10354 return Success( 10355 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10356 } 10357 10358 bool Success(const APValue &V, const Expr *E) { 10359 return Success(V.getFixedPoint(), E); 10360 } 10361 10362 bool Success(const APFixedPoint &V, const Expr *E) { 10363 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10364 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10365 "Invalid evaluation result."); 10366 Result = APValue(V); 10367 return true; 10368 } 10369 10370 //===--------------------------------------------------------------------===// 10371 // Visitor Methods 10372 //===--------------------------------------------------------------------===// 10373 10374 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10375 return Success(E->getValue(), E); 10376 } 10377 10378 bool VisitCastExpr(const CastExpr *E); 10379 bool VisitUnaryOperator(const UnaryOperator *E); 10380 bool VisitBinaryOperator(const BinaryOperator *E); 10381 }; 10382 } // end anonymous namespace 10383 10384 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10385 /// produce either the integer value or a pointer. 10386 /// 10387 /// GCC has a heinous extension which folds casts between pointer types and 10388 /// pointer-sized integral types. We support this by allowing the evaluation of 10389 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10390 /// Some simple arithmetic on such values is supported (they are treated much 10391 /// like char*). 10392 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10393 EvalInfo &Info) { 10394 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10395 return IntExprEvaluator(Info, Result).Visit(E); 10396 } 10397 10398 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10399 APValue Val; 10400 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10401 return false; 10402 if (!Val.isInt()) { 10403 // FIXME: It would be better to produce the diagnostic for casting 10404 // a pointer to an integer. 10405 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10406 return false; 10407 } 10408 Result = Val.getInt(); 10409 return true; 10410 } 10411 10412 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10413 APValue Evaluated = E->EvaluateInContext( 10414 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10415 return Success(Evaluated, E); 10416 } 10417 10418 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10419 EvalInfo &Info) { 10420 if (E->getType()->isFixedPointType()) { 10421 APValue Val; 10422 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10423 return false; 10424 if (!Val.isFixedPoint()) 10425 return false; 10426 10427 Result = Val.getFixedPoint(); 10428 return true; 10429 } 10430 return false; 10431 } 10432 10433 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10434 EvalInfo &Info) { 10435 if (E->getType()->isIntegerType()) { 10436 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10437 APSInt Val; 10438 if (!EvaluateInteger(E, Val, Info)) 10439 return false; 10440 Result = APFixedPoint(Val, FXSema); 10441 return true; 10442 } else if (E->getType()->isFixedPointType()) { 10443 return EvaluateFixedPoint(E, Result, Info); 10444 } 10445 return false; 10446 } 10447 10448 /// Check whether the given declaration can be directly converted to an integral 10449 /// rvalue. If not, no diagnostic is produced; there are other things we can 10450 /// try. 10451 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10452 // Enums are integer constant exprs. 10453 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10454 // Check for signedness/width mismatches between E type and ECD value. 10455 bool SameSign = (ECD->getInitVal().isSigned() 10456 == E->getType()->isSignedIntegerOrEnumerationType()); 10457 bool SameWidth = (ECD->getInitVal().getBitWidth() 10458 == Info.Ctx.getIntWidth(E->getType())); 10459 if (SameSign && SameWidth) 10460 return Success(ECD->getInitVal(), E); 10461 else { 10462 // Get rid of mismatch (otherwise Success assertions will fail) 10463 // by computing a new value matching the type of E. 10464 llvm::APSInt Val = ECD->getInitVal(); 10465 if (!SameSign) 10466 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10467 if (!SameWidth) 10468 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10469 return Success(Val, E); 10470 } 10471 } 10472 return false; 10473 } 10474 10475 /// Values returned by __builtin_classify_type, chosen to match the values 10476 /// produced by GCC's builtin. 10477 enum class GCCTypeClass { 10478 None = -1, 10479 Void = 0, 10480 Integer = 1, 10481 // GCC reserves 2 for character types, but instead classifies them as 10482 // integers. 10483 Enum = 3, 10484 Bool = 4, 10485 Pointer = 5, 10486 // GCC reserves 6 for references, but appears to never use it (because 10487 // expressions never have reference type, presumably). 10488 PointerToDataMember = 7, 10489 RealFloat = 8, 10490 Complex = 9, 10491 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10492 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10493 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10494 // uses 12 for that purpose, same as for a class or struct. Maybe it 10495 // internally implements a pointer to member as a struct? Who knows. 10496 PointerToMemberFunction = 12, // Not a bug, see above. 10497 ClassOrStruct = 12, 10498 Union = 13, 10499 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10500 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10501 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10502 // literals. 10503 }; 10504 10505 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10506 /// as GCC. 10507 static GCCTypeClass 10508 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10509 assert(!T->isDependentType() && "unexpected dependent type"); 10510 10511 QualType CanTy = T.getCanonicalType(); 10512 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10513 10514 switch (CanTy->getTypeClass()) { 10515 #define TYPE(ID, BASE) 10516 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10517 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10518 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10519 #include "clang/AST/TypeNodes.inc" 10520 case Type::Auto: 10521 case Type::DeducedTemplateSpecialization: 10522 llvm_unreachable("unexpected non-canonical or dependent type"); 10523 10524 case Type::Builtin: 10525 switch (BT->getKind()) { 10526 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10527 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10528 case BuiltinType::ID: return GCCTypeClass::Integer; 10529 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10530 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10531 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10532 case BuiltinType::ID: break; 10533 #include "clang/AST/BuiltinTypes.def" 10534 case BuiltinType::Void: 10535 return GCCTypeClass::Void; 10536 10537 case BuiltinType::Bool: 10538 return GCCTypeClass::Bool; 10539 10540 case BuiltinType::Char_U: 10541 case BuiltinType::UChar: 10542 case BuiltinType::WChar_U: 10543 case BuiltinType::Char8: 10544 case BuiltinType::Char16: 10545 case BuiltinType::Char32: 10546 case BuiltinType::UShort: 10547 case BuiltinType::UInt: 10548 case BuiltinType::ULong: 10549 case BuiltinType::ULongLong: 10550 case BuiltinType::UInt128: 10551 return GCCTypeClass::Integer; 10552 10553 case BuiltinType::UShortAccum: 10554 case BuiltinType::UAccum: 10555 case BuiltinType::ULongAccum: 10556 case BuiltinType::UShortFract: 10557 case BuiltinType::UFract: 10558 case BuiltinType::ULongFract: 10559 case BuiltinType::SatUShortAccum: 10560 case BuiltinType::SatUAccum: 10561 case BuiltinType::SatULongAccum: 10562 case BuiltinType::SatUShortFract: 10563 case BuiltinType::SatUFract: 10564 case BuiltinType::SatULongFract: 10565 return GCCTypeClass::None; 10566 10567 case BuiltinType::NullPtr: 10568 10569 case BuiltinType::ObjCId: 10570 case BuiltinType::ObjCClass: 10571 case BuiltinType::ObjCSel: 10572 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10573 case BuiltinType::Id: 10574 #include "clang/Basic/OpenCLImageTypes.def" 10575 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10576 case BuiltinType::Id: 10577 #include "clang/Basic/OpenCLExtensionTypes.def" 10578 case BuiltinType::OCLSampler: 10579 case BuiltinType::OCLEvent: 10580 case BuiltinType::OCLClkEvent: 10581 case BuiltinType::OCLQueue: 10582 case BuiltinType::OCLReserveID: 10583 #define SVE_TYPE(Name, Id, SingletonId) \ 10584 case BuiltinType::Id: 10585 #include "clang/Basic/AArch64SVEACLETypes.def" 10586 return GCCTypeClass::None; 10587 10588 case BuiltinType::Dependent: 10589 llvm_unreachable("unexpected dependent type"); 10590 }; 10591 llvm_unreachable("unexpected placeholder type"); 10592 10593 case Type::Enum: 10594 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 10595 10596 case Type::Pointer: 10597 case Type::ConstantArray: 10598 case Type::VariableArray: 10599 case Type::IncompleteArray: 10600 case Type::FunctionNoProto: 10601 case Type::FunctionProto: 10602 return GCCTypeClass::Pointer; 10603 10604 case Type::MemberPointer: 10605 return CanTy->isMemberDataPointerType() 10606 ? GCCTypeClass::PointerToDataMember 10607 : GCCTypeClass::PointerToMemberFunction; 10608 10609 case Type::Complex: 10610 return GCCTypeClass::Complex; 10611 10612 case Type::Record: 10613 return CanTy->isUnionType() ? GCCTypeClass::Union 10614 : GCCTypeClass::ClassOrStruct; 10615 10616 case Type::Atomic: 10617 // GCC classifies _Atomic T the same as T. 10618 return EvaluateBuiltinClassifyType( 10619 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 10620 10621 case Type::BlockPointer: 10622 case Type::Vector: 10623 case Type::ExtVector: 10624 case Type::ConstantMatrix: 10625 case Type::ObjCObject: 10626 case Type::ObjCInterface: 10627 case Type::ObjCObjectPointer: 10628 case Type::Pipe: 10629 case Type::ExtInt: 10630 // GCC classifies vectors as None. We follow its lead and classify all 10631 // other types that don't fit into the regular classification the same way. 10632 return GCCTypeClass::None; 10633 10634 case Type::LValueReference: 10635 case Type::RValueReference: 10636 llvm_unreachable("invalid type for expression"); 10637 } 10638 10639 llvm_unreachable("unexpected type class"); 10640 } 10641 10642 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10643 /// as GCC. 10644 static GCCTypeClass 10645 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 10646 // If no argument was supplied, default to None. This isn't 10647 // ideal, however it is what gcc does. 10648 if (E->getNumArgs() == 0) 10649 return GCCTypeClass::None; 10650 10651 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 10652 // being an ICE, but still folds it to a constant using the type of the first 10653 // argument. 10654 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 10655 } 10656 10657 /// EvaluateBuiltinConstantPForLValue - Determine the result of 10658 /// __builtin_constant_p when applied to the given pointer. 10659 /// 10660 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 10661 /// or it points to the first character of a string literal. 10662 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 10663 APValue::LValueBase Base = LV.getLValueBase(); 10664 if (Base.isNull()) { 10665 // A null base is acceptable. 10666 return true; 10667 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 10668 if (!isa<StringLiteral>(E)) 10669 return false; 10670 return LV.getLValueOffset().isZero(); 10671 } else if (Base.is<TypeInfoLValue>()) { 10672 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 10673 // evaluate to true. 10674 return true; 10675 } else { 10676 // Any other base is not constant enough for GCC. 10677 return false; 10678 } 10679 } 10680 10681 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 10682 /// GCC as we can manage. 10683 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 10684 // This evaluation is not permitted to have side-effects, so evaluate it in 10685 // a speculative evaluation context. 10686 SpeculativeEvaluationRAII SpeculativeEval(Info); 10687 10688 // Constant-folding is always enabled for the operand of __builtin_constant_p 10689 // (even when the enclosing evaluation context otherwise requires a strict 10690 // language-specific constant expression). 10691 FoldConstant Fold(Info, true); 10692 10693 QualType ArgType = Arg->getType(); 10694 10695 // __builtin_constant_p always has one operand. The rules which gcc follows 10696 // are not precisely documented, but are as follows: 10697 // 10698 // - If the operand is of integral, floating, complex or enumeration type, 10699 // and can be folded to a known value of that type, it returns 1. 10700 // - If the operand can be folded to a pointer to the first character 10701 // of a string literal (or such a pointer cast to an integral type) 10702 // or to a null pointer or an integer cast to a pointer, it returns 1. 10703 // 10704 // Otherwise, it returns 0. 10705 // 10706 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 10707 // its support for this did not work prior to GCC 9 and is not yet well 10708 // understood. 10709 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 10710 ArgType->isAnyComplexType() || ArgType->isPointerType() || 10711 ArgType->isNullPtrType()) { 10712 APValue V; 10713 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 10714 Fold.keepDiagnostics(); 10715 return false; 10716 } 10717 10718 // For a pointer (possibly cast to integer), there are special rules. 10719 if (V.getKind() == APValue::LValue) 10720 return EvaluateBuiltinConstantPForLValue(V); 10721 10722 // Otherwise, any constant value is good enough. 10723 return V.hasValue(); 10724 } 10725 10726 // Anything else isn't considered to be sufficiently constant. 10727 return false; 10728 } 10729 10730 /// Retrieves the "underlying object type" of the given expression, 10731 /// as used by __builtin_object_size. 10732 static QualType getObjectType(APValue::LValueBase B) { 10733 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 10734 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 10735 return VD->getType(); 10736 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 10737 if (isa<CompoundLiteralExpr>(E)) 10738 return E->getType(); 10739 } else if (B.is<TypeInfoLValue>()) { 10740 return B.getTypeInfoType(); 10741 } else if (B.is<DynamicAllocLValue>()) { 10742 return B.getDynamicAllocType(); 10743 } 10744 10745 return QualType(); 10746 } 10747 10748 /// A more selective version of E->IgnoreParenCasts for 10749 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 10750 /// to change the type of E. 10751 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 10752 /// 10753 /// Always returns an RValue with a pointer representation. 10754 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 10755 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 10756 10757 auto *NoParens = E->IgnoreParens(); 10758 auto *Cast = dyn_cast<CastExpr>(NoParens); 10759 if (Cast == nullptr) 10760 return NoParens; 10761 10762 // We only conservatively allow a few kinds of casts, because this code is 10763 // inherently a simple solution that seeks to support the common case. 10764 auto CastKind = Cast->getCastKind(); 10765 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 10766 CastKind != CK_AddressSpaceConversion) 10767 return NoParens; 10768 10769 auto *SubExpr = Cast->getSubExpr(); 10770 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 10771 return NoParens; 10772 return ignorePointerCastsAndParens(SubExpr); 10773 } 10774 10775 /// Checks to see if the given LValue's Designator is at the end of the LValue's 10776 /// record layout. e.g. 10777 /// struct { struct { int a, b; } fst, snd; } obj; 10778 /// obj.fst // no 10779 /// obj.snd // yes 10780 /// obj.fst.a // no 10781 /// obj.fst.b // no 10782 /// obj.snd.a // no 10783 /// obj.snd.b // yes 10784 /// 10785 /// Please note: this function is specialized for how __builtin_object_size 10786 /// views "objects". 10787 /// 10788 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 10789 /// correct result, it will always return true. 10790 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 10791 assert(!LVal.Designator.Invalid); 10792 10793 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 10794 const RecordDecl *Parent = FD->getParent(); 10795 Invalid = Parent->isInvalidDecl(); 10796 if (Invalid || Parent->isUnion()) 10797 return true; 10798 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 10799 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 10800 }; 10801 10802 auto &Base = LVal.getLValueBase(); 10803 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 10804 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 10805 bool Invalid; 10806 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10807 return Invalid; 10808 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 10809 for (auto *FD : IFD->chain()) { 10810 bool Invalid; 10811 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 10812 return Invalid; 10813 } 10814 } 10815 } 10816 10817 unsigned I = 0; 10818 QualType BaseType = getType(Base); 10819 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 10820 // If we don't know the array bound, conservatively assume we're looking at 10821 // the final array element. 10822 ++I; 10823 if (BaseType->isIncompleteArrayType()) 10824 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 10825 else 10826 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 10827 } 10828 10829 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 10830 const auto &Entry = LVal.Designator.Entries[I]; 10831 if (BaseType->isArrayType()) { 10832 // Because __builtin_object_size treats arrays as objects, we can ignore 10833 // the index iff this is the last array in the Designator. 10834 if (I + 1 == E) 10835 return true; 10836 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 10837 uint64_t Index = Entry.getAsArrayIndex(); 10838 if (Index + 1 != CAT->getSize()) 10839 return false; 10840 BaseType = CAT->getElementType(); 10841 } else if (BaseType->isAnyComplexType()) { 10842 const auto *CT = BaseType->castAs<ComplexType>(); 10843 uint64_t Index = Entry.getAsArrayIndex(); 10844 if (Index != 1) 10845 return false; 10846 BaseType = CT->getElementType(); 10847 } else if (auto *FD = getAsField(Entry)) { 10848 bool Invalid; 10849 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10850 return Invalid; 10851 BaseType = FD->getType(); 10852 } else { 10853 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 10854 return false; 10855 } 10856 } 10857 return true; 10858 } 10859 10860 /// Tests to see if the LValue has a user-specified designator (that isn't 10861 /// necessarily valid). Note that this always returns 'true' if the LValue has 10862 /// an unsized array as its first designator entry, because there's currently no 10863 /// way to tell if the user typed *foo or foo[0]. 10864 static bool refersToCompleteObject(const LValue &LVal) { 10865 if (LVal.Designator.Invalid) 10866 return false; 10867 10868 if (!LVal.Designator.Entries.empty()) 10869 return LVal.Designator.isMostDerivedAnUnsizedArray(); 10870 10871 if (!LVal.InvalidBase) 10872 return true; 10873 10874 // If `E` is a MemberExpr, then the first part of the designator is hiding in 10875 // the LValueBase. 10876 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 10877 return !E || !isa<MemberExpr>(E); 10878 } 10879 10880 /// Attempts to detect a user writing into a piece of memory that's impossible 10881 /// to figure out the size of by just using types. 10882 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 10883 const SubobjectDesignator &Designator = LVal.Designator; 10884 // Notes: 10885 // - Users can only write off of the end when we have an invalid base. Invalid 10886 // bases imply we don't know where the memory came from. 10887 // - We used to be a bit more aggressive here; we'd only be conservative if 10888 // the array at the end was flexible, or if it had 0 or 1 elements. This 10889 // broke some common standard library extensions (PR30346), but was 10890 // otherwise seemingly fine. It may be useful to reintroduce this behavior 10891 // with some sort of list. OTOH, it seems that GCC is always 10892 // conservative with the last element in structs (if it's an array), so our 10893 // current behavior is more compatible than an explicit list approach would 10894 // be. 10895 return LVal.InvalidBase && 10896 Designator.Entries.size() == Designator.MostDerivedPathLength && 10897 Designator.MostDerivedIsArrayElement && 10898 isDesignatorAtObjectEnd(Ctx, LVal); 10899 } 10900 10901 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 10902 /// Fails if the conversion would cause loss of precision. 10903 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 10904 CharUnits &Result) { 10905 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 10906 if (Int.ugt(CharUnitsMax)) 10907 return false; 10908 Result = CharUnits::fromQuantity(Int.getZExtValue()); 10909 return true; 10910 } 10911 10912 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 10913 /// determine how many bytes exist from the beginning of the object to either 10914 /// the end of the current subobject, or the end of the object itself, depending 10915 /// on what the LValue looks like + the value of Type. 10916 /// 10917 /// If this returns false, the value of Result is undefined. 10918 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 10919 unsigned Type, const LValue &LVal, 10920 CharUnits &EndOffset) { 10921 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 10922 10923 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 10924 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 10925 return false; 10926 return HandleSizeof(Info, ExprLoc, Ty, Result); 10927 }; 10928 10929 // We want to evaluate the size of the entire object. This is a valid fallback 10930 // for when Type=1 and the designator is invalid, because we're asked for an 10931 // upper-bound. 10932 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 10933 // Type=3 wants a lower bound, so we can't fall back to this. 10934 if (Type == 3 && !DetermineForCompleteObject) 10935 return false; 10936 10937 llvm::APInt APEndOffset; 10938 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 10939 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 10940 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 10941 10942 if (LVal.InvalidBase) 10943 return false; 10944 10945 QualType BaseTy = getObjectType(LVal.getLValueBase()); 10946 return CheckedHandleSizeof(BaseTy, EndOffset); 10947 } 10948 10949 // We want to evaluate the size of a subobject. 10950 const SubobjectDesignator &Designator = LVal.Designator; 10951 10952 // The following is a moderately common idiom in C: 10953 // 10954 // struct Foo { int a; char c[1]; }; 10955 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 10956 // strcpy(&F->c[0], Bar); 10957 // 10958 // In order to not break too much legacy code, we need to support it. 10959 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 10960 // If we can resolve this to an alloc_size call, we can hand that back, 10961 // because we know for certain how many bytes there are to write to. 10962 llvm::APInt APEndOffset; 10963 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 10964 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 10965 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 10966 10967 // If we cannot determine the size of the initial allocation, then we can't 10968 // given an accurate upper-bound. However, we are still able to give 10969 // conservative lower-bounds for Type=3. 10970 if (Type == 1) 10971 return false; 10972 } 10973 10974 CharUnits BytesPerElem; 10975 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 10976 return false; 10977 10978 // According to the GCC documentation, we want the size of the subobject 10979 // denoted by the pointer. But that's not quite right -- what we actually 10980 // want is the size of the immediately-enclosing array, if there is one. 10981 int64_t ElemsRemaining; 10982 if (Designator.MostDerivedIsArrayElement && 10983 Designator.Entries.size() == Designator.MostDerivedPathLength) { 10984 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 10985 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 10986 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 10987 } else { 10988 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 10989 } 10990 10991 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 10992 return true; 10993 } 10994 10995 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 10996 /// returns true and stores the result in @p Size. 10997 /// 10998 /// If @p WasError is non-null, this will report whether the failure to evaluate 10999 /// is to be treated as an Error in IntExprEvaluator. 11000 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11001 EvalInfo &Info, uint64_t &Size) { 11002 // Determine the denoted object. 11003 LValue LVal; 11004 { 11005 // The operand of __builtin_object_size is never evaluated for side-effects. 11006 // If there are any, but we can determine the pointed-to object anyway, then 11007 // ignore the side-effects. 11008 SpeculativeEvaluationRAII SpeculativeEval(Info); 11009 IgnoreSideEffectsRAII Fold(Info); 11010 11011 if (E->isGLValue()) { 11012 // It's possible for us to be given GLValues if we're called via 11013 // Expr::tryEvaluateObjectSize. 11014 APValue RVal; 11015 if (!EvaluateAsRValue(Info, E, RVal)) 11016 return false; 11017 LVal.setFrom(Info.Ctx, RVal); 11018 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11019 /*InvalidBaseOK=*/true)) 11020 return false; 11021 } 11022 11023 // If we point to before the start of the object, there are no accessible 11024 // bytes. 11025 if (LVal.getLValueOffset().isNegative()) { 11026 Size = 0; 11027 return true; 11028 } 11029 11030 CharUnits EndOffset; 11031 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11032 return false; 11033 11034 // If we've fallen outside of the end offset, just pretend there's nothing to 11035 // write to/read from. 11036 if (EndOffset <= LVal.getLValueOffset()) 11037 Size = 0; 11038 else 11039 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11040 return true; 11041 } 11042 11043 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11044 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11045 return VisitBuiltinCallExpr(E, BuiltinOp); 11046 11047 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11048 } 11049 11050 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11051 APValue &Val, APSInt &Alignment) { 11052 QualType SrcTy = E->getArg(0)->getType(); 11053 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11054 return false; 11055 // Even though we are evaluating integer expressions we could get a pointer 11056 // argument for the __builtin_is_aligned() case. 11057 if (SrcTy->isPointerType()) { 11058 LValue Ptr; 11059 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11060 return false; 11061 Ptr.moveInto(Val); 11062 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11063 Info.FFDiag(E->getArg(0)); 11064 return false; 11065 } else { 11066 APSInt SrcInt; 11067 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11068 return false; 11069 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11070 "Bit widths must be the same"); 11071 Val = APValue(SrcInt); 11072 } 11073 assert(Val.hasValue()); 11074 return true; 11075 } 11076 11077 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11078 unsigned BuiltinOp) { 11079 switch (BuiltinOp) { 11080 default: 11081 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11082 11083 case Builtin::BI__builtin_dynamic_object_size: 11084 case Builtin::BI__builtin_object_size: { 11085 // The type was checked when we built the expression. 11086 unsigned Type = 11087 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11088 assert(Type <= 3 && "unexpected type"); 11089 11090 uint64_t Size; 11091 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11092 return Success(Size, E); 11093 11094 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11095 return Success((Type & 2) ? 0 : -1, E); 11096 11097 // Expression had no side effects, but we couldn't statically determine the 11098 // size of the referenced object. 11099 switch (Info.EvalMode) { 11100 case EvalInfo::EM_ConstantExpression: 11101 case EvalInfo::EM_ConstantFold: 11102 case EvalInfo::EM_IgnoreSideEffects: 11103 // Leave it to IR generation. 11104 return Error(E); 11105 case EvalInfo::EM_ConstantExpressionUnevaluated: 11106 // Reduce it to a constant now. 11107 return Success((Type & 2) ? 0 : -1, E); 11108 } 11109 11110 llvm_unreachable("unexpected EvalMode"); 11111 } 11112 11113 case Builtin::BI__builtin_os_log_format_buffer_size: { 11114 analyze_os_log::OSLogBufferLayout Layout; 11115 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11116 return Success(Layout.size().getQuantity(), E); 11117 } 11118 11119 case Builtin::BI__builtin_is_aligned: { 11120 APValue Src; 11121 APSInt Alignment; 11122 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11123 return false; 11124 if (Src.isLValue()) { 11125 // If we evaluated a pointer, check the minimum known alignment. 11126 LValue Ptr; 11127 Ptr.setFrom(Info.Ctx, Src); 11128 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11129 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11130 // We can return true if the known alignment at the computed offset is 11131 // greater than the requested alignment. 11132 assert(PtrAlign.isPowerOfTwo()); 11133 assert(Alignment.isPowerOf2()); 11134 if (PtrAlign.getQuantity() >= Alignment) 11135 return Success(1, E); 11136 // If the alignment is not known to be sufficient, some cases could still 11137 // be aligned at run time. However, if the requested alignment is less or 11138 // equal to the base alignment and the offset is not aligned, we know that 11139 // the run-time value can never be aligned. 11140 if (BaseAlignment.getQuantity() >= Alignment && 11141 PtrAlign.getQuantity() < Alignment) 11142 return Success(0, E); 11143 // Otherwise we can't infer whether the value is sufficiently aligned. 11144 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11145 // in cases where we can't fully evaluate the pointer. 11146 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11147 << Alignment; 11148 return false; 11149 } 11150 assert(Src.isInt()); 11151 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11152 } 11153 case Builtin::BI__builtin_align_up: { 11154 APValue Src; 11155 APSInt Alignment; 11156 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11157 return false; 11158 if (!Src.isInt()) 11159 return Error(E); 11160 APSInt AlignedVal = 11161 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11162 Src.getInt().isUnsigned()); 11163 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11164 return Success(AlignedVal, E); 11165 } 11166 case Builtin::BI__builtin_align_down: { 11167 APValue Src; 11168 APSInt Alignment; 11169 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11170 return false; 11171 if (!Src.isInt()) 11172 return Error(E); 11173 APSInt AlignedVal = 11174 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11175 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11176 return Success(AlignedVal, E); 11177 } 11178 11179 case Builtin::BI__builtin_bswap16: 11180 case Builtin::BI__builtin_bswap32: 11181 case Builtin::BI__builtin_bswap64: { 11182 APSInt Val; 11183 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11184 return false; 11185 11186 return Success(Val.byteSwap(), E); 11187 } 11188 11189 case Builtin::BI__builtin_classify_type: 11190 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11191 11192 case Builtin::BI__builtin_clrsb: 11193 case Builtin::BI__builtin_clrsbl: 11194 case Builtin::BI__builtin_clrsbll: { 11195 APSInt Val; 11196 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11197 return false; 11198 11199 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11200 } 11201 11202 case Builtin::BI__builtin_clz: 11203 case Builtin::BI__builtin_clzl: 11204 case Builtin::BI__builtin_clzll: 11205 case Builtin::BI__builtin_clzs: { 11206 APSInt Val; 11207 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11208 return false; 11209 if (!Val) 11210 return Error(E); 11211 11212 return Success(Val.countLeadingZeros(), E); 11213 } 11214 11215 case Builtin::BI__builtin_constant_p: { 11216 const Expr *Arg = E->getArg(0); 11217 if (EvaluateBuiltinConstantP(Info, Arg)) 11218 return Success(true, E); 11219 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11220 // Outside a constant context, eagerly evaluate to false in the presence 11221 // of side-effects in order to avoid -Wunsequenced false-positives in 11222 // a branch on __builtin_constant_p(expr). 11223 return Success(false, E); 11224 } 11225 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11226 return false; 11227 } 11228 11229 case Builtin::BI__builtin_is_constant_evaluated: { 11230 const auto *Callee = Info.CurrentCall->getCallee(); 11231 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11232 (Info.CallStackDepth == 1 || 11233 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11234 Callee->getIdentifier() && 11235 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11236 // FIXME: Find a better way to avoid duplicated diagnostics. 11237 if (Info.EvalStatus.Diag) 11238 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11239 : Info.CurrentCall->CallLoc, 11240 diag::warn_is_constant_evaluated_always_true_constexpr) 11241 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11242 : "std::is_constant_evaluated"); 11243 } 11244 11245 return Success(Info.InConstantContext, E); 11246 } 11247 11248 case Builtin::BI__builtin_ctz: 11249 case Builtin::BI__builtin_ctzl: 11250 case Builtin::BI__builtin_ctzll: 11251 case Builtin::BI__builtin_ctzs: { 11252 APSInt Val; 11253 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11254 return false; 11255 if (!Val) 11256 return Error(E); 11257 11258 return Success(Val.countTrailingZeros(), E); 11259 } 11260 11261 case Builtin::BI__builtin_eh_return_data_regno: { 11262 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11263 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11264 return Success(Operand, E); 11265 } 11266 11267 case Builtin::BI__builtin_expect: 11268 case Builtin::BI__builtin_expect_with_probability: 11269 return Visit(E->getArg(0)); 11270 11271 case Builtin::BI__builtin_ffs: 11272 case Builtin::BI__builtin_ffsl: 11273 case Builtin::BI__builtin_ffsll: { 11274 APSInt Val; 11275 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11276 return false; 11277 11278 unsigned N = Val.countTrailingZeros(); 11279 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11280 } 11281 11282 case Builtin::BI__builtin_fpclassify: { 11283 APFloat Val(0.0); 11284 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11285 return false; 11286 unsigned Arg; 11287 switch (Val.getCategory()) { 11288 case APFloat::fcNaN: Arg = 0; break; 11289 case APFloat::fcInfinity: Arg = 1; break; 11290 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11291 case APFloat::fcZero: Arg = 4; break; 11292 } 11293 return Visit(E->getArg(Arg)); 11294 } 11295 11296 case Builtin::BI__builtin_isinf_sign: { 11297 APFloat Val(0.0); 11298 return EvaluateFloat(E->getArg(0), Val, Info) && 11299 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11300 } 11301 11302 case Builtin::BI__builtin_isinf: { 11303 APFloat Val(0.0); 11304 return EvaluateFloat(E->getArg(0), Val, Info) && 11305 Success(Val.isInfinity() ? 1 : 0, E); 11306 } 11307 11308 case Builtin::BI__builtin_isfinite: { 11309 APFloat Val(0.0); 11310 return EvaluateFloat(E->getArg(0), Val, Info) && 11311 Success(Val.isFinite() ? 1 : 0, E); 11312 } 11313 11314 case Builtin::BI__builtin_isnan: { 11315 APFloat Val(0.0); 11316 return EvaluateFloat(E->getArg(0), Val, Info) && 11317 Success(Val.isNaN() ? 1 : 0, E); 11318 } 11319 11320 case Builtin::BI__builtin_isnormal: { 11321 APFloat Val(0.0); 11322 return EvaluateFloat(E->getArg(0), Val, Info) && 11323 Success(Val.isNormal() ? 1 : 0, E); 11324 } 11325 11326 case Builtin::BI__builtin_parity: 11327 case Builtin::BI__builtin_parityl: 11328 case Builtin::BI__builtin_parityll: { 11329 APSInt Val; 11330 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11331 return false; 11332 11333 return Success(Val.countPopulation() % 2, E); 11334 } 11335 11336 case Builtin::BI__builtin_popcount: 11337 case Builtin::BI__builtin_popcountl: 11338 case Builtin::BI__builtin_popcountll: { 11339 APSInt Val; 11340 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11341 return false; 11342 11343 return Success(Val.countPopulation(), E); 11344 } 11345 11346 case Builtin::BIstrlen: 11347 case Builtin::BIwcslen: 11348 // A call to strlen is not a constant expression. 11349 if (Info.getLangOpts().CPlusPlus11) 11350 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11351 << /*isConstexpr*/0 << /*isConstructor*/0 11352 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11353 else 11354 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11355 LLVM_FALLTHROUGH; 11356 case Builtin::BI__builtin_strlen: 11357 case Builtin::BI__builtin_wcslen: { 11358 // As an extension, we support __builtin_strlen() as a constant expression, 11359 // and support folding strlen() to a constant. 11360 LValue String; 11361 if (!EvaluatePointer(E->getArg(0), String, Info)) 11362 return false; 11363 11364 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11365 11366 // Fast path: if it's a string literal, search the string value. 11367 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11368 String.getLValueBase().dyn_cast<const Expr *>())) { 11369 // The string literal may have embedded null characters. Find the first 11370 // one and truncate there. 11371 StringRef Str = S->getBytes(); 11372 int64_t Off = String.Offset.getQuantity(); 11373 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11374 S->getCharByteWidth() == 1 && 11375 // FIXME: Add fast-path for wchar_t too. 11376 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11377 Str = Str.substr(Off); 11378 11379 StringRef::size_type Pos = Str.find(0); 11380 if (Pos != StringRef::npos) 11381 Str = Str.substr(0, Pos); 11382 11383 return Success(Str.size(), E); 11384 } 11385 11386 // Fall through to slow path to issue appropriate diagnostic. 11387 } 11388 11389 // Slow path: scan the bytes of the string looking for the terminating 0. 11390 for (uint64_t Strlen = 0; /**/; ++Strlen) { 11391 APValue Char; 11392 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11393 !Char.isInt()) 11394 return false; 11395 if (!Char.getInt()) 11396 return Success(Strlen, E); 11397 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11398 return false; 11399 } 11400 } 11401 11402 case Builtin::BIstrcmp: 11403 case Builtin::BIwcscmp: 11404 case Builtin::BIstrncmp: 11405 case Builtin::BIwcsncmp: 11406 case Builtin::BImemcmp: 11407 case Builtin::BIbcmp: 11408 case Builtin::BIwmemcmp: 11409 // A call to strlen is not a constant expression. 11410 if (Info.getLangOpts().CPlusPlus11) 11411 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11412 << /*isConstexpr*/0 << /*isConstructor*/0 11413 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11414 else 11415 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11416 LLVM_FALLTHROUGH; 11417 case Builtin::BI__builtin_strcmp: 11418 case Builtin::BI__builtin_wcscmp: 11419 case Builtin::BI__builtin_strncmp: 11420 case Builtin::BI__builtin_wcsncmp: 11421 case Builtin::BI__builtin_memcmp: 11422 case Builtin::BI__builtin_bcmp: 11423 case Builtin::BI__builtin_wmemcmp: { 11424 LValue String1, String2; 11425 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11426 !EvaluatePointer(E->getArg(1), String2, Info)) 11427 return false; 11428 11429 uint64_t MaxLength = uint64_t(-1); 11430 if (BuiltinOp != Builtin::BIstrcmp && 11431 BuiltinOp != Builtin::BIwcscmp && 11432 BuiltinOp != Builtin::BI__builtin_strcmp && 11433 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11434 APSInt N; 11435 if (!EvaluateInteger(E->getArg(2), N, Info)) 11436 return false; 11437 MaxLength = N.getExtValue(); 11438 } 11439 11440 // Empty substrings compare equal by definition. 11441 if (MaxLength == 0u) 11442 return Success(0, E); 11443 11444 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11445 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11446 String1.Designator.Invalid || String2.Designator.Invalid) 11447 return false; 11448 11449 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11450 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11451 11452 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11453 BuiltinOp == Builtin::BIbcmp || 11454 BuiltinOp == Builtin::BI__builtin_memcmp || 11455 BuiltinOp == Builtin::BI__builtin_bcmp; 11456 11457 assert(IsRawByte || 11458 (Info.Ctx.hasSameUnqualifiedType( 11459 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11460 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11461 11462 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11463 // 'char8_t', but no other types. 11464 if (IsRawByte && 11465 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11466 // FIXME: Consider using our bit_cast implementation to support this. 11467 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11468 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11469 << CharTy1 << CharTy2; 11470 return false; 11471 } 11472 11473 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11474 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11475 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11476 Char1.isInt() && Char2.isInt(); 11477 }; 11478 const auto &AdvanceElems = [&] { 11479 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11480 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11481 }; 11482 11483 bool StopAtNull = 11484 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11485 BuiltinOp != Builtin::BIwmemcmp && 11486 BuiltinOp != Builtin::BI__builtin_memcmp && 11487 BuiltinOp != Builtin::BI__builtin_bcmp && 11488 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11489 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11490 BuiltinOp == Builtin::BIwcsncmp || 11491 BuiltinOp == Builtin::BIwmemcmp || 11492 BuiltinOp == Builtin::BI__builtin_wcscmp || 11493 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11494 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11495 11496 for (; MaxLength; --MaxLength) { 11497 APValue Char1, Char2; 11498 if (!ReadCurElems(Char1, Char2)) 11499 return false; 11500 if (Char1.getInt().ne(Char2.getInt())) { 11501 if (IsWide) // wmemcmp compares with wchar_t signedness. 11502 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11503 // memcmp always compares unsigned chars. 11504 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11505 } 11506 if (StopAtNull && !Char1.getInt()) 11507 return Success(0, E); 11508 assert(!(StopAtNull && !Char2.getInt())); 11509 if (!AdvanceElems()) 11510 return false; 11511 } 11512 // We hit the strncmp / memcmp limit. 11513 return Success(0, E); 11514 } 11515 11516 case Builtin::BI__atomic_always_lock_free: 11517 case Builtin::BI__atomic_is_lock_free: 11518 case Builtin::BI__c11_atomic_is_lock_free: { 11519 APSInt SizeVal; 11520 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11521 return false; 11522 11523 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11524 // of two less than or equal to the maximum inline atomic width, we know it 11525 // is lock-free. If the size isn't a power of two, or greater than the 11526 // maximum alignment where we promote atomics, we know it is not lock-free 11527 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11528 // the answer can only be determined at runtime; for example, 16-byte 11529 // atomics have lock-free implementations on some, but not all, 11530 // x86-64 processors. 11531 11532 // Check power-of-two. 11533 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11534 if (Size.isPowerOfTwo()) { 11535 // Check against inlining width. 11536 unsigned InlineWidthBits = 11537 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11538 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11539 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11540 Size == CharUnits::One() || 11541 E->getArg(1)->isNullPointerConstant(Info.Ctx, 11542 Expr::NPC_NeverValueDependent)) 11543 // OK, we will inline appropriately-aligned operations of this size, 11544 // and _Atomic(T) is appropriately-aligned. 11545 return Success(1, E); 11546 11547 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 11548 castAs<PointerType>()->getPointeeType(); 11549 if (!PointeeType->isIncompleteType() && 11550 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 11551 // OK, we will inline operations on this object. 11552 return Success(1, E); 11553 } 11554 } 11555 } 11556 11557 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 11558 Success(0, E) : Error(E); 11559 } 11560 case Builtin::BIomp_is_initial_device: 11561 // We can decide statically which value the runtime would return if called. 11562 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 11563 case Builtin::BI__builtin_add_overflow: 11564 case Builtin::BI__builtin_sub_overflow: 11565 case Builtin::BI__builtin_mul_overflow: 11566 case Builtin::BI__builtin_sadd_overflow: 11567 case Builtin::BI__builtin_uadd_overflow: 11568 case Builtin::BI__builtin_uaddl_overflow: 11569 case Builtin::BI__builtin_uaddll_overflow: 11570 case Builtin::BI__builtin_usub_overflow: 11571 case Builtin::BI__builtin_usubl_overflow: 11572 case Builtin::BI__builtin_usubll_overflow: 11573 case Builtin::BI__builtin_umul_overflow: 11574 case Builtin::BI__builtin_umull_overflow: 11575 case Builtin::BI__builtin_umulll_overflow: 11576 case Builtin::BI__builtin_saddl_overflow: 11577 case Builtin::BI__builtin_saddll_overflow: 11578 case Builtin::BI__builtin_ssub_overflow: 11579 case Builtin::BI__builtin_ssubl_overflow: 11580 case Builtin::BI__builtin_ssubll_overflow: 11581 case Builtin::BI__builtin_smul_overflow: 11582 case Builtin::BI__builtin_smull_overflow: 11583 case Builtin::BI__builtin_smulll_overflow: { 11584 LValue ResultLValue; 11585 APSInt LHS, RHS; 11586 11587 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 11588 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 11589 !EvaluateInteger(E->getArg(1), RHS, Info) || 11590 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 11591 return false; 11592 11593 APSInt Result; 11594 bool DidOverflow = false; 11595 11596 // If the types don't have to match, enlarge all 3 to the largest of them. 11597 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11598 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11599 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11600 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 11601 ResultType->isSignedIntegerOrEnumerationType(); 11602 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 11603 ResultType->isSignedIntegerOrEnumerationType(); 11604 uint64_t LHSSize = LHS.getBitWidth(); 11605 uint64_t RHSSize = RHS.getBitWidth(); 11606 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 11607 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 11608 11609 // Add an additional bit if the signedness isn't uniformly agreed to. We 11610 // could do this ONLY if there is a signed and an unsigned that both have 11611 // MaxBits, but the code to check that is pretty nasty. The issue will be 11612 // caught in the shrink-to-result later anyway. 11613 if (IsSigned && !AllSigned) 11614 ++MaxBits; 11615 11616 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 11617 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 11618 Result = APSInt(MaxBits, !IsSigned); 11619 } 11620 11621 // Find largest int. 11622 switch (BuiltinOp) { 11623 default: 11624 llvm_unreachable("Invalid value for BuiltinOp"); 11625 case Builtin::BI__builtin_add_overflow: 11626 case Builtin::BI__builtin_sadd_overflow: 11627 case Builtin::BI__builtin_saddl_overflow: 11628 case Builtin::BI__builtin_saddll_overflow: 11629 case Builtin::BI__builtin_uadd_overflow: 11630 case Builtin::BI__builtin_uaddl_overflow: 11631 case Builtin::BI__builtin_uaddll_overflow: 11632 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 11633 : LHS.uadd_ov(RHS, DidOverflow); 11634 break; 11635 case Builtin::BI__builtin_sub_overflow: 11636 case Builtin::BI__builtin_ssub_overflow: 11637 case Builtin::BI__builtin_ssubl_overflow: 11638 case Builtin::BI__builtin_ssubll_overflow: 11639 case Builtin::BI__builtin_usub_overflow: 11640 case Builtin::BI__builtin_usubl_overflow: 11641 case Builtin::BI__builtin_usubll_overflow: 11642 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 11643 : LHS.usub_ov(RHS, DidOverflow); 11644 break; 11645 case Builtin::BI__builtin_mul_overflow: 11646 case Builtin::BI__builtin_smul_overflow: 11647 case Builtin::BI__builtin_smull_overflow: 11648 case Builtin::BI__builtin_smulll_overflow: 11649 case Builtin::BI__builtin_umul_overflow: 11650 case Builtin::BI__builtin_umull_overflow: 11651 case Builtin::BI__builtin_umulll_overflow: 11652 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 11653 : LHS.umul_ov(RHS, DidOverflow); 11654 break; 11655 } 11656 11657 // In the case where multiple sizes are allowed, truncate and see if 11658 // the values are the same. 11659 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11660 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11661 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11662 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 11663 // since it will give us the behavior of a TruncOrSelf in the case where 11664 // its parameter <= its size. We previously set Result to be at least the 11665 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 11666 // will work exactly like TruncOrSelf. 11667 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 11668 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 11669 11670 if (!APSInt::isSameValue(Temp, Result)) 11671 DidOverflow = true; 11672 Result = Temp; 11673 } 11674 11675 APValue APV{Result}; 11676 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 11677 return false; 11678 return Success(DidOverflow, E); 11679 } 11680 } 11681 } 11682 11683 /// Determine whether this is a pointer past the end of the complete 11684 /// object referred to by the lvalue. 11685 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 11686 const LValue &LV) { 11687 // A null pointer can be viewed as being "past the end" but we don't 11688 // choose to look at it that way here. 11689 if (!LV.getLValueBase()) 11690 return false; 11691 11692 // If the designator is valid and refers to a subobject, we're not pointing 11693 // past the end. 11694 if (!LV.getLValueDesignator().Invalid && 11695 !LV.getLValueDesignator().isOnePastTheEnd()) 11696 return false; 11697 11698 // A pointer to an incomplete type might be past-the-end if the type's size is 11699 // zero. We cannot tell because the type is incomplete. 11700 QualType Ty = getType(LV.getLValueBase()); 11701 if (Ty->isIncompleteType()) 11702 return true; 11703 11704 // We're a past-the-end pointer if we point to the byte after the object, 11705 // no matter what our type or path is. 11706 auto Size = Ctx.getTypeSizeInChars(Ty); 11707 return LV.getLValueOffset() == Size; 11708 } 11709 11710 namespace { 11711 11712 /// Data recursive integer evaluator of certain binary operators. 11713 /// 11714 /// We use a data recursive algorithm for binary operators so that we are able 11715 /// to handle extreme cases of chained binary operators without causing stack 11716 /// overflow. 11717 class DataRecursiveIntBinOpEvaluator { 11718 struct EvalResult { 11719 APValue Val; 11720 bool Failed; 11721 11722 EvalResult() : Failed(false) { } 11723 11724 void swap(EvalResult &RHS) { 11725 Val.swap(RHS.Val); 11726 Failed = RHS.Failed; 11727 RHS.Failed = false; 11728 } 11729 }; 11730 11731 struct Job { 11732 const Expr *E; 11733 EvalResult LHSResult; // meaningful only for binary operator expression. 11734 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 11735 11736 Job() = default; 11737 Job(Job &&) = default; 11738 11739 void startSpeculativeEval(EvalInfo &Info) { 11740 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 11741 } 11742 11743 private: 11744 SpeculativeEvaluationRAII SpecEvalRAII; 11745 }; 11746 11747 SmallVector<Job, 16> Queue; 11748 11749 IntExprEvaluator &IntEval; 11750 EvalInfo &Info; 11751 APValue &FinalResult; 11752 11753 public: 11754 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 11755 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 11756 11757 /// True if \param E is a binary operator that we are going to handle 11758 /// data recursively. 11759 /// We handle binary operators that are comma, logical, or that have operands 11760 /// with integral or enumeration type. 11761 static bool shouldEnqueue(const BinaryOperator *E) { 11762 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 11763 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 11764 E->getLHS()->getType()->isIntegralOrEnumerationType() && 11765 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11766 } 11767 11768 bool Traverse(const BinaryOperator *E) { 11769 enqueue(E); 11770 EvalResult PrevResult; 11771 while (!Queue.empty()) 11772 process(PrevResult); 11773 11774 if (PrevResult.Failed) return false; 11775 11776 FinalResult.swap(PrevResult.Val); 11777 return true; 11778 } 11779 11780 private: 11781 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 11782 return IntEval.Success(Value, E, Result); 11783 } 11784 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 11785 return IntEval.Success(Value, E, Result); 11786 } 11787 bool Error(const Expr *E) { 11788 return IntEval.Error(E); 11789 } 11790 bool Error(const Expr *E, diag::kind D) { 11791 return IntEval.Error(E, D); 11792 } 11793 11794 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 11795 return Info.CCEDiag(E, D); 11796 } 11797 11798 // Returns true if visiting the RHS is necessary, false otherwise. 11799 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11800 bool &SuppressRHSDiags); 11801 11802 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 11803 const BinaryOperator *E, APValue &Result); 11804 11805 void EvaluateExpr(const Expr *E, EvalResult &Result) { 11806 Result.Failed = !Evaluate(Result.Val, Info, E); 11807 if (Result.Failed) 11808 Result.Val = APValue(); 11809 } 11810 11811 void process(EvalResult &Result); 11812 11813 void enqueue(const Expr *E) { 11814 E = E->IgnoreParens(); 11815 Queue.resize(Queue.size()+1); 11816 Queue.back().E = E; 11817 Queue.back().Kind = Job::AnyExprKind; 11818 } 11819 }; 11820 11821 } 11822 11823 bool DataRecursiveIntBinOpEvaluator:: 11824 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11825 bool &SuppressRHSDiags) { 11826 if (E->getOpcode() == BO_Comma) { 11827 // Ignore LHS but note if we could not evaluate it. 11828 if (LHSResult.Failed) 11829 return Info.noteSideEffect(); 11830 return true; 11831 } 11832 11833 if (E->isLogicalOp()) { 11834 bool LHSAsBool; 11835 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 11836 // We were able to evaluate the LHS, see if we can get away with not 11837 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 11838 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 11839 Success(LHSAsBool, E, LHSResult.Val); 11840 return false; // Ignore RHS 11841 } 11842 } else { 11843 LHSResult.Failed = true; 11844 11845 // Since we weren't able to evaluate the left hand side, it 11846 // might have had side effects. 11847 if (!Info.noteSideEffect()) 11848 return false; 11849 11850 // We can't evaluate the LHS; however, sometimes the result 11851 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 11852 // Don't ignore RHS and suppress diagnostics from this arm. 11853 SuppressRHSDiags = true; 11854 } 11855 11856 return true; 11857 } 11858 11859 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 11860 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11861 11862 if (LHSResult.Failed && !Info.noteFailure()) 11863 return false; // Ignore RHS; 11864 11865 return true; 11866 } 11867 11868 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 11869 bool IsSub) { 11870 // Compute the new offset in the appropriate width, wrapping at 64 bits. 11871 // FIXME: When compiling for a 32-bit target, we should use 32-bit 11872 // offsets. 11873 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 11874 CharUnits &Offset = LVal.getLValueOffset(); 11875 uint64_t Offset64 = Offset.getQuantity(); 11876 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 11877 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 11878 : Offset64 + Index64); 11879 } 11880 11881 bool DataRecursiveIntBinOpEvaluator:: 11882 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 11883 const BinaryOperator *E, APValue &Result) { 11884 if (E->getOpcode() == BO_Comma) { 11885 if (RHSResult.Failed) 11886 return false; 11887 Result = RHSResult.Val; 11888 return true; 11889 } 11890 11891 if (E->isLogicalOp()) { 11892 bool lhsResult, rhsResult; 11893 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 11894 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 11895 11896 if (LHSIsOK) { 11897 if (RHSIsOK) { 11898 if (E->getOpcode() == BO_LOr) 11899 return Success(lhsResult || rhsResult, E, Result); 11900 else 11901 return Success(lhsResult && rhsResult, E, Result); 11902 } 11903 } else { 11904 if (RHSIsOK) { 11905 // We can't evaluate the LHS; however, sometimes the result 11906 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 11907 if (rhsResult == (E->getOpcode() == BO_LOr)) 11908 return Success(rhsResult, E, Result); 11909 } 11910 } 11911 11912 return false; 11913 } 11914 11915 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 11916 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11917 11918 if (LHSResult.Failed || RHSResult.Failed) 11919 return false; 11920 11921 const APValue &LHSVal = LHSResult.Val; 11922 const APValue &RHSVal = RHSResult.Val; 11923 11924 // Handle cases like (unsigned long)&a + 4. 11925 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 11926 Result = LHSVal; 11927 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 11928 return true; 11929 } 11930 11931 // Handle cases like 4 + (unsigned long)&a 11932 if (E->getOpcode() == BO_Add && 11933 RHSVal.isLValue() && LHSVal.isInt()) { 11934 Result = RHSVal; 11935 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 11936 return true; 11937 } 11938 11939 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 11940 // Handle (intptr_t)&&A - (intptr_t)&&B. 11941 if (!LHSVal.getLValueOffset().isZero() || 11942 !RHSVal.getLValueOffset().isZero()) 11943 return false; 11944 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 11945 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 11946 if (!LHSExpr || !RHSExpr) 11947 return false; 11948 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 11949 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 11950 if (!LHSAddrExpr || !RHSAddrExpr) 11951 return false; 11952 // Make sure both labels come from the same function. 11953 if (LHSAddrExpr->getLabel()->getDeclContext() != 11954 RHSAddrExpr->getLabel()->getDeclContext()) 11955 return false; 11956 Result = APValue(LHSAddrExpr, RHSAddrExpr); 11957 return true; 11958 } 11959 11960 // All the remaining cases expect both operands to be an integer 11961 if (!LHSVal.isInt() || !RHSVal.isInt()) 11962 return Error(E); 11963 11964 // Set up the width and signedness manually, in case it can't be deduced 11965 // from the operation we're performing. 11966 // FIXME: Don't do this in the cases where we can deduce it. 11967 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 11968 E->getType()->isUnsignedIntegerOrEnumerationType()); 11969 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 11970 RHSVal.getInt(), Value)) 11971 return false; 11972 return Success(Value, E, Result); 11973 } 11974 11975 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 11976 Job &job = Queue.back(); 11977 11978 switch (job.Kind) { 11979 case Job::AnyExprKind: { 11980 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 11981 if (shouldEnqueue(Bop)) { 11982 job.Kind = Job::BinOpKind; 11983 enqueue(Bop->getLHS()); 11984 return; 11985 } 11986 } 11987 11988 EvaluateExpr(job.E, Result); 11989 Queue.pop_back(); 11990 return; 11991 } 11992 11993 case Job::BinOpKind: { 11994 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 11995 bool SuppressRHSDiags = false; 11996 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 11997 Queue.pop_back(); 11998 return; 11999 } 12000 if (SuppressRHSDiags) 12001 job.startSpeculativeEval(Info); 12002 job.LHSResult.swap(Result); 12003 job.Kind = Job::BinOpVisitedLHSKind; 12004 enqueue(Bop->getRHS()); 12005 return; 12006 } 12007 12008 case Job::BinOpVisitedLHSKind: { 12009 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12010 EvalResult RHS; 12011 RHS.swap(Result); 12012 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12013 Queue.pop_back(); 12014 return; 12015 } 12016 } 12017 12018 llvm_unreachable("Invalid Job::Kind!"); 12019 } 12020 12021 namespace { 12022 /// Used when we determine that we should fail, but can keep evaluating prior to 12023 /// noting that we had a failure. 12024 class DelayedNoteFailureRAII { 12025 EvalInfo &Info; 12026 bool NoteFailure; 12027 12028 public: 12029 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 12030 : Info(Info), NoteFailure(NoteFailure) {} 12031 ~DelayedNoteFailureRAII() { 12032 if (NoteFailure) { 12033 bool ContinueAfterFailure = Info.noteFailure(); 12034 (void)ContinueAfterFailure; 12035 assert(ContinueAfterFailure && 12036 "Shouldn't have kept evaluating on failure."); 12037 } 12038 } 12039 }; 12040 12041 enum class CmpResult { 12042 Unequal, 12043 Less, 12044 Equal, 12045 Greater, 12046 Unordered, 12047 }; 12048 } 12049 12050 template <class SuccessCB, class AfterCB> 12051 static bool 12052 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12053 SuccessCB &&Success, AfterCB &&DoAfter) { 12054 assert(E->isComparisonOp() && "expected comparison operator"); 12055 assert((E->getOpcode() == BO_Cmp || 12056 E->getType()->isIntegralOrEnumerationType()) && 12057 "unsupported binary expression evaluation"); 12058 auto Error = [&](const Expr *E) { 12059 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12060 return false; 12061 }; 12062 12063 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12064 bool IsEquality = E->isEqualityOp(); 12065 12066 QualType LHSTy = E->getLHS()->getType(); 12067 QualType RHSTy = E->getRHS()->getType(); 12068 12069 if (LHSTy->isIntegralOrEnumerationType() && 12070 RHSTy->isIntegralOrEnumerationType()) { 12071 APSInt LHS, RHS; 12072 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12073 if (!LHSOK && !Info.noteFailure()) 12074 return false; 12075 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12076 return false; 12077 if (LHS < RHS) 12078 return Success(CmpResult::Less, E); 12079 if (LHS > RHS) 12080 return Success(CmpResult::Greater, E); 12081 return Success(CmpResult::Equal, E); 12082 } 12083 12084 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12085 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12086 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12087 12088 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12089 if (!LHSOK && !Info.noteFailure()) 12090 return false; 12091 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12092 return false; 12093 if (LHSFX < RHSFX) 12094 return Success(CmpResult::Less, E); 12095 if (LHSFX > RHSFX) 12096 return Success(CmpResult::Greater, E); 12097 return Success(CmpResult::Equal, E); 12098 } 12099 12100 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12101 ComplexValue LHS, RHS; 12102 bool LHSOK; 12103 if (E->isAssignmentOp()) { 12104 LValue LV; 12105 EvaluateLValue(E->getLHS(), LV, Info); 12106 LHSOK = false; 12107 } else if (LHSTy->isRealFloatingType()) { 12108 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12109 if (LHSOK) { 12110 LHS.makeComplexFloat(); 12111 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12112 } 12113 } else { 12114 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12115 } 12116 if (!LHSOK && !Info.noteFailure()) 12117 return false; 12118 12119 if (E->getRHS()->getType()->isRealFloatingType()) { 12120 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12121 return false; 12122 RHS.makeComplexFloat(); 12123 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12124 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12125 return false; 12126 12127 if (LHS.isComplexFloat()) { 12128 APFloat::cmpResult CR_r = 12129 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12130 APFloat::cmpResult CR_i = 12131 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12132 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12133 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12134 } else { 12135 assert(IsEquality && "invalid complex comparison"); 12136 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12137 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12138 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12139 } 12140 } 12141 12142 if (LHSTy->isRealFloatingType() && 12143 RHSTy->isRealFloatingType()) { 12144 APFloat RHS(0.0), LHS(0.0); 12145 12146 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12147 if (!LHSOK && !Info.noteFailure()) 12148 return false; 12149 12150 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12151 return false; 12152 12153 assert(E->isComparisonOp() && "Invalid binary operator!"); 12154 auto GetCmpRes = [&]() { 12155 switch (LHS.compare(RHS)) { 12156 case APFloat::cmpEqual: 12157 return CmpResult::Equal; 12158 case APFloat::cmpLessThan: 12159 return CmpResult::Less; 12160 case APFloat::cmpGreaterThan: 12161 return CmpResult::Greater; 12162 case APFloat::cmpUnordered: 12163 return CmpResult::Unordered; 12164 } 12165 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12166 }; 12167 return Success(GetCmpRes(), E); 12168 } 12169 12170 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12171 LValue LHSValue, RHSValue; 12172 12173 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12174 if (!LHSOK && !Info.noteFailure()) 12175 return false; 12176 12177 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12178 return false; 12179 12180 // Reject differing bases from the normal codepath; we special-case 12181 // comparisons to null. 12182 if (!HasSameBase(LHSValue, RHSValue)) { 12183 // Inequalities and subtractions between unrelated pointers have 12184 // unspecified or undefined behavior. 12185 if (!IsEquality) { 12186 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12187 return false; 12188 } 12189 // A constant address may compare equal to the address of a symbol. 12190 // The one exception is that address of an object cannot compare equal 12191 // to a null pointer constant. 12192 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12193 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12194 return Error(E); 12195 // It's implementation-defined whether distinct literals will have 12196 // distinct addresses. In clang, the result of such a comparison is 12197 // unspecified, so it is not a constant expression. However, we do know 12198 // that the address of a literal will be non-null. 12199 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12200 LHSValue.Base && RHSValue.Base) 12201 return Error(E); 12202 // We can't tell whether weak symbols will end up pointing to the same 12203 // object. 12204 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12205 return Error(E); 12206 // We can't compare the address of the start of one object with the 12207 // past-the-end address of another object, per C++ DR1652. 12208 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12209 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12210 (RHSValue.Base && RHSValue.Offset.isZero() && 12211 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12212 return Error(E); 12213 // We can't tell whether an object is at the same address as another 12214 // zero sized object. 12215 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12216 (LHSValue.Base && isZeroSized(RHSValue))) 12217 return Error(E); 12218 return Success(CmpResult::Unequal, E); 12219 } 12220 12221 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12222 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12223 12224 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12225 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12226 12227 // C++11 [expr.rel]p3: 12228 // Pointers to void (after pointer conversions) can be compared, with a 12229 // result defined as follows: If both pointers represent the same 12230 // address or are both the null pointer value, the result is true if the 12231 // operator is <= or >= and false otherwise; otherwise the result is 12232 // unspecified. 12233 // We interpret this as applying to pointers to *cv* void. 12234 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12235 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12236 12237 // C++11 [expr.rel]p2: 12238 // - If two pointers point to non-static data members of the same object, 12239 // or to subobjects or array elements fo such members, recursively, the 12240 // pointer to the later declared member compares greater provided the 12241 // two members have the same access control and provided their class is 12242 // not a union. 12243 // [...] 12244 // - Otherwise pointer comparisons are unspecified. 12245 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12246 bool WasArrayIndex; 12247 unsigned Mismatch = FindDesignatorMismatch( 12248 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12249 // At the point where the designators diverge, the comparison has a 12250 // specified value if: 12251 // - we are comparing array indices 12252 // - we are comparing fields of a union, or fields with the same access 12253 // Otherwise, the result is unspecified and thus the comparison is not a 12254 // constant expression. 12255 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12256 Mismatch < RHSDesignator.Entries.size()) { 12257 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12258 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12259 if (!LF && !RF) 12260 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12261 else if (!LF) 12262 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12263 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12264 << RF->getParent() << RF; 12265 else if (!RF) 12266 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12267 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12268 << LF->getParent() << LF; 12269 else if (!LF->getParent()->isUnion() && 12270 LF->getAccess() != RF->getAccess()) 12271 Info.CCEDiag(E, 12272 diag::note_constexpr_pointer_comparison_differing_access) 12273 << LF << LF->getAccess() << RF << RF->getAccess() 12274 << LF->getParent(); 12275 } 12276 } 12277 12278 // The comparison here must be unsigned, and performed with the same 12279 // width as the pointer. 12280 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12281 uint64_t CompareLHS = LHSOffset.getQuantity(); 12282 uint64_t CompareRHS = RHSOffset.getQuantity(); 12283 assert(PtrSize <= 64 && "Unexpected pointer width"); 12284 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12285 CompareLHS &= Mask; 12286 CompareRHS &= Mask; 12287 12288 // If there is a base and this is a relational operator, we can only 12289 // compare pointers within the object in question; otherwise, the result 12290 // depends on where the object is located in memory. 12291 if (!LHSValue.Base.isNull() && IsRelational) { 12292 QualType BaseTy = getType(LHSValue.Base); 12293 if (BaseTy->isIncompleteType()) 12294 return Error(E); 12295 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12296 uint64_t OffsetLimit = Size.getQuantity(); 12297 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12298 return Error(E); 12299 } 12300 12301 if (CompareLHS < CompareRHS) 12302 return Success(CmpResult::Less, E); 12303 if (CompareLHS > CompareRHS) 12304 return Success(CmpResult::Greater, E); 12305 return Success(CmpResult::Equal, E); 12306 } 12307 12308 if (LHSTy->isMemberPointerType()) { 12309 assert(IsEquality && "unexpected member pointer operation"); 12310 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12311 12312 MemberPtr LHSValue, RHSValue; 12313 12314 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12315 if (!LHSOK && !Info.noteFailure()) 12316 return false; 12317 12318 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12319 return false; 12320 12321 // C++11 [expr.eq]p2: 12322 // If both operands are null, they compare equal. Otherwise if only one is 12323 // null, they compare unequal. 12324 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12325 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12326 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12327 } 12328 12329 // Otherwise if either is a pointer to a virtual member function, the 12330 // result is unspecified. 12331 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12332 if (MD->isVirtual()) 12333 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12334 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12335 if (MD->isVirtual()) 12336 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12337 12338 // Otherwise they compare equal if and only if they would refer to the 12339 // same member of the same most derived object or the same subobject if 12340 // they were dereferenced with a hypothetical object of the associated 12341 // class type. 12342 bool Equal = LHSValue == RHSValue; 12343 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12344 } 12345 12346 if (LHSTy->isNullPtrType()) { 12347 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12348 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12349 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12350 // are compared, the result is true of the operator is <=, >= or ==, and 12351 // false otherwise. 12352 return Success(CmpResult::Equal, E); 12353 } 12354 12355 return DoAfter(); 12356 } 12357 12358 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12359 if (!CheckLiteralType(Info, E)) 12360 return false; 12361 12362 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12363 ComparisonCategoryResult CCR; 12364 switch (CR) { 12365 case CmpResult::Unequal: 12366 llvm_unreachable("should never produce Unequal for three-way comparison"); 12367 case CmpResult::Less: 12368 CCR = ComparisonCategoryResult::Less; 12369 break; 12370 case CmpResult::Equal: 12371 CCR = ComparisonCategoryResult::Equal; 12372 break; 12373 case CmpResult::Greater: 12374 CCR = ComparisonCategoryResult::Greater; 12375 break; 12376 case CmpResult::Unordered: 12377 CCR = ComparisonCategoryResult::Unordered; 12378 break; 12379 } 12380 // Evaluation succeeded. Lookup the information for the comparison category 12381 // type and fetch the VarDecl for the result. 12382 const ComparisonCategoryInfo &CmpInfo = 12383 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12384 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12385 // Check and evaluate the result as a constant expression. 12386 LValue LV; 12387 LV.set(VD); 12388 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12389 return false; 12390 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 12391 }; 12392 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12393 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12394 }); 12395 } 12396 12397 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12398 // We don't call noteFailure immediately because the assignment happens after 12399 // we evaluate LHS and RHS. 12400 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 12401 return Error(E); 12402 12403 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 12404 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12405 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12406 12407 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12408 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12409 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12410 12411 if (E->isComparisonOp()) { 12412 // Evaluate builtin binary comparisons by evaluating them as three-way 12413 // comparisons and then translating the result. 12414 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12415 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12416 "should only produce Unequal for equality comparisons"); 12417 bool IsEqual = CR == CmpResult::Equal, 12418 IsLess = CR == CmpResult::Less, 12419 IsGreater = CR == CmpResult::Greater; 12420 auto Op = E->getOpcode(); 12421 switch (Op) { 12422 default: 12423 llvm_unreachable("unsupported binary operator"); 12424 case BO_EQ: 12425 case BO_NE: 12426 return Success(IsEqual == (Op == BO_EQ), E); 12427 case BO_LT: 12428 return Success(IsLess, E); 12429 case BO_GT: 12430 return Success(IsGreater, E); 12431 case BO_LE: 12432 return Success(IsEqual || IsLess, E); 12433 case BO_GE: 12434 return Success(IsEqual || IsGreater, E); 12435 } 12436 }; 12437 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12438 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12439 }); 12440 } 12441 12442 QualType LHSTy = E->getLHS()->getType(); 12443 QualType RHSTy = E->getRHS()->getType(); 12444 12445 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12446 E->getOpcode() == BO_Sub) { 12447 LValue LHSValue, RHSValue; 12448 12449 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12450 if (!LHSOK && !Info.noteFailure()) 12451 return false; 12452 12453 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12454 return false; 12455 12456 // Reject differing bases from the normal codepath; we special-case 12457 // comparisons to null. 12458 if (!HasSameBase(LHSValue, RHSValue)) { 12459 // Handle &&A - &&B. 12460 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12461 return Error(E); 12462 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12463 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12464 if (!LHSExpr || !RHSExpr) 12465 return Error(E); 12466 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12467 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12468 if (!LHSAddrExpr || !RHSAddrExpr) 12469 return Error(E); 12470 // Make sure both labels come from the same function. 12471 if (LHSAddrExpr->getLabel()->getDeclContext() != 12472 RHSAddrExpr->getLabel()->getDeclContext()) 12473 return Error(E); 12474 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12475 } 12476 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12477 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12478 12479 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12480 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12481 12482 // C++11 [expr.add]p6: 12483 // Unless both pointers point to elements of the same array object, or 12484 // one past the last element of the array object, the behavior is 12485 // undefined. 12486 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12487 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12488 RHSDesignator)) 12489 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12490 12491 QualType Type = E->getLHS()->getType(); 12492 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12493 12494 CharUnits ElementSize; 12495 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12496 return false; 12497 12498 // As an extension, a type may have zero size (empty struct or union in 12499 // C, array of zero length). Pointer subtraction in such cases has 12500 // undefined behavior, so is not constant. 12501 if (ElementSize.isZero()) { 12502 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12503 << ElementType; 12504 return false; 12505 } 12506 12507 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12508 // and produce incorrect results when it overflows. Such behavior 12509 // appears to be non-conforming, but is common, so perhaps we should 12510 // assume the standard intended for such cases to be undefined behavior 12511 // and check for them. 12512 12513 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12514 // overflow in the final conversion to ptrdiff_t. 12515 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12516 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12517 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12518 false); 12519 APSInt TrueResult = (LHS - RHS) / ElemSize; 12520 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12521 12522 if (Result.extend(65) != TrueResult && 12523 !HandleOverflow(Info, E, TrueResult, E->getType())) 12524 return false; 12525 return Success(Result, E); 12526 } 12527 12528 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12529 } 12530 12531 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12532 /// a result as the expression's type. 12533 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12534 const UnaryExprOrTypeTraitExpr *E) { 12535 switch(E->getKind()) { 12536 case UETT_PreferredAlignOf: 12537 case UETT_AlignOf: { 12538 if (E->isArgumentType()) 12539 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 12540 E); 12541 else 12542 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 12543 E); 12544 } 12545 12546 case UETT_VecStep: { 12547 QualType Ty = E->getTypeOfArgument(); 12548 12549 if (Ty->isVectorType()) { 12550 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 12551 12552 // The vec_step built-in functions that take a 3-component 12553 // vector return 4. (OpenCL 1.1 spec 6.11.12) 12554 if (n == 3) 12555 n = 4; 12556 12557 return Success(n, E); 12558 } else 12559 return Success(1, E); 12560 } 12561 12562 case UETT_SizeOf: { 12563 QualType SrcTy = E->getTypeOfArgument(); 12564 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 12565 // the result is the size of the referenced type." 12566 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 12567 SrcTy = Ref->getPointeeType(); 12568 12569 CharUnits Sizeof; 12570 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 12571 return false; 12572 return Success(Sizeof, E); 12573 } 12574 case UETT_OpenMPRequiredSimdAlign: 12575 assert(E->isArgumentType()); 12576 return Success( 12577 Info.Ctx.toCharUnitsFromBits( 12578 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 12579 .getQuantity(), 12580 E); 12581 } 12582 12583 llvm_unreachable("unknown expr/type trait"); 12584 } 12585 12586 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 12587 CharUnits Result; 12588 unsigned n = OOE->getNumComponents(); 12589 if (n == 0) 12590 return Error(OOE); 12591 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 12592 for (unsigned i = 0; i != n; ++i) { 12593 OffsetOfNode ON = OOE->getComponent(i); 12594 switch (ON.getKind()) { 12595 case OffsetOfNode::Array: { 12596 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 12597 APSInt IdxResult; 12598 if (!EvaluateInteger(Idx, IdxResult, Info)) 12599 return false; 12600 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 12601 if (!AT) 12602 return Error(OOE); 12603 CurrentType = AT->getElementType(); 12604 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 12605 Result += IdxResult.getSExtValue() * ElementSize; 12606 break; 12607 } 12608 12609 case OffsetOfNode::Field: { 12610 FieldDecl *MemberDecl = ON.getField(); 12611 const RecordType *RT = CurrentType->getAs<RecordType>(); 12612 if (!RT) 12613 return Error(OOE); 12614 RecordDecl *RD = RT->getDecl(); 12615 if (RD->isInvalidDecl()) return false; 12616 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12617 unsigned i = MemberDecl->getFieldIndex(); 12618 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 12619 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 12620 CurrentType = MemberDecl->getType().getNonReferenceType(); 12621 break; 12622 } 12623 12624 case OffsetOfNode::Identifier: 12625 llvm_unreachable("dependent __builtin_offsetof"); 12626 12627 case OffsetOfNode::Base: { 12628 CXXBaseSpecifier *BaseSpec = ON.getBase(); 12629 if (BaseSpec->isVirtual()) 12630 return Error(OOE); 12631 12632 // Find the layout of the class whose base we are looking into. 12633 const RecordType *RT = CurrentType->getAs<RecordType>(); 12634 if (!RT) 12635 return Error(OOE); 12636 RecordDecl *RD = RT->getDecl(); 12637 if (RD->isInvalidDecl()) return false; 12638 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12639 12640 // Find the base class itself. 12641 CurrentType = BaseSpec->getType(); 12642 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 12643 if (!BaseRT) 12644 return Error(OOE); 12645 12646 // Add the offset to the base. 12647 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 12648 break; 12649 } 12650 } 12651 } 12652 return Success(Result, OOE); 12653 } 12654 12655 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12656 switch (E->getOpcode()) { 12657 default: 12658 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 12659 // See C99 6.6p3. 12660 return Error(E); 12661 case UO_Extension: 12662 // FIXME: Should extension allow i-c-e extension expressions in its scope? 12663 // If so, we could clear the diagnostic ID. 12664 return Visit(E->getSubExpr()); 12665 case UO_Plus: 12666 // The result is just the value. 12667 return Visit(E->getSubExpr()); 12668 case UO_Minus: { 12669 if (!Visit(E->getSubExpr())) 12670 return false; 12671 if (!Result.isInt()) return Error(E); 12672 const APSInt &Value = Result.getInt(); 12673 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 12674 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 12675 E->getType())) 12676 return false; 12677 return Success(-Value, E); 12678 } 12679 case UO_Not: { 12680 if (!Visit(E->getSubExpr())) 12681 return false; 12682 if (!Result.isInt()) return Error(E); 12683 return Success(~Result.getInt(), E); 12684 } 12685 case UO_LNot: { 12686 bool bres; 12687 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 12688 return false; 12689 return Success(!bres, E); 12690 } 12691 } 12692 } 12693 12694 /// HandleCast - This is used to evaluate implicit or explicit casts where the 12695 /// result type is integer. 12696 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 12697 const Expr *SubExpr = E->getSubExpr(); 12698 QualType DestType = E->getType(); 12699 QualType SrcType = SubExpr->getType(); 12700 12701 switch (E->getCastKind()) { 12702 case CK_BaseToDerived: 12703 case CK_DerivedToBase: 12704 case CK_UncheckedDerivedToBase: 12705 case CK_Dynamic: 12706 case CK_ToUnion: 12707 case CK_ArrayToPointerDecay: 12708 case CK_FunctionToPointerDecay: 12709 case CK_NullToPointer: 12710 case CK_NullToMemberPointer: 12711 case CK_BaseToDerivedMemberPointer: 12712 case CK_DerivedToBaseMemberPointer: 12713 case CK_ReinterpretMemberPointer: 12714 case CK_ConstructorConversion: 12715 case CK_IntegralToPointer: 12716 case CK_ToVoid: 12717 case CK_VectorSplat: 12718 case CK_IntegralToFloating: 12719 case CK_FloatingCast: 12720 case CK_CPointerToObjCPointerCast: 12721 case CK_BlockPointerToObjCPointerCast: 12722 case CK_AnyPointerToBlockPointerCast: 12723 case CK_ObjCObjectLValueCast: 12724 case CK_FloatingRealToComplex: 12725 case CK_FloatingComplexToReal: 12726 case CK_FloatingComplexCast: 12727 case CK_FloatingComplexToIntegralComplex: 12728 case CK_IntegralRealToComplex: 12729 case CK_IntegralComplexCast: 12730 case CK_IntegralComplexToFloatingComplex: 12731 case CK_BuiltinFnToFnPtr: 12732 case CK_ZeroToOCLOpaqueType: 12733 case CK_NonAtomicToAtomic: 12734 case CK_AddressSpaceConversion: 12735 case CK_IntToOCLSampler: 12736 case CK_FixedPointCast: 12737 case CK_IntegralToFixedPoint: 12738 llvm_unreachable("invalid cast kind for integral value"); 12739 12740 case CK_BitCast: 12741 case CK_Dependent: 12742 case CK_LValueBitCast: 12743 case CK_ARCProduceObject: 12744 case CK_ARCConsumeObject: 12745 case CK_ARCReclaimReturnedObject: 12746 case CK_ARCExtendBlockObject: 12747 case CK_CopyAndAutoreleaseBlockObject: 12748 return Error(E); 12749 12750 case CK_UserDefinedConversion: 12751 case CK_LValueToRValue: 12752 case CK_AtomicToNonAtomic: 12753 case CK_NoOp: 12754 case CK_LValueToRValueBitCast: 12755 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12756 12757 case CK_MemberPointerToBoolean: 12758 case CK_PointerToBoolean: 12759 case CK_IntegralToBoolean: 12760 case CK_FloatingToBoolean: 12761 case CK_BooleanToSignedIntegral: 12762 case CK_FloatingComplexToBoolean: 12763 case CK_IntegralComplexToBoolean: { 12764 bool BoolResult; 12765 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 12766 return false; 12767 uint64_t IntResult = BoolResult; 12768 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 12769 IntResult = (uint64_t)-1; 12770 return Success(IntResult, E); 12771 } 12772 12773 case CK_FixedPointToIntegral: { 12774 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 12775 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 12776 return false; 12777 bool Overflowed; 12778 llvm::APSInt Result = Src.convertToInt( 12779 Info.Ctx.getIntWidth(DestType), 12780 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 12781 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 12782 return false; 12783 return Success(Result, E); 12784 } 12785 12786 case CK_FixedPointToBoolean: { 12787 // Unsigned padding does not affect this. 12788 APValue Val; 12789 if (!Evaluate(Val, Info, SubExpr)) 12790 return false; 12791 return Success(Val.getFixedPoint().getBoolValue(), E); 12792 } 12793 12794 case CK_IntegralCast: { 12795 if (!Visit(SubExpr)) 12796 return false; 12797 12798 if (!Result.isInt()) { 12799 // Allow casts of address-of-label differences if they are no-ops 12800 // or narrowing. (The narrowing case isn't actually guaranteed to 12801 // be constant-evaluatable except in some narrow cases which are hard 12802 // to detect here. We let it through on the assumption the user knows 12803 // what they are doing.) 12804 if (Result.isAddrLabelDiff()) 12805 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 12806 // Only allow casts of lvalues if they are lossless. 12807 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 12808 } 12809 12810 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 12811 Result.getInt()), E); 12812 } 12813 12814 case CK_PointerToIntegral: { 12815 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 12816 12817 LValue LV; 12818 if (!EvaluatePointer(SubExpr, LV, Info)) 12819 return false; 12820 12821 if (LV.getLValueBase()) { 12822 // Only allow based lvalue casts if they are lossless. 12823 // FIXME: Allow a larger integer size than the pointer size, and allow 12824 // narrowing back down to pointer width in subsequent integral casts. 12825 // FIXME: Check integer type's active bits, not its type size. 12826 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 12827 return Error(E); 12828 12829 LV.Designator.setInvalid(); 12830 LV.moveInto(Result); 12831 return true; 12832 } 12833 12834 APSInt AsInt; 12835 APValue V; 12836 LV.moveInto(V); 12837 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 12838 llvm_unreachable("Can't cast this!"); 12839 12840 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 12841 } 12842 12843 case CK_IntegralComplexToReal: { 12844 ComplexValue C; 12845 if (!EvaluateComplex(SubExpr, C, Info)) 12846 return false; 12847 return Success(C.getComplexIntReal(), E); 12848 } 12849 12850 case CK_FloatingToIntegral: { 12851 APFloat F(0.0); 12852 if (!EvaluateFloat(SubExpr, F, Info)) 12853 return false; 12854 12855 APSInt Value; 12856 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 12857 return false; 12858 return Success(Value, E); 12859 } 12860 } 12861 12862 llvm_unreachable("unknown cast resulting in integral value"); 12863 } 12864 12865 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 12866 if (E->getSubExpr()->getType()->isAnyComplexType()) { 12867 ComplexValue LV; 12868 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 12869 return false; 12870 if (!LV.isComplexInt()) 12871 return Error(E); 12872 return Success(LV.getComplexIntReal(), E); 12873 } 12874 12875 return Visit(E->getSubExpr()); 12876 } 12877 12878 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 12879 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 12880 ComplexValue LV; 12881 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 12882 return false; 12883 if (!LV.isComplexInt()) 12884 return Error(E); 12885 return Success(LV.getComplexIntImag(), E); 12886 } 12887 12888 VisitIgnoredValue(E->getSubExpr()); 12889 return Success(0, E); 12890 } 12891 12892 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 12893 return Success(E->getPackLength(), E); 12894 } 12895 12896 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 12897 return Success(E->getValue(), E); 12898 } 12899 12900 bool IntExprEvaluator::VisitConceptSpecializationExpr( 12901 const ConceptSpecializationExpr *E) { 12902 return Success(E->isSatisfied(), E); 12903 } 12904 12905 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 12906 return Success(E->isSatisfied(), E); 12907 } 12908 12909 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12910 switch (E->getOpcode()) { 12911 default: 12912 // Invalid unary operators 12913 return Error(E); 12914 case UO_Plus: 12915 // The result is just the value. 12916 return Visit(E->getSubExpr()); 12917 case UO_Minus: { 12918 if (!Visit(E->getSubExpr())) return false; 12919 if (!Result.isFixedPoint()) 12920 return Error(E); 12921 bool Overflowed; 12922 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 12923 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 12924 return false; 12925 return Success(Negated, E); 12926 } 12927 case UO_LNot: { 12928 bool bres; 12929 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 12930 return false; 12931 return Success(!bres, E); 12932 } 12933 } 12934 } 12935 12936 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 12937 const Expr *SubExpr = E->getSubExpr(); 12938 QualType DestType = E->getType(); 12939 assert(DestType->isFixedPointType() && 12940 "Expected destination type to be a fixed point type"); 12941 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 12942 12943 switch (E->getCastKind()) { 12944 case CK_FixedPointCast: { 12945 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 12946 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 12947 return false; 12948 bool Overflowed; 12949 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 12950 if (Overflowed) { 12951 if (Info.checkingForUndefinedBehavior()) 12952 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 12953 diag::warn_fixedpoint_constant_overflow) 12954 << Result.toString() << E->getType(); 12955 else if (!HandleOverflow(Info, E, Result, E->getType())) 12956 return false; 12957 } 12958 return Success(Result, E); 12959 } 12960 case CK_IntegralToFixedPoint: { 12961 APSInt Src; 12962 if (!EvaluateInteger(SubExpr, Src, Info)) 12963 return false; 12964 12965 bool Overflowed; 12966 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 12967 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 12968 12969 if (Overflowed) { 12970 if (Info.checkingForUndefinedBehavior()) 12971 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 12972 diag::warn_fixedpoint_constant_overflow) 12973 << IntResult.toString() << E->getType(); 12974 else if (!HandleOverflow(Info, E, IntResult, E->getType())) 12975 return false; 12976 } 12977 12978 return Success(IntResult, E); 12979 } 12980 case CK_NoOp: 12981 case CK_LValueToRValue: 12982 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12983 default: 12984 return Error(E); 12985 } 12986 } 12987 12988 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12989 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 12990 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12991 12992 const Expr *LHS = E->getLHS(); 12993 const Expr *RHS = E->getRHS(); 12994 FixedPointSemantics ResultFXSema = 12995 Info.Ctx.getFixedPointSemantics(E->getType()); 12996 12997 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 12998 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 12999 return false; 13000 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13001 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13002 return false; 13003 13004 bool OpOverflow = false, ConversionOverflow = false; 13005 APFixedPoint Result(LHSFX.getSemantics()); 13006 switch (E->getOpcode()) { 13007 case BO_Add: { 13008 Result = LHSFX.add(RHSFX, &OpOverflow) 13009 .convert(ResultFXSema, &ConversionOverflow); 13010 break; 13011 } 13012 case BO_Sub: { 13013 Result = LHSFX.sub(RHSFX, &OpOverflow) 13014 .convert(ResultFXSema, &ConversionOverflow); 13015 break; 13016 } 13017 case BO_Mul: { 13018 Result = LHSFX.mul(RHSFX, &OpOverflow) 13019 .convert(ResultFXSema, &ConversionOverflow); 13020 break; 13021 } 13022 case BO_Div: { 13023 if (RHSFX.getValue() == 0) { 13024 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13025 return false; 13026 } 13027 Result = LHSFX.div(RHSFX, &OpOverflow) 13028 .convert(ResultFXSema, &ConversionOverflow); 13029 break; 13030 } 13031 case BO_Shl: 13032 case BO_Shr: { 13033 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13034 llvm::APSInt RHSVal = RHSFX.getValue(); 13035 13036 unsigned ShiftBW = 13037 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13038 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13039 // Embedded-C 4.1.6.2.2: 13040 // The right operand must be nonnegative and less than the total number 13041 // of (nonpadding) bits of the fixed-point operand ... 13042 if (RHSVal.isNegative()) 13043 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13044 else if (Amt != RHSVal) 13045 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13046 << RHSVal << E->getType() << ShiftBW; 13047 13048 if (E->getOpcode() == BO_Shl) 13049 Result = LHSFX.shl(Amt, &OpOverflow); 13050 else 13051 Result = LHSFX.shr(Amt, &OpOverflow); 13052 break; 13053 } 13054 default: 13055 return false; 13056 } 13057 if (OpOverflow || ConversionOverflow) { 13058 if (Info.checkingForUndefinedBehavior()) 13059 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13060 diag::warn_fixedpoint_constant_overflow) 13061 << Result.toString() << E->getType(); 13062 else if (!HandleOverflow(Info, E, Result, E->getType())) 13063 return false; 13064 } 13065 return Success(Result, E); 13066 } 13067 13068 //===----------------------------------------------------------------------===// 13069 // Float Evaluation 13070 //===----------------------------------------------------------------------===// 13071 13072 namespace { 13073 class FloatExprEvaluator 13074 : public ExprEvaluatorBase<FloatExprEvaluator> { 13075 APFloat &Result; 13076 public: 13077 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13078 : ExprEvaluatorBaseTy(info), Result(result) {} 13079 13080 bool Success(const APValue &V, const Expr *e) { 13081 Result = V.getFloat(); 13082 return true; 13083 } 13084 13085 bool ZeroInitialization(const Expr *E) { 13086 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13087 return true; 13088 } 13089 13090 bool VisitCallExpr(const CallExpr *E); 13091 13092 bool VisitUnaryOperator(const UnaryOperator *E); 13093 bool VisitBinaryOperator(const BinaryOperator *E); 13094 bool VisitFloatingLiteral(const FloatingLiteral *E); 13095 bool VisitCastExpr(const CastExpr *E); 13096 13097 bool VisitUnaryReal(const UnaryOperator *E); 13098 bool VisitUnaryImag(const UnaryOperator *E); 13099 13100 // FIXME: Missing: array subscript of vector, member of vector 13101 }; 13102 } // end anonymous namespace 13103 13104 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13105 assert(E->isRValue() && E->getType()->isRealFloatingType()); 13106 return FloatExprEvaluator(Info, Result).Visit(E); 13107 } 13108 13109 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13110 QualType ResultTy, 13111 const Expr *Arg, 13112 bool SNaN, 13113 llvm::APFloat &Result) { 13114 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13115 if (!S) return false; 13116 13117 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13118 13119 llvm::APInt fill; 13120 13121 // Treat empty strings as if they were zero. 13122 if (S->getString().empty()) 13123 fill = llvm::APInt(32, 0); 13124 else if (S->getString().getAsInteger(0, fill)) 13125 return false; 13126 13127 if (Context.getTargetInfo().isNan2008()) { 13128 if (SNaN) 13129 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13130 else 13131 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13132 } else { 13133 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13134 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13135 // a different encoding to what became a standard in 2008, and for pre- 13136 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13137 // sNaN. This is now known as "legacy NaN" encoding. 13138 if (SNaN) 13139 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13140 else 13141 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13142 } 13143 13144 return true; 13145 } 13146 13147 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13148 switch (E->getBuiltinCallee()) { 13149 default: 13150 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13151 13152 case Builtin::BI__builtin_huge_val: 13153 case Builtin::BI__builtin_huge_valf: 13154 case Builtin::BI__builtin_huge_vall: 13155 case Builtin::BI__builtin_huge_valf128: 13156 case Builtin::BI__builtin_inf: 13157 case Builtin::BI__builtin_inff: 13158 case Builtin::BI__builtin_infl: 13159 case Builtin::BI__builtin_inff128: { 13160 const llvm::fltSemantics &Sem = 13161 Info.Ctx.getFloatTypeSemantics(E->getType()); 13162 Result = llvm::APFloat::getInf(Sem); 13163 return true; 13164 } 13165 13166 case Builtin::BI__builtin_nans: 13167 case Builtin::BI__builtin_nansf: 13168 case Builtin::BI__builtin_nansl: 13169 case Builtin::BI__builtin_nansf128: 13170 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13171 true, Result)) 13172 return Error(E); 13173 return true; 13174 13175 case Builtin::BI__builtin_nan: 13176 case Builtin::BI__builtin_nanf: 13177 case Builtin::BI__builtin_nanl: 13178 case Builtin::BI__builtin_nanf128: 13179 // If this is __builtin_nan() turn this into a nan, otherwise we 13180 // can't constant fold it. 13181 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13182 false, Result)) 13183 return Error(E); 13184 return true; 13185 13186 case Builtin::BI__builtin_fabs: 13187 case Builtin::BI__builtin_fabsf: 13188 case Builtin::BI__builtin_fabsl: 13189 case Builtin::BI__builtin_fabsf128: 13190 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13191 return false; 13192 13193 if (Result.isNegative()) 13194 Result.changeSign(); 13195 return true; 13196 13197 // FIXME: Builtin::BI__builtin_powi 13198 // FIXME: Builtin::BI__builtin_powif 13199 // FIXME: Builtin::BI__builtin_powil 13200 13201 case Builtin::BI__builtin_copysign: 13202 case Builtin::BI__builtin_copysignf: 13203 case Builtin::BI__builtin_copysignl: 13204 case Builtin::BI__builtin_copysignf128: { 13205 APFloat RHS(0.); 13206 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13207 !EvaluateFloat(E->getArg(1), RHS, Info)) 13208 return false; 13209 Result.copySign(RHS); 13210 return true; 13211 } 13212 } 13213 } 13214 13215 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13216 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13217 ComplexValue CV; 13218 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13219 return false; 13220 Result = CV.FloatReal; 13221 return true; 13222 } 13223 13224 return Visit(E->getSubExpr()); 13225 } 13226 13227 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13228 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13229 ComplexValue CV; 13230 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13231 return false; 13232 Result = CV.FloatImag; 13233 return true; 13234 } 13235 13236 VisitIgnoredValue(E->getSubExpr()); 13237 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13238 Result = llvm::APFloat::getZero(Sem); 13239 return true; 13240 } 13241 13242 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13243 switch (E->getOpcode()) { 13244 default: return Error(E); 13245 case UO_Plus: 13246 return EvaluateFloat(E->getSubExpr(), Result, Info); 13247 case UO_Minus: 13248 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13249 return false; 13250 Result.changeSign(); 13251 return true; 13252 } 13253 } 13254 13255 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13256 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13257 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13258 13259 APFloat RHS(0.0); 13260 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13261 if (!LHSOK && !Info.noteFailure()) 13262 return false; 13263 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13264 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13265 } 13266 13267 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13268 Result = E->getValue(); 13269 return true; 13270 } 13271 13272 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13273 const Expr* SubExpr = E->getSubExpr(); 13274 13275 switch (E->getCastKind()) { 13276 default: 13277 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13278 13279 case CK_IntegralToFloating: { 13280 APSInt IntResult; 13281 return EvaluateInteger(SubExpr, IntResult, Info) && 13282 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 13283 E->getType(), Result); 13284 } 13285 13286 case CK_FloatingCast: { 13287 if (!Visit(SubExpr)) 13288 return false; 13289 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13290 Result); 13291 } 13292 13293 case CK_FloatingComplexToReal: { 13294 ComplexValue V; 13295 if (!EvaluateComplex(SubExpr, V, Info)) 13296 return false; 13297 Result = V.getComplexFloatReal(); 13298 return true; 13299 } 13300 } 13301 } 13302 13303 //===----------------------------------------------------------------------===// 13304 // Complex Evaluation (for float and integer) 13305 //===----------------------------------------------------------------------===// 13306 13307 namespace { 13308 class ComplexExprEvaluator 13309 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13310 ComplexValue &Result; 13311 13312 public: 13313 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13314 : ExprEvaluatorBaseTy(info), Result(Result) {} 13315 13316 bool Success(const APValue &V, const Expr *e) { 13317 Result.setFrom(V); 13318 return true; 13319 } 13320 13321 bool ZeroInitialization(const Expr *E); 13322 13323 //===--------------------------------------------------------------------===// 13324 // Visitor Methods 13325 //===--------------------------------------------------------------------===// 13326 13327 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13328 bool VisitCastExpr(const CastExpr *E); 13329 bool VisitBinaryOperator(const BinaryOperator *E); 13330 bool VisitUnaryOperator(const UnaryOperator *E); 13331 bool VisitInitListExpr(const InitListExpr *E); 13332 bool VisitCallExpr(const CallExpr *E); 13333 }; 13334 } // end anonymous namespace 13335 13336 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13337 EvalInfo &Info) { 13338 assert(E->isRValue() && E->getType()->isAnyComplexType()); 13339 return ComplexExprEvaluator(Info, Result).Visit(E); 13340 } 13341 13342 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13343 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13344 if (ElemTy->isRealFloatingType()) { 13345 Result.makeComplexFloat(); 13346 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13347 Result.FloatReal = Zero; 13348 Result.FloatImag = Zero; 13349 } else { 13350 Result.makeComplexInt(); 13351 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13352 Result.IntReal = Zero; 13353 Result.IntImag = Zero; 13354 } 13355 return true; 13356 } 13357 13358 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13359 const Expr* SubExpr = E->getSubExpr(); 13360 13361 if (SubExpr->getType()->isRealFloatingType()) { 13362 Result.makeComplexFloat(); 13363 APFloat &Imag = Result.FloatImag; 13364 if (!EvaluateFloat(SubExpr, Imag, Info)) 13365 return false; 13366 13367 Result.FloatReal = APFloat(Imag.getSemantics()); 13368 return true; 13369 } else { 13370 assert(SubExpr->getType()->isIntegerType() && 13371 "Unexpected imaginary literal."); 13372 13373 Result.makeComplexInt(); 13374 APSInt &Imag = Result.IntImag; 13375 if (!EvaluateInteger(SubExpr, Imag, Info)) 13376 return false; 13377 13378 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13379 return true; 13380 } 13381 } 13382 13383 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13384 13385 switch (E->getCastKind()) { 13386 case CK_BitCast: 13387 case CK_BaseToDerived: 13388 case CK_DerivedToBase: 13389 case CK_UncheckedDerivedToBase: 13390 case CK_Dynamic: 13391 case CK_ToUnion: 13392 case CK_ArrayToPointerDecay: 13393 case CK_FunctionToPointerDecay: 13394 case CK_NullToPointer: 13395 case CK_NullToMemberPointer: 13396 case CK_BaseToDerivedMemberPointer: 13397 case CK_DerivedToBaseMemberPointer: 13398 case CK_MemberPointerToBoolean: 13399 case CK_ReinterpretMemberPointer: 13400 case CK_ConstructorConversion: 13401 case CK_IntegralToPointer: 13402 case CK_PointerToIntegral: 13403 case CK_PointerToBoolean: 13404 case CK_ToVoid: 13405 case CK_VectorSplat: 13406 case CK_IntegralCast: 13407 case CK_BooleanToSignedIntegral: 13408 case CK_IntegralToBoolean: 13409 case CK_IntegralToFloating: 13410 case CK_FloatingToIntegral: 13411 case CK_FloatingToBoolean: 13412 case CK_FloatingCast: 13413 case CK_CPointerToObjCPointerCast: 13414 case CK_BlockPointerToObjCPointerCast: 13415 case CK_AnyPointerToBlockPointerCast: 13416 case CK_ObjCObjectLValueCast: 13417 case CK_FloatingComplexToReal: 13418 case CK_FloatingComplexToBoolean: 13419 case CK_IntegralComplexToReal: 13420 case CK_IntegralComplexToBoolean: 13421 case CK_ARCProduceObject: 13422 case CK_ARCConsumeObject: 13423 case CK_ARCReclaimReturnedObject: 13424 case CK_ARCExtendBlockObject: 13425 case CK_CopyAndAutoreleaseBlockObject: 13426 case CK_BuiltinFnToFnPtr: 13427 case CK_ZeroToOCLOpaqueType: 13428 case CK_NonAtomicToAtomic: 13429 case CK_AddressSpaceConversion: 13430 case CK_IntToOCLSampler: 13431 case CK_FixedPointCast: 13432 case CK_FixedPointToBoolean: 13433 case CK_FixedPointToIntegral: 13434 case CK_IntegralToFixedPoint: 13435 llvm_unreachable("invalid cast kind for complex value"); 13436 13437 case CK_LValueToRValue: 13438 case CK_AtomicToNonAtomic: 13439 case CK_NoOp: 13440 case CK_LValueToRValueBitCast: 13441 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13442 13443 case CK_Dependent: 13444 case CK_LValueBitCast: 13445 case CK_UserDefinedConversion: 13446 return Error(E); 13447 13448 case CK_FloatingRealToComplex: { 13449 APFloat &Real = Result.FloatReal; 13450 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13451 return false; 13452 13453 Result.makeComplexFloat(); 13454 Result.FloatImag = APFloat(Real.getSemantics()); 13455 return true; 13456 } 13457 13458 case CK_FloatingComplexCast: { 13459 if (!Visit(E->getSubExpr())) 13460 return false; 13461 13462 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13463 QualType From 13464 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13465 13466 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13467 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13468 } 13469 13470 case CK_FloatingComplexToIntegralComplex: { 13471 if (!Visit(E->getSubExpr())) 13472 return false; 13473 13474 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13475 QualType From 13476 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13477 Result.makeComplexInt(); 13478 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13479 To, Result.IntReal) && 13480 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13481 To, Result.IntImag); 13482 } 13483 13484 case CK_IntegralRealToComplex: { 13485 APSInt &Real = Result.IntReal; 13486 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13487 return false; 13488 13489 Result.makeComplexInt(); 13490 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13491 return true; 13492 } 13493 13494 case CK_IntegralComplexCast: { 13495 if (!Visit(E->getSubExpr())) 13496 return false; 13497 13498 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13499 QualType From 13500 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13501 13502 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 13503 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 13504 return true; 13505 } 13506 13507 case CK_IntegralComplexToFloatingComplex: { 13508 if (!Visit(E->getSubExpr())) 13509 return false; 13510 13511 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13512 QualType From 13513 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13514 Result.makeComplexFloat(); 13515 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 13516 To, Result.FloatReal) && 13517 HandleIntToFloatCast(Info, E, From, Result.IntImag, 13518 To, Result.FloatImag); 13519 } 13520 } 13521 13522 llvm_unreachable("unknown cast resulting in complex value"); 13523 } 13524 13525 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13526 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13527 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13528 13529 // Track whether the LHS or RHS is real at the type system level. When this is 13530 // the case we can simplify our evaluation strategy. 13531 bool LHSReal = false, RHSReal = false; 13532 13533 bool LHSOK; 13534 if (E->getLHS()->getType()->isRealFloatingType()) { 13535 LHSReal = true; 13536 APFloat &Real = Result.FloatReal; 13537 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 13538 if (LHSOK) { 13539 Result.makeComplexFloat(); 13540 Result.FloatImag = APFloat(Real.getSemantics()); 13541 } 13542 } else { 13543 LHSOK = Visit(E->getLHS()); 13544 } 13545 if (!LHSOK && !Info.noteFailure()) 13546 return false; 13547 13548 ComplexValue RHS; 13549 if (E->getRHS()->getType()->isRealFloatingType()) { 13550 RHSReal = true; 13551 APFloat &Real = RHS.FloatReal; 13552 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 13553 return false; 13554 RHS.makeComplexFloat(); 13555 RHS.FloatImag = APFloat(Real.getSemantics()); 13556 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 13557 return false; 13558 13559 assert(!(LHSReal && RHSReal) && 13560 "Cannot have both operands of a complex operation be real."); 13561 switch (E->getOpcode()) { 13562 default: return Error(E); 13563 case BO_Add: 13564 if (Result.isComplexFloat()) { 13565 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 13566 APFloat::rmNearestTiesToEven); 13567 if (LHSReal) 13568 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13569 else if (!RHSReal) 13570 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 13571 APFloat::rmNearestTiesToEven); 13572 } else { 13573 Result.getComplexIntReal() += RHS.getComplexIntReal(); 13574 Result.getComplexIntImag() += RHS.getComplexIntImag(); 13575 } 13576 break; 13577 case BO_Sub: 13578 if (Result.isComplexFloat()) { 13579 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 13580 APFloat::rmNearestTiesToEven); 13581 if (LHSReal) { 13582 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13583 Result.getComplexFloatImag().changeSign(); 13584 } else if (!RHSReal) { 13585 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 13586 APFloat::rmNearestTiesToEven); 13587 } 13588 } else { 13589 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 13590 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 13591 } 13592 break; 13593 case BO_Mul: 13594 if (Result.isComplexFloat()) { 13595 // This is an implementation of complex multiplication according to the 13596 // constraints laid out in C11 Annex G. The implementation uses the 13597 // following naming scheme: 13598 // (a + ib) * (c + id) 13599 ComplexValue LHS = Result; 13600 APFloat &A = LHS.getComplexFloatReal(); 13601 APFloat &B = LHS.getComplexFloatImag(); 13602 APFloat &C = RHS.getComplexFloatReal(); 13603 APFloat &D = RHS.getComplexFloatImag(); 13604 APFloat &ResR = Result.getComplexFloatReal(); 13605 APFloat &ResI = Result.getComplexFloatImag(); 13606 if (LHSReal) { 13607 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 13608 ResR = A * C; 13609 ResI = A * D; 13610 } else if (RHSReal) { 13611 ResR = C * A; 13612 ResI = C * B; 13613 } else { 13614 // In the fully general case, we need to handle NaNs and infinities 13615 // robustly. 13616 APFloat AC = A * C; 13617 APFloat BD = B * D; 13618 APFloat AD = A * D; 13619 APFloat BC = B * C; 13620 ResR = AC - BD; 13621 ResI = AD + BC; 13622 if (ResR.isNaN() && ResI.isNaN()) { 13623 bool Recalc = false; 13624 if (A.isInfinity() || B.isInfinity()) { 13625 A = APFloat::copySign( 13626 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13627 B = APFloat::copySign( 13628 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13629 if (C.isNaN()) 13630 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13631 if (D.isNaN()) 13632 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13633 Recalc = true; 13634 } 13635 if (C.isInfinity() || D.isInfinity()) { 13636 C = APFloat::copySign( 13637 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13638 D = APFloat::copySign( 13639 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13640 if (A.isNaN()) 13641 A = APFloat::copySign(APFloat(A.getSemantics()), A); 13642 if (B.isNaN()) 13643 B = APFloat::copySign(APFloat(B.getSemantics()), B); 13644 Recalc = true; 13645 } 13646 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 13647 AD.isInfinity() || BC.isInfinity())) { 13648 if (A.isNaN()) 13649 A = APFloat::copySign(APFloat(A.getSemantics()), A); 13650 if (B.isNaN()) 13651 B = APFloat::copySign(APFloat(B.getSemantics()), B); 13652 if (C.isNaN()) 13653 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13654 if (D.isNaN()) 13655 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13656 Recalc = true; 13657 } 13658 if (Recalc) { 13659 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 13660 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 13661 } 13662 } 13663 } 13664 } else { 13665 ComplexValue LHS = Result; 13666 Result.getComplexIntReal() = 13667 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 13668 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 13669 Result.getComplexIntImag() = 13670 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 13671 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 13672 } 13673 break; 13674 case BO_Div: 13675 if (Result.isComplexFloat()) { 13676 // This is an implementation of complex division according to the 13677 // constraints laid out in C11 Annex G. The implementation uses the 13678 // following naming scheme: 13679 // (a + ib) / (c + id) 13680 ComplexValue LHS = Result; 13681 APFloat &A = LHS.getComplexFloatReal(); 13682 APFloat &B = LHS.getComplexFloatImag(); 13683 APFloat &C = RHS.getComplexFloatReal(); 13684 APFloat &D = RHS.getComplexFloatImag(); 13685 APFloat &ResR = Result.getComplexFloatReal(); 13686 APFloat &ResI = Result.getComplexFloatImag(); 13687 if (RHSReal) { 13688 ResR = A / C; 13689 ResI = B / C; 13690 } else { 13691 if (LHSReal) { 13692 // No real optimizations we can do here, stub out with zero. 13693 B = APFloat::getZero(A.getSemantics()); 13694 } 13695 int DenomLogB = 0; 13696 APFloat MaxCD = maxnum(abs(C), abs(D)); 13697 if (MaxCD.isFinite()) { 13698 DenomLogB = ilogb(MaxCD); 13699 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 13700 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 13701 } 13702 APFloat Denom = C * C + D * D; 13703 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 13704 APFloat::rmNearestTiesToEven); 13705 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 13706 APFloat::rmNearestTiesToEven); 13707 if (ResR.isNaN() && ResI.isNaN()) { 13708 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 13709 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 13710 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 13711 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 13712 D.isFinite()) { 13713 A = APFloat::copySign( 13714 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13715 B = APFloat::copySign( 13716 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13717 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 13718 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 13719 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 13720 C = APFloat::copySign( 13721 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13722 D = APFloat::copySign( 13723 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13724 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 13725 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 13726 } 13727 } 13728 } 13729 } else { 13730 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 13731 return Error(E, diag::note_expr_divide_by_zero); 13732 13733 ComplexValue LHS = Result; 13734 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 13735 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 13736 Result.getComplexIntReal() = 13737 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 13738 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 13739 Result.getComplexIntImag() = 13740 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 13741 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 13742 } 13743 break; 13744 } 13745 13746 return true; 13747 } 13748 13749 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13750 // Get the operand value into 'Result'. 13751 if (!Visit(E->getSubExpr())) 13752 return false; 13753 13754 switch (E->getOpcode()) { 13755 default: 13756 return Error(E); 13757 case UO_Extension: 13758 return true; 13759 case UO_Plus: 13760 // The result is always just the subexpr. 13761 return true; 13762 case UO_Minus: 13763 if (Result.isComplexFloat()) { 13764 Result.getComplexFloatReal().changeSign(); 13765 Result.getComplexFloatImag().changeSign(); 13766 } 13767 else { 13768 Result.getComplexIntReal() = -Result.getComplexIntReal(); 13769 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13770 } 13771 return true; 13772 case UO_Not: 13773 if (Result.isComplexFloat()) 13774 Result.getComplexFloatImag().changeSign(); 13775 else 13776 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13777 return true; 13778 } 13779 } 13780 13781 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 13782 if (E->getNumInits() == 2) { 13783 if (E->getType()->isComplexType()) { 13784 Result.makeComplexFloat(); 13785 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 13786 return false; 13787 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 13788 return false; 13789 } else { 13790 Result.makeComplexInt(); 13791 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 13792 return false; 13793 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 13794 return false; 13795 } 13796 return true; 13797 } 13798 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 13799 } 13800 13801 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 13802 switch (E->getBuiltinCallee()) { 13803 case Builtin::BI__builtin_complex: 13804 Result.makeComplexFloat(); 13805 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 13806 return false; 13807 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 13808 return false; 13809 return true; 13810 13811 default: 13812 break; 13813 } 13814 13815 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13816 } 13817 13818 //===----------------------------------------------------------------------===// 13819 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 13820 // implicit conversion. 13821 //===----------------------------------------------------------------------===// 13822 13823 namespace { 13824 class AtomicExprEvaluator : 13825 public ExprEvaluatorBase<AtomicExprEvaluator> { 13826 const LValue *This; 13827 APValue &Result; 13828 public: 13829 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 13830 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 13831 13832 bool Success(const APValue &V, const Expr *E) { 13833 Result = V; 13834 return true; 13835 } 13836 13837 bool ZeroInitialization(const Expr *E) { 13838 ImplicitValueInitExpr VIE( 13839 E->getType()->castAs<AtomicType>()->getValueType()); 13840 // For atomic-qualified class (and array) types in C++, initialize the 13841 // _Atomic-wrapped subobject directly, in-place. 13842 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 13843 : Evaluate(Result, Info, &VIE); 13844 } 13845 13846 bool VisitCastExpr(const CastExpr *E) { 13847 switch (E->getCastKind()) { 13848 default: 13849 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13850 case CK_NonAtomicToAtomic: 13851 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 13852 : Evaluate(Result, Info, E->getSubExpr()); 13853 } 13854 } 13855 }; 13856 } // end anonymous namespace 13857 13858 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 13859 EvalInfo &Info) { 13860 assert(E->isRValue() && E->getType()->isAtomicType()); 13861 return AtomicExprEvaluator(Info, This, Result).Visit(E); 13862 } 13863 13864 //===----------------------------------------------------------------------===// 13865 // Void expression evaluation, primarily for a cast to void on the LHS of a 13866 // comma operator 13867 //===----------------------------------------------------------------------===// 13868 13869 namespace { 13870 class VoidExprEvaluator 13871 : public ExprEvaluatorBase<VoidExprEvaluator> { 13872 public: 13873 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 13874 13875 bool Success(const APValue &V, const Expr *e) { return true; } 13876 13877 bool ZeroInitialization(const Expr *E) { return true; } 13878 13879 bool VisitCastExpr(const CastExpr *E) { 13880 switch (E->getCastKind()) { 13881 default: 13882 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13883 case CK_ToVoid: 13884 VisitIgnoredValue(E->getSubExpr()); 13885 return true; 13886 } 13887 } 13888 13889 bool VisitCallExpr(const CallExpr *E) { 13890 switch (E->getBuiltinCallee()) { 13891 case Builtin::BI__assume: 13892 case Builtin::BI__builtin_assume: 13893 // The argument is not evaluated! 13894 return true; 13895 13896 case Builtin::BI__builtin_operator_delete: 13897 return HandleOperatorDeleteCall(Info, E); 13898 13899 default: 13900 break; 13901 } 13902 13903 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13904 } 13905 13906 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 13907 }; 13908 } // end anonymous namespace 13909 13910 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 13911 // We cannot speculatively evaluate a delete expression. 13912 if (Info.SpeculativeEvaluationDepth) 13913 return false; 13914 13915 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 13916 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 13917 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 13918 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 13919 return false; 13920 } 13921 13922 const Expr *Arg = E->getArgument(); 13923 13924 LValue Pointer; 13925 if (!EvaluatePointer(Arg, Pointer, Info)) 13926 return false; 13927 if (Pointer.Designator.Invalid) 13928 return false; 13929 13930 // Deleting a null pointer has no effect. 13931 if (Pointer.isNullPointer()) { 13932 // This is the only case where we need to produce an extension warning: 13933 // the only other way we can succeed is if we find a dynamic allocation, 13934 // and we will have warned when we allocated it in that case. 13935 if (!Info.getLangOpts().CPlusPlus20) 13936 Info.CCEDiag(E, diag::note_constexpr_new); 13937 return true; 13938 } 13939 13940 Optional<DynAlloc *> Alloc = CheckDeleteKind( 13941 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 13942 if (!Alloc) 13943 return false; 13944 QualType AllocType = Pointer.Base.getDynamicAllocType(); 13945 13946 // For the non-array case, the designator must be empty if the static type 13947 // does not have a virtual destructor. 13948 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 13949 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 13950 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 13951 << Arg->getType()->getPointeeType() << AllocType; 13952 return false; 13953 } 13954 13955 // For a class type with a virtual destructor, the selected operator delete 13956 // is the one looked up when building the destructor. 13957 if (!E->isArrayForm() && !E->isGlobalDelete()) { 13958 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 13959 if (VirtualDelete && 13960 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 13961 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 13962 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 13963 return false; 13964 } 13965 } 13966 13967 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 13968 (*Alloc)->Value, AllocType)) 13969 return false; 13970 13971 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 13972 // The element was already erased. This means the destructor call also 13973 // deleted the object. 13974 // FIXME: This probably results in undefined behavior before we get this 13975 // far, and should be diagnosed elsewhere first. 13976 Info.FFDiag(E, diag::note_constexpr_double_delete); 13977 return false; 13978 } 13979 13980 return true; 13981 } 13982 13983 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 13984 assert(E->isRValue() && E->getType()->isVoidType()); 13985 return VoidExprEvaluator(Info).Visit(E); 13986 } 13987 13988 //===----------------------------------------------------------------------===// 13989 // Top level Expr::EvaluateAsRValue method. 13990 //===----------------------------------------------------------------------===// 13991 13992 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 13993 // In C, function designators are not lvalues, but we evaluate them as if they 13994 // are. 13995 QualType T = E->getType(); 13996 if (E->isGLValue() || T->isFunctionType()) { 13997 LValue LV; 13998 if (!EvaluateLValue(E, LV, Info)) 13999 return false; 14000 LV.moveInto(Result); 14001 } else if (T->isVectorType()) { 14002 if (!EvaluateVector(E, Result, Info)) 14003 return false; 14004 } else if (T->isIntegralOrEnumerationType()) { 14005 if (!IntExprEvaluator(Info, Result).Visit(E)) 14006 return false; 14007 } else if (T->hasPointerRepresentation()) { 14008 LValue LV; 14009 if (!EvaluatePointer(E, LV, Info)) 14010 return false; 14011 LV.moveInto(Result); 14012 } else if (T->isRealFloatingType()) { 14013 llvm::APFloat F(0.0); 14014 if (!EvaluateFloat(E, F, Info)) 14015 return false; 14016 Result = APValue(F); 14017 } else if (T->isAnyComplexType()) { 14018 ComplexValue C; 14019 if (!EvaluateComplex(E, C, Info)) 14020 return false; 14021 C.moveInto(Result); 14022 } else if (T->isFixedPointType()) { 14023 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14024 } else if (T->isMemberPointerType()) { 14025 MemberPtr P; 14026 if (!EvaluateMemberPointer(E, P, Info)) 14027 return false; 14028 P.moveInto(Result); 14029 return true; 14030 } else if (T->isArrayType()) { 14031 LValue LV; 14032 APValue &Value = 14033 Info.CurrentCall->createTemporary(E, T, false, LV); 14034 if (!EvaluateArray(E, LV, Value, Info)) 14035 return false; 14036 Result = Value; 14037 } else if (T->isRecordType()) { 14038 LValue LV; 14039 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV); 14040 if (!EvaluateRecord(E, LV, Value, Info)) 14041 return false; 14042 Result = Value; 14043 } else if (T->isVoidType()) { 14044 if (!Info.getLangOpts().CPlusPlus11) 14045 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14046 << E->getType(); 14047 if (!EvaluateVoid(E, Info)) 14048 return false; 14049 } else if (T->isAtomicType()) { 14050 QualType Unqual = T.getAtomicUnqualifiedType(); 14051 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14052 LValue LV; 14053 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV); 14054 if (!EvaluateAtomic(E, &LV, Value, Info)) 14055 return false; 14056 } else { 14057 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14058 return false; 14059 } 14060 } else if (Info.getLangOpts().CPlusPlus11) { 14061 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14062 return false; 14063 } else { 14064 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14065 return false; 14066 } 14067 14068 return true; 14069 } 14070 14071 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14072 /// cases, the in-place evaluation is essential, since later initializers for 14073 /// an object can indirectly refer to subobjects which were initialized earlier. 14074 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14075 const Expr *E, bool AllowNonLiteralTypes) { 14076 assert(!E->isValueDependent()); 14077 14078 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14079 return false; 14080 14081 if (E->isRValue()) { 14082 // Evaluate arrays and record types in-place, so that later initializers can 14083 // refer to earlier-initialized members of the object. 14084 QualType T = E->getType(); 14085 if (T->isArrayType()) 14086 return EvaluateArray(E, This, Result, Info); 14087 else if (T->isRecordType()) 14088 return EvaluateRecord(E, This, Result, Info); 14089 else if (T->isAtomicType()) { 14090 QualType Unqual = T.getAtomicUnqualifiedType(); 14091 if (Unqual->isArrayType() || Unqual->isRecordType()) 14092 return EvaluateAtomic(E, &This, Result, Info); 14093 } 14094 } 14095 14096 // For any other type, in-place evaluation is unimportant. 14097 return Evaluate(Result, Info, E); 14098 } 14099 14100 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14101 /// lvalue-to-rvalue cast if it is an lvalue. 14102 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14103 if (Info.EnableNewConstInterp) { 14104 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14105 return false; 14106 } else { 14107 if (E->getType().isNull()) 14108 return false; 14109 14110 if (!CheckLiteralType(Info, E)) 14111 return false; 14112 14113 if (!::Evaluate(Result, Info, E)) 14114 return false; 14115 14116 if (E->isGLValue()) { 14117 LValue LV; 14118 LV.setFrom(Info.Ctx, Result); 14119 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14120 return false; 14121 } 14122 } 14123 14124 // Check this core constant expression is a constant expression. 14125 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) && 14126 CheckMemoryLeaks(Info); 14127 } 14128 14129 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14130 const ASTContext &Ctx, bool &IsConst) { 14131 // Fast-path evaluations of integer literals, since we sometimes see files 14132 // containing vast quantities of these. 14133 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14134 Result.Val = APValue(APSInt(L->getValue(), 14135 L->getType()->isUnsignedIntegerType())); 14136 IsConst = true; 14137 return true; 14138 } 14139 14140 // This case should be rare, but we need to check it before we check on 14141 // the type below. 14142 if (Exp->getType().isNull()) { 14143 IsConst = false; 14144 return true; 14145 } 14146 14147 // FIXME: Evaluating values of large array and record types can cause 14148 // performance problems. Only do so in C++11 for now. 14149 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 14150 Exp->getType()->isRecordType()) && 14151 !Ctx.getLangOpts().CPlusPlus11) { 14152 IsConst = false; 14153 return true; 14154 } 14155 return false; 14156 } 14157 14158 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14159 Expr::SideEffectsKind SEK) { 14160 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14161 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14162 } 14163 14164 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14165 const ASTContext &Ctx, EvalInfo &Info) { 14166 bool IsConst; 14167 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14168 return IsConst; 14169 14170 return EvaluateAsRValue(Info, E, Result.Val); 14171 } 14172 14173 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14174 const ASTContext &Ctx, 14175 Expr::SideEffectsKind AllowSideEffects, 14176 EvalInfo &Info) { 14177 if (!E->getType()->isIntegralOrEnumerationType()) 14178 return false; 14179 14180 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14181 !ExprResult.Val.isInt() || 14182 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14183 return false; 14184 14185 return true; 14186 } 14187 14188 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14189 const ASTContext &Ctx, 14190 Expr::SideEffectsKind AllowSideEffects, 14191 EvalInfo &Info) { 14192 if (!E->getType()->isFixedPointType()) 14193 return false; 14194 14195 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14196 return false; 14197 14198 if (!ExprResult.Val.isFixedPoint() || 14199 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14200 return false; 14201 14202 return true; 14203 } 14204 14205 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14206 /// any crazy technique (that has nothing to do with language standards) that 14207 /// we want to. If this function returns true, it returns the folded constant 14208 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14209 /// will be applied to the result. 14210 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14211 bool InConstantContext) const { 14212 assert(!isValueDependent() && 14213 "Expression evaluator can't be called on a dependent expression."); 14214 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14215 Info.InConstantContext = InConstantContext; 14216 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14217 } 14218 14219 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14220 bool InConstantContext) const { 14221 assert(!isValueDependent() && 14222 "Expression evaluator can't be called on a dependent expression."); 14223 EvalResult Scratch; 14224 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14225 HandleConversionToBool(Scratch.Val, Result); 14226 } 14227 14228 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14229 SideEffectsKind AllowSideEffects, 14230 bool InConstantContext) const { 14231 assert(!isValueDependent() && 14232 "Expression evaluator can't be called on a dependent expression."); 14233 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14234 Info.InConstantContext = InConstantContext; 14235 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14236 } 14237 14238 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14239 SideEffectsKind AllowSideEffects, 14240 bool InConstantContext) const { 14241 assert(!isValueDependent() && 14242 "Expression evaluator can't be called on a dependent expression."); 14243 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14244 Info.InConstantContext = InConstantContext; 14245 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14246 } 14247 14248 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14249 SideEffectsKind AllowSideEffects, 14250 bool InConstantContext) const { 14251 assert(!isValueDependent() && 14252 "Expression evaluator can't be called on a dependent expression."); 14253 14254 if (!getType()->isRealFloatingType()) 14255 return false; 14256 14257 EvalResult ExprResult; 14258 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14259 !ExprResult.Val.isFloat() || 14260 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14261 return false; 14262 14263 Result = ExprResult.Val.getFloat(); 14264 return true; 14265 } 14266 14267 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14268 bool InConstantContext) const { 14269 assert(!isValueDependent() && 14270 "Expression evaluator can't be called on a dependent expression."); 14271 14272 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14273 Info.InConstantContext = InConstantContext; 14274 LValue LV; 14275 CheckedTemporaries CheckedTemps; 14276 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14277 Result.HasSideEffects || 14278 !CheckLValueConstantExpression(Info, getExprLoc(), 14279 Ctx.getLValueReferenceType(getType()), LV, 14280 Expr::EvaluateForCodeGen, CheckedTemps)) 14281 return false; 14282 14283 LV.moveInto(Result.Val); 14284 return true; 14285 } 14286 14287 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 14288 const ASTContext &Ctx, bool InPlace) const { 14289 assert(!isValueDependent() && 14290 "Expression evaluator can't be called on a dependent expression."); 14291 14292 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14293 EvalInfo Info(Ctx, Result, EM); 14294 Info.InConstantContext = true; 14295 14296 if (InPlace) { 14297 Info.setEvaluatingDecl(this, Result.Val); 14298 LValue LVal; 14299 LVal.set(this); 14300 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || 14301 Result.HasSideEffects) 14302 return false; 14303 } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects) 14304 return false; 14305 14306 if (!Info.discardCleanups()) 14307 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14308 14309 return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14310 Result.Val, Usage) && 14311 CheckMemoryLeaks(Info); 14312 } 14313 14314 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14315 const VarDecl *VD, 14316 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14317 assert(!isValueDependent() && 14318 "Expression evaluator can't be called on a dependent expression."); 14319 14320 // FIXME: Evaluating initializers for large array and record types can cause 14321 // performance problems. Only do so in C++11 for now. 14322 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14323 !Ctx.getLangOpts().CPlusPlus11) 14324 return false; 14325 14326 Expr::EvalStatus EStatus; 14327 EStatus.Diag = &Notes; 14328 14329 EvalInfo Info(Ctx, EStatus, VD->isConstexpr() 14330 ? EvalInfo::EM_ConstantExpression 14331 : EvalInfo::EM_ConstantFold); 14332 Info.setEvaluatingDecl(VD, Value); 14333 Info.InConstantContext = true; 14334 14335 SourceLocation DeclLoc = VD->getLocation(); 14336 QualType DeclTy = VD->getType(); 14337 14338 if (Info.EnableNewConstInterp) { 14339 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14340 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14341 return false; 14342 } else { 14343 LValue LVal; 14344 LVal.set(VD); 14345 14346 if (!EvaluateInPlace(Value, Info, LVal, this, 14347 /*AllowNonLiteralTypes=*/true) || 14348 EStatus.HasSideEffects) 14349 return false; 14350 14351 // At this point, any lifetime-extended temporaries are completely 14352 // initialized. 14353 Info.performLifetimeExtension(); 14354 14355 if (!Info.discardCleanups()) 14356 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14357 } 14358 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) && 14359 CheckMemoryLeaks(Info); 14360 } 14361 14362 bool VarDecl::evaluateDestruction( 14363 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14364 Expr::EvalStatus EStatus; 14365 EStatus.Diag = &Notes; 14366 14367 // Make a copy of the value for the destructor to mutate, if we know it. 14368 // Otherwise, treat the value as default-initialized; if the destructor works 14369 // anyway, then the destruction is constant (and must be essentially empty). 14370 APValue DestroyedValue; 14371 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14372 DestroyedValue = *getEvaluatedValue(); 14373 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14374 return false; 14375 14376 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression); 14377 Info.setEvaluatingDecl(this, DestroyedValue, 14378 EvalInfo::EvaluatingDeclKind::Dtor); 14379 Info.InConstantContext = true; 14380 14381 SourceLocation DeclLoc = getLocation(); 14382 QualType DeclTy = getType(); 14383 14384 LValue LVal; 14385 LVal.set(this); 14386 14387 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) || 14388 EStatus.HasSideEffects) 14389 return false; 14390 14391 if (!Info.discardCleanups()) 14392 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14393 14394 ensureEvaluatedStmt()->HasConstantDestruction = true; 14395 return true; 14396 } 14397 14398 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14399 /// constant folded, but discard the result. 14400 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14401 assert(!isValueDependent() && 14402 "Expression evaluator can't be called on a dependent expression."); 14403 14404 EvalResult Result; 14405 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14406 !hasUnacceptableSideEffect(Result, SEK); 14407 } 14408 14409 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14410 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14411 assert(!isValueDependent() && 14412 "Expression evaluator can't be called on a dependent expression."); 14413 14414 EvalResult EVResult; 14415 EVResult.Diag = Diag; 14416 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14417 Info.InConstantContext = true; 14418 14419 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14420 (void)Result; 14421 assert(Result && "Could not evaluate expression"); 14422 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14423 14424 return EVResult.Val.getInt(); 14425 } 14426 14427 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14428 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14429 assert(!isValueDependent() && 14430 "Expression evaluator can't be called on a dependent expression."); 14431 14432 EvalResult EVResult; 14433 EVResult.Diag = Diag; 14434 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14435 Info.InConstantContext = true; 14436 Info.CheckingForUndefinedBehavior = true; 14437 14438 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 14439 (void)Result; 14440 assert(Result && "Could not evaluate expression"); 14441 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14442 14443 return EVResult.Val.getInt(); 14444 } 14445 14446 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 14447 assert(!isValueDependent() && 14448 "Expression evaluator can't be called on a dependent expression."); 14449 14450 bool IsConst; 14451 EvalResult EVResult; 14452 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 14453 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14454 Info.CheckingForUndefinedBehavior = true; 14455 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 14456 } 14457 } 14458 14459 bool Expr::EvalResult::isGlobalLValue() const { 14460 assert(Val.isLValue()); 14461 return IsGlobalLValue(Val.getLValueBase()); 14462 } 14463 14464 14465 /// isIntegerConstantExpr - this recursive routine will test if an expression is 14466 /// an integer constant expression. 14467 14468 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 14469 /// comma, etc 14470 14471 // CheckICE - This function does the fundamental ICE checking: the returned 14472 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 14473 // and a (possibly null) SourceLocation indicating the location of the problem. 14474 // 14475 // Note that to reduce code duplication, this helper does no evaluation 14476 // itself; the caller checks whether the expression is evaluatable, and 14477 // in the rare cases where CheckICE actually cares about the evaluated 14478 // value, it calls into Evaluate. 14479 14480 namespace { 14481 14482 enum ICEKind { 14483 /// This expression is an ICE. 14484 IK_ICE, 14485 /// This expression is not an ICE, but if it isn't evaluated, it's 14486 /// a legal subexpression for an ICE. This return value is used to handle 14487 /// the comma operator in C99 mode, and non-constant subexpressions. 14488 IK_ICEIfUnevaluated, 14489 /// This expression is not an ICE, and is not a legal subexpression for one. 14490 IK_NotICE 14491 }; 14492 14493 struct ICEDiag { 14494 ICEKind Kind; 14495 SourceLocation Loc; 14496 14497 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 14498 }; 14499 14500 } 14501 14502 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 14503 14504 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 14505 14506 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 14507 Expr::EvalResult EVResult; 14508 Expr::EvalStatus Status; 14509 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 14510 14511 Info.InConstantContext = true; 14512 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 14513 !EVResult.Val.isInt()) 14514 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14515 14516 return NoDiag(); 14517 } 14518 14519 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 14520 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 14521 if (!E->getType()->isIntegralOrEnumerationType()) 14522 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14523 14524 switch (E->getStmtClass()) { 14525 #define ABSTRACT_STMT(Node) 14526 #define STMT(Node, Base) case Expr::Node##Class: 14527 #define EXPR(Node, Base) 14528 #include "clang/AST/StmtNodes.inc" 14529 case Expr::PredefinedExprClass: 14530 case Expr::FloatingLiteralClass: 14531 case Expr::ImaginaryLiteralClass: 14532 case Expr::StringLiteralClass: 14533 case Expr::ArraySubscriptExprClass: 14534 case Expr::MatrixSubscriptExprClass: 14535 case Expr::OMPArraySectionExprClass: 14536 case Expr::OMPArrayShapingExprClass: 14537 case Expr::OMPIteratorExprClass: 14538 case Expr::MemberExprClass: 14539 case Expr::CompoundAssignOperatorClass: 14540 case Expr::CompoundLiteralExprClass: 14541 case Expr::ExtVectorElementExprClass: 14542 case Expr::DesignatedInitExprClass: 14543 case Expr::ArrayInitLoopExprClass: 14544 case Expr::ArrayInitIndexExprClass: 14545 case Expr::NoInitExprClass: 14546 case Expr::DesignatedInitUpdateExprClass: 14547 case Expr::ImplicitValueInitExprClass: 14548 case Expr::ParenListExprClass: 14549 case Expr::VAArgExprClass: 14550 case Expr::AddrLabelExprClass: 14551 case Expr::StmtExprClass: 14552 case Expr::CXXMemberCallExprClass: 14553 case Expr::CUDAKernelCallExprClass: 14554 case Expr::CXXAddrspaceCastExprClass: 14555 case Expr::CXXDynamicCastExprClass: 14556 case Expr::CXXTypeidExprClass: 14557 case Expr::CXXUuidofExprClass: 14558 case Expr::MSPropertyRefExprClass: 14559 case Expr::MSPropertySubscriptExprClass: 14560 case Expr::CXXNullPtrLiteralExprClass: 14561 case Expr::UserDefinedLiteralClass: 14562 case Expr::CXXThisExprClass: 14563 case Expr::CXXThrowExprClass: 14564 case Expr::CXXNewExprClass: 14565 case Expr::CXXDeleteExprClass: 14566 case Expr::CXXPseudoDestructorExprClass: 14567 case Expr::UnresolvedLookupExprClass: 14568 case Expr::TypoExprClass: 14569 case Expr::RecoveryExprClass: 14570 case Expr::DependentScopeDeclRefExprClass: 14571 case Expr::CXXConstructExprClass: 14572 case Expr::CXXInheritedCtorInitExprClass: 14573 case Expr::CXXStdInitializerListExprClass: 14574 case Expr::CXXBindTemporaryExprClass: 14575 case Expr::ExprWithCleanupsClass: 14576 case Expr::CXXTemporaryObjectExprClass: 14577 case Expr::CXXUnresolvedConstructExprClass: 14578 case Expr::CXXDependentScopeMemberExprClass: 14579 case Expr::UnresolvedMemberExprClass: 14580 case Expr::ObjCStringLiteralClass: 14581 case Expr::ObjCBoxedExprClass: 14582 case Expr::ObjCArrayLiteralClass: 14583 case Expr::ObjCDictionaryLiteralClass: 14584 case Expr::ObjCEncodeExprClass: 14585 case Expr::ObjCMessageExprClass: 14586 case Expr::ObjCSelectorExprClass: 14587 case Expr::ObjCProtocolExprClass: 14588 case Expr::ObjCIvarRefExprClass: 14589 case Expr::ObjCPropertyRefExprClass: 14590 case Expr::ObjCSubscriptRefExprClass: 14591 case Expr::ObjCIsaExprClass: 14592 case Expr::ObjCAvailabilityCheckExprClass: 14593 case Expr::ShuffleVectorExprClass: 14594 case Expr::ConvertVectorExprClass: 14595 case Expr::BlockExprClass: 14596 case Expr::NoStmtClass: 14597 case Expr::OpaqueValueExprClass: 14598 case Expr::PackExpansionExprClass: 14599 case Expr::SubstNonTypeTemplateParmPackExprClass: 14600 case Expr::FunctionParmPackExprClass: 14601 case Expr::AsTypeExprClass: 14602 case Expr::ObjCIndirectCopyRestoreExprClass: 14603 case Expr::MaterializeTemporaryExprClass: 14604 case Expr::PseudoObjectExprClass: 14605 case Expr::AtomicExprClass: 14606 case Expr::LambdaExprClass: 14607 case Expr::CXXFoldExprClass: 14608 case Expr::CoawaitExprClass: 14609 case Expr::DependentCoawaitExprClass: 14610 case Expr::CoyieldExprClass: 14611 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14612 14613 case Expr::InitListExprClass: { 14614 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 14615 // form "T x = { a };" is equivalent to "T x = a;". 14616 // Unless we're initializing a reference, T is a scalar as it is known to be 14617 // of integral or enumeration type. 14618 if (E->isRValue()) 14619 if (cast<InitListExpr>(E)->getNumInits() == 1) 14620 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 14621 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14622 } 14623 14624 case Expr::SizeOfPackExprClass: 14625 case Expr::GNUNullExprClass: 14626 case Expr::SourceLocExprClass: 14627 return NoDiag(); 14628 14629 case Expr::SubstNonTypeTemplateParmExprClass: 14630 return 14631 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 14632 14633 case Expr::ConstantExprClass: 14634 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 14635 14636 case Expr::ParenExprClass: 14637 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 14638 case Expr::GenericSelectionExprClass: 14639 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 14640 case Expr::IntegerLiteralClass: 14641 case Expr::FixedPointLiteralClass: 14642 case Expr::CharacterLiteralClass: 14643 case Expr::ObjCBoolLiteralExprClass: 14644 case Expr::CXXBoolLiteralExprClass: 14645 case Expr::CXXScalarValueInitExprClass: 14646 case Expr::TypeTraitExprClass: 14647 case Expr::ConceptSpecializationExprClass: 14648 case Expr::RequiresExprClass: 14649 case Expr::ArrayTypeTraitExprClass: 14650 case Expr::ExpressionTraitExprClass: 14651 case Expr::CXXNoexceptExprClass: 14652 return NoDiag(); 14653 case Expr::CallExprClass: 14654 case Expr::CXXOperatorCallExprClass: { 14655 // C99 6.6/3 allows function calls within unevaluated subexpressions of 14656 // constant expressions, but they can never be ICEs because an ICE cannot 14657 // contain an operand of (pointer to) function type. 14658 const CallExpr *CE = cast<CallExpr>(E); 14659 if (CE->getBuiltinCallee()) 14660 return CheckEvalInICE(E, Ctx); 14661 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14662 } 14663 case Expr::CXXRewrittenBinaryOperatorClass: 14664 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 14665 Ctx); 14666 case Expr::DeclRefExprClass: { 14667 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 14668 return NoDiag(); 14669 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 14670 if (Ctx.getLangOpts().CPlusPlus && 14671 D && IsConstNonVolatile(D->getType())) { 14672 // Parameter variables are never constants. Without this check, 14673 // getAnyInitializer() can find a default argument, which leads 14674 // to chaos. 14675 if (isa<ParmVarDecl>(D)) 14676 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14677 14678 // C++ 7.1.5.1p2 14679 // A variable of non-volatile const-qualified integral or enumeration 14680 // type initialized by an ICE can be used in ICEs. 14681 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 14682 if (!Dcl->getType()->isIntegralOrEnumerationType()) 14683 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14684 14685 const VarDecl *VD; 14686 // Look for a declaration of this variable that has an initializer, and 14687 // check whether it is an ICE. 14688 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 14689 return NoDiag(); 14690 else 14691 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14692 } 14693 } 14694 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14695 } 14696 case Expr::UnaryOperatorClass: { 14697 const UnaryOperator *Exp = cast<UnaryOperator>(E); 14698 switch (Exp->getOpcode()) { 14699 case UO_PostInc: 14700 case UO_PostDec: 14701 case UO_PreInc: 14702 case UO_PreDec: 14703 case UO_AddrOf: 14704 case UO_Deref: 14705 case UO_Coawait: 14706 // C99 6.6/3 allows increment and decrement within unevaluated 14707 // subexpressions of constant expressions, but they can never be ICEs 14708 // because an ICE cannot contain an lvalue operand. 14709 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14710 case UO_Extension: 14711 case UO_LNot: 14712 case UO_Plus: 14713 case UO_Minus: 14714 case UO_Not: 14715 case UO_Real: 14716 case UO_Imag: 14717 return CheckICE(Exp->getSubExpr(), Ctx); 14718 } 14719 llvm_unreachable("invalid unary operator class"); 14720 } 14721 case Expr::OffsetOfExprClass: { 14722 // Note that per C99, offsetof must be an ICE. And AFAIK, using 14723 // EvaluateAsRValue matches the proposed gcc behavior for cases like 14724 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 14725 // compliance: we should warn earlier for offsetof expressions with 14726 // array subscripts that aren't ICEs, and if the array subscripts 14727 // are ICEs, the value of the offsetof must be an integer constant. 14728 return CheckEvalInICE(E, Ctx); 14729 } 14730 case Expr::UnaryExprOrTypeTraitExprClass: { 14731 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 14732 if ((Exp->getKind() == UETT_SizeOf) && 14733 Exp->getTypeOfArgument()->isVariableArrayType()) 14734 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14735 return NoDiag(); 14736 } 14737 case Expr::BinaryOperatorClass: { 14738 const BinaryOperator *Exp = cast<BinaryOperator>(E); 14739 switch (Exp->getOpcode()) { 14740 case BO_PtrMemD: 14741 case BO_PtrMemI: 14742 case BO_Assign: 14743 case BO_MulAssign: 14744 case BO_DivAssign: 14745 case BO_RemAssign: 14746 case BO_AddAssign: 14747 case BO_SubAssign: 14748 case BO_ShlAssign: 14749 case BO_ShrAssign: 14750 case BO_AndAssign: 14751 case BO_XorAssign: 14752 case BO_OrAssign: 14753 // C99 6.6/3 allows assignments within unevaluated subexpressions of 14754 // constant expressions, but they can never be ICEs because an ICE cannot 14755 // contain an lvalue operand. 14756 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14757 14758 case BO_Mul: 14759 case BO_Div: 14760 case BO_Rem: 14761 case BO_Add: 14762 case BO_Sub: 14763 case BO_Shl: 14764 case BO_Shr: 14765 case BO_LT: 14766 case BO_GT: 14767 case BO_LE: 14768 case BO_GE: 14769 case BO_EQ: 14770 case BO_NE: 14771 case BO_And: 14772 case BO_Xor: 14773 case BO_Or: 14774 case BO_Comma: 14775 case BO_Cmp: { 14776 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14777 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14778 if (Exp->getOpcode() == BO_Div || 14779 Exp->getOpcode() == BO_Rem) { 14780 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 14781 // we don't evaluate one. 14782 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 14783 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 14784 if (REval == 0) 14785 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14786 if (REval.isSigned() && REval.isAllOnesValue()) { 14787 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 14788 if (LEval.isMinSignedValue()) 14789 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14790 } 14791 } 14792 } 14793 if (Exp->getOpcode() == BO_Comma) { 14794 if (Ctx.getLangOpts().C99) { 14795 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 14796 // if it isn't evaluated. 14797 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 14798 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14799 } else { 14800 // In both C89 and C++, commas in ICEs are illegal. 14801 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14802 } 14803 } 14804 return Worst(LHSResult, RHSResult); 14805 } 14806 case BO_LAnd: 14807 case BO_LOr: { 14808 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14809 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14810 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 14811 // Rare case where the RHS has a comma "side-effect"; we need 14812 // to actually check the condition to see whether the side 14813 // with the comma is evaluated. 14814 if ((Exp->getOpcode() == BO_LAnd) != 14815 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 14816 return RHSResult; 14817 return NoDiag(); 14818 } 14819 14820 return Worst(LHSResult, RHSResult); 14821 } 14822 } 14823 llvm_unreachable("invalid binary operator kind"); 14824 } 14825 case Expr::ImplicitCastExprClass: 14826 case Expr::CStyleCastExprClass: 14827 case Expr::CXXFunctionalCastExprClass: 14828 case Expr::CXXStaticCastExprClass: 14829 case Expr::CXXReinterpretCastExprClass: 14830 case Expr::CXXConstCastExprClass: 14831 case Expr::ObjCBridgedCastExprClass: { 14832 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 14833 if (isa<ExplicitCastExpr>(E)) { 14834 if (const FloatingLiteral *FL 14835 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 14836 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 14837 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 14838 APSInt IgnoredVal(DestWidth, !DestSigned); 14839 bool Ignored; 14840 // If the value does not fit in the destination type, the behavior is 14841 // undefined, so we are not required to treat it as a constant 14842 // expression. 14843 if (FL->getValue().convertToInteger(IgnoredVal, 14844 llvm::APFloat::rmTowardZero, 14845 &Ignored) & APFloat::opInvalidOp) 14846 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14847 return NoDiag(); 14848 } 14849 } 14850 switch (cast<CastExpr>(E)->getCastKind()) { 14851 case CK_LValueToRValue: 14852 case CK_AtomicToNonAtomic: 14853 case CK_NonAtomicToAtomic: 14854 case CK_NoOp: 14855 case CK_IntegralToBoolean: 14856 case CK_IntegralCast: 14857 return CheckICE(SubExpr, Ctx); 14858 default: 14859 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14860 } 14861 } 14862 case Expr::BinaryConditionalOperatorClass: { 14863 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 14864 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 14865 if (CommonResult.Kind == IK_NotICE) return CommonResult; 14866 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 14867 if (FalseResult.Kind == IK_NotICE) return FalseResult; 14868 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 14869 if (FalseResult.Kind == IK_ICEIfUnevaluated && 14870 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 14871 return FalseResult; 14872 } 14873 case Expr::ConditionalOperatorClass: { 14874 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 14875 // If the condition (ignoring parens) is a __builtin_constant_p call, 14876 // then only the true side is actually considered in an integer constant 14877 // expression, and it is fully evaluated. This is an important GNU 14878 // extension. See GCC PR38377 for discussion. 14879 if (const CallExpr *CallCE 14880 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 14881 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 14882 return CheckEvalInICE(E, Ctx); 14883 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 14884 if (CondResult.Kind == IK_NotICE) 14885 return CondResult; 14886 14887 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 14888 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 14889 14890 if (TrueResult.Kind == IK_NotICE) 14891 return TrueResult; 14892 if (FalseResult.Kind == IK_NotICE) 14893 return FalseResult; 14894 if (CondResult.Kind == IK_ICEIfUnevaluated) 14895 return CondResult; 14896 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 14897 return NoDiag(); 14898 // Rare case where the diagnostics depend on which side is evaluated 14899 // Note that if we get here, CondResult is 0, and at least one of 14900 // TrueResult and FalseResult is non-zero. 14901 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 14902 return FalseResult; 14903 return TrueResult; 14904 } 14905 case Expr::CXXDefaultArgExprClass: 14906 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 14907 case Expr::CXXDefaultInitExprClass: 14908 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 14909 case Expr::ChooseExprClass: { 14910 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 14911 } 14912 case Expr::BuiltinBitCastExprClass: { 14913 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 14914 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14915 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 14916 } 14917 } 14918 14919 llvm_unreachable("Invalid StmtClass!"); 14920 } 14921 14922 /// Evaluate an expression as a C++11 integral constant expression. 14923 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 14924 const Expr *E, 14925 llvm::APSInt *Value, 14926 SourceLocation *Loc) { 14927 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14928 if (Loc) *Loc = E->getExprLoc(); 14929 return false; 14930 } 14931 14932 APValue Result; 14933 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 14934 return false; 14935 14936 if (!Result.isInt()) { 14937 if (Loc) *Loc = E->getExprLoc(); 14938 return false; 14939 } 14940 14941 if (Value) *Value = Result.getInt(); 14942 return true; 14943 } 14944 14945 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 14946 SourceLocation *Loc) const { 14947 assert(!isValueDependent() && 14948 "Expression evaluator can't be called on a dependent expression."); 14949 14950 if (Ctx.getLangOpts().CPlusPlus11) 14951 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 14952 14953 ICEDiag D = CheckICE(this, Ctx); 14954 if (D.Kind != IK_ICE) { 14955 if (Loc) *Loc = D.Loc; 14956 return false; 14957 } 14958 return true; 14959 } 14960 14961 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 14962 SourceLocation *Loc, 14963 bool isEvaluated) const { 14964 assert(!isValueDependent() && 14965 "Expression evaluator can't be called on a dependent expression."); 14966 14967 APSInt Value; 14968 14969 if (Ctx.getLangOpts().CPlusPlus11) { 14970 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 14971 return Value; 14972 return None; 14973 } 14974 14975 if (!isIntegerConstantExpr(Ctx, Loc)) 14976 return None; 14977 14978 // The only possible side-effects here are due to UB discovered in the 14979 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 14980 // required to treat the expression as an ICE, so we produce the folded 14981 // value. 14982 EvalResult ExprResult; 14983 Expr::EvalStatus Status; 14984 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 14985 Info.InConstantContext = true; 14986 14987 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 14988 llvm_unreachable("ICE cannot be evaluated!"); 14989 14990 return ExprResult.Val.getInt(); 14991 } 14992 14993 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 14994 assert(!isValueDependent() && 14995 "Expression evaluator can't be called on a dependent expression."); 14996 14997 return CheckICE(this, Ctx).Kind == IK_ICE; 14998 } 14999 15000 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15001 SourceLocation *Loc) const { 15002 assert(!isValueDependent() && 15003 "Expression evaluator can't be called on a dependent expression."); 15004 15005 // We support this checking in C++98 mode in order to diagnose compatibility 15006 // issues. 15007 assert(Ctx.getLangOpts().CPlusPlus); 15008 15009 // Build evaluation settings. 15010 Expr::EvalStatus Status; 15011 SmallVector<PartialDiagnosticAt, 8> Diags; 15012 Status.Diag = &Diags; 15013 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15014 15015 APValue Scratch; 15016 bool IsConstExpr = 15017 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15018 // FIXME: We don't produce a diagnostic for this, but the callers that 15019 // call us on arbitrary full-expressions should generally not care. 15020 Info.discardCleanups() && !Status.HasSideEffects; 15021 15022 if (!Diags.empty()) { 15023 IsConstExpr = false; 15024 if (Loc) *Loc = Diags[0].first; 15025 } else if (!IsConstExpr) { 15026 // FIXME: This shouldn't happen. 15027 if (Loc) *Loc = getExprLoc(); 15028 } 15029 15030 return IsConstExpr; 15031 } 15032 15033 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15034 const FunctionDecl *Callee, 15035 ArrayRef<const Expr*> Args, 15036 const Expr *This) const { 15037 assert(!isValueDependent() && 15038 "Expression evaluator can't be called on a dependent expression."); 15039 15040 Expr::EvalStatus Status; 15041 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15042 Info.InConstantContext = true; 15043 15044 LValue ThisVal; 15045 const LValue *ThisPtr = nullptr; 15046 if (This) { 15047 #ifndef NDEBUG 15048 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15049 assert(MD && "Don't provide `this` for non-methods."); 15050 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15051 #endif 15052 if (!This->isValueDependent() && 15053 EvaluateObjectArgument(Info, This, ThisVal) && 15054 !Info.EvalStatus.HasSideEffects) 15055 ThisPtr = &ThisVal; 15056 15057 // Ignore any side-effects from a failed evaluation. This is safe because 15058 // they can't interfere with any other argument evaluation. 15059 Info.EvalStatus.HasSideEffects = false; 15060 } 15061 15062 ArgVector ArgValues(Args.size()); 15063 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15064 I != E; ++I) { 15065 if ((*I)->isValueDependent() || 15066 !Evaluate(ArgValues[I - Args.begin()], Info, *I) || 15067 Info.EvalStatus.HasSideEffects) 15068 // If evaluation fails, throw away the argument entirely. 15069 ArgValues[I - Args.begin()] = APValue(); 15070 15071 // Ignore any side-effects from a failed evaluation. This is safe because 15072 // they can't interfere with any other argument evaluation. 15073 Info.EvalStatus.HasSideEffects = false; 15074 } 15075 15076 // Parameter cleanups happen in the caller and are not part of this 15077 // evaluation. 15078 Info.discardCleanups(); 15079 Info.EvalStatus.HasSideEffects = false; 15080 15081 // Build fake call to Callee. 15082 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 15083 ArgValues.data()); 15084 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15085 FullExpressionRAII Scope(Info); 15086 return Evaluate(Value, Info, this) && Scope.destroy() && 15087 !Info.EvalStatus.HasSideEffects; 15088 } 15089 15090 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15091 SmallVectorImpl< 15092 PartialDiagnosticAt> &Diags) { 15093 // FIXME: It would be useful to check constexpr function templates, but at the 15094 // moment the constant expression evaluator cannot cope with the non-rigorous 15095 // ASTs which we build for dependent expressions. 15096 if (FD->isDependentContext()) 15097 return true; 15098 15099 // Bail out if a constexpr constructor has an initializer that contains an 15100 // error. We deliberately don't produce a diagnostic, as we have produced a 15101 // relevant diagnostic when parsing the error initializer. 15102 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 15103 for (const auto *InitExpr : Ctor->inits()) { 15104 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 15105 return false; 15106 } 15107 } 15108 Expr::EvalStatus Status; 15109 Status.Diag = &Diags; 15110 15111 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15112 Info.InConstantContext = true; 15113 Info.CheckingPotentialConstantExpression = true; 15114 15115 // The constexpr VM attempts to compile all methods to bytecode here. 15116 if (Info.EnableNewConstInterp) { 15117 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15118 return Diags.empty(); 15119 } 15120 15121 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15122 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15123 15124 // Fabricate an arbitrary expression on the stack and pretend that it 15125 // is a temporary being used as the 'this' pointer. 15126 LValue This; 15127 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15128 This.set({&VIE, Info.CurrentCall->Index}); 15129 15130 ArrayRef<const Expr*> Args; 15131 15132 APValue Scratch; 15133 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15134 // Evaluate the call as a constant initializer, to allow the construction 15135 // of objects of non-literal types. 15136 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15137 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15138 } else { 15139 SourceLocation Loc = FD->getLocation(); 15140 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15141 Args, FD->getBody(), Info, Scratch, nullptr); 15142 } 15143 15144 return Diags.empty(); 15145 } 15146 15147 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15148 const FunctionDecl *FD, 15149 SmallVectorImpl< 15150 PartialDiagnosticAt> &Diags) { 15151 assert(!E->isValueDependent() && 15152 "Expression evaluator can't be called on a dependent expression."); 15153 15154 Expr::EvalStatus Status; 15155 Status.Diag = &Diags; 15156 15157 EvalInfo Info(FD->getASTContext(), Status, 15158 EvalInfo::EM_ConstantExpressionUnevaluated); 15159 Info.InConstantContext = true; 15160 Info.CheckingPotentialConstantExpression = true; 15161 15162 // Fabricate a call stack frame to give the arguments a plausible cover story. 15163 ArrayRef<const Expr*> Args; 15164 ArgVector ArgValues(0); 15165 bool Success = EvaluateArgs(Args, ArgValues, Info, FD); 15166 (void)Success; 15167 assert(Success && 15168 "Failed to set up arguments for potential constant evaluation"); 15169 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 15170 15171 APValue ResultScratch; 15172 Evaluate(ResultScratch, Info, E); 15173 return Diags.empty(); 15174 } 15175 15176 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15177 unsigned Type) const { 15178 if (!getType()->isPointerType()) 15179 return false; 15180 15181 Expr::EvalStatus Status; 15182 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15183 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15184 } 15185