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 if (Arguments) { 1860 const APValue &Arg = Arguments[ArgIndex]; 1861 Arg.printPretty(Out, Info.Ctx, Param->getType()); 1862 } else { 1863 Out << "<...>"; 1864 } 1865 1866 if (ArgIndex == 0 && IsMemberCall) 1867 Out << "->" << *Callee << '('; 1868 } 1869 1870 Out << ')'; 1871 } 1872 1873 /// Evaluate an expression to see if it had side-effects, and discard its 1874 /// result. 1875 /// \return \c true if the caller should keep evaluating. 1876 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1877 APValue Scratch; 1878 if (!Evaluate(Scratch, Info, E)) 1879 // We don't need the value, but we might have skipped a side effect here. 1880 return Info.noteSideEffect(); 1881 return true; 1882 } 1883 1884 /// Should this call expression be treated as a string literal? 1885 static bool IsStringLiteralCall(const CallExpr *E) { 1886 unsigned Builtin = E->getBuiltinCallee(); 1887 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1888 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1889 } 1890 1891 static bool IsGlobalLValue(APValue::LValueBase B) { 1892 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1893 // constant expression of pointer type that evaluates to... 1894 1895 // ... a null pointer value, or a prvalue core constant expression of type 1896 // std::nullptr_t. 1897 if (!B) return true; 1898 1899 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1900 // ... the address of an object with static storage duration, 1901 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1902 return VD->hasGlobalStorage(); 1903 // ... the address of a function, 1904 // ... the address of a GUID [MS extension], 1905 return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1906 } 1907 1908 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1909 return true; 1910 1911 const Expr *E = B.get<const Expr*>(); 1912 switch (E->getStmtClass()) { 1913 default: 1914 return false; 1915 case Expr::CompoundLiteralExprClass: { 1916 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1917 return CLE->isFileScope() && CLE->isLValue(); 1918 } 1919 case Expr::MaterializeTemporaryExprClass: 1920 // A materialized temporary might have been lifetime-extended to static 1921 // storage duration. 1922 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1923 // A string literal has static storage duration. 1924 case Expr::StringLiteralClass: 1925 case Expr::PredefinedExprClass: 1926 case Expr::ObjCStringLiteralClass: 1927 case Expr::ObjCEncodeExprClass: 1928 return true; 1929 case Expr::ObjCBoxedExprClass: 1930 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 1931 case Expr::CallExprClass: 1932 return IsStringLiteralCall(cast<CallExpr>(E)); 1933 // For GCC compatibility, &&label has static storage duration. 1934 case Expr::AddrLabelExprClass: 1935 return true; 1936 // A Block literal expression may be used as the initialization value for 1937 // Block variables at global or local static scope. 1938 case Expr::BlockExprClass: 1939 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1940 case Expr::ImplicitValueInitExprClass: 1941 // FIXME: 1942 // We can never form an lvalue with an implicit value initialization as its 1943 // base through expression evaluation, so these only appear in one case: the 1944 // implicit variable declaration we invent when checking whether a constexpr 1945 // constructor can produce a constant expression. We must assume that such 1946 // an expression might be a global lvalue. 1947 return true; 1948 } 1949 } 1950 1951 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1952 return LVal.Base.dyn_cast<const ValueDecl*>(); 1953 } 1954 1955 static bool IsLiteralLValue(const LValue &Value) { 1956 if (Value.getLValueCallIndex()) 1957 return false; 1958 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1959 return E && !isa<MaterializeTemporaryExpr>(E); 1960 } 1961 1962 static bool IsWeakLValue(const LValue &Value) { 1963 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1964 return Decl && Decl->isWeak(); 1965 } 1966 1967 static bool isZeroSized(const LValue &Value) { 1968 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1969 if (Decl && isa<VarDecl>(Decl)) { 1970 QualType Ty = Decl->getType(); 1971 if (Ty->isArrayType()) 1972 return Ty->isIncompleteType() || 1973 Decl->getASTContext().getTypeSize(Ty) == 0; 1974 } 1975 return false; 1976 } 1977 1978 static bool HasSameBase(const LValue &A, const LValue &B) { 1979 if (!A.getLValueBase()) 1980 return !B.getLValueBase(); 1981 if (!B.getLValueBase()) 1982 return false; 1983 1984 if (A.getLValueBase().getOpaqueValue() != 1985 B.getLValueBase().getOpaqueValue()) 1986 return false; 1987 1988 return A.getLValueCallIndex() == B.getLValueCallIndex() && 1989 A.getLValueVersion() == B.getLValueVersion(); 1990 } 1991 1992 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1993 assert(Base && "no location for a null lvalue"); 1994 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1995 if (VD) 1996 Info.Note(VD->getLocation(), diag::note_declared_at); 1997 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 1998 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 1999 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2000 // FIXME: Produce a note for dangling pointers too. 2001 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2002 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2003 diag::note_constexpr_dynamic_alloc_here); 2004 } 2005 // We have no information to show for a typeid(T) object. 2006 } 2007 2008 enum class CheckEvaluationResultKind { 2009 ConstantExpression, 2010 FullyInitialized, 2011 }; 2012 2013 /// Materialized temporaries that we've already checked to determine if they're 2014 /// initializsed by a constant expression. 2015 using CheckedTemporaries = 2016 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2017 2018 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2019 EvalInfo &Info, SourceLocation DiagLoc, 2020 QualType Type, const APValue &Value, 2021 Expr::ConstExprUsage Usage, 2022 SourceLocation SubobjectLoc, 2023 CheckedTemporaries &CheckedTemps); 2024 2025 /// Check that this reference or pointer core constant expression is a valid 2026 /// value for an address or reference constant expression. Return true if we 2027 /// can fold this expression, whether or not it's a constant expression. 2028 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2029 QualType Type, const LValue &LVal, 2030 Expr::ConstExprUsage Usage, 2031 CheckedTemporaries &CheckedTemps) { 2032 bool IsReferenceType = Type->isReferenceType(); 2033 2034 APValue::LValueBase Base = LVal.getLValueBase(); 2035 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2036 2037 if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) { 2038 if (auto *FD = dyn_cast<FunctionDecl>(VD)) { 2039 if (FD->isConsteval()) { 2040 Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2041 << !Type->isAnyPointerType(); 2042 Info.Note(FD->getLocation(), diag::note_declared_at); 2043 return false; 2044 } 2045 } 2046 } 2047 2048 // Check that the object is a global. Note that the fake 'this' object we 2049 // manufacture when checking potential constant expressions is conservatively 2050 // assumed to be global here. 2051 if (!IsGlobalLValue(Base)) { 2052 if (Info.getLangOpts().CPlusPlus11) { 2053 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2054 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2055 << IsReferenceType << !Designator.Entries.empty() 2056 << !!VD << VD; 2057 2058 auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2059 if (VarD && VarD->isConstexpr()) { 2060 // Non-static local constexpr variables have unintuitive semantics: 2061 // constexpr int a = 1; 2062 // constexpr const int *p = &a; 2063 // ... is invalid because the address of 'a' is not constant. Suggest 2064 // adding a 'static' in this case. 2065 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2066 << VarD 2067 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2068 } else { 2069 NoteLValueLocation(Info, Base); 2070 } 2071 } else { 2072 Info.FFDiag(Loc); 2073 } 2074 // Don't allow references to temporaries to escape. 2075 return false; 2076 } 2077 assert((Info.checkingPotentialConstantExpression() || 2078 LVal.getLValueCallIndex() == 0) && 2079 "have call index for global lvalue"); 2080 2081 if (Base.is<DynamicAllocLValue>()) { 2082 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2083 << IsReferenceType << !Designator.Entries.empty(); 2084 NoteLValueLocation(Info, Base); 2085 return false; 2086 } 2087 2088 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 2089 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 2090 // Check if this is a thread-local variable. 2091 if (Var->getTLSKind()) 2092 // FIXME: Diagnostic! 2093 return false; 2094 2095 // A dllimport variable never acts like a constant. 2096 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 2097 // FIXME: Diagnostic! 2098 return false; 2099 } 2100 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 2101 // __declspec(dllimport) must be handled very carefully: 2102 // We must never initialize an expression with the thunk in C++. 2103 // Doing otherwise would allow the same id-expression to yield 2104 // different addresses for the same function in different translation 2105 // units. However, this means that we must dynamically initialize the 2106 // expression with the contents of the import address table at runtime. 2107 // 2108 // The C language has no notion of ODR; furthermore, it has no notion of 2109 // dynamic initialization. This means that we are permitted to 2110 // perform initialization with the address of the thunk. 2111 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 2112 FD->hasAttr<DLLImportAttr>()) 2113 // FIXME: Diagnostic! 2114 return false; 2115 } 2116 } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>( 2117 Base.dyn_cast<const Expr *>())) { 2118 if (CheckedTemps.insert(MTE).second) { 2119 QualType TempType = getType(Base); 2120 if (TempType.isDestructedType()) { 2121 Info.FFDiag(MTE->getExprLoc(), 2122 diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor) 2123 << TempType; 2124 return false; 2125 } 2126 2127 APValue *V = MTE->getOrCreateValue(false); 2128 assert(V && "evasluation result refers to uninitialised temporary"); 2129 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2130 Info, MTE->getExprLoc(), TempType, *V, 2131 Usage, SourceLocation(), CheckedTemps)) 2132 return false; 2133 } 2134 } 2135 2136 // Allow address constant expressions to be past-the-end pointers. This is 2137 // an extension: the standard requires them to point to an object. 2138 if (!IsReferenceType) 2139 return true; 2140 2141 // A reference constant expression must refer to an object. 2142 if (!Base) { 2143 // FIXME: diagnostic 2144 Info.CCEDiag(Loc); 2145 return true; 2146 } 2147 2148 // Does this refer one past the end of some object? 2149 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2150 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2151 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2152 << !Designator.Entries.empty() << !!VD << VD; 2153 NoteLValueLocation(Info, Base); 2154 } 2155 2156 return true; 2157 } 2158 2159 /// Member pointers are constant expressions unless they point to a 2160 /// non-virtual dllimport member function. 2161 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2162 SourceLocation Loc, 2163 QualType Type, 2164 const APValue &Value, 2165 Expr::ConstExprUsage Usage) { 2166 const ValueDecl *Member = Value.getMemberPointerDecl(); 2167 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2168 if (!FD) 2169 return true; 2170 if (FD->isConsteval()) { 2171 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2172 Info.Note(FD->getLocation(), diag::note_declared_at); 2173 return false; 2174 } 2175 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 2176 !FD->hasAttr<DLLImportAttr>(); 2177 } 2178 2179 /// Check that this core constant expression is of literal type, and if not, 2180 /// produce an appropriate diagnostic. 2181 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2182 const LValue *This = nullptr) { 2183 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2184 return true; 2185 2186 // C++1y: A constant initializer for an object o [...] may also invoke 2187 // constexpr constructors for o and its subobjects even if those objects 2188 // are of non-literal class types. 2189 // 2190 // C++11 missed this detail for aggregates, so classes like this: 2191 // struct foo_t { union { int i; volatile int j; } u; }; 2192 // are not (obviously) initializable like so: 2193 // __attribute__((__require_constant_initialization__)) 2194 // static const foo_t x = {{0}}; 2195 // because "i" is a subobject with non-literal initialization (due to the 2196 // volatile member of the union). See: 2197 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2198 // Therefore, we use the C++1y behavior. 2199 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2200 return true; 2201 2202 // Prvalue constant expressions must be of literal types. 2203 if (Info.getLangOpts().CPlusPlus11) 2204 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2205 << E->getType(); 2206 else 2207 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2208 return false; 2209 } 2210 2211 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2212 EvalInfo &Info, SourceLocation DiagLoc, 2213 QualType Type, const APValue &Value, 2214 Expr::ConstExprUsage Usage, 2215 SourceLocation SubobjectLoc, 2216 CheckedTemporaries &CheckedTemps) { 2217 if (!Value.hasValue()) { 2218 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2219 << true << Type; 2220 if (SubobjectLoc.isValid()) 2221 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2222 return false; 2223 } 2224 2225 // We allow _Atomic(T) to be initialized from anything that T can be 2226 // initialized from. 2227 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2228 Type = AT->getValueType(); 2229 2230 // Core issue 1454: For a literal constant expression of array or class type, 2231 // each subobject of its value shall have been initialized by a constant 2232 // expression. 2233 if (Value.isArray()) { 2234 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2235 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2236 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2237 Value.getArrayInitializedElt(I), Usage, 2238 SubobjectLoc, CheckedTemps)) 2239 return false; 2240 } 2241 if (!Value.hasArrayFiller()) 2242 return true; 2243 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2244 Value.getArrayFiller(), Usage, SubobjectLoc, 2245 CheckedTemps); 2246 } 2247 if (Value.isUnion() && Value.getUnionField()) { 2248 return CheckEvaluationResult( 2249 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2250 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(), 2251 CheckedTemps); 2252 } 2253 if (Value.isStruct()) { 2254 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2255 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2256 unsigned BaseIndex = 0; 2257 for (const CXXBaseSpecifier &BS : CD->bases()) { 2258 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2259 Value.getStructBase(BaseIndex), Usage, 2260 BS.getBeginLoc(), CheckedTemps)) 2261 return false; 2262 ++BaseIndex; 2263 } 2264 } 2265 for (const auto *I : RD->fields()) { 2266 if (I->isUnnamedBitfield()) 2267 continue; 2268 2269 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2270 Value.getStructField(I->getFieldIndex()), 2271 Usage, I->getLocation(), CheckedTemps)) 2272 return false; 2273 } 2274 } 2275 2276 if (Value.isLValue() && 2277 CERK == CheckEvaluationResultKind::ConstantExpression) { 2278 LValue LVal; 2279 LVal.setFrom(Info.Ctx, Value); 2280 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage, 2281 CheckedTemps); 2282 } 2283 2284 if (Value.isMemberPointer() && 2285 CERK == CheckEvaluationResultKind::ConstantExpression) 2286 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 2287 2288 // Everything else is fine. 2289 return true; 2290 } 2291 2292 /// Check that this core constant expression value is a valid value for a 2293 /// constant expression. If not, report an appropriate diagnostic. Does not 2294 /// check that the expression is of literal type. 2295 static bool 2296 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 2297 const APValue &Value, 2298 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) { 2299 // Nothing to check for a constant expression of type 'cv void'. 2300 if (Type->isVoidType()) 2301 return true; 2302 2303 CheckedTemporaries CheckedTemps; 2304 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2305 Info, DiagLoc, Type, Value, Usage, 2306 SourceLocation(), CheckedTemps); 2307 } 2308 2309 /// Check that this evaluated value is fully-initialized and can be loaded by 2310 /// an lvalue-to-rvalue conversion. 2311 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2312 QualType Type, const APValue &Value) { 2313 CheckedTemporaries CheckedTemps; 2314 return CheckEvaluationResult( 2315 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2316 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps); 2317 } 2318 2319 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2320 /// "the allocated storage is deallocated within the evaluation". 2321 static bool CheckMemoryLeaks(EvalInfo &Info) { 2322 if (!Info.HeapAllocs.empty()) { 2323 // We can still fold to a constant despite a compile-time memory leak, 2324 // so long as the heap allocation isn't referenced in the result (we check 2325 // that in CheckConstantExpression). 2326 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2327 diag::note_constexpr_memory_leak) 2328 << unsigned(Info.HeapAllocs.size() - 1); 2329 } 2330 return true; 2331 } 2332 2333 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2334 // A null base expression indicates a null pointer. These are always 2335 // evaluatable, and they are false unless the offset is zero. 2336 if (!Value.getLValueBase()) { 2337 Result = !Value.getLValueOffset().isZero(); 2338 return true; 2339 } 2340 2341 // We have a non-null base. These are generally known to be true, but if it's 2342 // a weak declaration it can be null at runtime. 2343 Result = true; 2344 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2345 return !Decl || !Decl->isWeak(); 2346 } 2347 2348 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2349 switch (Val.getKind()) { 2350 case APValue::None: 2351 case APValue::Indeterminate: 2352 return false; 2353 case APValue::Int: 2354 Result = Val.getInt().getBoolValue(); 2355 return true; 2356 case APValue::FixedPoint: 2357 Result = Val.getFixedPoint().getBoolValue(); 2358 return true; 2359 case APValue::Float: 2360 Result = !Val.getFloat().isZero(); 2361 return true; 2362 case APValue::ComplexInt: 2363 Result = Val.getComplexIntReal().getBoolValue() || 2364 Val.getComplexIntImag().getBoolValue(); 2365 return true; 2366 case APValue::ComplexFloat: 2367 Result = !Val.getComplexFloatReal().isZero() || 2368 !Val.getComplexFloatImag().isZero(); 2369 return true; 2370 case APValue::LValue: 2371 return EvalPointerValueAsBool(Val, Result); 2372 case APValue::MemberPointer: 2373 Result = Val.getMemberPointerDecl(); 2374 return true; 2375 case APValue::Vector: 2376 case APValue::Array: 2377 case APValue::Struct: 2378 case APValue::Union: 2379 case APValue::AddrLabelDiff: 2380 return false; 2381 } 2382 2383 llvm_unreachable("unknown APValue kind"); 2384 } 2385 2386 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2387 EvalInfo &Info) { 2388 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2389 APValue Val; 2390 if (!Evaluate(Val, Info, E)) 2391 return false; 2392 return HandleConversionToBool(Val, Result); 2393 } 2394 2395 template<typename T> 2396 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2397 const T &SrcValue, QualType DestType) { 2398 Info.CCEDiag(E, diag::note_constexpr_overflow) 2399 << SrcValue << DestType; 2400 return Info.noteUndefinedBehavior(); 2401 } 2402 2403 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2404 QualType SrcType, const APFloat &Value, 2405 QualType DestType, APSInt &Result) { 2406 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2407 // Determine whether we are converting to unsigned or signed. 2408 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2409 2410 Result = APSInt(DestWidth, !DestSigned); 2411 bool ignored; 2412 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2413 & APFloat::opInvalidOp) 2414 return HandleOverflow(Info, E, Value, DestType); 2415 return true; 2416 } 2417 2418 /// Get rounding mode used for evaluation of the specified expression. 2419 /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2420 /// dynamic. 2421 /// If rounding mode is unknown at compile time, still try to evaluate the 2422 /// expression. If the result is exact, it does not depend on rounding mode. 2423 /// So return "tonearest" mode instead of "dynamic". 2424 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2425 bool &DynamicRM) { 2426 llvm::RoundingMode RM = 2427 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2428 DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2429 if (DynamicRM) 2430 RM = llvm::RoundingMode::NearestTiesToEven; 2431 return RM; 2432 } 2433 2434 /// Check if the given evaluation result is allowed for constant evaluation. 2435 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2436 APFloat::opStatus St) { 2437 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2438 if ((St & APFloat::opInexact) && 2439 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2440 // Inexact result means that it depends on rounding mode. If the requested 2441 // mode is dynamic, the evaluation cannot be made in compile time. 2442 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2443 return false; 2444 } 2445 2446 if ((St & APFloat::opStatus::opInvalidOp) && 2447 FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2448 // There is no usefully definable result. 2449 Info.FFDiag(E); 2450 return false; 2451 } 2452 2453 // FIXME: if: 2454 // - evaluation triggered other FP exception, and 2455 // - exception mode is not "ignore", and 2456 // - the expression being evaluated is not a part of global variable 2457 // initializer, 2458 // the evaluation probably need to be rejected. 2459 return true; 2460 } 2461 2462 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2463 QualType SrcType, QualType DestType, 2464 APFloat &Result) { 2465 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2466 bool DynamicRM; 2467 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2468 APFloat::opStatus St; 2469 APFloat Value = Result; 2470 bool ignored; 2471 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2472 return checkFloatingPointResult(Info, E, St); 2473 } 2474 2475 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2476 QualType DestType, QualType SrcType, 2477 const APSInt &Value) { 2478 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2479 // Figure out if this is a truncate, extend or noop cast. 2480 // If the input is signed, do a sign extend, noop, or truncate. 2481 APSInt Result = Value.extOrTrunc(DestWidth); 2482 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2483 if (DestType->isBooleanType()) 2484 Result = Value.getBoolValue(); 2485 return Result; 2486 } 2487 2488 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2489 QualType SrcType, const APSInt &Value, 2490 QualType DestType, APFloat &Result) { 2491 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2492 Result.convertFromAPInt(Value, Value.isSigned(), 2493 APFloat::rmNearestTiesToEven); 2494 return true; 2495 } 2496 2497 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2498 APValue &Value, const FieldDecl *FD) { 2499 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2500 2501 if (!Value.isInt()) { 2502 // Trying to store a pointer-cast-to-integer into a bitfield. 2503 // FIXME: In this case, we should provide the diagnostic for casting 2504 // a pointer to an integer. 2505 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2506 Info.FFDiag(E); 2507 return false; 2508 } 2509 2510 APSInt &Int = Value.getInt(); 2511 unsigned OldBitWidth = Int.getBitWidth(); 2512 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2513 if (NewBitWidth < OldBitWidth) 2514 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2515 return true; 2516 } 2517 2518 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2519 llvm::APInt &Res) { 2520 APValue SVal; 2521 if (!Evaluate(SVal, Info, E)) 2522 return false; 2523 if (SVal.isInt()) { 2524 Res = SVal.getInt(); 2525 return true; 2526 } 2527 if (SVal.isFloat()) { 2528 Res = SVal.getFloat().bitcastToAPInt(); 2529 return true; 2530 } 2531 if (SVal.isVector()) { 2532 QualType VecTy = E->getType(); 2533 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2534 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2535 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2536 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2537 Res = llvm::APInt::getNullValue(VecSize); 2538 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2539 APValue &Elt = SVal.getVectorElt(i); 2540 llvm::APInt EltAsInt; 2541 if (Elt.isInt()) { 2542 EltAsInt = Elt.getInt(); 2543 } else if (Elt.isFloat()) { 2544 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2545 } else { 2546 // Don't try to handle vectors of anything other than int or float 2547 // (not sure if it's possible to hit this case). 2548 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2549 return false; 2550 } 2551 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2552 if (BigEndian) 2553 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2554 else 2555 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2556 } 2557 return true; 2558 } 2559 // Give up if the input isn't an int, float, or vector. For example, we 2560 // reject "(v4i16)(intptr_t)&a". 2561 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2562 return false; 2563 } 2564 2565 /// Perform the given integer operation, which is known to need at most BitWidth 2566 /// bits, and check for overflow in the original type (if that type was not an 2567 /// unsigned type). 2568 template<typename Operation> 2569 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2570 const APSInt &LHS, const APSInt &RHS, 2571 unsigned BitWidth, Operation Op, 2572 APSInt &Result) { 2573 if (LHS.isUnsigned()) { 2574 Result = Op(LHS, RHS); 2575 return true; 2576 } 2577 2578 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2579 Result = Value.trunc(LHS.getBitWidth()); 2580 if (Result.extend(BitWidth) != Value) { 2581 if (Info.checkingForUndefinedBehavior()) 2582 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2583 diag::warn_integer_constant_overflow) 2584 << Result.toString(10) << E->getType(); 2585 else 2586 return HandleOverflow(Info, E, Value, E->getType()); 2587 } 2588 return true; 2589 } 2590 2591 /// Perform the given binary integer operation. 2592 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2593 BinaryOperatorKind Opcode, APSInt RHS, 2594 APSInt &Result) { 2595 switch (Opcode) { 2596 default: 2597 Info.FFDiag(E); 2598 return false; 2599 case BO_Mul: 2600 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2601 std::multiplies<APSInt>(), Result); 2602 case BO_Add: 2603 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2604 std::plus<APSInt>(), Result); 2605 case BO_Sub: 2606 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2607 std::minus<APSInt>(), Result); 2608 case BO_And: Result = LHS & RHS; return true; 2609 case BO_Xor: Result = LHS ^ RHS; return true; 2610 case BO_Or: Result = LHS | RHS; return true; 2611 case BO_Div: 2612 case BO_Rem: 2613 if (RHS == 0) { 2614 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2615 return false; 2616 } 2617 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2618 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2619 // this operation and gives the two's complement result. 2620 if (RHS.isNegative() && RHS.isAllOnesValue() && 2621 LHS.isSigned() && LHS.isMinSignedValue()) 2622 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2623 E->getType()); 2624 return true; 2625 case BO_Shl: { 2626 if (Info.getLangOpts().OpenCL) 2627 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2628 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2629 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2630 RHS.isUnsigned()); 2631 else if (RHS.isSigned() && RHS.isNegative()) { 2632 // During constant-folding, a negative shift is an opposite shift. Such 2633 // a shift is not a constant expression. 2634 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2635 RHS = -RHS; 2636 goto shift_right; 2637 } 2638 shift_left: 2639 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2640 // the shifted type. 2641 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2642 if (SA != RHS) { 2643 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2644 << RHS << E->getType() << LHS.getBitWidth(); 2645 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2646 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2647 // operand, and must not overflow the corresponding unsigned type. 2648 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2649 // E1 x 2^E2 module 2^N. 2650 if (LHS.isNegative()) 2651 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2652 else if (LHS.countLeadingZeros() < SA) 2653 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2654 } 2655 Result = LHS << SA; 2656 return true; 2657 } 2658 case BO_Shr: { 2659 if (Info.getLangOpts().OpenCL) 2660 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2661 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2662 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2663 RHS.isUnsigned()); 2664 else if (RHS.isSigned() && RHS.isNegative()) { 2665 // During constant-folding, a negative shift is an opposite shift. Such a 2666 // shift is not a constant expression. 2667 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2668 RHS = -RHS; 2669 goto shift_left; 2670 } 2671 shift_right: 2672 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2673 // shifted type. 2674 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2675 if (SA != RHS) 2676 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2677 << RHS << E->getType() << LHS.getBitWidth(); 2678 Result = LHS >> SA; 2679 return true; 2680 } 2681 2682 case BO_LT: Result = LHS < RHS; return true; 2683 case BO_GT: Result = LHS > RHS; return true; 2684 case BO_LE: Result = LHS <= RHS; return true; 2685 case BO_GE: Result = LHS >= RHS; return true; 2686 case BO_EQ: Result = LHS == RHS; return true; 2687 case BO_NE: Result = LHS != RHS; return true; 2688 case BO_Cmp: 2689 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2690 } 2691 } 2692 2693 /// Perform the given binary floating-point operation, in-place, on LHS. 2694 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2695 APFloat &LHS, BinaryOperatorKind Opcode, 2696 const APFloat &RHS) { 2697 bool DynamicRM; 2698 llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2699 APFloat::opStatus St; 2700 switch (Opcode) { 2701 default: 2702 Info.FFDiag(E); 2703 return false; 2704 case BO_Mul: 2705 St = LHS.multiply(RHS, RM); 2706 break; 2707 case BO_Add: 2708 St = LHS.add(RHS, RM); 2709 break; 2710 case BO_Sub: 2711 St = LHS.subtract(RHS, RM); 2712 break; 2713 case BO_Div: 2714 // [expr.mul]p4: 2715 // If the second operand of / or % is zero the behavior is undefined. 2716 if (RHS.isZero()) 2717 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2718 St = LHS.divide(RHS, RM); 2719 break; 2720 } 2721 2722 // [expr.pre]p4: 2723 // If during the evaluation of an expression, the result is not 2724 // mathematically defined [...], the behavior is undefined. 2725 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2726 if (LHS.isNaN()) { 2727 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2728 return Info.noteUndefinedBehavior(); 2729 } 2730 2731 return checkFloatingPointResult(Info, E, St); 2732 } 2733 2734 static bool handleLogicalOpForVector(const APInt &LHSValue, 2735 BinaryOperatorKind Opcode, 2736 const APInt &RHSValue, APInt &Result) { 2737 bool LHS = (LHSValue != 0); 2738 bool RHS = (RHSValue != 0); 2739 2740 if (Opcode == BO_LAnd) 2741 Result = LHS && RHS; 2742 else 2743 Result = LHS || RHS; 2744 return true; 2745 } 2746 static bool handleLogicalOpForVector(const APFloat &LHSValue, 2747 BinaryOperatorKind Opcode, 2748 const APFloat &RHSValue, APInt &Result) { 2749 bool LHS = !LHSValue.isZero(); 2750 bool RHS = !RHSValue.isZero(); 2751 2752 if (Opcode == BO_LAnd) 2753 Result = LHS && RHS; 2754 else 2755 Result = LHS || RHS; 2756 return true; 2757 } 2758 2759 static bool handleLogicalOpForVector(const APValue &LHSValue, 2760 BinaryOperatorKind Opcode, 2761 const APValue &RHSValue, APInt &Result) { 2762 // The result is always an int type, however operands match the first. 2763 if (LHSValue.getKind() == APValue::Int) 2764 return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2765 RHSValue.getInt(), Result); 2766 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2767 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2768 RHSValue.getFloat(), Result); 2769 } 2770 2771 template <typename APTy> 2772 static bool 2773 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2774 const APTy &RHSValue, APInt &Result) { 2775 switch (Opcode) { 2776 default: 2777 llvm_unreachable("unsupported binary operator"); 2778 case BO_EQ: 2779 Result = (LHSValue == RHSValue); 2780 break; 2781 case BO_NE: 2782 Result = (LHSValue != RHSValue); 2783 break; 2784 case BO_LT: 2785 Result = (LHSValue < RHSValue); 2786 break; 2787 case BO_GT: 2788 Result = (LHSValue > RHSValue); 2789 break; 2790 case BO_LE: 2791 Result = (LHSValue <= RHSValue); 2792 break; 2793 case BO_GE: 2794 Result = (LHSValue >= RHSValue); 2795 break; 2796 } 2797 2798 return true; 2799 } 2800 2801 static bool handleCompareOpForVector(const APValue &LHSValue, 2802 BinaryOperatorKind Opcode, 2803 const APValue &RHSValue, APInt &Result) { 2804 // The result is always an int type, however operands match the first. 2805 if (LHSValue.getKind() == APValue::Int) 2806 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2807 RHSValue.getInt(), Result); 2808 assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2809 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2810 RHSValue.getFloat(), Result); 2811 } 2812 2813 // Perform binary operations for vector types, in place on the LHS. 2814 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2815 BinaryOperatorKind Opcode, 2816 APValue &LHSValue, 2817 const APValue &RHSValue) { 2818 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2819 "Operation not supported on vector types"); 2820 2821 const auto *VT = E->getType()->castAs<VectorType>(); 2822 unsigned NumElements = VT->getNumElements(); 2823 QualType EltTy = VT->getElementType(); 2824 2825 // In the cases (typically C as I've observed) where we aren't evaluating 2826 // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2827 // just give up. 2828 if (!LHSValue.isVector()) { 2829 assert(LHSValue.isLValue() && 2830 "A vector result that isn't a vector OR uncalculated LValue"); 2831 Info.FFDiag(E); 2832 return false; 2833 } 2834 2835 assert(LHSValue.getVectorLength() == NumElements && 2836 RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2837 2838 SmallVector<APValue, 4> ResultElements; 2839 2840 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2841 APValue LHSElt = LHSValue.getVectorElt(EltNum); 2842 APValue RHSElt = RHSValue.getVectorElt(EltNum); 2843 2844 if (EltTy->isIntegerType()) { 2845 APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2846 EltTy->isUnsignedIntegerType()}; 2847 bool Success = true; 2848 2849 if (BinaryOperator::isLogicalOp(Opcode)) 2850 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2851 else if (BinaryOperator::isComparisonOp(Opcode)) 2852 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2853 else 2854 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2855 RHSElt.getInt(), EltResult); 2856 2857 if (!Success) { 2858 Info.FFDiag(E); 2859 return false; 2860 } 2861 ResultElements.emplace_back(EltResult); 2862 2863 } else if (EltTy->isFloatingType()) { 2864 assert(LHSElt.getKind() == APValue::Float && 2865 RHSElt.getKind() == APValue::Float && 2866 "Mismatched LHS/RHS/Result Type"); 2867 APFloat LHSFloat = LHSElt.getFloat(); 2868 2869 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 2870 RHSElt.getFloat())) { 2871 Info.FFDiag(E); 2872 return false; 2873 } 2874 2875 ResultElements.emplace_back(LHSFloat); 2876 } 2877 } 2878 2879 LHSValue = APValue(ResultElements.data(), ResultElements.size()); 2880 return true; 2881 } 2882 2883 /// Cast an lvalue referring to a base subobject to a derived class, by 2884 /// truncating the lvalue's path to the given length. 2885 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2886 const RecordDecl *TruncatedType, 2887 unsigned TruncatedElements) { 2888 SubobjectDesignator &D = Result.Designator; 2889 2890 // Check we actually point to a derived class object. 2891 if (TruncatedElements == D.Entries.size()) 2892 return true; 2893 assert(TruncatedElements >= D.MostDerivedPathLength && 2894 "not casting to a derived class"); 2895 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2896 return false; 2897 2898 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2899 const RecordDecl *RD = TruncatedType; 2900 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2901 if (RD->isInvalidDecl()) return false; 2902 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2903 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2904 if (isVirtualBaseClass(D.Entries[I])) 2905 Result.Offset -= Layout.getVBaseClassOffset(Base); 2906 else 2907 Result.Offset -= Layout.getBaseClassOffset(Base); 2908 RD = Base; 2909 } 2910 D.Entries.resize(TruncatedElements); 2911 return true; 2912 } 2913 2914 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2915 const CXXRecordDecl *Derived, 2916 const CXXRecordDecl *Base, 2917 const ASTRecordLayout *RL = nullptr) { 2918 if (!RL) { 2919 if (Derived->isInvalidDecl()) return false; 2920 RL = &Info.Ctx.getASTRecordLayout(Derived); 2921 } 2922 2923 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2924 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2925 return true; 2926 } 2927 2928 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2929 const CXXRecordDecl *DerivedDecl, 2930 const CXXBaseSpecifier *Base) { 2931 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2932 2933 if (!Base->isVirtual()) 2934 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2935 2936 SubobjectDesignator &D = Obj.Designator; 2937 if (D.Invalid) 2938 return false; 2939 2940 // Extract most-derived object and corresponding type. 2941 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2942 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2943 return false; 2944 2945 // Find the virtual base class. 2946 if (DerivedDecl->isInvalidDecl()) return false; 2947 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2948 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2949 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2950 return true; 2951 } 2952 2953 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2954 QualType Type, LValue &Result) { 2955 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2956 PathE = E->path_end(); 2957 PathI != PathE; ++PathI) { 2958 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2959 *PathI)) 2960 return false; 2961 Type = (*PathI)->getType(); 2962 } 2963 return true; 2964 } 2965 2966 /// Cast an lvalue referring to a derived class to a known base subobject. 2967 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 2968 const CXXRecordDecl *DerivedRD, 2969 const CXXRecordDecl *BaseRD) { 2970 CXXBasePaths Paths(/*FindAmbiguities=*/false, 2971 /*RecordPaths=*/true, /*DetectVirtual=*/false); 2972 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 2973 llvm_unreachable("Class must be derived from the passed in base class!"); 2974 2975 for (CXXBasePathElement &Elem : Paths.front()) 2976 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 2977 return false; 2978 return true; 2979 } 2980 2981 /// Update LVal to refer to the given field, which must be a member of the type 2982 /// currently described by LVal. 2983 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2984 const FieldDecl *FD, 2985 const ASTRecordLayout *RL = nullptr) { 2986 if (!RL) { 2987 if (FD->getParent()->isInvalidDecl()) return false; 2988 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2989 } 2990 2991 unsigned I = FD->getFieldIndex(); 2992 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2993 LVal.addDecl(Info, E, FD); 2994 return true; 2995 } 2996 2997 /// Update LVal to refer to the given indirect field. 2998 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2999 LValue &LVal, 3000 const IndirectFieldDecl *IFD) { 3001 for (const auto *C : IFD->chain()) 3002 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3003 return false; 3004 return true; 3005 } 3006 3007 /// Get the size of the given type in char units. 3008 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3009 QualType Type, CharUnits &Size) { 3010 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3011 // extension. 3012 if (Type->isVoidType() || Type->isFunctionType()) { 3013 Size = CharUnits::One(); 3014 return true; 3015 } 3016 3017 if (Type->isDependentType()) { 3018 Info.FFDiag(Loc); 3019 return false; 3020 } 3021 3022 if (!Type->isConstantSizeType()) { 3023 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3024 // FIXME: Better diagnostic. 3025 Info.FFDiag(Loc); 3026 return false; 3027 } 3028 3029 Size = Info.Ctx.getTypeSizeInChars(Type); 3030 return true; 3031 } 3032 3033 /// Update a pointer value to model pointer arithmetic. 3034 /// \param Info - Information about the ongoing evaluation. 3035 /// \param E - The expression being evaluated, for diagnostic purposes. 3036 /// \param LVal - The pointer value to be updated. 3037 /// \param EltTy - The pointee type represented by LVal. 3038 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3039 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3040 LValue &LVal, QualType EltTy, 3041 APSInt Adjustment) { 3042 CharUnits SizeOfPointee; 3043 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3044 return false; 3045 3046 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3047 return true; 3048 } 3049 3050 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3051 LValue &LVal, QualType EltTy, 3052 int64_t Adjustment) { 3053 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3054 APSInt::get(Adjustment)); 3055 } 3056 3057 /// Update an lvalue to refer to a component of a complex number. 3058 /// \param Info - Information about the ongoing evaluation. 3059 /// \param LVal - The lvalue to be updated. 3060 /// \param EltTy - The complex number's component type. 3061 /// \param Imag - False for the real component, true for the imaginary. 3062 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3063 LValue &LVal, QualType EltTy, 3064 bool Imag) { 3065 if (Imag) { 3066 CharUnits SizeOfComponent; 3067 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3068 return false; 3069 LVal.Offset += SizeOfComponent; 3070 } 3071 LVal.addComplex(Info, E, EltTy, Imag); 3072 return true; 3073 } 3074 3075 /// Try to evaluate the initializer for a variable declaration. 3076 /// 3077 /// \param Info Information about the ongoing evaluation. 3078 /// \param E An expression to be used when printing diagnostics. 3079 /// \param VD The variable whose initializer should be obtained. 3080 /// \param Frame The frame in which the variable was created. Must be null 3081 /// if this variable is not local to the evaluation. 3082 /// \param Result Filled in with a pointer to the value of the variable. 3083 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3084 const VarDecl *VD, CallStackFrame *Frame, 3085 APValue *&Result, const LValue *LVal) { 3086 3087 // If this is a parameter to an active constexpr function call, perform 3088 // argument substitution. 3089 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 3090 // Assume arguments of a potential constant expression are unknown 3091 // constant expressions. 3092 if (Info.checkingPotentialConstantExpression()) 3093 return false; 3094 if (!Frame || !Frame->Arguments) { 3095 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) << VD; 3096 return false; 3097 } 3098 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 3099 return true; 3100 } 3101 3102 // If this is a local variable, dig out its value. 3103 if (Frame) { 3104 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 3105 : Frame->getCurrentTemporary(VD); 3106 if (!Result) { 3107 // Assume variables referenced within a lambda's call operator that were 3108 // not declared within the call operator are captures and during checking 3109 // of a potential constant expression, assume they are unknown constant 3110 // expressions. 3111 assert(isLambdaCallOperator(Frame->Callee) && 3112 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3113 "missing value for local variable"); 3114 if (Info.checkingPotentialConstantExpression()) 3115 return false; 3116 // FIXME: implement capture evaluation during constant expr evaluation. 3117 Info.FFDiag(E->getBeginLoc(), 3118 diag::note_unimplemented_constexpr_lambda_feature_ast) 3119 << "captures not currently allowed"; 3120 return false; 3121 } 3122 return true; 3123 } 3124 3125 // Dig out the initializer, and use the declaration which it's attached to. 3126 // FIXME: We should eventually check whether the variable has a reachable 3127 // initializing declaration. 3128 const Expr *Init = VD->getAnyInitializer(VD); 3129 if (!Init) { 3130 // Don't diagnose during potential constant expression checking; an 3131 // initializer might be added later. 3132 if (!Info.checkingPotentialConstantExpression()) { 3133 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3134 << VD; 3135 Info.Note(VD->getLocation(), diag::note_declared_at); 3136 } 3137 return false; 3138 } 3139 3140 if (Init->isValueDependent()) { 3141 // The DeclRefExpr is not value-dependent, but the variable it refers to 3142 // has a value-dependent initializer. This should only happen in 3143 // constant-folding cases, where the variable is not actually of a suitable 3144 // type for use in a constant expression (otherwise the DeclRefExpr would 3145 // have been value-dependent too), so diagnose that. 3146 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3147 if (!Info.checkingPotentialConstantExpression()) { 3148 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3149 ? diag::note_constexpr_ltor_non_constexpr 3150 : diag::note_constexpr_ltor_non_integral, 1) 3151 << VD << VD->getType(); 3152 Info.Note(VD->getLocation(), diag::note_declared_at); 3153 } 3154 return false; 3155 } 3156 3157 // If we're currently evaluating the initializer of this declaration, use that 3158 // in-flight value. 3159 if (declaresSameEntity(Info.EvaluatingDecl.dyn_cast<const ValueDecl *>(), 3160 VD)) { 3161 Result = Info.EvaluatingDeclValue; 3162 return true; 3163 } 3164 3165 // Check that we can fold the initializer. In C++, we will have already done 3166 // this in the cases where it matters for conformance. 3167 SmallVector<PartialDiagnosticAt, 8> Notes; 3168 if (!VD->evaluateValue(Notes)) { 3169 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 3170 Notes.size() + 1) << VD; 3171 Info.Note(VD->getLocation(), diag::note_declared_at); 3172 Info.addNotes(Notes); 3173 return false; 3174 } 3175 3176 // Check that the variable is actually usable in constant expressions. 3177 if (!VD->checkInitIsICE()) { 3178 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 3179 Notes.size() + 1) << VD; 3180 Info.Note(VD->getLocation(), diag::note_declared_at); 3181 Info.addNotes(Notes); 3182 } 3183 3184 // Never use the initializer of a weak variable, not even for constant 3185 // folding. We can't be sure that this is the definition that will be used. 3186 if (VD->isWeak()) { 3187 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3188 Info.Note(VD->getLocation(), diag::note_declared_at); 3189 return false; 3190 } 3191 3192 Result = VD->getEvaluatedValue(); 3193 return true; 3194 } 3195 3196 static bool IsConstNonVolatile(QualType T) { 3197 Qualifiers Quals = T.getQualifiers(); 3198 return Quals.hasConst() && !Quals.hasVolatile(); 3199 } 3200 3201 /// Get the base index of the given base class within an APValue representing 3202 /// the given derived class. 3203 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3204 const CXXRecordDecl *Base) { 3205 Base = Base->getCanonicalDecl(); 3206 unsigned Index = 0; 3207 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3208 E = Derived->bases_end(); I != E; ++I, ++Index) { 3209 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3210 return Index; 3211 } 3212 3213 llvm_unreachable("base class missing from derived class's bases list"); 3214 } 3215 3216 /// Extract the value of a character from a string literal. 3217 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3218 uint64_t Index) { 3219 assert(!isa<SourceLocExpr>(Lit) && 3220 "SourceLocExpr should have already been converted to a StringLiteral"); 3221 3222 // FIXME: Support MakeStringConstant 3223 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3224 std::string Str; 3225 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3226 assert(Index <= Str.size() && "Index too large"); 3227 return APSInt::getUnsigned(Str.c_str()[Index]); 3228 } 3229 3230 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3231 Lit = PE->getFunctionName(); 3232 const StringLiteral *S = cast<StringLiteral>(Lit); 3233 const ConstantArrayType *CAT = 3234 Info.Ctx.getAsConstantArrayType(S->getType()); 3235 assert(CAT && "string literal isn't an array"); 3236 QualType CharType = CAT->getElementType(); 3237 assert(CharType->isIntegerType() && "unexpected character type"); 3238 3239 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3240 CharType->isUnsignedIntegerType()); 3241 if (Index < S->getLength()) 3242 Value = S->getCodeUnit(Index); 3243 return Value; 3244 } 3245 3246 // Expand a string literal into an array of characters. 3247 // 3248 // FIXME: This is inefficient; we should probably introduce something similar 3249 // to the LLVM ConstantDataArray to make this cheaper. 3250 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3251 APValue &Result, 3252 QualType AllocType = QualType()) { 3253 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3254 AllocType.isNull() ? S->getType() : AllocType); 3255 assert(CAT && "string literal isn't an array"); 3256 QualType CharType = CAT->getElementType(); 3257 assert(CharType->isIntegerType() && "unexpected character type"); 3258 3259 unsigned Elts = CAT->getSize().getZExtValue(); 3260 Result = APValue(APValue::UninitArray(), 3261 std::min(S->getLength(), Elts), Elts); 3262 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3263 CharType->isUnsignedIntegerType()); 3264 if (Result.hasArrayFiller()) 3265 Result.getArrayFiller() = APValue(Value); 3266 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3267 Value = S->getCodeUnit(I); 3268 Result.getArrayInitializedElt(I) = APValue(Value); 3269 } 3270 } 3271 3272 // Expand an array so that it has more than Index filled elements. 3273 static void expandArray(APValue &Array, unsigned Index) { 3274 unsigned Size = Array.getArraySize(); 3275 assert(Index < Size); 3276 3277 // Always at least double the number of elements for which we store a value. 3278 unsigned OldElts = Array.getArrayInitializedElts(); 3279 unsigned NewElts = std::max(Index+1, OldElts * 2); 3280 NewElts = std::min(Size, std::max(NewElts, 8u)); 3281 3282 // Copy the data across. 3283 APValue NewValue(APValue::UninitArray(), NewElts, Size); 3284 for (unsigned I = 0; I != OldElts; ++I) 3285 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3286 for (unsigned I = OldElts; I != NewElts; ++I) 3287 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3288 if (NewValue.hasArrayFiller()) 3289 NewValue.getArrayFiller() = Array.getArrayFiller(); 3290 Array.swap(NewValue); 3291 } 3292 3293 /// Determine whether a type would actually be read by an lvalue-to-rvalue 3294 /// conversion. If it's of class type, we may assume that the copy operation 3295 /// is trivial. Note that this is never true for a union type with fields 3296 /// (because the copy always "reads" the active member) and always true for 3297 /// a non-class type. 3298 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3299 static bool isReadByLvalueToRvalueConversion(QualType T) { 3300 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3301 return !RD || isReadByLvalueToRvalueConversion(RD); 3302 } 3303 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3304 // FIXME: A trivial copy of a union copies the object representation, even if 3305 // the union is empty. 3306 if (RD->isUnion()) 3307 return !RD->field_empty(); 3308 if (RD->isEmpty()) 3309 return false; 3310 3311 for (auto *Field : RD->fields()) 3312 if (!Field->isUnnamedBitfield() && 3313 isReadByLvalueToRvalueConversion(Field->getType())) 3314 return true; 3315 3316 for (auto &BaseSpec : RD->bases()) 3317 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3318 return true; 3319 3320 return false; 3321 } 3322 3323 /// Diagnose an attempt to read from any unreadable field within the specified 3324 /// type, which might be a class type. 3325 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3326 QualType T) { 3327 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3328 if (!RD) 3329 return false; 3330 3331 if (!RD->hasMutableFields()) 3332 return false; 3333 3334 for (auto *Field : RD->fields()) { 3335 // If we're actually going to read this field in some way, then it can't 3336 // be mutable. If we're in a union, then assigning to a mutable field 3337 // (even an empty one) can change the active member, so that's not OK. 3338 // FIXME: Add core issue number for the union case. 3339 if (Field->isMutable() && 3340 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3341 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3342 Info.Note(Field->getLocation(), diag::note_declared_at); 3343 return true; 3344 } 3345 3346 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3347 return true; 3348 } 3349 3350 for (auto &BaseSpec : RD->bases()) 3351 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3352 return true; 3353 3354 // All mutable fields were empty, and thus not actually read. 3355 return false; 3356 } 3357 3358 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3359 APValue::LValueBase Base, 3360 bool MutableSubobject = false) { 3361 // A temporary we created. 3362 if (Base.getCallIndex()) 3363 return true; 3364 3365 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3366 if (!Evaluating) 3367 return false; 3368 3369 auto *BaseD = Base.dyn_cast<const ValueDecl*>(); 3370 3371 switch (Info.IsEvaluatingDecl) { 3372 case EvalInfo::EvaluatingDeclKind::None: 3373 return false; 3374 3375 case EvalInfo::EvaluatingDeclKind::Ctor: 3376 // The variable whose initializer we're evaluating. 3377 if (BaseD) 3378 return declaresSameEntity(Evaluating, BaseD); 3379 3380 // A temporary lifetime-extended by the variable whose initializer we're 3381 // evaluating. 3382 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3383 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3384 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating); 3385 return false; 3386 3387 case EvalInfo::EvaluatingDeclKind::Dtor: 3388 // C++2a [expr.const]p6: 3389 // [during constant destruction] the lifetime of a and its non-mutable 3390 // subobjects (but not its mutable subobjects) [are] considered to start 3391 // within e. 3392 // 3393 // FIXME: We can meaningfully extend this to cover non-const objects, but 3394 // we will need special handling: we should be able to access only 3395 // subobjects of such objects that are themselves declared const. 3396 if (!BaseD || 3397 !(BaseD->getType().isConstQualified() || 3398 BaseD->getType()->isReferenceType()) || 3399 MutableSubobject) 3400 return false; 3401 return declaresSameEntity(Evaluating, BaseD); 3402 } 3403 3404 llvm_unreachable("unknown evaluating decl kind"); 3405 } 3406 3407 namespace { 3408 /// A handle to a complete object (an object that is not a subobject of 3409 /// another object). 3410 struct CompleteObject { 3411 /// The identity of the object. 3412 APValue::LValueBase Base; 3413 /// The value of the complete object. 3414 APValue *Value; 3415 /// The type of the complete object. 3416 QualType Type; 3417 3418 CompleteObject() : Value(nullptr) {} 3419 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3420 : Base(Base), Value(Value), Type(Type) {} 3421 3422 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3423 // If this isn't a "real" access (eg, if it's just accessing the type 3424 // info), allow it. We assume the type doesn't change dynamically for 3425 // subobjects of constexpr objects (even though we'd hit UB here if it 3426 // did). FIXME: Is this right? 3427 if (!isAnyAccess(AK)) 3428 return true; 3429 3430 // In C++14 onwards, it is permitted to read a mutable member whose 3431 // lifetime began within the evaluation. 3432 // FIXME: Should we also allow this in C++11? 3433 if (!Info.getLangOpts().CPlusPlus14) 3434 return false; 3435 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3436 } 3437 3438 explicit operator bool() const { return !Type.isNull(); } 3439 }; 3440 } // end anonymous namespace 3441 3442 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3443 bool IsMutable = false) { 3444 // C++ [basic.type.qualifier]p1: 3445 // - A const object is an object of type const T or a non-mutable subobject 3446 // of a const object. 3447 if (ObjType.isConstQualified() && !IsMutable) 3448 SubobjType.addConst(); 3449 // - A volatile object is an object of type const T or a subobject of a 3450 // volatile object. 3451 if (ObjType.isVolatileQualified()) 3452 SubobjType.addVolatile(); 3453 return SubobjType; 3454 } 3455 3456 /// Find the designated sub-object of an rvalue. 3457 template<typename SubobjectHandler> 3458 typename SubobjectHandler::result_type 3459 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3460 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3461 if (Sub.Invalid) 3462 // A diagnostic will have already been produced. 3463 return handler.failed(); 3464 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3465 if (Info.getLangOpts().CPlusPlus11) 3466 Info.FFDiag(E, Sub.isOnePastTheEnd() 3467 ? diag::note_constexpr_access_past_end 3468 : diag::note_constexpr_access_unsized_array) 3469 << handler.AccessKind; 3470 else 3471 Info.FFDiag(E); 3472 return handler.failed(); 3473 } 3474 3475 APValue *O = Obj.Value; 3476 QualType ObjType = Obj.Type; 3477 const FieldDecl *LastField = nullptr; 3478 const FieldDecl *VolatileField = nullptr; 3479 3480 // Walk the designator's path to find the subobject. 3481 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3482 // Reading an indeterminate value is undefined, but assigning over one is OK. 3483 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3484 (O->isIndeterminate() && 3485 !isValidIndeterminateAccess(handler.AccessKind))) { 3486 if (!Info.checkingPotentialConstantExpression()) 3487 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3488 << handler.AccessKind << O->isIndeterminate(); 3489 return handler.failed(); 3490 } 3491 3492 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3493 // const and volatile semantics are not applied on an object under 3494 // {con,de}struction. 3495 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3496 ObjType->isRecordType() && 3497 Info.isEvaluatingCtorDtor( 3498 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3499 Sub.Entries.begin() + I)) != 3500 ConstructionPhase::None) { 3501 ObjType = Info.Ctx.getCanonicalType(ObjType); 3502 ObjType.removeLocalConst(); 3503 ObjType.removeLocalVolatile(); 3504 } 3505 3506 // If this is our last pass, check that the final object type is OK. 3507 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3508 // Accesses to volatile objects are prohibited. 3509 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3510 if (Info.getLangOpts().CPlusPlus) { 3511 int DiagKind; 3512 SourceLocation Loc; 3513 const NamedDecl *Decl = nullptr; 3514 if (VolatileField) { 3515 DiagKind = 2; 3516 Loc = VolatileField->getLocation(); 3517 Decl = VolatileField; 3518 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3519 DiagKind = 1; 3520 Loc = VD->getLocation(); 3521 Decl = VD; 3522 } else { 3523 DiagKind = 0; 3524 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3525 Loc = E->getExprLoc(); 3526 } 3527 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3528 << handler.AccessKind << DiagKind << Decl; 3529 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3530 } else { 3531 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3532 } 3533 return handler.failed(); 3534 } 3535 3536 // If we are reading an object of class type, there may still be more 3537 // things we need to check: if there are any mutable subobjects, we 3538 // cannot perform this read. (This only happens when performing a trivial 3539 // copy or assignment.) 3540 if (ObjType->isRecordType() && 3541 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3542 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3543 return handler.failed(); 3544 } 3545 3546 if (I == N) { 3547 if (!handler.found(*O, ObjType)) 3548 return false; 3549 3550 // If we modified a bit-field, truncate it to the right width. 3551 if (isModification(handler.AccessKind) && 3552 LastField && LastField->isBitField() && 3553 !truncateBitfieldValue(Info, E, *O, LastField)) 3554 return false; 3555 3556 return true; 3557 } 3558 3559 LastField = nullptr; 3560 if (ObjType->isArrayType()) { 3561 // Next subobject is an array element. 3562 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3563 assert(CAT && "vla in literal type?"); 3564 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3565 if (CAT->getSize().ule(Index)) { 3566 // Note, it should not be possible to form a pointer with a valid 3567 // designator which points more than one past the end of the array. 3568 if (Info.getLangOpts().CPlusPlus11) 3569 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3570 << handler.AccessKind; 3571 else 3572 Info.FFDiag(E); 3573 return handler.failed(); 3574 } 3575 3576 ObjType = CAT->getElementType(); 3577 3578 if (O->getArrayInitializedElts() > Index) 3579 O = &O->getArrayInitializedElt(Index); 3580 else if (!isRead(handler.AccessKind)) { 3581 expandArray(*O, Index); 3582 O = &O->getArrayInitializedElt(Index); 3583 } else 3584 O = &O->getArrayFiller(); 3585 } else if (ObjType->isAnyComplexType()) { 3586 // Next subobject is a complex number. 3587 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3588 if (Index > 1) { 3589 if (Info.getLangOpts().CPlusPlus11) 3590 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3591 << handler.AccessKind; 3592 else 3593 Info.FFDiag(E); 3594 return handler.failed(); 3595 } 3596 3597 ObjType = getSubobjectType( 3598 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3599 3600 assert(I == N - 1 && "extracting subobject of scalar?"); 3601 if (O->isComplexInt()) { 3602 return handler.found(Index ? O->getComplexIntImag() 3603 : O->getComplexIntReal(), ObjType); 3604 } else { 3605 assert(O->isComplexFloat()); 3606 return handler.found(Index ? O->getComplexFloatImag() 3607 : O->getComplexFloatReal(), ObjType); 3608 } 3609 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3610 if (Field->isMutable() && 3611 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3612 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3613 << handler.AccessKind << Field; 3614 Info.Note(Field->getLocation(), diag::note_declared_at); 3615 return handler.failed(); 3616 } 3617 3618 // Next subobject is a class, struct or union field. 3619 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3620 if (RD->isUnion()) { 3621 const FieldDecl *UnionField = O->getUnionField(); 3622 if (!UnionField || 3623 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3624 if (I == N - 1 && handler.AccessKind == AK_Construct) { 3625 // Placement new onto an inactive union member makes it active. 3626 O->setUnion(Field, APValue()); 3627 } else { 3628 // FIXME: If O->getUnionValue() is absent, report that there's no 3629 // active union member rather than reporting the prior active union 3630 // member. We'll need to fix nullptr_t to not use APValue() as its 3631 // representation first. 3632 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3633 << handler.AccessKind << Field << !UnionField << UnionField; 3634 return handler.failed(); 3635 } 3636 } 3637 O = &O->getUnionValue(); 3638 } else 3639 O = &O->getStructField(Field->getFieldIndex()); 3640 3641 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3642 LastField = Field; 3643 if (Field->getType().isVolatileQualified()) 3644 VolatileField = Field; 3645 } else { 3646 // Next subobject is a base class. 3647 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3648 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3649 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3650 3651 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3652 } 3653 } 3654 } 3655 3656 namespace { 3657 struct ExtractSubobjectHandler { 3658 EvalInfo &Info; 3659 const Expr *E; 3660 APValue &Result; 3661 const AccessKinds AccessKind; 3662 3663 typedef bool result_type; 3664 bool failed() { return false; } 3665 bool found(APValue &Subobj, QualType SubobjType) { 3666 Result = Subobj; 3667 if (AccessKind == AK_ReadObjectRepresentation) 3668 return true; 3669 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3670 } 3671 bool found(APSInt &Value, QualType SubobjType) { 3672 Result = APValue(Value); 3673 return true; 3674 } 3675 bool found(APFloat &Value, QualType SubobjType) { 3676 Result = APValue(Value); 3677 return true; 3678 } 3679 }; 3680 } // end anonymous namespace 3681 3682 /// Extract the designated sub-object of an rvalue. 3683 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3684 const CompleteObject &Obj, 3685 const SubobjectDesignator &Sub, APValue &Result, 3686 AccessKinds AK = AK_Read) { 3687 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3688 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3689 return findSubobject(Info, E, Obj, Sub, Handler); 3690 } 3691 3692 namespace { 3693 struct ModifySubobjectHandler { 3694 EvalInfo &Info; 3695 APValue &NewVal; 3696 const Expr *E; 3697 3698 typedef bool result_type; 3699 static const AccessKinds AccessKind = AK_Assign; 3700 3701 bool checkConst(QualType QT) { 3702 // Assigning to a const object has undefined behavior. 3703 if (QT.isConstQualified()) { 3704 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3705 return false; 3706 } 3707 return true; 3708 } 3709 3710 bool failed() { return false; } 3711 bool found(APValue &Subobj, QualType SubobjType) { 3712 if (!checkConst(SubobjType)) 3713 return false; 3714 // We've been given ownership of NewVal, so just swap it in. 3715 Subobj.swap(NewVal); 3716 return true; 3717 } 3718 bool found(APSInt &Value, QualType SubobjType) { 3719 if (!checkConst(SubobjType)) 3720 return false; 3721 if (!NewVal.isInt()) { 3722 // Maybe trying to write a cast pointer value into a complex? 3723 Info.FFDiag(E); 3724 return false; 3725 } 3726 Value = NewVal.getInt(); 3727 return true; 3728 } 3729 bool found(APFloat &Value, QualType SubobjType) { 3730 if (!checkConst(SubobjType)) 3731 return false; 3732 Value = NewVal.getFloat(); 3733 return true; 3734 } 3735 }; 3736 } // end anonymous namespace 3737 3738 const AccessKinds ModifySubobjectHandler::AccessKind; 3739 3740 /// Update the designated sub-object of an rvalue to the given value. 3741 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3742 const CompleteObject &Obj, 3743 const SubobjectDesignator &Sub, 3744 APValue &NewVal) { 3745 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3746 return findSubobject(Info, E, Obj, Sub, Handler); 3747 } 3748 3749 /// Find the position where two subobject designators diverge, or equivalently 3750 /// the length of the common initial subsequence. 3751 static unsigned FindDesignatorMismatch(QualType ObjType, 3752 const SubobjectDesignator &A, 3753 const SubobjectDesignator &B, 3754 bool &WasArrayIndex) { 3755 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3756 for (/**/; I != N; ++I) { 3757 if (!ObjType.isNull() && 3758 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3759 // Next subobject is an array element. 3760 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3761 WasArrayIndex = true; 3762 return I; 3763 } 3764 if (ObjType->isAnyComplexType()) 3765 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3766 else 3767 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3768 } else { 3769 if (A.Entries[I].getAsBaseOrMember() != 3770 B.Entries[I].getAsBaseOrMember()) { 3771 WasArrayIndex = false; 3772 return I; 3773 } 3774 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3775 // Next subobject is a field. 3776 ObjType = FD->getType(); 3777 else 3778 // Next subobject is a base class. 3779 ObjType = QualType(); 3780 } 3781 } 3782 WasArrayIndex = false; 3783 return I; 3784 } 3785 3786 /// Determine whether the given subobject designators refer to elements of the 3787 /// same array object. 3788 static bool AreElementsOfSameArray(QualType ObjType, 3789 const SubobjectDesignator &A, 3790 const SubobjectDesignator &B) { 3791 if (A.Entries.size() != B.Entries.size()) 3792 return false; 3793 3794 bool IsArray = A.MostDerivedIsArrayElement; 3795 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3796 // A is a subobject of the array element. 3797 return false; 3798 3799 // If A (and B) designates an array element, the last entry will be the array 3800 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3801 // of length 1' case, and the entire path must match. 3802 bool WasArrayIndex; 3803 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3804 return CommonLength >= A.Entries.size() - IsArray; 3805 } 3806 3807 /// Find the complete object to which an LValue refers. 3808 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3809 AccessKinds AK, const LValue &LVal, 3810 QualType LValType) { 3811 if (LVal.InvalidBase) { 3812 Info.FFDiag(E); 3813 return CompleteObject(); 3814 } 3815 3816 if (!LVal.Base) { 3817 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3818 return CompleteObject(); 3819 } 3820 3821 CallStackFrame *Frame = nullptr; 3822 unsigned Depth = 0; 3823 if (LVal.getLValueCallIndex()) { 3824 std::tie(Frame, Depth) = 3825 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3826 if (!Frame) { 3827 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3828 << AK << LVal.Base.is<const ValueDecl*>(); 3829 NoteLValueLocation(Info, LVal.Base); 3830 return CompleteObject(); 3831 } 3832 } 3833 3834 bool IsAccess = isAnyAccess(AK); 3835 3836 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3837 // is not a constant expression (even if the object is non-volatile). We also 3838 // apply this rule to C++98, in order to conform to the expected 'volatile' 3839 // semantics. 3840 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3841 if (Info.getLangOpts().CPlusPlus) 3842 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3843 << AK << LValType; 3844 else 3845 Info.FFDiag(E); 3846 return CompleteObject(); 3847 } 3848 3849 // Compute value storage location and type of base object. 3850 APValue *BaseVal = nullptr; 3851 QualType BaseType = getType(LVal.Base); 3852 3853 if (const ConstantExpr *CE = 3854 dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) { 3855 /// Nested immediate invocation have been previously removed so if we found 3856 /// a ConstantExpr it can only be the EvaluatingDecl. 3857 assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl); 3858 (void)CE; 3859 BaseVal = Info.EvaluatingDeclValue; 3860 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3861 // Allow reading from a GUID declaration. 3862 if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 3863 if (isModification(AK)) { 3864 // All the remaining cases do not permit modification of the object. 3865 Info.FFDiag(E, diag::note_constexpr_modify_global); 3866 return CompleteObject(); 3867 } 3868 APValue &V = GD->getAsAPValue(); 3869 if (V.isAbsent()) { 3870 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 3871 << GD->getType(); 3872 return CompleteObject(); 3873 } 3874 return CompleteObject(LVal.Base, &V, GD->getType()); 3875 } 3876 3877 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3878 // In C++11, constexpr, non-volatile variables initialized with constant 3879 // expressions are constant expressions too. Inside constexpr functions, 3880 // parameters are constant expressions even if they're non-const. 3881 // In C++1y, objects local to a constant expression (those with a Frame) are 3882 // both readable and writable inside constant expressions. 3883 // In C, such things can also be folded, although they are not ICEs. 3884 const VarDecl *VD = dyn_cast<VarDecl>(D); 3885 if (VD) { 3886 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3887 VD = VDef; 3888 } 3889 if (!VD || VD->isInvalidDecl()) { 3890 Info.FFDiag(E); 3891 return CompleteObject(); 3892 } 3893 3894 // In OpenCL if a variable is in constant address space it is a const value. 3895 bool IsConstant = BaseType.isConstQualified() || 3896 (Info.getLangOpts().OpenCL && 3897 BaseType.getAddressSpace() == LangAS::opencl_constant); 3898 3899 // Unless we're looking at a local variable or argument in a constexpr call, 3900 // the variable we're reading must be const. 3901 if (!Frame) { 3902 if (Info.getLangOpts().CPlusPlus14 && 3903 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3904 // OK, we can read and modify an object if we're in the process of 3905 // evaluating its initializer, because its lifetime began in this 3906 // evaluation. 3907 } else if (isModification(AK)) { 3908 // All the remaining cases do not permit modification of the object. 3909 Info.FFDiag(E, diag::note_constexpr_modify_global); 3910 return CompleteObject(); 3911 } else if (VD->isConstexpr()) { 3912 // OK, we can read this variable. 3913 } else if (BaseType->isIntegralOrEnumerationType()) { 3914 // In OpenCL if a variable is in constant address space it is a const 3915 // value. 3916 if (!IsConstant) { 3917 if (!IsAccess) 3918 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3919 if (Info.getLangOpts().CPlusPlus) { 3920 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3921 Info.Note(VD->getLocation(), diag::note_declared_at); 3922 } else { 3923 Info.FFDiag(E); 3924 } 3925 return CompleteObject(); 3926 } 3927 } else if (!IsAccess) { 3928 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3929 } else if (IsConstant && Info.checkingPotentialConstantExpression() && 3930 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 3931 // This variable might end up being constexpr. Don't diagnose it yet. 3932 } else if (IsConstant) { 3933 // Keep evaluating to see what we can do. In particular, we support 3934 // folding of const floating-point types, in order to make static const 3935 // data members of such types (supported as an extension) more useful. 3936 if (Info.getLangOpts().CPlusPlus) { 3937 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 3938 ? diag::note_constexpr_ltor_non_constexpr 3939 : diag::note_constexpr_ltor_non_integral, 1) 3940 << VD << BaseType; 3941 Info.Note(VD->getLocation(), diag::note_declared_at); 3942 } else { 3943 Info.CCEDiag(E); 3944 } 3945 } else { 3946 // Never allow reading a non-const value. 3947 if (Info.getLangOpts().CPlusPlus) { 3948 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3949 ? diag::note_constexpr_ltor_non_constexpr 3950 : diag::note_constexpr_ltor_non_integral, 1) 3951 << VD << BaseType; 3952 Info.Note(VD->getLocation(), diag::note_declared_at); 3953 } else { 3954 Info.FFDiag(E); 3955 } 3956 return CompleteObject(); 3957 } 3958 } 3959 3960 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3961 return CompleteObject(); 3962 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 3963 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 3964 if (!Alloc) { 3965 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 3966 return CompleteObject(); 3967 } 3968 return CompleteObject(LVal.Base, &(*Alloc)->Value, 3969 LVal.Base.getDynamicAllocType()); 3970 } else { 3971 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3972 3973 if (!Frame) { 3974 if (const MaterializeTemporaryExpr *MTE = 3975 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 3976 assert(MTE->getStorageDuration() == SD_Static && 3977 "should have a frame for a non-global materialized temporary"); 3978 3979 // Per C++1y [expr.const]p2: 3980 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3981 // - a [...] glvalue of integral or enumeration type that refers to 3982 // a non-volatile const object [...] 3983 // [...] 3984 // - a [...] glvalue of literal type that refers to a non-volatile 3985 // object whose lifetime began within the evaluation of e. 3986 // 3987 // C++11 misses the 'began within the evaluation of e' check and 3988 // instead allows all temporaries, including things like: 3989 // int &&r = 1; 3990 // int x = ++r; 3991 // constexpr int k = r; 3992 // Therefore we use the C++14 rules in C++11 too. 3993 // 3994 // Note that temporaries whose lifetimes began while evaluating a 3995 // variable's constructor are not usable while evaluating the 3996 // corresponding destructor, not even if they're of const-qualified 3997 // types. 3998 if (!(BaseType.isConstQualified() && 3999 BaseType->isIntegralOrEnumerationType()) && 4000 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4001 if (!IsAccess) 4002 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4003 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4004 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4005 return CompleteObject(); 4006 } 4007 4008 BaseVal = MTE->getOrCreateValue(false); 4009 assert(BaseVal && "got reference to unevaluated temporary"); 4010 } else { 4011 if (!IsAccess) 4012 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4013 APValue Val; 4014 LVal.moveInto(Val); 4015 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4016 << AK 4017 << Val.getAsString(Info.Ctx, 4018 Info.Ctx.getLValueReferenceType(LValType)); 4019 NoteLValueLocation(Info, LVal.Base); 4020 return CompleteObject(); 4021 } 4022 } else { 4023 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4024 assert(BaseVal && "missing value for temporary"); 4025 } 4026 } 4027 4028 // In C++14, we can't safely access any mutable state when we might be 4029 // evaluating after an unmodeled side effect. 4030 // 4031 // FIXME: Not all local state is mutable. Allow local constant subobjects 4032 // to be read here (but take care with 'mutable' fields). 4033 if ((Frame && Info.getLangOpts().CPlusPlus14 && 4034 Info.EvalStatus.HasSideEffects) || 4035 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth)) 4036 return CompleteObject(); 4037 4038 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4039 } 4040 4041 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4042 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4043 /// glvalue referred to by an entity of reference type. 4044 /// 4045 /// \param Info - Information about the ongoing evaluation. 4046 /// \param Conv - The expression for which we are performing the conversion. 4047 /// Used for diagnostics. 4048 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4049 /// case of a non-class type). 4050 /// \param LVal - The glvalue on which we are attempting to perform this action. 4051 /// \param RVal - The produced value will be placed here. 4052 /// \param WantObjectRepresentation - If true, we're looking for the object 4053 /// representation rather than the value, and in particular, 4054 /// there is no requirement that the result be fully initialized. 4055 static bool 4056 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4057 const LValue &LVal, APValue &RVal, 4058 bool WantObjectRepresentation = false) { 4059 if (LVal.Designator.Invalid) 4060 return false; 4061 4062 // Check for special cases where there is no existing APValue to look at. 4063 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4064 4065 AccessKinds AK = 4066 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4067 4068 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4069 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4070 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4071 // initializer until now for such expressions. Such an expression can't be 4072 // an ICE in C, so this only matters for fold. 4073 if (Type.isVolatileQualified()) { 4074 Info.FFDiag(Conv); 4075 return false; 4076 } 4077 APValue Lit; 4078 if (!Evaluate(Lit, Info, CLE->getInitializer())) 4079 return false; 4080 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4081 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4082 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4083 // Special-case character extraction so we don't have to construct an 4084 // APValue for the whole string. 4085 assert(LVal.Designator.Entries.size() <= 1 && 4086 "Can only read characters from string literals"); 4087 if (LVal.Designator.Entries.empty()) { 4088 // Fail for now for LValue to RValue conversion of an array. 4089 // (This shouldn't show up in C/C++, but it could be triggered by a 4090 // weird EvaluateAsRValue call from a tool.) 4091 Info.FFDiag(Conv); 4092 return false; 4093 } 4094 if (LVal.Designator.isOnePastTheEnd()) { 4095 if (Info.getLangOpts().CPlusPlus11) 4096 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4097 else 4098 Info.FFDiag(Conv); 4099 return false; 4100 } 4101 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4102 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4103 return true; 4104 } 4105 } 4106 4107 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4108 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4109 } 4110 4111 /// Perform an assignment of Val to LVal. Takes ownership of Val. 4112 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4113 QualType LValType, APValue &Val) { 4114 if (LVal.Designator.Invalid) 4115 return false; 4116 4117 if (!Info.getLangOpts().CPlusPlus14) { 4118 Info.FFDiag(E); 4119 return false; 4120 } 4121 4122 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4123 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4124 } 4125 4126 namespace { 4127 struct CompoundAssignSubobjectHandler { 4128 EvalInfo &Info; 4129 const CompoundAssignOperator *E; 4130 QualType PromotedLHSType; 4131 BinaryOperatorKind Opcode; 4132 const APValue &RHS; 4133 4134 static const AccessKinds AccessKind = AK_Assign; 4135 4136 typedef bool result_type; 4137 4138 bool checkConst(QualType QT) { 4139 // Assigning to a const object has undefined behavior. 4140 if (QT.isConstQualified()) { 4141 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4142 return false; 4143 } 4144 return true; 4145 } 4146 4147 bool failed() { return false; } 4148 bool found(APValue &Subobj, QualType SubobjType) { 4149 switch (Subobj.getKind()) { 4150 case APValue::Int: 4151 return found(Subobj.getInt(), SubobjType); 4152 case APValue::Float: 4153 return found(Subobj.getFloat(), SubobjType); 4154 case APValue::ComplexInt: 4155 case APValue::ComplexFloat: 4156 // FIXME: Implement complex compound assignment. 4157 Info.FFDiag(E); 4158 return false; 4159 case APValue::LValue: 4160 return foundPointer(Subobj, SubobjType); 4161 case APValue::Vector: 4162 return foundVector(Subobj, SubobjType); 4163 default: 4164 // FIXME: can this happen? 4165 Info.FFDiag(E); 4166 return false; 4167 } 4168 } 4169 4170 bool foundVector(APValue &Value, QualType SubobjType) { 4171 if (!checkConst(SubobjType)) 4172 return false; 4173 4174 if (!SubobjType->isVectorType()) { 4175 Info.FFDiag(E); 4176 return false; 4177 } 4178 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4179 } 4180 4181 bool found(APSInt &Value, QualType SubobjType) { 4182 if (!checkConst(SubobjType)) 4183 return false; 4184 4185 if (!SubobjType->isIntegerType()) { 4186 // We don't support compound assignment on integer-cast-to-pointer 4187 // values. 4188 Info.FFDiag(E); 4189 return false; 4190 } 4191 4192 if (RHS.isInt()) { 4193 APSInt LHS = 4194 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4195 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4196 return false; 4197 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4198 return true; 4199 } else if (RHS.isFloat()) { 4200 APFloat FValue(0.0); 4201 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, 4202 FValue) && 4203 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4204 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4205 Value); 4206 } 4207 4208 Info.FFDiag(E); 4209 return false; 4210 } 4211 bool found(APFloat &Value, QualType SubobjType) { 4212 return checkConst(SubobjType) && 4213 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4214 Value) && 4215 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4216 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4217 } 4218 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4219 if (!checkConst(SubobjType)) 4220 return false; 4221 4222 QualType PointeeType; 4223 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4224 PointeeType = PT->getPointeeType(); 4225 4226 if (PointeeType.isNull() || !RHS.isInt() || 4227 (Opcode != BO_Add && Opcode != BO_Sub)) { 4228 Info.FFDiag(E); 4229 return false; 4230 } 4231 4232 APSInt Offset = RHS.getInt(); 4233 if (Opcode == BO_Sub) 4234 negateAsSigned(Offset); 4235 4236 LValue LVal; 4237 LVal.setFrom(Info.Ctx, Subobj); 4238 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4239 return false; 4240 LVal.moveInto(Subobj); 4241 return true; 4242 } 4243 }; 4244 } // end anonymous namespace 4245 4246 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4247 4248 /// Perform a compound assignment of LVal <op>= RVal. 4249 static bool handleCompoundAssignment(EvalInfo &Info, 4250 const CompoundAssignOperator *E, 4251 const LValue &LVal, QualType LValType, 4252 QualType PromotedLValType, 4253 BinaryOperatorKind Opcode, 4254 const APValue &RVal) { 4255 if (LVal.Designator.Invalid) 4256 return false; 4257 4258 if (!Info.getLangOpts().CPlusPlus14) { 4259 Info.FFDiag(E); 4260 return false; 4261 } 4262 4263 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4264 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4265 RVal }; 4266 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4267 } 4268 4269 namespace { 4270 struct IncDecSubobjectHandler { 4271 EvalInfo &Info; 4272 const UnaryOperator *E; 4273 AccessKinds AccessKind; 4274 APValue *Old; 4275 4276 typedef bool result_type; 4277 4278 bool checkConst(QualType QT) { 4279 // Assigning to a const object has undefined behavior. 4280 if (QT.isConstQualified()) { 4281 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4282 return false; 4283 } 4284 return true; 4285 } 4286 4287 bool failed() { return false; } 4288 bool found(APValue &Subobj, QualType SubobjType) { 4289 // Stash the old value. Also clear Old, so we don't clobber it later 4290 // if we're post-incrementing a complex. 4291 if (Old) { 4292 *Old = Subobj; 4293 Old = nullptr; 4294 } 4295 4296 switch (Subobj.getKind()) { 4297 case APValue::Int: 4298 return found(Subobj.getInt(), SubobjType); 4299 case APValue::Float: 4300 return found(Subobj.getFloat(), SubobjType); 4301 case APValue::ComplexInt: 4302 return found(Subobj.getComplexIntReal(), 4303 SubobjType->castAs<ComplexType>()->getElementType() 4304 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4305 case APValue::ComplexFloat: 4306 return found(Subobj.getComplexFloatReal(), 4307 SubobjType->castAs<ComplexType>()->getElementType() 4308 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4309 case APValue::LValue: 4310 return foundPointer(Subobj, SubobjType); 4311 default: 4312 // FIXME: can this happen? 4313 Info.FFDiag(E); 4314 return false; 4315 } 4316 } 4317 bool found(APSInt &Value, QualType SubobjType) { 4318 if (!checkConst(SubobjType)) 4319 return false; 4320 4321 if (!SubobjType->isIntegerType()) { 4322 // We don't support increment / decrement on integer-cast-to-pointer 4323 // values. 4324 Info.FFDiag(E); 4325 return false; 4326 } 4327 4328 if (Old) *Old = APValue(Value); 4329 4330 // bool arithmetic promotes to int, and the conversion back to bool 4331 // doesn't reduce mod 2^n, so special-case it. 4332 if (SubobjType->isBooleanType()) { 4333 if (AccessKind == AK_Increment) 4334 Value = 1; 4335 else 4336 Value = !Value; 4337 return true; 4338 } 4339 4340 bool WasNegative = Value.isNegative(); 4341 if (AccessKind == AK_Increment) { 4342 ++Value; 4343 4344 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4345 APSInt ActualValue(Value, /*IsUnsigned*/true); 4346 return HandleOverflow(Info, E, ActualValue, SubobjType); 4347 } 4348 } else { 4349 --Value; 4350 4351 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4352 unsigned BitWidth = Value.getBitWidth(); 4353 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4354 ActualValue.setBit(BitWidth); 4355 return HandleOverflow(Info, E, ActualValue, SubobjType); 4356 } 4357 } 4358 return true; 4359 } 4360 bool found(APFloat &Value, QualType SubobjType) { 4361 if (!checkConst(SubobjType)) 4362 return false; 4363 4364 if (Old) *Old = APValue(Value); 4365 4366 APFloat One(Value.getSemantics(), 1); 4367 if (AccessKind == AK_Increment) 4368 Value.add(One, APFloat::rmNearestTiesToEven); 4369 else 4370 Value.subtract(One, APFloat::rmNearestTiesToEven); 4371 return true; 4372 } 4373 bool foundPointer(APValue &Subobj, QualType SubobjType) { 4374 if (!checkConst(SubobjType)) 4375 return false; 4376 4377 QualType PointeeType; 4378 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4379 PointeeType = PT->getPointeeType(); 4380 else { 4381 Info.FFDiag(E); 4382 return false; 4383 } 4384 4385 LValue LVal; 4386 LVal.setFrom(Info.Ctx, Subobj); 4387 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4388 AccessKind == AK_Increment ? 1 : -1)) 4389 return false; 4390 LVal.moveInto(Subobj); 4391 return true; 4392 } 4393 }; 4394 } // end anonymous namespace 4395 4396 /// Perform an increment or decrement on LVal. 4397 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4398 QualType LValType, bool IsIncrement, APValue *Old) { 4399 if (LVal.Designator.Invalid) 4400 return false; 4401 4402 if (!Info.getLangOpts().CPlusPlus14) { 4403 Info.FFDiag(E); 4404 return false; 4405 } 4406 4407 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4408 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4409 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4410 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4411 } 4412 4413 /// Build an lvalue for the object argument of a member function call. 4414 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4415 LValue &This) { 4416 if (Object->getType()->isPointerType() && Object->isRValue()) 4417 return EvaluatePointer(Object, This, Info); 4418 4419 if (Object->isGLValue()) 4420 return EvaluateLValue(Object, This, Info); 4421 4422 if (Object->getType()->isLiteralType(Info.Ctx)) 4423 return EvaluateTemporary(Object, This, Info); 4424 4425 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4426 return false; 4427 } 4428 4429 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4430 /// lvalue referring to the result. 4431 /// 4432 /// \param Info - Information about the ongoing evaluation. 4433 /// \param LV - An lvalue referring to the base of the member pointer. 4434 /// \param RHS - The member pointer expression. 4435 /// \param IncludeMember - Specifies whether the member itself is included in 4436 /// the resulting LValue subobject designator. This is not possible when 4437 /// creating a bound member function. 4438 /// \return The field or method declaration to which the member pointer refers, 4439 /// or 0 if evaluation fails. 4440 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4441 QualType LVType, 4442 LValue &LV, 4443 const Expr *RHS, 4444 bool IncludeMember = true) { 4445 MemberPtr MemPtr; 4446 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4447 return nullptr; 4448 4449 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4450 // member value, the behavior is undefined. 4451 if (!MemPtr.getDecl()) { 4452 // FIXME: Specific diagnostic. 4453 Info.FFDiag(RHS); 4454 return nullptr; 4455 } 4456 4457 if (MemPtr.isDerivedMember()) { 4458 // This is a member of some derived class. Truncate LV appropriately. 4459 // The end of the derived-to-base path for the base object must match the 4460 // derived-to-base path for the member pointer. 4461 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4462 LV.Designator.Entries.size()) { 4463 Info.FFDiag(RHS); 4464 return nullptr; 4465 } 4466 unsigned PathLengthToMember = 4467 LV.Designator.Entries.size() - MemPtr.Path.size(); 4468 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4469 const CXXRecordDecl *LVDecl = getAsBaseClass( 4470 LV.Designator.Entries[PathLengthToMember + I]); 4471 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4472 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4473 Info.FFDiag(RHS); 4474 return nullptr; 4475 } 4476 } 4477 4478 // Truncate the lvalue to the appropriate derived class. 4479 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4480 PathLengthToMember)) 4481 return nullptr; 4482 } else if (!MemPtr.Path.empty()) { 4483 // Extend the LValue path with the member pointer's path. 4484 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4485 MemPtr.Path.size() + IncludeMember); 4486 4487 // Walk down to the appropriate base class. 4488 if (const PointerType *PT = LVType->getAs<PointerType>()) 4489 LVType = PT->getPointeeType(); 4490 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4491 assert(RD && "member pointer access on non-class-type expression"); 4492 // The first class in the path is that of the lvalue. 4493 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4494 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4495 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4496 return nullptr; 4497 RD = Base; 4498 } 4499 // Finally cast to the class containing the member. 4500 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4501 MemPtr.getContainingRecord())) 4502 return nullptr; 4503 } 4504 4505 // Add the member. Note that we cannot build bound member functions here. 4506 if (IncludeMember) { 4507 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4508 if (!HandleLValueMember(Info, RHS, LV, FD)) 4509 return nullptr; 4510 } else if (const IndirectFieldDecl *IFD = 4511 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4512 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4513 return nullptr; 4514 } else { 4515 llvm_unreachable("can't construct reference to bound member function"); 4516 } 4517 } 4518 4519 return MemPtr.getDecl(); 4520 } 4521 4522 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4523 const BinaryOperator *BO, 4524 LValue &LV, 4525 bool IncludeMember = true) { 4526 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4527 4528 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4529 if (Info.noteFailure()) { 4530 MemberPtr MemPtr; 4531 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4532 } 4533 return nullptr; 4534 } 4535 4536 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4537 BO->getRHS(), IncludeMember); 4538 } 4539 4540 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4541 /// the provided lvalue, which currently refers to the base object. 4542 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4543 LValue &Result) { 4544 SubobjectDesignator &D = Result.Designator; 4545 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4546 return false; 4547 4548 QualType TargetQT = E->getType(); 4549 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4550 TargetQT = PT->getPointeeType(); 4551 4552 // Check this cast lands within the final derived-to-base subobject path. 4553 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4554 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4555 << D.MostDerivedType << TargetQT; 4556 return false; 4557 } 4558 4559 // Check the type of the final cast. We don't need to check the path, 4560 // since a cast can only be formed if the path is unique. 4561 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4562 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4563 const CXXRecordDecl *FinalType; 4564 if (NewEntriesSize == D.MostDerivedPathLength) 4565 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4566 else 4567 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4568 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4569 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4570 << D.MostDerivedType << TargetQT; 4571 return false; 4572 } 4573 4574 // Truncate the lvalue to the appropriate derived class. 4575 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4576 } 4577 4578 /// Get the value to use for a default-initialized object of type T. 4579 /// Return false if it encounters something invalid. 4580 static bool getDefaultInitValue(QualType T, APValue &Result) { 4581 bool Success = true; 4582 if (auto *RD = T->getAsCXXRecordDecl()) { 4583 if (RD->isInvalidDecl()) { 4584 Result = APValue(); 4585 return false; 4586 } 4587 if (RD->isUnion()) { 4588 Result = APValue((const FieldDecl *)nullptr); 4589 return true; 4590 } 4591 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4592 std::distance(RD->field_begin(), RD->field_end())); 4593 4594 unsigned Index = 0; 4595 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4596 End = RD->bases_end(); 4597 I != End; ++I, ++Index) 4598 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4599 4600 for (const auto *I : RD->fields()) { 4601 if (I->isUnnamedBitfield()) 4602 continue; 4603 Success &= getDefaultInitValue(I->getType(), 4604 Result.getStructField(I->getFieldIndex())); 4605 } 4606 return Success; 4607 } 4608 4609 if (auto *AT = 4610 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4611 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4612 if (Result.hasArrayFiller()) 4613 Success &= 4614 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4615 4616 return Success; 4617 } 4618 4619 Result = APValue::IndeterminateValue(); 4620 return true; 4621 } 4622 4623 namespace { 4624 enum EvalStmtResult { 4625 /// Evaluation failed. 4626 ESR_Failed, 4627 /// Hit a 'return' statement. 4628 ESR_Returned, 4629 /// Evaluation succeeded. 4630 ESR_Succeeded, 4631 /// Hit a 'continue' statement. 4632 ESR_Continue, 4633 /// Hit a 'break' statement. 4634 ESR_Break, 4635 /// Still scanning for 'case' or 'default' statement. 4636 ESR_CaseNotFound 4637 }; 4638 } 4639 4640 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4641 // We don't need to evaluate the initializer for a static local. 4642 if (!VD->hasLocalStorage()) 4643 return true; 4644 4645 LValue Result; 4646 APValue &Val = 4647 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result); 4648 4649 const Expr *InitE = VD->getInit(); 4650 if (!InitE) 4651 return getDefaultInitValue(VD->getType(), Val); 4652 4653 if (InitE->isValueDependent()) 4654 return false; 4655 4656 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4657 // Wipe out any partially-computed value, to allow tracking that this 4658 // evaluation failed. 4659 Val = APValue(); 4660 return false; 4661 } 4662 4663 return true; 4664 } 4665 4666 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4667 bool OK = true; 4668 4669 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4670 OK &= EvaluateVarDecl(Info, VD); 4671 4672 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4673 for (auto *BD : DD->bindings()) 4674 if (auto *VD = BD->getHoldingVar()) 4675 OK &= EvaluateDecl(Info, VD); 4676 4677 return OK; 4678 } 4679 4680 4681 /// Evaluate a condition (either a variable declaration or an expression). 4682 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4683 const Expr *Cond, bool &Result) { 4684 FullExpressionRAII Scope(Info); 4685 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4686 return false; 4687 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4688 return false; 4689 return Scope.destroy(); 4690 } 4691 4692 namespace { 4693 /// A location where the result (returned value) of evaluating a 4694 /// statement should be stored. 4695 struct StmtResult { 4696 /// The APValue that should be filled in with the returned value. 4697 APValue &Value; 4698 /// The location containing the result, if any (used to support RVO). 4699 const LValue *Slot; 4700 }; 4701 4702 struct TempVersionRAII { 4703 CallStackFrame &Frame; 4704 4705 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4706 Frame.pushTempVersion(); 4707 } 4708 4709 ~TempVersionRAII() { 4710 Frame.popTempVersion(); 4711 } 4712 }; 4713 4714 } 4715 4716 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4717 const Stmt *S, 4718 const SwitchCase *SC = nullptr); 4719 4720 /// Evaluate the body of a loop, and translate the result as appropriate. 4721 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4722 const Stmt *Body, 4723 const SwitchCase *Case = nullptr) { 4724 BlockScopeRAII Scope(Info); 4725 4726 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4727 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4728 ESR = ESR_Failed; 4729 4730 switch (ESR) { 4731 case ESR_Break: 4732 return ESR_Succeeded; 4733 case ESR_Succeeded: 4734 case ESR_Continue: 4735 return ESR_Continue; 4736 case ESR_Failed: 4737 case ESR_Returned: 4738 case ESR_CaseNotFound: 4739 return ESR; 4740 } 4741 llvm_unreachable("Invalid EvalStmtResult!"); 4742 } 4743 4744 /// Evaluate a switch statement. 4745 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4746 const SwitchStmt *SS) { 4747 BlockScopeRAII Scope(Info); 4748 4749 // Evaluate the switch condition. 4750 APSInt Value; 4751 { 4752 if (const Stmt *Init = SS->getInit()) { 4753 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4754 if (ESR != ESR_Succeeded) { 4755 if (ESR != ESR_Failed && !Scope.destroy()) 4756 ESR = ESR_Failed; 4757 return ESR; 4758 } 4759 } 4760 4761 FullExpressionRAII CondScope(Info); 4762 if (SS->getConditionVariable() && 4763 !EvaluateDecl(Info, SS->getConditionVariable())) 4764 return ESR_Failed; 4765 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4766 return ESR_Failed; 4767 if (!CondScope.destroy()) 4768 return ESR_Failed; 4769 } 4770 4771 // Find the switch case corresponding to the value of the condition. 4772 // FIXME: Cache this lookup. 4773 const SwitchCase *Found = nullptr; 4774 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4775 SC = SC->getNextSwitchCase()) { 4776 if (isa<DefaultStmt>(SC)) { 4777 Found = SC; 4778 continue; 4779 } 4780 4781 const CaseStmt *CS = cast<CaseStmt>(SC); 4782 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4783 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4784 : LHS; 4785 if (LHS <= Value && Value <= RHS) { 4786 Found = SC; 4787 break; 4788 } 4789 } 4790 4791 if (!Found) 4792 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4793 4794 // Search the switch body for the switch case and evaluate it from there. 4795 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4796 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4797 return ESR_Failed; 4798 4799 switch (ESR) { 4800 case ESR_Break: 4801 return ESR_Succeeded; 4802 case ESR_Succeeded: 4803 case ESR_Continue: 4804 case ESR_Failed: 4805 case ESR_Returned: 4806 return ESR; 4807 case ESR_CaseNotFound: 4808 // This can only happen if the switch case is nested within a statement 4809 // expression. We have no intention of supporting that. 4810 Info.FFDiag(Found->getBeginLoc(), 4811 diag::note_constexpr_stmt_expr_unsupported); 4812 return ESR_Failed; 4813 } 4814 llvm_unreachable("Invalid EvalStmtResult!"); 4815 } 4816 4817 // Evaluate a statement. 4818 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4819 const Stmt *S, const SwitchCase *Case) { 4820 if (!Info.nextStep(S)) 4821 return ESR_Failed; 4822 4823 // If we're hunting down a 'case' or 'default' label, recurse through 4824 // substatements until we hit the label. 4825 if (Case) { 4826 switch (S->getStmtClass()) { 4827 case Stmt::CompoundStmtClass: 4828 // FIXME: Precompute which substatement of a compound statement we 4829 // would jump to, and go straight there rather than performing a 4830 // linear scan each time. 4831 case Stmt::LabelStmtClass: 4832 case Stmt::AttributedStmtClass: 4833 case Stmt::DoStmtClass: 4834 break; 4835 4836 case Stmt::CaseStmtClass: 4837 case Stmt::DefaultStmtClass: 4838 if (Case == S) 4839 Case = nullptr; 4840 break; 4841 4842 case Stmt::IfStmtClass: { 4843 // FIXME: Precompute which side of an 'if' we would jump to, and go 4844 // straight there rather than scanning both sides. 4845 const IfStmt *IS = cast<IfStmt>(S); 4846 4847 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4848 // preceded by our switch label. 4849 BlockScopeRAII Scope(Info); 4850 4851 // Step into the init statement in case it brings an (uninitialized) 4852 // variable into scope. 4853 if (const Stmt *Init = IS->getInit()) { 4854 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4855 if (ESR != ESR_CaseNotFound) { 4856 assert(ESR != ESR_Succeeded); 4857 return ESR; 4858 } 4859 } 4860 4861 // Condition variable must be initialized if it exists. 4862 // FIXME: We can skip evaluating the body if there's a condition 4863 // variable, as there can't be any case labels within it. 4864 // (The same is true for 'for' statements.) 4865 4866 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4867 if (ESR == ESR_Failed) 4868 return ESR; 4869 if (ESR != ESR_CaseNotFound) 4870 return Scope.destroy() ? ESR : ESR_Failed; 4871 if (!IS->getElse()) 4872 return ESR_CaseNotFound; 4873 4874 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 4875 if (ESR == ESR_Failed) 4876 return ESR; 4877 if (ESR != ESR_CaseNotFound) 4878 return Scope.destroy() ? ESR : ESR_Failed; 4879 return ESR_CaseNotFound; 4880 } 4881 4882 case Stmt::WhileStmtClass: { 4883 EvalStmtResult ESR = 4884 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4885 if (ESR != ESR_Continue) 4886 return ESR; 4887 break; 4888 } 4889 4890 case Stmt::ForStmtClass: { 4891 const ForStmt *FS = cast<ForStmt>(S); 4892 BlockScopeRAII Scope(Info); 4893 4894 // Step into the init statement in case it brings an (uninitialized) 4895 // variable into scope. 4896 if (const Stmt *Init = FS->getInit()) { 4897 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4898 if (ESR != ESR_CaseNotFound) { 4899 assert(ESR != ESR_Succeeded); 4900 return ESR; 4901 } 4902 } 4903 4904 EvalStmtResult ESR = 4905 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4906 if (ESR != ESR_Continue) 4907 return ESR; 4908 if (FS->getInc()) { 4909 FullExpressionRAII IncScope(Info); 4910 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 4911 return ESR_Failed; 4912 } 4913 break; 4914 } 4915 4916 case Stmt::DeclStmtClass: { 4917 // Start the lifetime of any uninitialized variables we encounter. They 4918 // might be used by the selected branch of the switch. 4919 const DeclStmt *DS = cast<DeclStmt>(S); 4920 for (const auto *D : DS->decls()) { 4921 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4922 if (VD->hasLocalStorage() && !VD->getInit()) 4923 if (!EvaluateVarDecl(Info, VD)) 4924 return ESR_Failed; 4925 // FIXME: If the variable has initialization that can't be jumped 4926 // over, bail out of any immediately-surrounding compound-statement 4927 // too. There can't be any case labels here. 4928 } 4929 } 4930 return ESR_CaseNotFound; 4931 } 4932 4933 default: 4934 return ESR_CaseNotFound; 4935 } 4936 } 4937 4938 switch (S->getStmtClass()) { 4939 default: 4940 if (const Expr *E = dyn_cast<Expr>(S)) { 4941 // Don't bother evaluating beyond an expression-statement which couldn't 4942 // be evaluated. 4943 // FIXME: Do we need the FullExpressionRAII object here? 4944 // VisitExprWithCleanups should create one when necessary. 4945 FullExpressionRAII Scope(Info); 4946 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 4947 return ESR_Failed; 4948 return ESR_Succeeded; 4949 } 4950 4951 Info.FFDiag(S->getBeginLoc()); 4952 return ESR_Failed; 4953 4954 case Stmt::NullStmtClass: 4955 return ESR_Succeeded; 4956 4957 case Stmt::DeclStmtClass: { 4958 const DeclStmt *DS = cast<DeclStmt>(S); 4959 for (const auto *D : DS->decls()) { 4960 // Each declaration initialization is its own full-expression. 4961 FullExpressionRAII Scope(Info); 4962 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 4963 return ESR_Failed; 4964 if (!Scope.destroy()) 4965 return ESR_Failed; 4966 } 4967 return ESR_Succeeded; 4968 } 4969 4970 case Stmt::ReturnStmtClass: { 4971 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4972 FullExpressionRAII Scope(Info); 4973 if (RetExpr && 4974 !(Result.Slot 4975 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4976 : Evaluate(Result.Value, Info, RetExpr))) 4977 return ESR_Failed; 4978 return Scope.destroy() ? ESR_Returned : ESR_Failed; 4979 } 4980 4981 case Stmt::CompoundStmtClass: { 4982 BlockScopeRAII Scope(Info); 4983 4984 const CompoundStmt *CS = cast<CompoundStmt>(S); 4985 for (const auto *BI : CS->body()) { 4986 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4987 if (ESR == ESR_Succeeded) 4988 Case = nullptr; 4989 else if (ESR != ESR_CaseNotFound) { 4990 if (ESR != ESR_Failed && !Scope.destroy()) 4991 return ESR_Failed; 4992 return ESR; 4993 } 4994 } 4995 if (Case) 4996 return ESR_CaseNotFound; 4997 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4998 } 4999 5000 case Stmt::IfStmtClass: { 5001 const IfStmt *IS = cast<IfStmt>(S); 5002 5003 // Evaluate the condition, as either a var decl or as an expression. 5004 BlockScopeRAII Scope(Info); 5005 if (const Stmt *Init = IS->getInit()) { 5006 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5007 if (ESR != ESR_Succeeded) { 5008 if (ESR != ESR_Failed && !Scope.destroy()) 5009 return ESR_Failed; 5010 return ESR; 5011 } 5012 } 5013 bool Cond; 5014 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 5015 return ESR_Failed; 5016 5017 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5018 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5019 if (ESR != ESR_Succeeded) { 5020 if (ESR != ESR_Failed && !Scope.destroy()) 5021 return ESR_Failed; 5022 return ESR; 5023 } 5024 } 5025 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5026 } 5027 5028 case Stmt::WhileStmtClass: { 5029 const WhileStmt *WS = cast<WhileStmt>(S); 5030 while (true) { 5031 BlockScopeRAII Scope(Info); 5032 bool Continue; 5033 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5034 Continue)) 5035 return ESR_Failed; 5036 if (!Continue) 5037 break; 5038 5039 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5040 if (ESR != ESR_Continue) { 5041 if (ESR != ESR_Failed && !Scope.destroy()) 5042 return ESR_Failed; 5043 return ESR; 5044 } 5045 if (!Scope.destroy()) 5046 return ESR_Failed; 5047 } 5048 return ESR_Succeeded; 5049 } 5050 5051 case Stmt::DoStmtClass: { 5052 const DoStmt *DS = cast<DoStmt>(S); 5053 bool Continue; 5054 do { 5055 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5056 if (ESR != ESR_Continue) 5057 return ESR; 5058 Case = nullptr; 5059 5060 FullExpressionRAII CondScope(Info); 5061 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5062 !CondScope.destroy()) 5063 return ESR_Failed; 5064 } while (Continue); 5065 return ESR_Succeeded; 5066 } 5067 5068 case Stmt::ForStmtClass: { 5069 const ForStmt *FS = cast<ForStmt>(S); 5070 BlockScopeRAII ForScope(Info); 5071 if (FS->getInit()) { 5072 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5073 if (ESR != ESR_Succeeded) { 5074 if (ESR != ESR_Failed && !ForScope.destroy()) 5075 return ESR_Failed; 5076 return ESR; 5077 } 5078 } 5079 while (true) { 5080 BlockScopeRAII IterScope(Info); 5081 bool Continue = true; 5082 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5083 FS->getCond(), Continue)) 5084 return ESR_Failed; 5085 if (!Continue) 5086 break; 5087 5088 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5089 if (ESR != ESR_Continue) { 5090 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5091 return ESR_Failed; 5092 return ESR; 5093 } 5094 5095 if (FS->getInc()) { 5096 FullExpressionRAII IncScope(Info); 5097 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 5098 return ESR_Failed; 5099 } 5100 5101 if (!IterScope.destroy()) 5102 return ESR_Failed; 5103 } 5104 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5105 } 5106 5107 case Stmt::CXXForRangeStmtClass: { 5108 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5109 BlockScopeRAII Scope(Info); 5110 5111 // Evaluate the init-statement if present. 5112 if (FS->getInit()) { 5113 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5114 if (ESR != ESR_Succeeded) { 5115 if (ESR != ESR_Failed && !Scope.destroy()) 5116 return ESR_Failed; 5117 return ESR; 5118 } 5119 } 5120 5121 // Initialize the __range variable. 5122 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5123 if (ESR != ESR_Succeeded) { 5124 if (ESR != ESR_Failed && !Scope.destroy()) 5125 return ESR_Failed; 5126 return ESR; 5127 } 5128 5129 // Create the __begin and __end iterators. 5130 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5131 if (ESR != ESR_Succeeded) { 5132 if (ESR != ESR_Failed && !Scope.destroy()) 5133 return ESR_Failed; 5134 return ESR; 5135 } 5136 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5137 if (ESR != ESR_Succeeded) { 5138 if (ESR != ESR_Failed && !Scope.destroy()) 5139 return ESR_Failed; 5140 return ESR; 5141 } 5142 5143 while (true) { 5144 // Condition: __begin != __end. 5145 { 5146 bool Continue = true; 5147 FullExpressionRAII CondExpr(Info); 5148 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5149 return ESR_Failed; 5150 if (!Continue) 5151 break; 5152 } 5153 5154 // User's variable declaration, initialized by *__begin. 5155 BlockScopeRAII InnerScope(Info); 5156 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5157 if (ESR != ESR_Succeeded) { 5158 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5159 return ESR_Failed; 5160 return ESR; 5161 } 5162 5163 // Loop body. 5164 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5165 if (ESR != ESR_Continue) { 5166 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5167 return ESR_Failed; 5168 return ESR; 5169 } 5170 5171 // Increment: ++__begin 5172 if (!EvaluateIgnoredValue(Info, FS->getInc())) 5173 return ESR_Failed; 5174 5175 if (!InnerScope.destroy()) 5176 return ESR_Failed; 5177 } 5178 5179 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5180 } 5181 5182 case Stmt::SwitchStmtClass: 5183 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5184 5185 case Stmt::ContinueStmtClass: 5186 return ESR_Continue; 5187 5188 case Stmt::BreakStmtClass: 5189 return ESR_Break; 5190 5191 case Stmt::LabelStmtClass: 5192 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5193 5194 case Stmt::AttributedStmtClass: 5195 // As a general principle, C++11 attributes can be ignored without 5196 // any semantic impact. 5197 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5198 Case); 5199 5200 case Stmt::CaseStmtClass: 5201 case Stmt::DefaultStmtClass: 5202 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5203 case Stmt::CXXTryStmtClass: 5204 // Evaluate try blocks by evaluating all sub statements. 5205 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5206 } 5207 } 5208 5209 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5210 /// default constructor. If so, we'll fold it whether or not it's marked as 5211 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5212 /// so we need special handling. 5213 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5214 const CXXConstructorDecl *CD, 5215 bool IsValueInitialization) { 5216 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5217 return false; 5218 5219 // Value-initialization does not call a trivial default constructor, so such a 5220 // call is a core constant expression whether or not the constructor is 5221 // constexpr. 5222 if (!CD->isConstexpr() && !IsValueInitialization) { 5223 if (Info.getLangOpts().CPlusPlus11) { 5224 // FIXME: If DiagDecl is an implicitly-declared special member function, 5225 // we should be much more explicit about why it's not constexpr. 5226 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5227 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5228 Info.Note(CD->getLocation(), diag::note_declared_at); 5229 } else { 5230 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5231 } 5232 } 5233 return true; 5234 } 5235 5236 /// CheckConstexprFunction - Check that a function can be called in a constant 5237 /// expression. 5238 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5239 const FunctionDecl *Declaration, 5240 const FunctionDecl *Definition, 5241 const Stmt *Body) { 5242 // Potential constant expressions can contain calls to declared, but not yet 5243 // defined, constexpr functions. 5244 if (Info.checkingPotentialConstantExpression() && !Definition && 5245 Declaration->isConstexpr()) 5246 return false; 5247 5248 // Bail out if the function declaration itself is invalid. We will 5249 // have produced a relevant diagnostic while parsing it, so just 5250 // note the problematic sub-expression. 5251 if (Declaration->isInvalidDecl()) { 5252 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5253 return false; 5254 } 5255 5256 // DR1872: An instantiated virtual constexpr function can't be called in a 5257 // constant expression (prior to C++20). We can still constant-fold such a 5258 // call. 5259 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5260 cast<CXXMethodDecl>(Declaration)->isVirtual()) 5261 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5262 5263 if (Definition && Definition->isInvalidDecl()) { 5264 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5265 return false; 5266 } 5267 5268 if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) { 5269 for (const auto *InitExpr : CtorDecl->inits()) { 5270 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 5271 return false; 5272 } 5273 } 5274 5275 // Can we evaluate this function call? 5276 if (Definition && Definition->isConstexpr() && Body) 5277 return true; 5278 5279 if (Info.getLangOpts().CPlusPlus11) { 5280 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5281 5282 // If this function is not constexpr because it is an inherited 5283 // non-constexpr constructor, diagnose that directly. 5284 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5285 if (CD && CD->isInheritingConstructor()) { 5286 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5287 if (!Inherited->isConstexpr()) 5288 DiagDecl = CD = Inherited; 5289 } 5290 5291 // FIXME: If DiagDecl is an implicitly-declared special member function 5292 // or an inheriting constructor, we should be much more explicit about why 5293 // it's not constexpr. 5294 if (CD && CD->isInheritingConstructor()) 5295 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5296 << CD->getInheritedConstructor().getConstructor()->getParent(); 5297 else 5298 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5299 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5300 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5301 } else { 5302 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5303 } 5304 return false; 5305 } 5306 5307 namespace { 5308 struct CheckDynamicTypeHandler { 5309 AccessKinds AccessKind; 5310 typedef bool result_type; 5311 bool failed() { return false; } 5312 bool found(APValue &Subobj, QualType SubobjType) { return true; } 5313 bool found(APSInt &Value, QualType SubobjType) { return true; } 5314 bool found(APFloat &Value, QualType SubobjType) { return true; } 5315 }; 5316 } // end anonymous namespace 5317 5318 /// Check that we can access the notional vptr of an object / determine its 5319 /// dynamic type. 5320 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5321 AccessKinds AK, bool Polymorphic) { 5322 if (This.Designator.Invalid) 5323 return false; 5324 5325 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5326 5327 if (!Obj) 5328 return false; 5329 5330 if (!Obj.Value) { 5331 // The object is not usable in constant expressions, so we can't inspect 5332 // its value to see if it's in-lifetime or what the active union members 5333 // are. We can still check for a one-past-the-end lvalue. 5334 if (This.Designator.isOnePastTheEnd() || 5335 This.Designator.isMostDerivedAnUnsizedArray()) { 5336 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5337 ? diag::note_constexpr_access_past_end 5338 : diag::note_constexpr_access_unsized_array) 5339 << AK; 5340 return false; 5341 } else if (Polymorphic) { 5342 // Conservatively refuse to perform a polymorphic operation if we would 5343 // not be able to read a notional 'vptr' value. 5344 APValue Val; 5345 This.moveInto(Val); 5346 QualType StarThisType = 5347 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5348 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5349 << AK << Val.getAsString(Info.Ctx, StarThisType); 5350 return false; 5351 } 5352 return true; 5353 } 5354 5355 CheckDynamicTypeHandler Handler{AK}; 5356 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5357 } 5358 5359 /// Check that the pointee of the 'this' pointer in a member function call is 5360 /// either within its lifetime or in its period of construction or destruction. 5361 static bool 5362 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5363 const LValue &This, 5364 const CXXMethodDecl *NamedMember) { 5365 return checkDynamicType( 5366 Info, E, This, 5367 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5368 } 5369 5370 struct DynamicType { 5371 /// The dynamic class type of the object. 5372 const CXXRecordDecl *Type; 5373 /// The corresponding path length in the lvalue. 5374 unsigned PathLength; 5375 }; 5376 5377 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5378 unsigned PathLength) { 5379 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5380 Designator.Entries.size() && "invalid path length"); 5381 return (PathLength == Designator.MostDerivedPathLength) 5382 ? Designator.MostDerivedType->getAsCXXRecordDecl() 5383 : getAsBaseClass(Designator.Entries[PathLength - 1]); 5384 } 5385 5386 /// Determine the dynamic type of an object. 5387 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5388 LValue &This, AccessKinds AK) { 5389 // If we don't have an lvalue denoting an object of class type, there is no 5390 // meaningful dynamic type. (We consider objects of non-class type to have no 5391 // dynamic type.) 5392 if (!checkDynamicType(Info, E, This, AK, true)) 5393 return None; 5394 5395 // Refuse to compute a dynamic type in the presence of virtual bases. This 5396 // shouldn't happen other than in constant-folding situations, since literal 5397 // types can't have virtual bases. 5398 // 5399 // Note that consumers of DynamicType assume that the type has no virtual 5400 // bases, and will need modifications if this restriction is relaxed. 5401 const CXXRecordDecl *Class = 5402 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5403 if (!Class || Class->getNumVBases()) { 5404 Info.FFDiag(E); 5405 return None; 5406 } 5407 5408 // FIXME: For very deep class hierarchies, it might be beneficial to use a 5409 // binary search here instead. But the overwhelmingly common case is that 5410 // we're not in the middle of a constructor, so it probably doesn't matter 5411 // in practice. 5412 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5413 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5414 PathLength <= Path.size(); ++PathLength) { 5415 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5416 Path.slice(0, PathLength))) { 5417 case ConstructionPhase::Bases: 5418 case ConstructionPhase::DestroyingBases: 5419 // We're constructing or destroying a base class. This is not the dynamic 5420 // type. 5421 break; 5422 5423 case ConstructionPhase::None: 5424 case ConstructionPhase::AfterBases: 5425 case ConstructionPhase::AfterFields: 5426 case ConstructionPhase::Destroying: 5427 // We've finished constructing the base classes and not yet started 5428 // destroying them again, so this is the dynamic type. 5429 return DynamicType{getBaseClassType(This.Designator, PathLength), 5430 PathLength}; 5431 } 5432 } 5433 5434 // CWG issue 1517: we're constructing a base class of the object described by 5435 // 'This', so that object has not yet begun its period of construction and 5436 // any polymorphic operation on it results in undefined behavior. 5437 Info.FFDiag(E); 5438 return None; 5439 } 5440 5441 /// Perform virtual dispatch. 5442 static const CXXMethodDecl *HandleVirtualDispatch( 5443 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5444 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5445 Optional<DynamicType> DynType = ComputeDynamicType( 5446 Info, E, This, 5447 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5448 if (!DynType) 5449 return nullptr; 5450 5451 // Find the final overrider. It must be declared in one of the classes on the 5452 // path from the dynamic type to the static type. 5453 // FIXME: If we ever allow literal types to have virtual base classes, that 5454 // won't be true. 5455 const CXXMethodDecl *Callee = Found; 5456 unsigned PathLength = DynType->PathLength; 5457 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5458 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5459 const CXXMethodDecl *Overrider = 5460 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5461 if (Overrider) { 5462 Callee = Overrider; 5463 break; 5464 } 5465 } 5466 5467 // C++2a [class.abstract]p6: 5468 // the effect of making a virtual call to a pure virtual function [...] is 5469 // undefined 5470 if (Callee->isPure()) { 5471 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5472 Info.Note(Callee->getLocation(), diag::note_declared_at); 5473 return nullptr; 5474 } 5475 5476 // If necessary, walk the rest of the path to determine the sequence of 5477 // covariant adjustment steps to apply. 5478 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5479 Found->getReturnType())) { 5480 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5481 for (unsigned CovariantPathLength = PathLength + 1; 5482 CovariantPathLength != This.Designator.Entries.size(); 5483 ++CovariantPathLength) { 5484 const CXXRecordDecl *NextClass = 5485 getBaseClassType(This.Designator, CovariantPathLength); 5486 const CXXMethodDecl *Next = 5487 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5488 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5489 Next->getReturnType(), CovariantAdjustmentPath.back())) 5490 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5491 } 5492 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5493 CovariantAdjustmentPath.back())) 5494 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5495 } 5496 5497 // Perform 'this' adjustment. 5498 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5499 return nullptr; 5500 5501 return Callee; 5502 } 5503 5504 /// Perform the adjustment from a value returned by a virtual function to 5505 /// a value of the statically expected type, which may be a pointer or 5506 /// reference to a base class of the returned type. 5507 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5508 APValue &Result, 5509 ArrayRef<QualType> Path) { 5510 assert(Result.isLValue() && 5511 "unexpected kind of APValue for covariant return"); 5512 if (Result.isNullPointer()) 5513 return true; 5514 5515 LValue LVal; 5516 LVal.setFrom(Info.Ctx, Result); 5517 5518 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5519 for (unsigned I = 1; I != Path.size(); ++I) { 5520 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5521 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5522 if (OldClass != NewClass && 5523 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5524 return false; 5525 OldClass = NewClass; 5526 } 5527 5528 LVal.moveInto(Result); 5529 return true; 5530 } 5531 5532 /// Determine whether \p Base, which is known to be a direct base class of 5533 /// \p Derived, is a public base class. 5534 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5535 const CXXRecordDecl *Base) { 5536 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5537 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5538 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5539 return BaseSpec.getAccessSpecifier() == AS_public; 5540 } 5541 llvm_unreachable("Base is not a direct base of Derived"); 5542 } 5543 5544 /// Apply the given dynamic cast operation on the provided lvalue. 5545 /// 5546 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5547 /// to find a suitable target subobject. 5548 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5549 LValue &Ptr) { 5550 // We can't do anything with a non-symbolic pointer value. 5551 SubobjectDesignator &D = Ptr.Designator; 5552 if (D.Invalid) 5553 return false; 5554 5555 // C++ [expr.dynamic.cast]p6: 5556 // If v is a null pointer value, the result is a null pointer value. 5557 if (Ptr.isNullPointer() && !E->isGLValue()) 5558 return true; 5559 5560 // For all the other cases, we need the pointer to point to an object within 5561 // its lifetime / period of construction / destruction, and we need to know 5562 // its dynamic type. 5563 Optional<DynamicType> DynType = 5564 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5565 if (!DynType) 5566 return false; 5567 5568 // C++ [expr.dynamic.cast]p7: 5569 // If T is "pointer to cv void", then the result is a pointer to the most 5570 // derived object 5571 if (E->getType()->isVoidPointerType()) 5572 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5573 5574 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5575 assert(C && "dynamic_cast target is not void pointer nor class"); 5576 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5577 5578 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5579 // C++ [expr.dynamic.cast]p9: 5580 if (!E->isGLValue()) { 5581 // The value of a failed cast to pointer type is the null pointer value 5582 // of the required result type. 5583 Ptr.setNull(Info.Ctx, E->getType()); 5584 return true; 5585 } 5586 5587 // A failed cast to reference type throws [...] std::bad_cast. 5588 unsigned DiagKind; 5589 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5590 DynType->Type->isDerivedFrom(C))) 5591 DiagKind = 0; 5592 else if (!Paths || Paths->begin() == Paths->end()) 5593 DiagKind = 1; 5594 else if (Paths->isAmbiguous(CQT)) 5595 DiagKind = 2; 5596 else { 5597 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5598 DiagKind = 3; 5599 } 5600 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5601 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5602 << Info.Ctx.getRecordType(DynType->Type) 5603 << E->getType().getUnqualifiedType(); 5604 return false; 5605 }; 5606 5607 // Runtime check, phase 1: 5608 // Walk from the base subobject towards the derived object looking for the 5609 // target type. 5610 for (int PathLength = Ptr.Designator.Entries.size(); 5611 PathLength >= (int)DynType->PathLength; --PathLength) { 5612 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5613 if (declaresSameEntity(Class, C)) 5614 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5615 // We can only walk across public inheritance edges. 5616 if (PathLength > (int)DynType->PathLength && 5617 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5618 Class)) 5619 return RuntimeCheckFailed(nullptr); 5620 } 5621 5622 // Runtime check, phase 2: 5623 // Search the dynamic type for an unambiguous public base of type C. 5624 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5625 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5626 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5627 Paths.front().Access == AS_public) { 5628 // Downcast to the dynamic type... 5629 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5630 return false; 5631 // ... then upcast to the chosen base class subobject. 5632 for (CXXBasePathElement &Elem : Paths.front()) 5633 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5634 return false; 5635 return true; 5636 } 5637 5638 // Otherwise, the runtime check fails. 5639 return RuntimeCheckFailed(&Paths); 5640 } 5641 5642 namespace { 5643 struct StartLifetimeOfUnionMemberHandler { 5644 EvalInfo &Info; 5645 const Expr *LHSExpr; 5646 const FieldDecl *Field; 5647 bool DuringInit; 5648 bool Failed = false; 5649 static const AccessKinds AccessKind = AK_Assign; 5650 5651 typedef bool result_type; 5652 bool failed() { return Failed; } 5653 bool found(APValue &Subobj, QualType SubobjType) { 5654 // We are supposed to perform no initialization but begin the lifetime of 5655 // the object. We interpret that as meaning to do what default 5656 // initialization of the object would do if all constructors involved were 5657 // trivial: 5658 // * All base, non-variant member, and array element subobjects' lifetimes 5659 // begin 5660 // * No variant members' lifetimes begin 5661 // * All scalar subobjects whose lifetimes begin have indeterminate values 5662 assert(SubobjType->isUnionType()); 5663 if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5664 // This union member is already active. If it's also in-lifetime, there's 5665 // nothing to do. 5666 if (Subobj.getUnionValue().hasValue()) 5667 return true; 5668 } else if (DuringInit) { 5669 // We're currently in the process of initializing a different union 5670 // member. If we carried on, that initialization would attempt to 5671 // store to an inactive union member, resulting in undefined behavior. 5672 Info.FFDiag(LHSExpr, 5673 diag::note_constexpr_union_member_change_during_init); 5674 return false; 5675 } 5676 APValue Result; 5677 Failed = !getDefaultInitValue(Field->getType(), Result); 5678 Subobj.setUnion(Field, Result); 5679 return true; 5680 } 5681 bool found(APSInt &Value, QualType SubobjType) { 5682 llvm_unreachable("wrong value kind for union object"); 5683 } 5684 bool found(APFloat &Value, QualType SubobjType) { 5685 llvm_unreachable("wrong value kind for union object"); 5686 } 5687 }; 5688 } // end anonymous namespace 5689 5690 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5691 5692 /// Handle a builtin simple-assignment or a call to a trivial assignment 5693 /// operator whose left-hand side might involve a union member access. If it 5694 /// does, implicitly start the lifetime of any accessed union elements per 5695 /// C++20 [class.union]5. 5696 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5697 const LValue &LHS) { 5698 if (LHS.InvalidBase || LHS.Designator.Invalid) 5699 return false; 5700 5701 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5702 // C++ [class.union]p5: 5703 // define the set S(E) of subexpressions of E as follows: 5704 unsigned PathLength = LHS.Designator.Entries.size(); 5705 for (const Expr *E = LHSExpr; E != nullptr;) { 5706 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5707 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5708 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5709 // Note that we can't implicitly start the lifetime of a reference, 5710 // so we don't need to proceed any further if we reach one. 5711 if (!FD || FD->getType()->isReferenceType()) 5712 break; 5713 5714 // ... and also contains A.B if B names a union member ... 5715 if (FD->getParent()->isUnion()) { 5716 // ... of a non-class, non-array type, or of a class type with a 5717 // trivial default constructor that is not deleted, or an array of 5718 // such types. 5719 auto *RD = 5720 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5721 if (!RD || RD->hasTrivialDefaultConstructor()) 5722 UnionPathLengths.push_back({PathLength - 1, FD}); 5723 } 5724 5725 E = ME->getBase(); 5726 --PathLength; 5727 assert(declaresSameEntity(FD, 5728 LHS.Designator.Entries[PathLength] 5729 .getAsBaseOrMember().getPointer())); 5730 5731 // -- If E is of the form A[B] and is interpreted as a built-in array 5732 // subscripting operator, S(E) is [S(the array operand, if any)]. 5733 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5734 // Step over an ArrayToPointerDecay implicit cast. 5735 auto *Base = ASE->getBase()->IgnoreImplicit(); 5736 if (!Base->getType()->isArrayType()) 5737 break; 5738 5739 E = Base; 5740 --PathLength; 5741 5742 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5743 // Step over a derived-to-base conversion. 5744 E = ICE->getSubExpr(); 5745 if (ICE->getCastKind() == CK_NoOp) 5746 continue; 5747 if (ICE->getCastKind() != CK_DerivedToBase && 5748 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5749 break; 5750 // Walk path backwards as we walk up from the base to the derived class. 5751 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5752 --PathLength; 5753 (void)Elt; 5754 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5755 LHS.Designator.Entries[PathLength] 5756 .getAsBaseOrMember().getPointer())); 5757 } 5758 5759 // -- Otherwise, S(E) is empty. 5760 } else { 5761 break; 5762 } 5763 } 5764 5765 // Common case: no unions' lifetimes are started. 5766 if (UnionPathLengths.empty()) 5767 return true; 5768 5769 // if modification of X [would access an inactive union member], an object 5770 // of the type of X is implicitly created 5771 CompleteObject Obj = 5772 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5773 if (!Obj) 5774 return false; 5775 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5776 llvm::reverse(UnionPathLengths)) { 5777 // Form a designator for the union object. 5778 SubobjectDesignator D = LHS.Designator; 5779 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5780 5781 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5782 ConstructionPhase::AfterBases; 5783 StartLifetimeOfUnionMemberHandler StartLifetime{ 5784 Info, LHSExpr, LengthAndField.second, DuringInit}; 5785 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5786 return false; 5787 } 5788 5789 return true; 5790 } 5791 5792 namespace { 5793 typedef SmallVector<APValue, 8> ArgVector; 5794 } 5795 5796 /// EvaluateArgs - Evaluate the arguments to a function call. 5797 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues, 5798 EvalInfo &Info, const FunctionDecl *Callee) { 5799 ArgValues.resize(Args.size()); 5800 5801 bool Success = true; 5802 llvm::SmallBitVector ForbiddenNullArgs; 5803 if (Callee->hasAttr<NonNullAttr>()) { 5804 ForbiddenNullArgs.resize(Args.size()); 5805 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 5806 if (!Attr->args_size()) { 5807 ForbiddenNullArgs.set(); 5808 break; 5809 } else 5810 for (auto Idx : Attr->args()) { 5811 unsigned ASTIdx = Idx.getASTIndex(); 5812 if (ASTIdx >= Args.size()) 5813 continue; 5814 ForbiddenNullArgs[ASTIdx] = 1; 5815 } 5816 } 5817 } 5818 for (unsigned Idx = 0; Idx < Args.size(); Idx++) { 5819 if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) { 5820 // If we're checking for a potential constant expression, evaluate all 5821 // initializers even if some of them fail. 5822 if (!Info.noteFailure()) 5823 return false; 5824 Success = false; 5825 } else if (!ForbiddenNullArgs.empty() && 5826 ForbiddenNullArgs[Idx] && 5827 ArgValues[Idx].isLValue() && 5828 ArgValues[Idx].isNullPointer()) { 5829 Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed); 5830 if (!Info.noteFailure()) 5831 return false; 5832 Success = false; 5833 } 5834 } 5835 return Success; 5836 } 5837 5838 /// Evaluate a function call. 5839 static bool HandleFunctionCall(SourceLocation CallLoc, 5840 const FunctionDecl *Callee, const LValue *This, 5841 ArrayRef<const Expr *> Args, APValue *ArgValues, 5842 const Stmt *Body, EvalInfo &Info, 5843 APValue &Result, const LValue *ResultSlot) { 5844 if (!Info.CheckCallLimit(CallLoc)) 5845 return false; 5846 5847 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues); 5848 5849 // For a trivial copy or move assignment, perform an APValue copy. This is 5850 // essential for unions, where the operations performed by the assignment 5851 // operator cannot be represented as statements. 5852 // 5853 // Skip this for non-union classes with no fields; in that case, the defaulted 5854 // copy/move does not actually read the object. 5855 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 5856 if (MD && MD->isDefaulted() && 5857 (MD->getParent()->isUnion() || 5858 (MD->isTrivial() && 5859 isReadByLvalueToRvalueConversion(MD->getParent())))) { 5860 assert(This && 5861 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 5862 LValue RHS; 5863 RHS.setFrom(Info.Ctx, ArgValues[0]); 5864 APValue RHSValue; 5865 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS, 5866 RHSValue, MD->getParent()->isUnion())) 5867 return false; 5868 if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 5869 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 5870 return false; 5871 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 5872 RHSValue)) 5873 return false; 5874 This->moveInto(Result); 5875 return true; 5876 } else if (MD && isLambdaCallOperator(MD)) { 5877 // We're in a lambda; determine the lambda capture field maps unless we're 5878 // just constexpr checking a lambda's call operator. constexpr checking is 5879 // done before the captures have been added to the closure object (unless 5880 // we're inferring constexpr-ness), so we don't have access to them in this 5881 // case. But since we don't need the captures to constexpr check, we can 5882 // just ignore them. 5883 if (!Info.checkingPotentialConstantExpression()) 5884 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 5885 Frame.LambdaThisCaptureField); 5886 } 5887 5888 StmtResult Ret = {Result, ResultSlot}; 5889 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 5890 if (ESR == ESR_Succeeded) { 5891 if (Callee->getReturnType()->isVoidType()) 5892 return true; 5893 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 5894 } 5895 return ESR == ESR_Returned; 5896 } 5897 5898 /// Evaluate a constructor call. 5899 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5900 APValue *ArgValues, 5901 const CXXConstructorDecl *Definition, 5902 EvalInfo &Info, APValue &Result) { 5903 SourceLocation CallLoc = E->getExprLoc(); 5904 if (!Info.CheckCallLimit(CallLoc)) 5905 return false; 5906 5907 const CXXRecordDecl *RD = Definition->getParent(); 5908 if (RD->getNumVBases()) { 5909 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 5910 return false; 5911 } 5912 5913 EvalInfo::EvaluatingConstructorRAII EvalObj( 5914 Info, 5915 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 5916 RD->getNumBases()); 5917 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 5918 5919 // FIXME: Creating an APValue just to hold a nonexistent return value is 5920 // wasteful. 5921 APValue RetVal; 5922 StmtResult Ret = {RetVal, nullptr}; 5923 5924 // If it's a delegating constructor, delegate. 5925 if (Definition->isDelegatingConstructor()) { 5926 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 5927 { 5928 FullExpressionRAII InitScope(Info); 5929 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 5930 !InitScope.destroy()) 5931 return false; 5932 } 5933 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5934 } 5935 5936 // For a trivial copy or move constructor, perform an APValue copy. This is 5937 // essential for unions (or classes with anonymous union members), where the 5938 // operations performed by the constructor cannot be represented by 5939 // ctor-initializers. 5940 // 5941 // Skip this for empty non-union classes; we should not perform an 5942 // lvalue-to-rvalue conversion on them because their copy constructor does not 5943 // actually read them. 5944 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 5945 (Definition->getParent()->isUnion() || 5946 (Definition->isTrivial() && 5947 isReadByLvalueToRvalueConversion(Definition->getParent())))) { 5948 LValue RHS; 5949 RHS.setFrom(Info.Ctx, ArgValues[0]); 5950 return handleLValueToRValueConversion( 5951 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 5952 RHS, Result, Definition->getParent()->isUnion()); 5953 } 5954 5955 // Reserve space for the struct members. 5956 if (!Result.hasValue()) { 5957 if (!RD->isUnion()) 5958 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 5959 std::distance(RD->field_begin(), RD->field_end())); 5960 else 5961 // A union starts with no active member. 5962 Result = APValue((const FieldDecl*)nullptr); 5963 } 5964 5965 if (RD->isInvalidDecl()) return false; 5966 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5967 5968 // A scope for temporaries lifetime-extended by reference members. 5969 BlockScopeRAII LifetimeExtendedScope(Info); 5970 5971 bool Success = true; 5972 unsigned BasesSeen = 0; 5973 #ifndef NDEBUG 5974 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 5975 #endif 5976 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 5977 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 5978 // We might be initializing the same field again if this is an indirect 5979 // field initialization. 5980 if (FieldIt == RD->field_end() || 5981 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 5982 assert(Indirect && "fields out of order?"); 5983 return; 5984 } 5985 5986 // Default-initialize any fields with no explicit initializer. 5987 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 5988 assert(FieldIt != RD->field_end() && "missing field?"); 5989 if (!FieldIt->isUnnamedBitfield()) 5990 Success &= getDefaultInitValue( 5991 FieldIt->getType(), 5992 Result.getStructField(FieldIt->getFieldIndex())); 5993 } 5994 ++FieldIt; 5995 }; 5996 for (const auto *I : Definition->inits()) { 5997 LValue Subobject = This; 5998 LValue SubobjectParent = This; 5999 APValue *Value = &Result; 6000 6001 // Determine the subobject to initialize. 6002 FieldDecl *FD = nullptr; 6003 if (I->isBaseInitializer()) { 6004 QualType BaseType(I->getBaseClass(), 0); 6005 #ifndef NDEBUG 6006 // Non-virtual base classes are initialized in the order in the class 6007 // definition. We have already checked for virtual base classes. 6008 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6009 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6010 "base class initializers not in expected order"); 6011 ++BaseIt; 6012 #endif 6013 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6014 BaseType->getAsCXXRecordDecl(), &Layout)) 6015 return false; 6016 Value = &Result.getStructBase(BasesSeen++); 6017 } else if ((FD = I->getMember())) { 6018 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6019 return false; 6020 if (RD->isUnion()) { 6021 Result = APValue(FD); 6022 Value = &Result.getUnionValue(); 6023 } else { 6024 SkipToField(FD, false); 6025 Value = &Result.getStructField(FD->getFieldIndex()); 6026 } 6027 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6028 // Walk the indirect field decl's chain to find the object to initialize, 6029 // and make sure we've initialized every step along it. 6030 auto IndirectFieldChain = IFD->chain(); 6031 for (auto *C : IndirectFieldChain) { 6032 FD = cast<FieldDecl>(C); 6033 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6034 // Switch the union field if it differs. This happens if we had 6035 // preceding zero-initialization, and we're now initializing a union 6036 // subobject other than the first. 6037 // FIXME: In this case, the values of the other subobjects are 6038 // specified, since zero-initialization sets all padding bits to zero. 6039 if (!Value->hasValue() || 6040 (Value->isUnion() && Value->getUnionField() != FD)) { 6041 if (CD->isUnion()) 6042 *Value = APValue(FD); 6043 else 6044 // FIXME: This immediately starts the lifetime of all members of 6045 // an anonymous struct. It would be preferable to strictly start 6046 // member lifetime in initialization order. 6047 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6048 } 6049 // Store Subobject as its parent before updating it for the last element 6050 // in the chain. 6051 if (C == IndirectFieldChain.back()) 6052 SubobjectParent = Subobject; 6053 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6054 return false; 6055 if (CD->isUnion()) 6056 Value = &Value->getUnionValue(); 6057 else { 6058 if (C == IndirectFieldChain.front() && !RD->isUnion()) 6059 SkipToField(FD, true); 6060 Value = &Value->getStructField(FD->getFieldIndex()); 6061 } 6062 } 6063 } else { 6064 llvm_unreachable("unknown base initializer kind"); 6065 } 6066 6067 // Need to override This for implicit field initializers as in this case 6068 // This refers to innermost anonymous struct/union containing initializer, 6069 // not to currently constructed class. 6070 const Expr *Init = I->getInit(); 6071 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6072 isa<CXXDefaultInitExpr>(Init)); 6073 FullExpressionRAII InitScope(Info); 6074 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6075 (FD && FD->isBitField() && 6076 !truncateBitfieldValue(Info, Init, *Value, FD))) { 6077 // If we're checking for a potential constant expression, evaluate all 6078 // initializers even if some of them fail. 6079 if (!Info.noteFailure()) 6080 return false; 6081 Success = false; 6082 } 6083 6084 // This is the point at which the dynamic type of the object becomes this 6085 // class type. 6086 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6087 EvalObj.finishedConstructingBases(); 6088 } 6089 6090 // Default-initialize any remaining fields. 6091 if (!RD->isUnion()) { 6092 for (; FieldIt != RD->field_end(); ++FieldIt) { 6093 if (!FieldIt->isUnnamedBitfield()) 6094 Success &= getDefaultInitValue( 6095 FieldIt->getType(), 6096 Result.getStructField(FieldIt->getFieldIndex())); 6097 } 6098 } 6099 6100 EvalObj.finishedConstructingFields(); 6101 6102 return Success && 6103 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6104 LifetimeExtendedScope.destroy(); 6105 } 6106 6107 static bool HandleConstructorCall(const Expr *E, const LValue &This, 6108 ArrayRef<const Expr*> Args, 6109 const CXXConstructorDecl *Definition, 6110 EvalInfo &Info, APValue &Result) { 6111 ArgVector ArgValues(Args.size()); 6112 if (!EvaluateArgs(Args, ArgValues, Info, Definition)) 6113 return false; 6114 6115 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 6116 Info, Result); 6117 } 6118 6119 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6120 const LValue &This, APValue &Value, 6121 QualType T) { 6122 // Objects can only be destroyed while they're within their lifetimes. 6123 // FIXME: We have no representation for whether an object of type nullptr_t 6124 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6125 // as indeterminate instead? 6126 if (Value.isAbsent() && !T->isNullPtrType()) { 6127 APValue Printable; 6128 This.moveInto(Printable); 6129 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6130 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6131 return false; 6132 } 6133 6134 // Invent an expression for location purposes. 6135 // FIXME: We shouldn't need to do this. 6136 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 6137 6138 // For arrays, destroy elements right-to-left. 6139 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6140 uint64_t Size = CAT->getSize().getZExtValue(); 6141 QualType ElemT = CAT->getElementType(); 6142 6143 LValue ElemLV = This; 6144 ElemLV.addArray(Info, &LocE, CAT); 6145 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6146 return false; 6147 6148 // Ensure that we have actual array elements available to destroy; the 6149 // destructors might mutate the value, so we can't run them on the array 6150 // filler. 6151 if (Size && Size > Value.getArrayInitializedElts()) 6152 expandArray(Value, Value.getArraySize() - 1); 6153 6154 for (; Size != 0; --Size) { 6155 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6156 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6157 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6158 return false; 6159 } 6160 6161 // End the lifetime of this array now. 6162 Value = APValue(); 6163 return true; 6164 } 6165 6166 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6167 if (!RD) { 6168 if (T.isDestructedType()) { 6169 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6170 return false; 6171 } 6172 6173 Value = APValue(); 6174 return true; 6175 } 6176 6177 if (RD->getNumVBases()) { 6178 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6179 return false; 6180 } 6181 6182 const CXXDestructorDecl *DD = RD->getDestructor(); 6183 if (!DD && !RD->hasTrivialDestructor()) { 6184 Info.FFDiag(CallLoc); 6185 return false; 6186 } 6187 6188 if (!DD || DD->isTrivial() || 6189 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6190 // A trivial destructor just ends the lifetime of the object. Check for 6191 // this case before checking for a body, because we might not bother 6192 // building a body for a trivial destructor. Note that it doesn't matter 6193 // whether the destructor is constexpr in this case; all trivial 6194 // destructors are constexpr. 6195 // 6196 // If an anonymous union would be destroyed, some enclosing destructor must 6197 // have been explicitly defined, and the anonymous union destruction should 6198 // have no effect. 6199 Value = APValue(); 6200 return true; 6201 } 6202 6203 if (!Info.CheckCallLimit(CallLoc)) 6204 return false; 6205 6206 const FunctionDecl *Definition = nullptr; 6207 const Stmt *Body = DD->getBody(Definition); 6208 6209 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6210 return false; 6211 6212 CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr); 6213 6214 // We're now in the period of destruction of this object. 6215 unsigned BasesLeft = RD->getNumBases(); 6216 EvalInfo::EvaluatingDestructorRAII EvalObj( 6217 Info, 6218 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6219 if (!EvalObj.DidInsert) { 6220 // C++2a [class.dtor]p19: 6221 // the behavior is undefined if the destructor is invoked for an object 6222 // whose lifetime has ended 6223 // (Note that formally the lifetime ends when the period of destruction 6224 // begins, even though certain uses of the object remain valid until the 6225 // period of destruction ends.) 6226 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6227 return false; 6228 } 6229 6230 // FIXME: Creating an APValue just to hold a nonexistent return value is 6231 // wasteful. 6232 APValue RetVal; 6233 StmtResult Ret = {RetVal, nullptr}; 6234 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6235 return false; 6236 6237 // A union destructor does not implicitly destroy its members. 6238 if (RD->isUnion()) 6239 return true; 6240 6241 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6242 6243 // We don't have a good way to iterate fields in reverse, so collect all the 6244 // fields first and then walk them backwards. 6245 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6246 for (const FieldDecl *FD : llvm::reverse(Fields)) { 6247 if (FD->isUnnamedBitfield()) 6248 continue; 6249 6250 LValue Subobject = This; 6251 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6252 return false; 6253 6254 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6255 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6256 FD->getType())) 6257 return false; 6258 } 6259 6260 if (BasesLeft != 0) 6261 EvalObj.startedDestroyingBases(); 6262 6263 // Destroy base classes in reverse order. 6264 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6265 --BasesLeft; 6266 6267 QualType BaseType = Base.getType(); 6268 LValue Subobject = This; 6269 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6270 BaseType->getAsCXXRecordDecl(), &Layout)) 6271 return false; 6272 6273 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6274 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6275 BaseType)) 6276 return false; 6277 } 6278 assert(BasesLeft == 0 && "NumBases was wrong?"); 6279 6280 // The period of destruction ends now. The object is gone. 6281 Value = APValue(); 6282 return true; 6283 } 6284 6285 namespace { 6286 struct DestroyObjectHandler { 6287 EvalInfo &Info; 6288 const Expr *E; 6289 const LValue &This; 6290 const AccessKinds AccessKind; 6291 6292 typedef bool result_type; 6293 bool failed() { return false; } 6294 bool found(APValue &Subobj, QualType SubobjType) { 6295 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6296 SubobjType); 6297 } 6298 bool found(APSInt &Value, QualType SubobjType) { 6299 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6300 return false; 6301 } 6302 bool found(APFloat &Value, QualType SubobjType) { 6303 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6304 return false; 6305 } 6306 }; 6307 } 6308 6309 /// Perform a destructor or pseudo-destructor call on the given object, which 6310 /// might in general not be a complete object. 6311 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6312 const LValue &This, QualType ThisType) { 6313 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6314 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6315 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6316 } 6317 6318 /// Destroy and end the lifetime of the given complete object. 6319 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6320 APValue::LValueBase LVBase, APValue &Value, 6321 QualType T) { 6322 // If we've had an unmodeled side-effect, we can't rely on mutable state 6323 // (such as the object we're about to destroy) being correct. 6324 if (Info.EvalStatus.HasSideEffects) 6325 return false; 6326 6327 LValue LV; 6328 LV.set({LVBase}); 6329 return HandleDestructionImpl(Info, Loc, LV, Value, T); 6330 } 6331 6332 /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6333 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6334 LValue &Result) { 6335 if (Info.checkingPotentialConstantExpression() || 6336 Info.SpeculativeEvaluationDepth) 6337 return false; 6338 6339 // This is permitted only within a call to std::allocator<T>::allocate. 6340 auto Caller = Info.getStdAllocatorCaller("allocate"); 6341 if (!Caller) { 6342 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6343 ? diag::note_constexpr_new_untyped 6344 : diag::note_constexpr_new); 6345 return false; 6346 } 6347 6348 QualType ElemType = Caller.ElemType; 6349 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6350 Info.FFDiag(E->getExprLoc(), 6351 diag::note_constexpr_new_not_complete_object_type) 6352 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6353 return false; 6354 } 6355 6356 APSInt ByteSize; 6357 if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6358 return false; 6359 bool IsNothrow = false; 6360 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6361 EvaluateIgnoredValue(Info, E->getArg(I)); 6362 IsNothrow |= E->getType()->isNothrowT(); 6363 } 6364 6365 CharUnits ElemSize; 6366 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6367 return false; 6368 APInt Size, Remainder; 6369 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6370 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6371 if (Remainder != 0) { 6372 // This likely indicates a bug in the implementation of 'std::allocator'. 6373 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6374 << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6375 return false; 6376 } 6377 6378 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6379 if (IsNothrow) { 6380 Result.setNull(Info.Ctx, E->getType()); 6381 return true; 6382 } 6383 6384 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6385 return false; 6386 } 6387 6388 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6389 ArrayType::Normal, 0); 6390 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6391 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6392 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6393 return true; 6394 } 6395 6396 static bool hasVirtualDestructor(QualType T) { 6397 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6398 if (CXXDestructorDecl *DD = RD->getDestructor()) 6399 return DD->isVirtual(); 6400 return false; 6401 } 6402 6403 static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6404 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6405 if (CXXDestructorDecl *DD = RD->getDestructor()) 6406 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6407 return nullptr; 6408 } 6409 6410 /// Check that the given object is a suitable pointer to a heap allocation that 6411 /// still exists and is of the right kind for the purpose of a deletion. 6412 /// 6413 /// On success, returns the heap allocation to deallocate. On failure, produces 6414 /// a diagnostic and returns None. 6415 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6416 const LValue &Pointer, 6417 DynAlloc::Kind DeallocKind) { 6418 auto PointerAsString = [&] { 6419 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6420 }; 6421 6422 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6423 if (!DA) { 6424 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6425 << PointerAsString(); 6426 if (Pointer.Base) 6427 NoteLValueLocation(Info, Pointer.Base); 6428 return None; 6429 } 6430 6431 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6432 if (!Alloc) { 6433 Info.FFDiag(E, diag::note_constexpr_double_delete); 6434 return None; 6435 } 6436 6437 QualType AllocType = Pointer.Base.getDynamicAllocType(); 6438 if (DeallocKind != (*Alloc)->getKind()) { 6439 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6440 << DeallocKind << (*Alloc)->getKind() << AllocType; 6441 NoteLValueLocation(Info, Pointer.Base); 6442 return None; 6443 } 6444 6445 bool Subobject = false; 6446 if (DeallocKind == DynAlloc::New) { 6447 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6448 Pointer.Designator.isOnePastTheEnd(); 6449 } else { 6450 Subobject = Pointer.Designator.Entries.size() != 1 || 6451 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6452 } 6453 if (Subobject) { 6454 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6455 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6456 return None; 6457 } 6458 6459 return Alloc; 6460 } 6461 6462 // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6463 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6464 if (Info.checkingPotentialConstantExpression() || 6465 Info.SpeculativeEvaluationDepth) 6466 return false; 6467 6468 // This is permitted only within a call to std::allocator<T>::deallocate. 6469 if (!Info.getStdAllocatorCaller("deallocate")) { 6470 Info.FFDiag(E->getExprLoc()); 6471 return true; 6472 } 6473 6474 LValue Pointer; 6475 if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6476 return false; 6477 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6478 EvaluateIgnoredValue(Info, E->getArg(I)); 6479 6480 if (Pointer.Designator.Invalid) 6481 return false; 6482 6483 // Deleting a null pointer has no effect. 6484 if (Pointer.isNullPointer()) 6485 return true; 6486 6487 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6488 return false; 6489 6490 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6491 return true; 6492 } 6493 6494 //===----------------------------------------------------------------------===// 6495 // Generic Evaluation 6496 //===----------------------------------------------------------------------===// 6497 namespace { 6498 6499 class BitCastBuffer { 6500 // FIXME: We're going to need bit-level granularity when we support 6501 // bit-fields. 6502 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6503 // we don't support a host or target where that is the case. Still, we should 6504 // use a more generic type in case we ever do. 6505 SmallVector<Optional<unsigned char>, 32> Bytes; 6506 6507 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6508 "Need at least 8 bit unsigned char"); 6509 6510 bool TargetIsLittleEndian; 6511 6512 public: 6513 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6514 : Bytes(Width.getQuantity()), 6515 TargetIsLittleEndian(TargetIsLittleEndian) {} 6516 6517 LLVM_NODISCARD 6518 bool readObject(CharUnits Offset, CharUnits Width, 6519 SmallVectorImpl<unsigned char> &Output) const { 6520 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6521 // If a byte of an integer is uninitialized, then the whole integer is 6522 // uninitalized. 6523 if (!Bytes[I.getQuantity()]) 6524 return false; 6525 Output.push_back(*Bytes[I.getQuantity()]); 6526 } 6527 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6528 std::reverse(Output.begin(), Output.end()); 6529 return true; 6530 } 6531 6532 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6533 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6534 std::reverse(Input.begin(), Input.end()); 6535 6536 size_t Index = 0; 6537 for (unsigned char Byte : Input) { 6538 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6539 Bytes[Offset.getQuantity() + Index] = Byte; 6540 ++Index; 6541 } 6542 } 6543 6544 size_t size() { return Bytes.size(); } 6545 }; 6546 6547 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6548 /// target would represent the value at runtime. 6549 class APValueToBufferConverter { 6550 EvalInfo &Info; 6551 BitCastBuffer Buffer; 6552 const CastExpr *BCE; 6553 6554 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6555 const CastExpr *BCE) 6556 : Info(Info), 6557 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6558 BCE(BCE) {} 6559 6560 bool visit(const APValue &Val, QualType Ty) { 6561 return visit(Val, Ty, CharUnits::fromQuantity(0)); 6562 } 6563 6564 // Write out Val with type Ty into Buffer starting at Offset. 6565 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6566 assert((size_t)Offset.getQuantity() <= Buffer.size()); 6567 6568 // As a special case, nullptr_t has an indeterminate value. 6569 if (Ty->isNullPtrType()) 6570 return true; 6571 6572 // Dig through Src to find the byte at SrcOffset. 6573 switch (Val.getKind()) { 6574 case APValue::Indeterminate: 6575 case APValue::None: 6576 return true; 6577 6578 case APValue::Int: 6579 return visitInt(Val.getInt(), Ty, Offset); 6580 case APValue::Float: 6581 return visitFloat(Val.getFloat(), Ty, Offset); 6582 case APValue::Array: 6583 return visitArray(Val, Ty, Offset); 6584 case APValue::Struct: 6585 return visitRecord(Val, Ty, Offset); 6586 6587 case APValue::ComplexInt: 6588 case APValue::ComplexFloat: 6589 case APValue::Vector: 6590 case APValue::FixedPoint: 6591 // FIXME: We should support these. 6592 6593 case APValue::Union: 6594 case APValue::MemberPointer: 6595 case APValue::AddrLabelDiff: { 6596 Info.FFDiag(BCE->getBeginLoc(), 6597 diag::note_constexpr_bit_cast_unsupported_type) 6598 << Ty; 6599 return false; 6600 } 6601 6602 case APValue::LValue: 6603 llvm_unreachable("LValue subobject in bit_cast?"); 6604 } 6605 llvm_unreachable("Unhandled APValue::ValueKind"); 6606 } 6607 6608 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6609 const RecordDecl *RD = Ty->getAsRecordDecl(); 6610 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6611 6612 // Visit the base classes. 6613 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6614 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6615 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6616 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6617 6618 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6619 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6620 return false; 6621 } 6622 } 6623 6624 // Visit the fields. 6625 unsigned FieldIdx = 0; 6626 for (FieldDecl *FD : RD->fields()) { 6627 if (FD->isBitField()) { 6628 Info.FFDiag(BCE->getBeginLoc(), 6629 diag::note_constexpr_bit_cast_unsupported_bitfield); 6630 return false; 6631 } 6632 6633 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6634 6635 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6636 "only bit-fields can have sub-char alignment"); 6637 CharUnits FieldOffset = 6638 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6639 QualType FieldTy = FD->getType(); 6640 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6641 return false; 6642 ++FieldIdx; 6643 } 6644 6645 return true; 6646 } 6647 6648 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6649 const auto *CAT = 6650 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6651 if (!CAT) 6652 return false; 6653 6654 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6655 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6656 unsigned ArraySize = Val.getArraySize(); 6657 // First, initialize the initialized elements. 6658 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6659 const APValue &SubObj = Val.getArrayInitializedElt(I); 6660 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6661 return false; 6662 } 6663 6664 // Next, initialize the rest of the array using the filler. 6665 if (Val.hasArrayFiller()) { 6666 const APValue &Filler = Val.getArrayFiller(); 6667 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6668 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6669 return false; 6670 } 6671 } 6672 6673 return true; 6674 } 6675 6676 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6677 APSInt AdjustedVal = Val; 6678 unsigned Width = AdjustedVal.getBitWidth(); 6679 if (Ty->isBooleanType()) { 6680 Width = Info.Ctx.getTypeSize(Ty); 6681 AdjustedVal = AdjustedVal.extend(Width); 6682 } 6683 6684 SmallVector<unsigned char, 8> Bytes(Width / 8); 6685 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6686 Buffer.writeObject(Offset, Bytes); 6687 return true; 6688 } 6689 6690 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6691 APSInt AsInt(Val.bitcastToAPInt()); 6692 return visitInt(AsInt, Ty, Offset); 6693 } 6694 6695 public: 6696 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6697 const CastExpr *BCE) { 6698 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6699 APValueToBufferConverter Converter(Info, DstSize, BCE); 6700 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6701 return None; 6702 return Converter.Buffer; 6703 } 6704 }; 6705 6706 /// Write an BitCastBuffer into an APValue. 6707 class BufferToAPValueConverter { 6708 EvalInfo &Info; 6709 const BitCastBuffer &Buffer; 6710 const CastExpr *BCE; 6711 6712 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6713 const CastExpr *BCE) 6714 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6715 6716 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6717 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6718 // Ideally this will be unreachable. 6719 llvm::NoneType unsupportedType(QualType Ty) { 6720 Info.FFDiag(BCE->getBeginLoc(), 6721 diag::note_constexpr_bit_cast_unsupported_type) 6722 << Ty; 6723 return None; 6724 } 6725 6726 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6727 Info.FFDiag(BCE->getBeginLoc(), 6728 diag::note_constexpr_bit_cast_unrepresentable_value) 6729 << Ty << Val.toString(/*Radix=*/10); 6730 return None; 6731 } 6732 6733 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6734 const EnumType *EnumSugar = nullptr) { 6735 if (T->isNullPtrType()) { 6736 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6737 return APValue((Expr *)nullptr, 6738 /*Offset=*/CharUnits::fromQuantity(NullValue), 6739 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6740 } 6741 6742 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6743 6744 // Work around floating point types that contain unused padding bytes. This 6745 // is really just `long double` on x86, which is the only fundamental type 6746 // with padding bytes. 6747 if (T->isRealFloatingType()) { 6748 const llvm::fltSemantics &Semantics = 6749 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6750 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 6751 assert(NumBits % 8 == 0); 6752 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 6753 if (NumBytes != SizeOf) 6754 SizeOf = NumBytes; 6755 } 6756 6757 SmallVector<uint8_t, 8> Bytes; 6758 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6759 // If this is std::byte or unsigned char, then its okay to store an 6760 // indeterminate value. 6761 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 6762 bool IsUChar = 6763 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 6764 T->isSpecificBuiltinType(BuiltinType::Char_U)); 6765 if (!IsStdByte && !IsUChar) { 6766 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 6767 Info.FFDiag(BCE->getExprLoc(), 6768 diag::note_constexpr_bit_cast_indet_dest) 6769 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 6770 return None; 6771 } 6772 6773 return APValue::IndeterminateValue(); 6774 } 6775 6776 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 6777 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 6778 6779 if (T->isIntegralOrEnumerationType()) { 6780 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 6781 6782 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 6783 if (IntWidth != Val.getBitWidth()) { 6784 APSInt Truncated = Val.trunc(IntWidth); 6785 if (Truncated.extend(Val.getBitWidth()) != Val) 6786 return unrepresentableValue(QualType(T, 0), Val); 6787 Val = Truncated; 6788 } 6789 6790 return APValue(Val); 6791 } 6792 6793 if (T->isRealFloatingType()) { 6794 const llvm::fltSemantics &Semantics = 6795 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6796 return APValue(APFloat(Semantics, Val)); 6797 } 6798 6799 return unsupportedType(QualType(T, 0)); 6800 } 6801 6802 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 6803 const RecordDecl *RD = RTy->getAsRecordDecl(); 6804 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6805 6806 unsigned NumBases = 0; 6807 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6808 NumBases = CXXRD->getNumBases(); 6809 6810 APValue ResultVal(APValue::UninitStruct(), NumBases, 6811 std::distance(RD->field_begin(), RD->field_end())); 6812 6813 // Visit the base classes. 6814 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6815 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6816 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6817 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6818 if (BaseDecl->isEmpty() || 6819 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 6820 continue; 6821 6822 Optional<APValue> SubObj = visitType( 6823 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 6824 if (!SubObj) 6825 return None; 6826 ResultVal.getStructBase(I) = *SubObj; 6827 } 6828 } 6829 6830 // Visit the fields. 6831 unsigned FieldIdx = 0; 6832 for (FieldDecl *FD : RD->fields()) { 6833 // FIXME: We don't currently support bit-fields. A lot of the logic for 6834 // this is in CodeGen, so we need to factor it around. 6835 if (FD->isBitField()) { 6836 Info.FFDiag(BCE->getBeginLoc(), 6837 diag::note_constexpr_bit_cast_unsupported_bitfield); 6838 return None; 6839 } 6840 6841 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6842 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 6843 6844 CharUnits FieldOffset = 6845 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 6846 Offset; 6847 QualType FieldTy = FD->getType(); 6848 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 6849 if (!SubObj) 6850 return None; 6851 ResultVal.getStructField(FieldIdx) = *SubObj; 6852 ++FieldIdx; 6853 } 6854 6855 return ResultVal; 6856 } 6857 6858 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 6859 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 6860 assert(!RepresentationType.isNull() && 6861 "enum forward decl should be caught by Sema"); 6862 const auto *AsBuiltin = 6863 RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 6864 // Recurse into the underlying type. Treat std::byte transparently as 6865 // unsigned char. 6866 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 6867 } 6868 6869 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 6870 size_t Size = Ty->getSize().getLimitedValue(); 6871 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 6872 6873 APValue ArrayValue(APValue::UninitArray(), Size, Size); 6874 for (size_t I = 0; I != Size; ++I) { 6875 Optional<APValue> ElementValue = 6876 visitType(Ty->getElementType(), Offset + I * ElementWidth); 6877 if (!ElementValue) 6878 return None; 6879 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 6880 } 6881 6882 return ArrayValue; 6883 } 6884 6885 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 6886 return unsupportedType(QualType(Ty, 0)); 6887 } 6888 6889 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 6890 QualType Can = Ty.getCanonicalType(); 6891 6892 switch (Can->getTypeClass()) { 6893 #define TYPE(Class, Base) \ 6894 case Type::Class: \ 6895 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 6896 #define ABSTRACT_TYPE(Class, Base) 6897 #define NON_CANONICAL_TYPE(Class, Base) \ 6898 case Type::Class: \ 6899 llvm_unreachable("non-canonical type should be impossible!"); 6900 #define DEPENDENT_TYPE(Class, Base) \ 6901 case Type::Class: \ 6902 llvm_unreachable( \ 6903 "dependent types aren't supported in the constant evaluator!"); 6904 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 6905 case Type::Class: \ 6906 llvm_unreachable("either dependent or not canonical!"); 6907 #include "clang/AST/TypeNodes.inc" 6908 } 6909 llvm_unreachable("Unhandled Type::TypeClass"); 6910 } 6911 6912 public: 6913 // Pull out a full value of type DstType. 6914 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 6915 const CastExpr *BCE) { 6916 BufferToAPValueConverter Converter(Info, Buffer, BCE); 6917 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 6918 } 6919 }; 6920 6921 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 6922 QualType Ty, EvalInfo *Info, 6923 const ASTContext &Ctx, 6924 bool CheckingDest) { 6925 Ty = Ty.getCanonicalType(); 6926 6927 auto diag = [&](int Reason) { 6928 if (Info) 6929 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 6930 << CheckingDest << (Reason == 4) << Reason; 6931 return false; 6932 }; 6933 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 6934 if (Info) 6935 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 6936 << NoteTy << Construct << Ty; 6937 return false; 6938 }; 6939 6940 if (Ty->isUnionType()) 6941 return diag(0); 6942 if (Ty->isPointerType()) 6943 return diag(1); 6944 if (Ty->isMemberPointerType()) 6945 return diag(2); 6946 if (Ty.isVolatileQualified()) 6947 return diag(3); 6948 6949 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 6950 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 6951 for (CXXBaseSpecifier &BS : CXXRD->bases()) 6952 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 6953 CheckingDest)) 6954 return note(1, BS.getType(), BS.getBeginLoc()); 6955 } 6956 for (FieldDecl *FD : Record->fields()) { 6957 if (FD->getType()->isReferenceType()) 6958 return diag(4); 6959 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 6960 CheckingDest)) 6961 return note(0, FD->getType(), FD->getBeginLoc()); 6962 } 6963 } 6964 6965 if (Ty->isArrayType() && 6966 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 6967 Info, Ctx, CheckingDest)) 6968 return false; 6969 6970 return true; 6971 } 6972 6973 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 6974 const ASTContext &Ctx, 6975 const CastExpr *BCE) { 6976 bool DestOK = checkBitCastConstexprEligibilityType( 6977 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 6978 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 6979 BCE->getBeginLoc(), 6980 BCE->getSubExpr()->getType(), Info, Ctx, false); 6981 return SourceOK; 6982 } 6983 6984 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 6985 APValue &SourceValue, 6986 const CastExpr *BCE) { 6987 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 6988 "no host or target supports non 8-bit chars"); 6989 assert(SourceValue.isLValue() && 6990 "LValueToRValueBitcast requires an lvalue operand!"); 6991 6992 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 6993 return false; 6994 6995 LValue SourceLValue; 6996 APValue SourceRValue; 6997 SourceLValue.setFrom(Info.Ctx, SourceValue); 6998 if (!handleLValueToRValueConversion( 6999 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7000 SourceRValue, /*WantObjectRepresentation=*/true)) 7001 return false; 7002 7003 // Read out SourceValue into a char buffer. 7004 Optional<BitCastBuffer> Buffer = 7005 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7006 if (!Buffer) 7007 return false; 7008 7009 // Write out the buffer into a new APValue. 7010 Optional<APValue> MaybeDestValue = 7011 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7012 if (!MaybeDestValue) 7013 return false; 7014 7015 DestValue = std::move(*MaybeDestValue); 7016 return true; 7017 } 7018 7019 template <class Derived> 7020 class ExprEvaluatorBase 7021 : public ConstStmtVisitor<Derived, bool> { 7022 private: 7023 Derived &getDerived() { return static_cast<Derived&>(*this); } 7024 bool DerivedSuccess(const APValue &V, const Expr *E) { 7025 return getDerived().Success(V, E); 7026 } 7027 bool DerivedZeroInitialization(const Expr *E) { 7028 return getDerived().ZeroInitialization(E); 7029 } 7030 7031 // Check whether a conditional operator with a non-constant condition is a 7032 // potential constant expression. If neither arm is a potential constant 7033 // expression, then the conditional operator is not either. 7034 template<typename ConditionalOperator> 7035 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7036 assert(Info.checkingPotentialConstantExpression()); 7037 7038 // Speculatively evaluate both arms. 7039 SmallVector<PartialDiagnosticAt, 8> Diag; 7040 { 7041 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7042 StmtVisitorTy::Visit(E->getFalseExpr()); 7043 if (Diag.empty()) 7044 return; 7045 } 7046 7047 { 7048 SpeculativeEvaluationRAII Speculate(Info, &Diag); 7049 Diag.clear(); 7050 StmtVisitorTy::Visit(E->getTrueExpr()); 7051 if (Diag.empty()) 7052 return; 7053 } 7054 7055 Error(E, diag::note_constexpr_conditional_never_const); 7056 } 7057 7058 7059 template<typename ConditionalOperator> 7060 bool HandleConditionalOperator(const ConditionalOperator *E) { 7061 bool BoolResult; 7062 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7063 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7064 CheckPotentialConstantConditional(E); 7065 return false; 7066 } 7067 if (Info.noteFailure()) { 7068 StmtVisitorTy::Visit(E->getTrueExpr()); 7069 StmtVisitorTy::Visit(E->getFalseExpr()); 7070 } 7071 return false; 7072 } 7073 7074 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7075 return StmtVisitorTy::Visit(EvalExpr); 7076 } 7077 7078 protected: 7079 EvalInfo &Info; 7080 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7081 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7082 7083 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7084 return Info.CCEDiag(E, D); 7085 } 7086 7087 bool ZeroInitialization(const Expr *E) { return Error(E); } 7088 7089 public: 7090 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7091 7092 EvalInfo &getEvalInfo() { return Info; } 7093 7094 /// Report an evaluation error. This should only be called when an error is 7095 /// first discovered. When propagating an error, just return false. 7096 bool Error(const Expr *E, diag::kind D) { 7097 Info.FFDiag(E, D); 7098 return false; 7099 } 7100 bool Error(const Expr *E) { 7101 return Error(E, diag::note_invalid_subexpr_in_const_expr); 7102 } 7103 7104 bool VisitStmt(const Stmt *) { 7105 llvm_unreachable("Expression evaluator should not be called on stmts"); 7106 } 7107 bool VisitExpr(const Expr *E) { 7108 return Error(E); 7109 } 7110 7111 bool VisitConstantExpr(const ConstantExpr *E) { 7112 if (E->hasAPValueResult()) 7113 return DerivedSuccess(E->getAPValueResult(), E); 7114 7115 return StmtVisitorTy::Visit(E->getSubExpr()); 7116 } 7117 7118 bool VisitParenExpr(const ParenExpr *E) 7119 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7120 bool VisitUnaryExtension(const UnaryOperator *E) 7121 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7122 bool VisitUnaryPlus(const UnaryOperator *E) 7123 { return StmtVisitorTy::Visit(E->getSubExpr()); } 7124 bool VisitChooseExpr(const ChooseExpr *E) 7125 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7126 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7127 { return StmtVisitorTy::Visit(E->getResultExpr()); } 7128 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7129 { return StmtVisitorTy::Visit(E->getReplacement()); } 7130 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7131 TempVersionRAII RAII(*Info.CurrentCall); 7132 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7133 return StmtVisitorTy::Visit(E->getExpr()); 7134 } 7135 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7136 TempVersionRAII RAII(*Info.CurrentCall); 7137 // The initializer may not have been parsed yet, or might be erroneous. 7138 if (!E->getExpr()) 7139 return Error(E); 7140 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7141 return StmtVisitorTy::Visit(E->getExpr()); 7142 } 7143 7144 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7145 FullExpressionRAII Scope(Info); 7146 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7147 } 7148 7149 // Temporaries are registered when created, so we don't care about 7150 // CXXBindTemporaryExpr. 7151 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7152 return StmtVisitorTy::Visit(E->getSubExpr()); 7153 } 7154 7155 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7156 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7157 return static_cast<Derived*>(this)->VisitCastExpr(E); 7158 } 7159 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7160 if (!Info.Ctx.getLangOpts().CPlusPlus20) 7161 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7162 return static_cast<Derived*>(this)->VisitCastExpr(E); 7163 } 7164 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7165 return static_cast<Derived*>(this)->VisitCastExpr(E); 7166 } 7167 7168 bool VisitBinaryOperator(const BinaryOperator *E) { 7169 switch (E->getOpcode()) { 7170 default: 7171 return Error(E); 7172 7173 case BO_Comma: 7174 VisitIgnoredValue(E->getLHS()); 7175 return StmtVisitorTy::Visit(E->getRHS()); 7176 7177 case BO_PtrMemD: 7178 case BO_PtrMemI: { 7179 LValue Obj; 7180 if (!HandleMemberPointerAccess(Info, E, Obj)) 7181 return false; 7182 APValue Result; 7183 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7184 return false; 7185 return DerivedSuccess(Result, E); 7186 } 7187 } 7188 } 7189 7190 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7191 return StmtVisitorTy::Visit(E->getSemanticForm()); 7192 } 7193 7194 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7195 // Evaluate and cache the common expression. We treat it as a temporary, 7196 // even though it's not quite the same thing. 7197 LValue CommonLV; 7198 if (!Evaluate(Info.CurrentCall->createTemporary( 7199 E->getOpaqueValue(), 7200 getStorageType(Info.Ctx, E->getOpaqueValue()), false, 7201 CommonLV), 7202 Info, E->getCommon())) 7203 return false; 7204 7205 return HandleConditionalOperator(E); 7206 } 7207 7208 bool VisitConditionalOperator(const ConditionalOperator *E) { 7209 bool IsBcpCall = false; 7210 // If the condition (ignoring parens) is a __builtin_constant_p call, 7211 // the result is a constant expression if it can be folded without 7212 // side-effects. This is an important GNU extension. See GCC PR38377 7213 // for discussion. 7214 if (const CallExpr *CallCE = 7215 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7216 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7217 IsBcpCall = true; 7218 7219 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7220 // constant expression; we can't check whether it's potentially foldable. 7221 // FIXME: We should instead treat __builtin_constant_p as non-constant if 7222 // it would return 'false' in this mode. 7223 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7224 return false; 7225 7226 FoldConstant Fold(Info, IsBcpCall); 7227 if (!HandleConditionalOperator(E)) { 7228 Fold.keepDiagnostics(); 7229 return false; 7230 } 7231 7232 return true; 7233 } 7234 7235 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7236 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7237 return DerivedSuccess(*Value, E); 7238 7239 const Expr *Source = E->getSourceExpr(); 7240 if (!Source) 7241 return Error(E); 7242 if (Source == E) { // sanity checking. 7243 assert(0 && "OpaqueValueExpr recursively refers to itself"); 7244 return Error(E); 7245 } 7246 return StmtVisitorTy::Visit(Source); 7247 } 7248 7249 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7250 for (const Expr *SemE : E->semantics()) { 7251 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7252 // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7253 // result expression: there could be two different LValues that would 7254 // refer to the same object in that case, and we can't model that. 7255 if (SemE == E->getResultExpr()) 7256 return Error(E); 7257 7258 // Unique OVEs get evaluated if and when we encounter them when 7259 // emitting the rest of the semantic form, rather than eagerly. 7260 if (OVE->isUnique()) 7261 continue; 7262 7263 LValue LV; 7264 if (!Evaluate(Info.CurrentCall->createTemporary( 7265 OVE, getStorageType(Info.Ctx, OVE), false, LV), 7266 Info, OVE->getSourceExpr())) 7267 return false; 7268 } else if (SemE == E->getResultExpr()) { 7269 if (!StmtVisitorTy::Visit(SemE)) 7270 return false; 7271 } else { 7272 if (!EvaluateIgnoredValue(Info, SemE)) 7273 return false; 7274 } 7275 } 7276 return true; 7277 } 7278 7279 bool VisitCallExpr(const CallExpr *E) { 7280 APValue Result; 7281 if (!handleCallExpr(E, Result, nullptr)) 7282 return false; 7283 return DerivedSuccess(Result, E); 7284 } 7285 7286 bool handleCallExpr(const CallExpr *E, APValue &Result, 7287 const LValue *ResultSlot) { 7288 const Expr *Callee = E->getCallee()->IgnoreParens(); 7289 QualType CalleeType = Callee->getType(); 7290 7291 const FunctionDecl *FD = nullptr; 7292 LValue *This = nullptr, ThisVal; 7293 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7294 bool HasQualifier = false; 7295 7296 ArgVector ArgValues; 7297 7298 // Extract function decl and 'this' pointer from the callee. 7299 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7300 const CXXMethodDecl *Member = nullptr; 7301 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7302 // Explicit bound member calls, such as x.f() or p->g(); 7303 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7304 return false; 7305 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7306 if (!Member) 7307 return Error(Callee); 7308 This = &ThisVal; 7309 HasQualifier = ME->hasQualifier(); 7310 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7311 // Indirect bound member calls ('.*' or '->*'). 7312 const ValueDecl *D = 7313 HandleMemberPointerAccess(Info, BE, ThisVal, false); 7314 if (!D) 7315 return false; 7316 Member = dyn_cast<CXXMethodDecl>(D); 7317 if (!Member) 7318 return Error(Callee); 7319 This = &ThisVal; 7320 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7321 if (!Info.getLangOpts().CPlusPlus20) 7322 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7323 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7324 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7325 } else 7326 return Error(Callee); 7327 FD = Member; 7328 } else if (CalleeType->isFunctionPointerType()) { 7329 LValue Call; 7330 if (!EvaluatePointer(Callee, Call, Info)) 7331 return false; 7332 7333 if (!Call.getLValueOffset().isZero()) 7334 return Error(Callee); 7335 FD = dyn_cast_or_null<FunctionDecl>( 7336 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 7337 if (!FD) 7338 return Error(Callee); 7339 // Don't call function pointers which have been cast to some other type. 7340 // Per DR (no number yet), the caller and callee can differ in noexcept. 7341 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7342 CalleeType->getPointeeType(), FD->getType())) { 7343 return Error(E); 7344 } 7345 7346 // For an (overloaded) assignment expression, evaluate the RHS before the 7347 // LHS. 7348 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7349 if (OCE && OCE->isAssignmentOp()) { 7350 assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7351 if (isa<CXXMethodDecl>(FD)) { 7352 // Args[0] is the object argument. 7353 if (!EvaluateArgs({Args[1]}, ArgValues, Info, FD)) 7354 return false; 7355 } else { 7356 if (!EvaluateArgs({Args[1], Args[0]}, ArgValues, Info, FD)) 7357 return false; 7358 std::swap(ArgValues[0], ArgValues[1]); 7359 } 7360 } 7361 7362 // Overloaded operator calls to member functions are represented as normal 7363 // calls with '*this' as the first argument. 7364 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7365 if (MD && !MD->isStatic()) { 7366 // FIXME: When selecting an implicit conversion for an overloaded 7367 // operator delete, we sometimes try to evaluate calls to conversion 7368 // operators without a 'this' parameter! 7369 if (Args.empty()) 7370 return Error(E); 7371 7372 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7373 return false; 7374 This = &ThisVal; 7375 Args = Args.slice(1); 7376 } else if (MD && MD->isLambdaStaticInvoker()) { 7377 // Map the static invoker for the lambda back to the call operator. 7378 // Conveniently, we don't have to slice out the 'this' argument (as is 7379 // being done for the non-static case), since a static member function 7380 // doesn't have an implicit argument passed in. 7381 const CXXRecordDecl *ClosureClass = MD->getParent(); 7382 assert( 7383 ClosureClass->captures_begin() == ClosureClass->captures_end() && 7384 "Number of captures must be zero for conversion to function-ptr"); 7385 7386 const CXXMethodDecl *LambdaCallOp = 7387 ClosureClass->getLambdaCallOperator(); 7388 7389 // Set 'FD', the function that will be called below, to the call 7390 // operator. If the closure object represents a generic lambda, find 7391 // the corresponding specialization of the call operator. 7392 7393 if (ClosureClass->isGenericLambda()) { 7394 assert(MD->isFunctionTemplateSpecialization() && 7395 "A generic lambda's static-invoker function must be a " 7396 "template specialization"); 7397 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7398 FunctionTemplateDecl *CallOpTemplate = 7399 LambdaCallOp->getDescribedFunctionTemplate(); 7400 void *InsertPos = nullptr; 7401 FunctionDecl *CorrespondingCallOpSpecialization = 7402 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7403 assert(CorrespondingCallOpSpecialization && 7404 "We must always have a function call operator specialization " 7405 "that corresponds to our static invoker specialization"); 7406 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7407 } else 7408 FD = LambdaCallOp; 7409 } else if (FD->isReplaceableGlobalAllocationFunction()) { 7410 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7411 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7412 LValue Ptr; 7413 if (!HandleOperatorNewCall(Info, E, Ptr)) 7414 return false; 7415 Ptr.moveInto(Result); 7416 return true; 7417 } else { 7418 return HandleOperatorDeleteCall(Info, E); 7419 } 7420 } 7421 } else 7422 return Error(E); 7423 7424 // Evaluate the arguments now if we've not already done so. 7425 if (ArgValues.empty() && !Args.empty() && 7426 !EvaluateArgs(Args, ArgValues, Info, FD)) 7427 return false; 7428 7429 SmallVector<QualType, 4> CovariantAdjustmentPath; 7430 if (This) { 7431 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7432 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7433 // Perform virtual dispatch, if necessary. 7434 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7435 CovariantAdjustmentPath); 7436 if (!FD) 7437 return false; 7438 } else { 7439 // Check that the 'this' pointer points to an object of the right type. 7440 // FIXME: If this is an assignment operator call, we may need to change 7441 // the active union member before we check this. 7442 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7443 return false; 7444 } 7445 } 7446 7447 // Destructor calls are different enough that they have their own codepath. 7448 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7449 assert(This && "no 'this' pointer for destructor call"); 7450 assert(ArgValues.empty() && "unexpected destructor arguments"); 7451 return HandleDestruction(Info, E, *This, 7452 Info.Ctx.getRecordType(DD->getParent())); 7453 } 7454 7455 const FunctionDecl *Definition = nullptr; 7456 Stmt *Body = FD->getBody(Definition); 7457 7458 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7459 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, 7460 ArgValues.data(), Body, Info, Result, ResultSlot)) 7461 return false; 7462 7463 if (!CovariantAdjustmentPath.empty() && 7464 !HandleCovariantReturnAdjustment(Info, E, Result, 7465 CovariantAdjustmentPath)) 7466 return false; 7467 7468 return true; 7469 } 7470 7471 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7472 return StmtVisitorTy::Visit(E->getInitializer()); 7473 } 7474 bool VisitInitListExpr(const InitListExpr *E) { 7475 if (E->getNumInits() == 0) 7476 return DerivedZeroInitialization(E); 7477 if (E->getNumInits() == 1) 7478 return StmtVisitorTy::Visit(E->getInit(0)); 7479 return Error(E); 7480 } 7481 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7482 return DerivedZeroInitialization(E); 7483 } 7484 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7485 return DerivedZeroInitialization(E); 7486 } 7487 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7488 return DerivedZeroInitialization(E); 7489 } 7490 7491 /// A member expression where the object is a prvalue is itself a prvalue. 7492 bool VisitMemberExpr(const MemberExpr *E) { 7493 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7494 "missing temporary materialization conversion"); 7495 assert(!E->isArrow() && "missing call to bound member function?"); 7496 7497 APValue Val; 7498 if (!Evaluate(Val, Info, E->getBase())) 7499 return false; 7500 7501 QualType BaseTy = E->getBase()->getType(); 7502 7503 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7504 if (!FD) return Error(E); 7505 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7506 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7507 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7508 7509 // Note: there is no lvalue base here. But this case should only ever 7510 // happen in C or in C++98, where we cannot be evaluating a constexpr 7511 // constructor, which is the only case the base matters. 7512 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7513 SubobjectDesignator Designator(BaseTy); 7514 Designator.addDeclUnchecked(FD); 7515 7516 APValue Result; 7517 return extractSubobject(Info, E, Obj, Designator, Result) && 7518 DerivedSuccess(Result, E); 7519 } 7520 7521 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7522 APValue Val; 7523 if (!Evaluate(Val, Info, E->getBase())) 7524 return false; 7525 7526 if (Val.isVector()) { 7527 SmallVector<uint32_t, 4> Indices; 7528 E->getEncodedElementAccess(Indices); 7529 if (Indices.size() == 1) { 7530 // Return scalar. 7531 return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7532 } else { 7533 // Construct new APValue vector. 7534 SmallVector<APValue, 4> Elts; 7535 for (unsigned I = 0; I < Indices.size(); ++I) { 7536 Elts.push_back(Val.getVectorElt(Indices[I])); 7537 } 7538 APValue VecResult(Elts.data(), Indices.size()); 7539 return DerivedSuccess(VecResult, E); 7540 } 7541 } 7542 7543 return false; 7544 } 7545 7546 bool VisitCastExpr(const CastExpr *E) { 7547 switch (E->getCastKind()) { 7548 default: 7549 break; 7550 7551 case CK_AtomicToNonAtomic: { 7552 APValue AtomicVal; 7553 // This does not need to be done in place even for class/array types: 7554 // atomic-to-non-atomic conversion implies copying the object 7555 // representation. 7556 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7557 return false; 7558 return DerivedSuccess(AtomicVal, E); 7559 } 7560 7561 case CK_NoOp: 7562 case CK_UserDefinedConversion: 7563 return StmtVisitorTy::Visit(E->getSubExpr()); 7564 7565 case CK_LValueToRValue: { 7566 LValue LVal; 7567 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7568 return false; 7569 APValue RVal; 7570 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7571 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7572 LVal, RVal)) 7573 return false; 7574 return DerivedSuccess(RVal, E); 7575 } 7576 case CK_LValueToRValueBitCast: { 7577 APValue DestValue, SourceValue; 7578 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7579 return false; 7580 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7581 return false; 7582 return DerivedSuccess(DestValue, E); 7583 } 7584 7585 case CK_AddressSpaceConversion: { 7586 APValue Value; 7587 if (!Evaluate(Value, Info, E->getSubExpr())) 7588 return false; 7589 return DerivedSuccess(Value, E); 7590 } 7591 } 7592 7593 return Error(E); 7594 } 7595 7596 bool VisitUnaryPostInc(const UnaryOperator *UO) { 7597 return VisitUnaryPostIncDec(UO); 7598 } 7599 bool VisitUnaryPostDec(const UnaryOperator *UO) { 7600 return VisitUnaryPostIncDec(UO); 7601 } 7602 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7603 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7604 return Error(UO); 7605 7606 LValue LVal; 7607 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7608 return false; 7609 APValue RVal; 7610 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7611 UO->isIncrementOp(), &RVal)) 7612 return false; 7613 return DerivedSuccess(RVal, UO); 7614 } 7615 7616 bool VisitStmtExpr(const StmtExpr *E) { 7617 // We will have checked the full-expressions inside the statement expression 7618 // when they were completed, and don't need to check them again now. 7619 if (Info.checkingForUndefinedBehavior()) 7620 return Error(E); 7621 7622 const CompoundStmt *CS = E->getSubStmt(); 7623 if (CS->body_empty()) 7624 return true; 7625 7626 BlockScopeRAII Scope(Info); 7627 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7628 BE = CS->body_end(); 7629 /**/; ++BI) { 7630 if (BI + 1 == BE) { 7631 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7632 if (!FinalExpr) { 7633 Info.FFDiag((*BI)->getBeginLoc(), 7634 diag::note_constexpr_stmt_expr_unsupported); 7635 return false; 7636 } 7637 return this->Visit(FinalExpr) && Scope.destroy(); 7638 } 7639 7640 APValue ReturnValue; 7641 StmtResult Result = { ReturnValue, nullptr }; 7642 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7643 if (ESR != ESR_Succeeded) { 7644 // FIXME: If the statement-expression terminated due to 'return', 7645 // 'break', or 'continue', it would be nice to propagate that to 7646 // the outer statement evaluation rather than bailing out. 7647 if (ESR != ESR_Failed) 7648 Info.FFDiag((*BI)->getBeginLoc(), 7649 diag::note_constexpr_stmt_expr_unsupported); 7650 return false; 7651 } 7652 } 7653 7654 llvm_unreachable("Return from function from the loop above."); 7655 } 7656 7657 /// Visit a value which is evaluated, but whose value is ignored. 7658 void VisitIgnoredValue(const Expr *E) { 7659 EvaluateIgnoredValue(Info, E); 7660 } 7661 7662 /// Potentially visit a MemberExpr's base expression. 7663 void VisitIgnoredBaseExpression(const Expr *E) { 7664 // While MSVC doesn't evaluate the base expression, it does diagnose the 7665 // presence of side-effecting behavior. 7666 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7667 return; 7668 VisitIgnoredValue(E); 7669 } 7670 }; 7671 7672 } // namespace 7673 7674 //===----------------------------------------------------------------------===// 7675 // Common base class for lvalue and temporary evaluation. 7676 //===----------------------------------------------------------------------===// 7677 namespace { 7678 template<class Derived> 7679 class LValueExprEvaluatorBase 7680 : public ExprEvaluatorBase<Derived> { 7681 protected: 7682 LValue &Result; 7683 bool InvalidBaseOK; 7684 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7685 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7686 7687 bool Success(APValue::LValueBase B) { 7688 Result.set(B); 7689 return true; 7690 } 7691 7692 bool evaluatePointer(const Expr *E, LValue &Result) { 7693 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7694 } 7695 7696 public: 7697 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7698 : ExprEvaluatorBaseTy(Info), Result(Result), 7699 InvalidBaseOK(InvalidBaseOK) {} 7700 7701 bool Success(const APValue &V, const Expr *E) { 7702 Result.setFrom(this->Info.Ctx, V); 7703 return true; 7704 } 7705 7706 bool VisitMemberExpr(const MemberExpr *E) { 7707 // Handle non-static data members. 7708 QualType BaseTy; 7709 bool EvalOK; 7710 if (E->isArrow()) { 7711 EvalOK = evaluatePointer(E->getBase(), Result); 7712 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7713 } else if (E->getBase()->isRValue()) { 7714 assert(E->getBase()->getType()->isRecordType()); 7715 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7716 BaseTy = E->getBase()->getType(); 7717 } else { 7718 EvalOK = this->Visit(E->getBase()); 7719 BaseTy = E->getBase()->getType(); 7720 } 7721 if (!EvalOK) { 7722 if (!InvalidBaseOK) 7723 return false; 7724 Result.setInvalid(E); 7725 return true; 7726 } 7727 7728 const ValueDecl *MD = E->getMemberDecl(); 7729 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7730 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7731 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7732 (void)BaseTy; 7733 if (!HandleLValueMember(this->Info, E, Result, FD)) 7734 return false; 7735 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7736 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7737 return false; 7738 } else 7739 return this->Error(E); 7740 7741 if (MD->getType()->isReferenceType()) { 7742 APValue RefValue; 7743 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7744 RefValue)) 7745 return false; 7746 return Success(RefValue, E); 7747 } 7748 return true; 7749 } 7750 7751 bool VisitBinaryOperator(const BinaryOperator *E) { 7752 switch (E->getOpcode()) { 7753 default: 7754 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7755 7756 case BO_PtrMemD: 7757 case BO_PtrMemI: 7758 return HandleMemberPointerAccess(this->Info, E, Result); 7759 } 7760 } 7761 7762 bool VisitCastExpr(const CastExpr *E) { 7763 switch (E->getCastKind()) { 7764 default: 7765 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7766 7767 case CK_DerivedToBase: 7768 case CK_UncheckedDerivedToBase: 7769 if (!this->Visit(E->getSubExpr())) 7770 return false; 7771 7772 // Now figure out the necessary offset to add to the base LV to get from 7773 // the derived class to the base class. 7774 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 7775 Result); 7776 } 7777 } 7778 }; 7779 } 7780 7781 //===----------------------------------------------------------------------===// 7782 // LValue Evaluation 7783 // 7784 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 7785 // function designators (in C), decl references to void objects (in C), and 7786 // temporaries (if building with -Wno-address-of-temporary). 7787 // 7788 // LValue evaluation produces values comprising a base expression of one of the 7789 // following types: 7790 // - Declarations 7791 // * VarDecl 7792 // * FunctionDecl 7793 // - Literals 7794 // * CompoundLiteralExpr in C (and in global scope in C++) 7795 // * StringLiteral 7796 // * PredefinedExpr 7797 // * ObjCStringLiteralExpr 7798 // * ObjCEncodeExpr 7799 // * AddrLabelExpr 7800 // * BlockExpr 7801 // * CallExpr for a MakeStringConstant builtin 7802 // - typeid(T) expressions, as TypeInfoLValues 7803 // - Locals and temporaries 7804 // * MaterializeTemporaryExpr 7805 // * Any Expr, with a CallIndex indicating the function in which the temporary 7806 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 7807 // from the AST (FIXME). 7808 // * A MaterializeTemporaryExpr that has static storage duration, with no 7809 // CallIndex, for a lifetime-extended temporary. 7810 // * The ConstantExpr that is currently being evaluated during evaluation of an 7811 // immediate invocation. 7812 // plus an offset in bytes. 7813 //===----------------------------------------------------------------------===// 7814 namespace { 7815 class LValueExprEvaluator 7816 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 7817 public: 7818 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 7819 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 7820 7821 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 7822 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 7823 7824 bool VisitDeclRefExpr(const DeclRefExpr *E); 7825 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 7826 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 7827 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 7828 bool VisitMemberExpr(const MemberExpr *E); 7829 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 7830 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 7831 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 7832 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 7833 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 7834 bool VisitUnaryDeref(const UnaryOperator *E); 7835 bool VisitUnaryReal(const UnaryOperator *E); 7836 bool VisitUnaryImag(const UnaryOperator *E); 7837 bool VisitUnaryPreInc(const UnaryOperator *UO) { 7838 return VisitUnaryPreIncDec(UO); 7839 } 7840 bool VisitUnaryPreDec(const UnaryOperator *UO) { 7841 return VisitUnaryPreIncDec(UO); 7842 } 7843 bool VisitBinAssign(const BinaryOperator *BO); 7844 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 7845 7846 bool VisitCastExpr(const CastExpr *E) { 7847 switch (E->getCastKind()) { 7848 default: 7849 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 7850 7851 case CK_LValueBitCast: 7852 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7853 if (!Visit(E->getSubExpr())) 7854 return false; 7855 Result.Designator.setInvalid(); 7856 return true; 7857 7858 case CK_BaseToDerived: 7859 if (!Visit(E->getSubExpr())) 7860 return false; 7861 return HandleBaseToDerivedCast(Info, E, Result); 7862 7863 case CK_Dynamic: 7864 if (!Visit(E->getSubExpr())) 7865 return false; 7866 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 7867 } 7868 } 7869 }; 7870 } // end anonymous namespace 7871 7872 /// Evaluate an expression as an lvalue. This can be legitimately called on 7873 /// expressions which are not glvalues, in three cases: 7874 /// * function designators in C, and 7875 /// * "extern void" objects 7876 /// * @selector() expressions in Objective-C 7877 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 7878 bool InvalidBaseOK) { 7879 assert(E->isGLValue() || E->getType()->isFunctionType() || 7880 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 7881 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 7882 } 7883 7884 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 7885 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 7886 return Success(FD); 7887 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 7888 return VisitVarDecl(E, VD); 7889 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 7890 return Visit(BD->getBinding()); 7891 if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(E->getDecl())) 7892 return Success(GD); 7893 return Error(E); 7894 } 7895 7896 7897 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 7898 7899 // If we are within a lambda's call operator, check whether the 'VD' referred 7900 // to within 'E' actually represents a lambda-capture that maps to a 7901 // data-member/field within the closure object, and if so, evaluate to the 7902 // field or what the field refers to. 7903 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 7904 isa<DeclRefExpr>(E) && 7905 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 7906 // We don't always have a complete capture-map when checking or inferring if 7907 // the function call operator meets the requirements of a constexpr function 7908 // - but we don't need to evaluate the captures to determine constexprness 7909 // (dcl.constexpr C++17). 7910 if (Info.checkingPotentialConstantExpression()) 7911 return false; 7912 7913 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 7914 // Start with 'Result' referring to the complete closure object... 7915 Result = *Info.CurrentCall->This; 7916 // ... then update it to refer to the field of the closure object 7917 // that represents the capture. 7918 if (!HandleLValueMember(Info, E, Result, FD)) 7919 return false; 7920 // And if the field is of reference type, update 'Result' to refer to what 7921 // the field refers to. 7922 if (FD->getType()->isReferenceType()) { 7923 APValue RVal; 7924 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 7925 RVal)) 7926 return false; 7927 Result.setFrom(Info.Ctx, RVal); 7928 } 7929 return true; 7930 } 7931 } 7932 CallStackFrame *Frame = nullptr; 7933 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 7934 // Only if a local variable was declared in the function currently being 7935 // evaluated, do we expect to be able to find its value in the current 7936 // frame. (Otherwise it was likely declared in an enclosing context and 7937 // could either have a valid evaluatable value (for e.g. a constexpr 7938 // variable) or be ill-formed (and trigger an appropriate evaluation 7939 // diagnostic)). 7940 if (Info.CurrentCall->Callee && 7941 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 7942 Frame = Info.CurrentCall; 7943 } 7944 } 7945 7946 if (!VD->getType()->isReferenceType()) { 7947 if (Frame) { 7948 Result.set({VD, Frame->Index, 7949 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 7950 return true; 7951 } 7952 return Success(VD); 7953 } 7954 7955 APValue *V; 7956 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 7957 return false; 7958 if (!V->hasValue()) { 7959 // FIXME: Is it possible for V to be indeterminate here? If so, we should 7960 // adjust the diagnostic to say that. 7961 if (!Info.checkingPotentialConstantExpression()) 7962 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 7963 return false; 7964 } 7965 return Success(*V, E); 7966 } 7967 7968 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 7969 const MaterializeTemporaryExpr *E) { 7970 // Walk through the expression to find the materialized temporary itself. 7971 SmallVector<const Expr *, 2> CommaLHSs; 7972 SmallVector<SubobjectAdjustment, 2> Adjustments; 7973 const Expr *Inner = 7974 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 7975 7976 // If we passed any comma operators, evaluate their LHSs. 7977 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 7978 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 7979 return false; 7980 7981 // A materialized temporary with static storage duration can appear within the 7982 // result of a constant expression evaluation, so we need to preserve its 7983 // value for use outside this evaluation. 7984 APValue *Value; 7985 if (E->getStorageDuration() == SD_Static) { 7986 Value = E->getOrCreateValue(true); 7987 *Value = APValue(); 7988 Result.set(E); 7989 } else { 7990 Value = &Info.CurrentCall->createTemporary( 7991 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result); 7992 } 7993 7994 QualType Type = Inner->getType(); 7995 7996 // Materialize the temporary itself. 7997 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 7998 *Value = APValue(); 7999 return false; 8000 } 8001 8002 // Adjust our lvalue to refer to the desired subobject. 8003 for (unsigned I = Adjustments.size(); I != 0; /**/) { 8004 --I; 8005 switch (Adjustments[I].Kind) { 8006 case SubobjectAdjustment::DerivedToBaseAdjustment: 8007 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8008 Type, Result)) 8009 return false; 8010 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8011 break; 8012 8013 case SubobjectAdjustment::FieldAdjustment: 8014 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8015 return false; 8016 Type = Adjustments[I].Field->getType(); 8017 break; 8018 8019 case SubobjectAdjustment::MemberPointerAdjustment: 8020 if (!HandleMemberPointerAccess(this->Info, Type, Result, 8021 Adjustments[I].Ptr.RHS)) 8022 return false; 8023 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8024 break; 8025 } 8026 } 8027 8028 return true; 8029 } 8030 8031 bool 8032 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8033 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8034 "lvalue compound literal in c++?"); 8035 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8036 // only see this when folding in C, so there's no standard to follow here. 8037 return Success(E); 8038 } 8039 8040 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8041 TypeInfoLValue TypeInfo; 8042 8043 if (!E->isPotentiallyEvaluated()) { 8044 if (E->isTypeOperand()) 8045 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8046 else 8047 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8048 } else { 8049 if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8050 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8051 << E->getExprOperand()->getType() 8052 << E->getExprOperand()->getSourceRange(); 8053 } 8054 8055 if (!Visit(E->getExprOperand())) 8056 return false; 8057 8058 Optional<DynamicType> DynType = 8059 ComputeDynamicType(Info, E, Result, AK_TypeId); 8060 if (!DynType) 8061 return false; 8062 8063 TypeInfo = 8064 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8065 } 8066 8067 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8068 } 8069 8070 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8071 return Success(E->getGuidDecl()); 8072 } 8073 8074 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8075 // Handle static data members. 8076 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8077 VisitIgnoredBaseExpression(E->getBase()); 8078 return VisitVarDecl(E, VD); 8079 } 8080 8081 // Handle static member functions. 8082 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8083 if (MD->isStatic()) { 8084 VisitIgnoredBaseExpression(E->getBase()); 8085 return Success(MD); 8086 } 8087 } 8088 8089 // Handle non-static data members. 8090 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8091 } 8092 8093 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8094 // FIXME: Deal with vectors as array subscript bases. 8095 if (E->getBase()->getType()->isVectorType()) 8096 return Error(E); 8097 8098 APSInt Index; 8099 bool Success = true; 8100 8101 // C++17's rules require us to evaluate the LHS first, regardless of which 8102 // side is the base. 8103 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8104 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8105 : !EvaluateInteger(SubExpr, Index, Info)) { 8106 if (!Info.noteFailure()) 8107 return false; 8108 Success = false; 8109 } 8110 } 8111 8112 return Success && 8113 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8114 } 8115 8116 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8117 return evaluatePointer(E->getSubExpr(), Result); 8118 } 8119 8120 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8121 if (!Visit(E->getSubExpr())) 8122 return false; 8123 // __real is a no-op on scalar lvalues. 8124 if (E->getSubExpr()->getType()->isAnyComplexType()) 8125 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8126 return true; 8127 } 8128 8129 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8130 assert(E->getSubExpr()->getType()->isAnyComplexType() && 8131 "lvalue __imag__ on scalar?"); 8132 if (!Visit(E->getSubExpr())) 8133 return false; 8134 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8135 return true; 8136 } 8137 8138 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8139 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8140 return Error(UO); 8141 8142 if (!this->Visit(UO->getSubExpr())) 8143 return false; 8144 8145 return handleIncDec( 8146 this->Info, UO, Result, UO->getSubExpr()->getType(), 8147 UO->isIncrementOp(), nullptr); 8148 } 8149 8150 bool LValueExprEvaluator::VisitCompoundAssignOperator( 8151 const CompoundAssignOperator *CAO) { 8152 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8153 return Error(CAO); 8154 8155 bool Success = true; 8156 8157 // C++17 onwards require that we evaluate the RHS first. 8158 APValue RHS; 8159 if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8160 if (!Info.noteFailure()) 8161 return false; 8162 Success = false; 8163 } 8164 8165 // The overall lvalue result is the result of evaluating the LHS. 8166 if (!this->Visit(CAO->getLHS()) || !Success) 8167 return false; 8168 8169 return handleCompoundAssignment( 8170 this->Info, CAO, 8171 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8172 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8173 } 8174 8175 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8176 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8177 return Error(E); 8178 8179 bool Success = true; 8180 8181 // C++17 onwards require that we evaluate the RHS first. 8182 APValue NewVal; 8183 if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8184 if (!Info.noteFailure()) 8185 return false; 8186 Success = false; 8187 } 8188 8189 if (!this->Visit(E->getLHS()) || !Success) 8190 return false; 8191 8192 if (Info.getLangOpts().CPlusPlus20 && 8193 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8194 return false; 8195 8196 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8197 NewVal); 8198 } 8199 8200 //===----------------------------------------------------------------------===// 8201 // Pointer Evaluation 8202 //===----------------------------------------------------------------------===// 8203 8204 /// Attempts to compute the number of bytes available at the pointer 8205 /// returned by a function with the alloc_size attribute. Returns true if we 8206 /// were successful. Places an unsigned number into `Result`. 8207 /// 8208 /// This expects the given CallExpr to be a call to a function with an 8209 /// alloc_size attribute. 8210 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8211 const CallExpr *Call, 8212 llvm::APInt &Result) { 8213 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8214 8215 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8216 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8217 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8218 if (Call->getNumArgs() <= SizeArgNo) 8219 return false; 8220 8221 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8222 Expr::EvalResult ExprResult; 8223 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8224 return false; 8225 Into = ExprResult.Val.getInt(); 8226 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8227 return false; 8228 Into = Into.zextOrSelf(BitsInSizeT); 8229 return true; 8230 }; 8231 8232 APSInt SizeOfElem; 8233 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8234 return false; 8235 8236 if (!AllocSize->getNumElemsParam().isValid()) { 8237 Result = std::move(SizeOfElem); 8238 return true; 8239 } 8240 8241 APSInt NumberOfElems; 8242 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8243 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8244 return false; 8245 8246 bool Overflow; 8247 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8248 if (Overflow) 8249 return false; 8250 8251 Result = std::move(BytesAvailable); 8252 return true; 8253 } 8254 8255 /// Convenience function. LVal's base must be a call to an alloc_size 8256 /// function. 8257 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8258 const LValue &LVal, 8259 llvm::APInt &Result) { 8260 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8261 "Can't get the size of a non alloc_size function"); 8262 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8263 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8264 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8265 } 8266 8267 /// Attempts to evaluate the given LValueBase as the result of a call to 8268 /// a function with the alloc_size attribute. If it was possible to do so, this 8269 /// function will return true, make Result's Base point to said function call, 8270 /// and mark Result's Base as invalid. 8271 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8272 LValue &Result) { 8273 if (Base.isNull()) 8274 return false; 8275 8276 // Because we do no form of static analysis, we only support const variables. 8277 // 8278 // Additionally, we can't support parameters, nor can we support static 8279 // variables (in the latter case, use-before-assign isn't UB; in the former, 8280 // we have no clue what they'll be assigned to). 8281 const auto *VD = 8282 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8283 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8284 return false; 8285 8286 const Expr *Init = VD->getAnyInitializer(); 8287 if (!Init) 8288 return false; 8289 8290 const Expr *E = Init->IgnoreParens(); 8291 if (!tryUnwrapAllocSizeCall(E)) 8292 return false; 8293 8294 // Store E instead of E unwrapped so that the type of the LValue's base is 8295 // what the user wanted. 8296 Result.setInvalid(E); 8297 8298 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8299 Result.addUnsizedArray(Info, E, Pointee); 8300 return true; 8301 } 8302 8303 namespace { 8304 class PointerExprEvaluator 8305 : public ExprEvaluatorBase<PointerExprEvaluator> { 8306 LValue &Result; 8307 bool InvalidBaseOK; 8308 8309 bool Success(const Expr *E) { 8310 Result.set(E); 8311 return true; 8312 } 8313 8314 bool evaluateLValue(const Expr *E, LValue &Result) { 8315 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8316 } 8317 8318 bool evaluatePointer(const Expr *E, LValue &Result) { 8319 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8320 } 8321 8322 bool visitNonBuiltinCallExpr(const CallExpr *E); 8323 public: 8324 8325 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8326 : ExprEvaluatorBaseTy(info), Result(Result), 8327 InvalidBaseOK(InvalidBaseOK) {} 8328 8329 bool Success(const APValue &V, const Expr *E) { 8330 Result.setFrom(Info.Ctx, V); 8331 return true; 8332 } 8333 bool ZeroInitialization(const Expr *E) { 8334 Result.setNull(Info.Ctx, E->getType()); 8335 return true; 8336 } 8337 8338 bool VisitBinaryOperator(const BinaryOperator *E); 8339 bool VisitCastExpr(const CastExpr* E); 8340 bool VisitUnaryAddrOf(const UnaryOperator *E); 8341 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8342 { return Success(E); } 8343 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8344 if (E->isExpressibleAsConstantInitializer()) 8345 return Success(E); 8346 if (Info.noteFailure()) 8347 EvaluateIgnoredValue(Info, E->getSubExpr()); 8348 return Error(E); 8349 } 8350 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8351 { return Success(E); } 8352 bool VisitCallExpr(const CallExpr *E); 8353 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8354 bool VisitBlockExpr(const BlockExpr *E) { 8355 if (!E->getBlockDecl()->hasCaptures()) 8356 return Success(E); 8357 return Error(E); 8358 } 8359 bool VisitCXXThisExpr(const CXXThisExpr *E) { 8360 // Can't look at 'this' when checking a potential constant expression. 8361 if (Info.checkingPotentialConstantExpression()) 8362 return false; 8363 if (!Info.CurrentCall->This) { 8364 if (Info.getLangOpts().CPlusPlus11) 8365 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8366 else 8367 Info.FFDiag(E); 8368 return false; 8369 } 8370 Result = *Info.CurrentCall->This; 8371 // If we are inside a lambda's call operator, the 'this' expression refers 8372 // to the enclosing '*this' object (either by value or reference) which is 8373 // either copied into the closure object's field that represents the '*this' 8374 // or refers to '*this'. 8375 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8376 // Ensure we actually have captured 'this'. (an error will have 8377 // been previously reported if not). 8378 if (!Info.CurrentCall->LambdaThisCaptureField) 8379 return false; 8380 8381 // Update 'Result' to refer to the data member/field of the closure object 8382 // that represents the '*this' capture. 8383 if (!HandleLValueMember(Info, E, Result, 8384 Info.CurrentCall->LambdaThisCaptureField)) 8385 return false; 8386 // If we captured '*this' by reference, replace the field with its referent. 8387 if (Info.CurrentCall->LambdaThisCaptureField->getType() 8388 ->isPointerType()) { 8389 APValue RVal; 8390 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8391 RVal)) 8392 return false; 8393 8394 Result.setFrom(Info.Ctx, RVal); 8395 } 8396 } 8397 return true; 8398 } 8399 8400 bool VisitCXXNewExpr(const CXXNewExpr *E); 8401 8402 bool VisitSourceLocExpr(const SourceLocExpr *E) { 8403 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8404 APValue LValResult = E->EvaluateInContext( 8405 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8406 Result.setFrom(Info.Ctx, LValResult); 8407 return true; 8408 } 8409 8410 // FIXME: Missing: @protocol, @selector 8411 }; 8412 } // end anonymous namespace 8413 8414 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8415 bool InvalidBaseOK) { 8416 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8417 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8418 } 8419 8420 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8421 if (E->getOpcode() != BO_Add && 8422 E->getOpcode() != BO_Sub) 8423 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8424 8425 const Expr *PExp = E->getLHS(); 8426 const Expr *IExp = E->getRHS(); 8427 if (IExp->getType()->isPointerType()) 8428 std::swap(PExp, IExp); 8429 8430 bool EvalPtrOK = evaluatePointer(PExp, Result); 8431 if (!EvalPtrOK && !Info.noteFailure()) 8432 return false; 8433 8434 llvm::APSInt Offset; 8435 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8436 return false; 8437 8438 if (E->getOpcode() == BO_Sub) 8439 negateAsSigned(Offset); 8440 8441 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8442 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8443 } 8444 8445 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8446 return evaluateLValue(E->getSubExpr(), Result); 8447 } 8448 8449 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8450 const Expr *SubExpr = E->getSubExpr(); 8451 8452 switch (E->getCastKind()) { 8453 default: 8454 break; 8455 case CK_BitCast: 8456 case CK_CPointerToObjCPointerCast: 8457 case CK_BlockPointerToObjCPointerCast: 8458 case CK_AnyPointerToBlockPointerCast: 8459 case CK_AddressSpaceConversion: 8460 if (!Visit(SubExpr)) 8461 return false; 8462 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8463 // permitted in constant expressions in C++11. Bitcasts from cv void* are 8464 // also static_casts, but we disallow them as a resolution to DR1312. 8465 if (!E->getType()->isVoidPointerType()) { 8466 if (!Result.InvalidBase && !Result.Designator.Invalid && 8467 !Result.IsNullPtr && 8468 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8469 E->getType()->getPointeeType()) && 8470 Info.getStdAllocatorCaller("allocate")) { 8471 // Inside a call to std::allocator::allocate and friends, we permit 8472 // casting from void* back to cv1 T* for a pointer that points to a 8473 // cv2 T. 8474 } else { 8475 Result.Designator.setInvalid(); 8476 if (SubExpr->getType()->isVoidPointerType()) 8477 CCEDiag(E, diag::note_constexpr_invalid_cast) 8478 << 3 << SubExpr->getType(); 8479 else 8480 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8481 } 8482 } 8483 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8484 ZeroInitialization(E); 8485 return true; 8486 8487 case CK_DerivedToBase: 8488 case CK_UncheckedDerivedToBase: 8489 if (!evaluatePointer(E->getSubExpr(), Result)) 8490 return false; 8491 if (!Result.Base && Result.Offset.isZero()) 8492 return true; 8493 8494 // Now figure out the necessary offset to add to the base LV to get from 8495 // the derived class to the base class. 8496 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8497 castAs<PointerType>()->getPointeeType(), 8498 Result); 8499 8500 case CK_BaseToDerived: 8501 if (!Visit(E->getSubExpr())) 8502 return false; 8503 if (!Result.Base && Result.Offset.isZero()) 8504 return true; 8505 return HandleBaseToDerivedCast(Info, E, Result); 8506 8507 case CK_Dynamic: 8508 if (!Visit(E->getSubExpr())) 8509 return false; 8510 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8511 8512 case CK_NullToPointer: 8513 VisitIgnoredValue(E->getSubExpr()); 8514 return ZeroInitialization(E); 8515 8516 case CK_IntegralToPointer: { 8517 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8518 8519 APValue Value; 8520 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8521 break; 8522 8523 if (Value.isInt()) { 8524 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8525 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8526 Result.Base = (Expr*)nullptr; 8527 Result.InvalidBase = false; 8528 Result.Offset = CharUnits::fromQuantity(N); 8529 Result.Designator.setInvalid(); 8530 Result.IsNullPtr = false; 8531 return true; 8532 } else { 8533 // Cast is of an lvalue, no need to change value. 8534 Result.setFrom(Info.Ctx, Value); 8535 return true; 8536 } 8537 } 8538 8539 case CK_ArrayToPointerDecay: { 8540 if (SubExpr->isGLValue()) { 8541 if (!evaluateLValue(SubExpr, Result)) 8542 return false; 8543 } else { 8544 APValue &Value = Info.CurrentCall->createTemporary( 8545 SubExpr, SubExpr->getType(), false, Result); 8546 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8547 return false; 8548 } 8549 // The result is a pointer to the first element of the array. 8550 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8551 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8552 Result.addArray(Info, E, CAT); 8553 else 8554 Result.addUnsizedArray(Info, E, AT->getElementType()); 8555 return true; 8556 } 8557 8558 case CK_FunctionToPointerDecay: 8559 return evaluateLValue(SubExpr, Result); 8560 8561 case CK_LValueToRValue: { 8562 LValue LVal; 8563 if (!evaluateLValue(E->getSubExpr(), LVal)) 8564 return false; 8565 8566 APValue RVal; 8567 // Note, we use the subexpression's type in order to retain cv-qualifiers. 8568 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8569 LVal, RVal)) 8570 return InvalidBaseOK && 8571 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8572 return Success(RVal, E); 8573 } 8574 } 8575 8576 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8577 } 8578 8579 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8580 UnaryExprOrTypeTrait ExprKind) { 8581 // C++ [expr.alignof]p3: 8582 // When alignof is applied to a reference type, the result is the 8583 // alignment of the referenced type. 8584 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8585 T = Ref->getPointeeType(); 8586 8587 if (T.getQualifiers().hasUnaligned()) 8588 return CharUnits::One(); 8589 8590 const bool AlignOfReturnsPreferred = 8591 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8592 8593 // __alignof is defined to return the preferred alignment. 8594 // Before 8, clang returned the preferred alignment for alignof and _Alignof 8595 // as well. 8596 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8597 return Info.Ctx.toCharUnitsFromBits( 8598 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8599 // alignof and _Alignof are defined to return the ABI alignment. 8600 else if (ExprKind == UETT_AlignOf) 8601 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8602 else 8603 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8604 } 8605 8606 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8607 UnaryExprOrTypeTrait ExprKind) { 8608 E = E->IgnoreParens(); 8609 8610 // The kinds of expressions that we have special-case logic here for 8611 // should be kept up to date with the special checks for those 8612 // expressions in Sema. 8613 8614 // alignof decl is always accepted, even if it doesn't make sense: we default 8615 // to 1 in those cases. 8616 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8617 return Info.Ctx.getDeclAlign(DRE->getDecl(), 8618 /*RefAsPointee*/true); 8619 8620 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8621 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8622 /*RefAsPointee*/true); 8623 8624 return GetAlignOfType(Info, E->getType(), ExprKind); 8625 } 8626 8627 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8628 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8629 return Info.Ctx.getDeclAlign(VD); 8630 if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8631 return GetAlignOfExpr(Info, E, UETT_AlignOf); 8632 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8633 } 8634 8635 /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8636 /// __builtin_is_aligned and __builtin_assume_aligned. 8637 static bool getAlignmentArgument(const Expr *E, QualType ForType, 8638 EvalInfo &Info, APSInt &Alignment) { 8639 if (!EvaluateInteger(E, Alignment, Info)) 8640 return false; 8641 if (Alignment < 0 || !Alignment.isPowerOf2()) { 8642 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8643 return false; 8644 } 8645 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8646 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8647 if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8648 Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8649 << MaxValue << ForType << Alignment; 8650 return false; 8651 } 8652 // Ensure both alignment and source value have the same bit width so that we 8653 // don't assert when computing the resulting value. 8654 APSInt ExtAlignment = 8655 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8656 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8657 "Alignment should not be changed by ext/trunc"); 8658 Alignment = ExtAlignment; 8659 assert(Alignment.getBitWidth() == SrcWidth); 8660 return true; 8661 } 8662 8663 // To be clear: this happily visits unsupported builtins. Better name welcomed. 8664 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8665 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8666 return true; 8667 8668 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8669 return false; 8670 8671 Result.setInvalid(E); 8672 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8673 Result.addUnsizedArray(Info, E, PointeeTy); 8674 return true; 8675 } 8676 8677 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8678 if (IsStringLiteralCall(E)) 8679 return Success(E); 8680 8681 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8682 return VisitBuiltinCallExpr(E, BuiltinOp); 8683 8684 return visitNonBuiltinCallExpr(E); 8685 } 8686 8687 // Determine if T is a character type for which we guarantee that 8688 // sizeof(T) == 1. 8689 static bool isOneByteCharacterType(QualType T) { 8690 return T->isCharType() || T->isChar8Type(); 8691 } 8692 8693 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8694 unsigned BuiltinOp) { 8695 switch (BuiltinOp) { 8696 case Builtin::BI__builtin_addressof: 8697 return evaluateLValue(E->getArg(0), Result); 8698 case Builtin::BI__builtin_assume_aligned: { 8699 // We need to be very careful here because: if the pointer does not have the 8700 // asserted alignment, then the behavior is undefined, and undefined 8701 // behavior is non-constant. 8702 if (!evaluatePointer(E->getArg(0), Result)) 8703 return false; 8704 8705 LValue OffsetResult(Result); 8706 APSInt Alignment; 8707 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8708 Alignment)) 8709 return false; 8710 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8711 8712 if (E->getNumArgs() > 2) { 8713 APSInt Offset; 8714 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8715 return false; 8716 8717 int64_t AdditionalOffset = -Offset.getZExtValue(); 8718 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8719 } 8720 8721 // If there is a base object, then it must have the correct alignment. 8722 if (OffsetResult.Base) { 8723 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 8724 8725 if (BaseAlignment < Align) { 8726 Result.Designator.setInvalid(); 8727 // FIXME: Add support to Diagnostic for long / long long. 8728 CCEDiag(E->getArg(0), 8729 diag::note_constexpr_baa_insufficient_alignment) << 0 8730 << (unsigned)BaseAlignment.getQuantity() 8731 << (unsigned)Align.getQuantity(); 8732 return false; 8733 } 8734 } 8735 8736 // The offset must also have the correct alignment. 8737 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 8738 Result.Designator.setInvalid(); 8739 8740 (OffsetResult.Base 8741 ? CCEDiag(E->getArg(0), 8742 diag::note_constexpr_baa_insufficient_alignment) << 1 8743 : CCEDiag(E->getArg(0), 8744 diag::note_constexpr_baa_value_insufficient_alignment)) 8745 << (int)OffsetResult.Offset.getQuantity() 8746 << (unsigned)Align.getQuantity(); 8747 return false; 8748 } 8749 8750 return true; 8751 } 8752 case Builtin::BI__builtin_align_up: 8753 case Builtin::BI__builtin_align_down: { 8754 if (!evaluatePointer(E->getArg(0), Result)) 8755 return false; 8756 APSInt Alignment; 8757 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8758 Alignment)) 8759 return false; 8760 CharUnits BaseAlignment = getBaseAlignment(Info, Result); 8761 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 8762 // For align_up/align_down, we can return the same value if the alignment 8763 // is known to be greater or equal to the requested value. 8764 if (PtrAlign.getQuantity() >= Alignment) 8765 return true; 8766 8767 // The alignment could be greater than the minimum at run-time, so we cannot 8768 // infer much about the resulting pointer value. One case is possible: 8769 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 8770 // can infer the correct index if the requested alignment is smaller than 8771 // the base alignment so we can perform the computation on the offset. 8772 if (BaseAlignment.getQuantity() >= Alignment) { 8773 assert(Alignment.getBitWidth() <= 64 && 8774 "Cannot handle > 64-bit address-space"); 8775 uint64_t Alignment64 = Alignment.getZExtValue(); 8776 CharUnits NewOffset = CharUnits::fromQuantity( 8777 BuiltinOp == Builtin::BI__builtin_align_down 8778 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 8779 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 8780 Result.adjustOffset(NewOffset - Result.Offset); 8781 // TODO: diagnose out-of-bounds values/only allow for arrays? 8782 return true; 8783 } 8784 // Otherwise, we cannot constant-evaluate the result. 8785 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 8786 << Alignment; 8787 return false; 8788 } 8789 case Builtin::BI__builtin_operator_new: 8790 return HandleOperatorNewCall(Info, E, Result); 8791 case Builtin::BI__builtin_launder: 8792 return evaluatePointer(E->getArg(0), Result); 8793 case Builtin::BIstrchr: 8794 case Builtin::BIwcschr: 8795 case Builtin::BImemchr: 8796 case Builtin::BIwmemchr: 8797 if (Info.getLangOpts().CPlusPlus11) 8798 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8799 << /*isConstexpr*/0 << /*isConstructor*/0 8800 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8801 else 8802 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8803 LLVM_FALLTHROUGH; 8804 case Builtin::BI__builtin_strchr: 8805 case Builtin::BI__builtin_wcschr: 8806 case Builtin::BI__builtin_memchr: 8807 case Builtin::BI__builtin_char_memchr: 8808 case Builtin::BI__builtin_wmemchr: { 8809 if (!Visit(E->getArg(0))) 8810 return false; 8811 APSInt Desired; 8812 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 8813 return false; 8814 uint64_t MaxLength = uint64_t(-1); 8815 if (BuiltinOp != Builtin::BIstrchr && 8816 BuiltinOp != Builtin::BIwcschr && 8817 BuiltinOp != Builtin::BI__builtin_strchr && 8818 BuiltinOp != Builtin::BI__builtin_wcschr) { 8819 APSInt N; 8820 if (!EvaluateInteger(E->getArg(2), N, Info)) 8821 return false; 8822 MaxLength = N.getExtValue(); 8823 } 8824 // We cannot find the value if there are no candidates to match against. 8825 if (MaxLength == 0u) 8826 return ZeroInitialization(E); 8827 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 8828 Result.Designator.Invalid) 8829 return false; 8830 QualType CharTy = Result.Designator.getType(Info.Ctx); 8831 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 8832 BuiltinOp == Builtin::BI__builtin_memchr; 8833 assert(IsRawByte || 8834 Info.Ctx.hasSameUnqualifiedType( 8835 CharTy, E->getArg(0)->getType()->getPointeeType())); 8836 // Pointers to const void may point to objects of incomplete type. 8837 if (IsRawByte && CharTy->isIncompleteType()) { 8838 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 8839 return false; 8840 } 8841 // Give up on byte-oriented matching against multibyte elements. 8842 // FIXME: We can compare the bytes in the correct order. 8843 if (IsRawByte && !isOneByteCharacterType(CharTy)) { 8844 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 8845 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 8846 << CharTy; 8847 return false; 8848 } 8849 // Figure out what value we're actually looking for (after converting to 8850 // the corresponding unsigned type if necessary). 8851 uint64_t DesiredVal; 8852 bool StopAtNull = false; 8853 switch (BuiltinOp) { 8854 case Builtin::BIstrchr: 8855 case Builtin::BI__builtin_strchr: 8856 // strchr compares directly to the passed integer, and therefore 8857 // always fails if given an int that is not a char. 8858 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 8859 E->getArg(1)->getType(), 8860 Desired), 8861 Desired)) 8862 return ZeroInitialization(E); 8863 StopAtNull = true; 8864 LLVM_FALLTHROUGH; 8865 case Builtin::BImemchr: 8866 case Builtin::BI__builtin_memchr: 8867 case Builtin::BI__builtin_char_memchr: 8868 // memchr compares by converting both sides to unsigned char. That's also 8869 // correct for strchr if we get this far (to cope with plain char being 8870 // unsigned in the strchr case). 8871 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 8872 break; 8873 8874 case Builtin::BIwcschr: 8875 case Builtin::BI__builtin_wcschr: 8876 StopAtNull = true; 8877 LLVM_FALLTHROUGH; 8878 case Builtin::BIwmemchr: 8879 case Builtin::BI__builtin_wmemchr: 8880 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 8881 DesiredVal = Desired.getZExtValue(); 8882 break; 8883 } 8884 8885 for (; MaxLength; --MaxLength) { 8886 APValue Char; 8887 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 8888 !Char.isInt()) 8889 return false; 8890 if (Char.getInt().getZExtValue() == DesiredVal) 8891 return true; 8892 if (StopAtNull && !Char.getInt()) 8893 break; 8894 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 8895 return false; 8896 } 8897 // Not found: return nullptr. 8898 return ZeroInitialization(E); 8899 } 8900 8901 case Builtin::BImemcpy: 8902 case Builtin::BImemmove: 8903 case Builtin::BIwmemcpy: 8904 case Builtin::BIwmemmove: 8905 if (Info.getLangOpts().CPlusPlus11) 8906 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8907 << /*isConstexpr*/0 << /*isConstructor*/0 8908 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8909 else 8910 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8911 LLVM_FALLTHROUGH; 8912 case Builtin::BI__builtin_memcpy: 8913 case Builtin::BI__builtin_memmove: 8914 case Builtin::BI__builtin_wmemcpy: 8915 case Builtin::BI__builtin_wmemmove: { 8916 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 8917 BuiltinOp == Builtin::BIwmemmove || 8918 BuiltinOp == Builtin::BI__builtin_wmemcpy || 8919 BuiltinOp == Builtin::BI__builtin_wmemmove; 8920 bool Move = BuiltinOp == Builtin::BImemmove || 8921 BuiltinOp == Builtin::BIwmemmove || 8922 BuiltinOp == Builtin::BI__builtin_memmove || 8923 BuiltinOp == Builtin::BI__builtin_wmemmove; 8924 8925 // The result of mem* is the first argument. 8926 if (!Visit(E->getArg(0))) 8927 return false; 8928 LValue Dest = Result; 8929 8930 LValue Src; 8931 if (!EvaluatePointer(E->getArg(1), Src, Info)) 8932 return false; 8933 8934 APSInt N; 8935 if (!EvaluateInteger(E->getArg(2), N, Info)) 8936 return false; 8937 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 8938 8939 // If the size is zero, we treat this as always being a valid no-op. 8940 // (Even if one of the src and dest pointers is null.) 8941 if (!N) 8942 return true; 8943 8944 // Otherwise, if either of the operands is null, we can't proceed. Don't 8945 // try to determine the type of the copied objects, because there aren't 8946 // any. 8947 if (!Src.Base || !Dest.Base) { 8948 APValue Val; 8949 (!Src.Base ? Src : Dest).moveInto(Val); 8950 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 8951 << Move << WChar << !!Src.Base 8952 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 8953 return false; 8954 } 8955 if (Src.Designator.Invalid || Dest.Designator.Invalid) 8956 return false; 8957 8958 // We require that Src and Dest are both pointers to arrays of 8959 // trivially-copyable type. (For the wide version, the designator will be 8960 // invalid if the designated object is not a wchar_t.) 8961 QualType T = Dest.Designator.getType(Info.Ctx); 8962 QualType SrcT = Src.Designator.getType(Info.Ctx); 8963 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 8964 // FIXME: Consider using our bit_cast implementation to support this. 8965 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 8966 return false; 8967 } 8968 if (T->isIncompleteType()) { 8969 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 8970 return false; 8971 } 8972 if (!T.isTriviallyCopyableType(Info.Ctx)) { 8973 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 8974 return false; 8975 } 8976 8977 // Figure out how many T's we're copying. 8978 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 8979 if (!WChar) { 8980 uint64_t Remainder; 8981 llvm::APInt OrigN = N; 8982 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 8983 if (Remainder) { 8984 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8985 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 8986 << (unsigned)TSize; 8987 return false; 8988 } 8989 } 8990 8991 // Check that the copying will remain within the arrays, just so that we 8992 // can give a more meaningful diagnostic. This implicitly also checks that 8993 // N fits into 64 bits. 8994 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 8995 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 8996 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 8997 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8998 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 8999 << N.toString(10, /*Signed*/false); 9000 return false; 9001 } 9002 uint64_t NElems = N.getZExtValue(); 9003 uint64_t NBytes = NElems * TSize; 9004 9005 // Check for overlap. 9006 int Direction = 1; 9007 if (HasSameBase(Src, Dest)) { 9008 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9009 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9010 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9011 // Dest is inside the source region. 9012 if (!Move) { 9013 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9014 return false; 9015 } 9016 // For memmove and friends, copy backwards. 9017 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9018 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9019 return false; 9020 Direction = -1; 9021 } else if (!Move && SrcOffset >= DestOffset && 9022 SrcOffset - DestOffset < NBytes) { 9023 // Src is inside the destination region for memcpy: invalid. 9024 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9025 return false; 9026 } 9027 } 9028 9029 while (true) { 9030 APValue Val; 9031 // FIXME: Set WantObjectRepresentation to true if we're copying a 9032 // char-like type? 9033 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9034 !handleAssignment(Info, E, Dest, T, Val)) 9035 return false; 9036 // Do not iterate past the last element; if we're copying backwards, that 9037 // might take us off the start of the array. 9038 if (--NElems == 0) 9039 return true; 9040 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9041 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9042 return false; 9043 } 9044 } 9045 9046 default: 9047 break; 9048 } 9049 9050 return visitNonBuiltinCallExpr(E); 9051 } 9052 9053 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9054 APValue &Result, const InitListExpr *ILE, 9055 QualType AllocType); 9056 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9057 APValue &Result, 9058 const CXXConstructExpr *CCE, 9059 QualType AllocType); 9060 9061 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9062 if (!Info.getLangOpts().CPlusPlus20) 9063 Info.CCEDiag(E, diag::note_constexpr_new); 9064 9065 // We cannot speculatively evaluate a delete expression. 9066 if (Info.SpeculativeEvaluationDepth) 9067 return false; 9068 9069 FunctionDecl *OperatorNew = E->getOperatorNew(); 9070 9071 bool IsNothrow = false; 9072 bool IsPlacement = false; 9073 if (OperatorNew->isReservedGlobalPlacementOperator() && 9074 Info.CurrentCall->isStdFunction() && !E->isArray()) { 9075 // FIXME Support array placement new. 9076 assert(E->getNumPlacementArgs() == 1); 9077 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9078 return false; 9079 if (Result.Designator.Invalid) 9080 return false; 9081 IsPlacement = true; 9082 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9083 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9084 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9085 return false; 9086 } else if (E->getNumPlacementArgs()) { 9087 // The only new-placement list we support is of the form (std::nothrow). 9088 // 9089 // FIXME: There is no restriction on this, but it's not clear that any 9090 // other form makes any sense. We get here for cases such as: 9091 // 9092 // new (std::align_val_t{N}) X(int) 9093 // 9094 // (which should presumably be valid only if N is a multiple of 9095 // alignof(int), and in any case can't be deallocated unless N is 9096 // alignof(X) and X has new-extended alignment). 9097 if (E->getNumPlacementArgs() != 1 || 9098 !E->getPlacementArg(0)->getType()->isNothrowT()) 9099 return Error(E, diag::note_constexpr_new_placement); 9100 9101 LValue Nothrow; 9102 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9103 return false; 9104 IsNothrow = true; 9105 } 9106 9107 const Expr *Init = E->getInitializer(); 9108 const InitListExpr *ResizedArrayILE = nullptr; 9109 const CXXConstructExpr *ResizedArrayCCE = nullptr; 9110 bool ValueInit = false; 9111 9112 QualType AllocType = E->getAllocatedType(); 9113 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9114 const Expr *Stripped = *ArraySize; 9115 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9116 Stripped = ICE->getSubExpr()) 9117 if (ICE->getCastKind() != CK_NoOp && 9118 ICE->getCastKind() != CK_IntegralCast) 9119 break; 9120 9121 llvm::APSInt ArrayBound; 9122 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9123 return false; 9124 9125 // C++ [expr.new]p9: 9126 // The expression is erroneous if: 9127 // -- [...] its value before converting to size_t [or] applying the 9128 // second standard conversion sequence is less than zero 9129 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9130 if (IsNothrow) 9131 return ZeroInitialization(E); 9132 9133 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9134 << ArrayBound << (*ArraySize)->getSourceRange(); 9135 return false; 9136 } 9137 9138 // -- its value is such that the size of the allocated object would 9139 // exceed the implementation-defined limit 9140 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9141 ArrayBound) > 9142 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9143 if (IsNothrow) 9144 return ZeroInitialization(E); 9145 9146 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9147 << ArrayBound << (*ArraySize)->getSourceRange(); 9148 return false; 9149 } 9150 9151 // -- the new-initializer is a braced-init-list and the number of 9152 // array elements for which initializers are provided [...] 9153 // exceeds the number of elements to initialize 9154 if (!Init) { 9155 // No initialization is performed. 9156 } else if (isa<CXXScalarValueInitExpr>(Init) || 9157 isa<ImplicitValueInitExpr>(Init)) { 9158 ValueInit = true; 9159 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9160 ResizedArrayCCE = CCE; 9161 } else { 9162 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9163 assert(CAT && "unexpected type for array initializer"); 9164 9165 unsigned Bits = 9166 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9167 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9168 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9169 if (InitBound.ugt(AllocBound)) { 9170 if (IsNothrow) 9171 return ZeroInitialization(E); 9172 9173 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9174 << AllocBound.toString(10, /*Signed=*/false) 9175 << InitBound.toString(10, /*Signed=*/false) 9176 << (*ArraySize)->getSourceRange(); 9177 return false; 9178 } 9179 9180 // If the sizes differ, we must have an initializer list, and we need 9181 // special handling for this case when we initialize. 9182 if (InitBound != AllocBound) 9183 ResizedArrayILE = cast<InitListExpr>(Init); 9184 } 9185 9186 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9187 ArrayType::Normal, 0); 9188 } else { 9189 assert(!AllocType->isArrayType() && 9190 "array allocation with non-array new"); 9191 } 9192 9193 APValue *Val; 9194 if (IsPlacement) { 9195 AccessKinds AK = AK_Construct; 9196 struct FindObjectHandler { 9197 EvalInfo &Info; 9198 const Expr *E; 9199 QualType AllocType; 9200 const AccessKinds AccessKind; 9201 APValue *Value; 9202 9203 typedef bool result_type; 9204 bool failed() { return false; } 9205 bool found(APValue &Subobj, QualType SubobjType) { 9206 // FIXME: Reject the cases where [basic.life]p8 would not permit the 9207 // old name of the object to be used to name the new object. 9208 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9209 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9210 SubobjType << AllocType; 9211 return false; 9212 } 9213 Value = &Subobj; 9214 return true; 9215 } 9216 bool found(APSInt &Value, QualType SubobjType) { 9217 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9218 return false; 9219 } 9220 bool found(APFloat &Value, QualType SubobjType) { 9221 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9222 return false; 9223 } 9224 } Handler = {Info, E, AllocType, AK, nullptr}; 9225 9226 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9227 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9228 return false; 9229 9230 Val = Handler.Value; 9231 9232 // [basic.life]p1: 9233 // The lifetime of an object o of type T ends when [...] the storage 9234 // which the object occupies is [...] reused by an object that is not 9235 // nested within o (6.6.2). 9236 *Val = APValue(); 9237 } else { 9238 // Perform the allocation and obtain a pointer to the resulting object. 9239 Val = Info.createHeapAlloc(E, AllocType, Result); 9240 if (!Val) 9241 return false; 9242 } 9243 9244 if (ValueInit) { 9245 ImplicitValueInitExpr VIE(AllocType); 9246 if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9247 return false; 9248 } else if (ResizedArrayILE) { 9249 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9250 AllocType)) 9251 return false; 9252 } else if (ResizedArrayCCE) { 9253 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9254 AllocType)) 9255 return false; 9256 } else if (Init) { 9257 if (!EvaluateInPlace(*Val, Info, Result, Init)) 9258 return false; 9259 } else if (!getDefaultInitValue(AllocType, *Val)) { 9260 return false; 9261 } 9262 9263 // Array new returns a pointer to the first element, not a pointer to the 9264 // array. 9265 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9266 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9267 9268 return true; 9269 } 9270 //===----------------------------------------------------------------------===// 9271 // Member Pointer Evaluation 9272 //===----------------------------------------------------------------------===// 9273 9274 namespace { 9275 class MemberPointerExprEvaluator 9276 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9277 MemberPtr &Result; 9278 9279 bool Success(const ValueDecl *D) { 9280 Result = MemberPtr(D); 9281 return true; 9282 } 9283 public: 9284 9285 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9286 : ExprEvaluatorBaseTy(Info), Result(Result) {} 9287 9288 bool Success(const APValue &V, const Expr *E) { 9289 Result.setFrom(V); 9290 return true; 9291 } 9292 bool ZeroInitialization(const Expr *E) { 9293 return Success((const ValueDecl*)nullptr); 9294 } 9295 9296 bool VisitCastExpr(const CastExpr *E); 9297 bool VisitUnaryAddrOf(const UnaryOperator *E); 9298 }; 9299 } // end anonymous namespace 9300 9301 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9302 EvalInfo &Info) { 9303 assert(E->isRValue() && E->getType()->isMemberPointerType()); 9304 return MemberPointerExprEvaluator(Info, Result).Visit(E); 9305 } 9306 9307 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9308 switch (E->getCastKind()) { 9309 default: 9310 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9311 9312 case CK_NullToMemberPointer: 9313 VisitIgnoredValue(E->getSubExpr()); 9314 return ZeroInitialization(E); 9315 9316 case CK_BaseToDerivedMemberPointer: { 9317 if (!Visit(E->getSubExpr())) 9318 return false; 9319 if (E->path_empty()) 9320 return true; 9321 // Base-to-derived member pointer casts store the path in derived-to-base 9322 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9323 // the wrong end of the derived->base arc, so stagger the path by one class. 9324 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9325 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9326 PathI != PathE; ++PathI) { 9327 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9328 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9329 if (!Result.castToDerived(Derived)) 9330 return Error(E); 9331 } 9332 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9333 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9334 return Error(E); 9335 return true; 9336 } 9337 9338 case CK_DerivedToBaseMemberPointer: 9339 if (!Visit(E->getSubExpr())) 9340 return false; 9341 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9342 PathE = E->path_end(); PathI != PathE; ++PathI) { 9343 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9344 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9345 if (!Result.castToBase(Base)) 9346 return Error(E); 9347 } 9348 return true; 9349 } 9350 } 9351 9352 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9353 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9354 // member can be formed. 9355 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9356 } 9357 9358 //===----------------------------------------------------------------------===// 9359 // Record Evaluation 9360 //===----------------------------------------------------------------------===// 9361 9362 namespace { 9363 class RecordExprEvaluator 9364 : public ExprEvaluatorBase<RecordExprEvaluator> { 9365 const LValue &This; 9366 APValue &Result; 9367 public: 9368 9369 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9370 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9371 9372 bool Success(const APValue &V, const Expr *E) { 9373 Result = V; 9374 return true; 9375 } 9376 bool ZeroInitialization(const Expr *E) { 9377 return ZeroInitialization(E, E->getType()); 9378 } 9379 bool ZeroInitialization(const Expr *E, QualType T); 9380 9381 bool VisitCallExpr(const CallExpr *E) { 9382 return handleCallExpr(E, Result, &This); 9383 } 9384 bool VisitCastExpr(const CastExpr *E); 9385 bool VisitInitListExpr(const InitListExpr *E); 9386 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9387 return VisitCXXConstructExpr(E, E->getType()); 9388 } 9389 bool VisitLambdaExpr(const LambdaExpr *E); 9390 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9391 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9392 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9393 bool VisitBinCmp(const BinaryOperator *E); 9394 }; 9395 } 9396 9397 /// Perform zero-initialization on an object of non-union class type. 9398 /// C++11 [dcl.init]p5: 9399 /// To zero-initialize an object or reference of type T means: 9400 /// [...] 9401 /// -- if T is a (possibly cv-qualified) non-union class type, 9402 /// each non-static data member and each base-class subobject is 9403 /// zero-initialized 9404 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9405 const RecordDecl *RD, 9406 const LValue &This, APValue &Result) { 9407 assert(!RD->isUnion() && "Expected non-union class type"); 9408 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9409 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9410 std::distance(RD->field_begin(), RD->field_end())); 9411 9412 if (RD->isInvalidDecl()) return false; 9413 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9414 9415 if (CD) { 9416 unsigned Index = 0; 9417 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9418 End = CD->bases_end(); I != End; ++I, ++Index) { 9419 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9420 LValue Subobject = This; 9421 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9422 return false; 9423 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9424 Result.getStructBase(Index))) 9425 return false; 9426 } 9427 } 9428 9429 for (const auto *I : RD->fields()) { 9430 // -- if T is a reference type, no initialization is performed. 9431 if (I->getType()->isReferenceType()) 9432 continue; 9433 9434 LValue Subobject = This; 9435 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9436 return false; 9437 9438 ImplicitValueInitExpr VIE(I->getType()); 9439 if (!EvaluateInPlace( 9440 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9441 return false; 9442 } 9443 9444 return true; 9445 } 9446 9447 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9448 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9449 if (RD->isInvalidDecl()) return false; 9450 if (RD->isUnion()) { 9451 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9452 // object's first non-static named data member is zero-initialized 9453 RecordDecl::field_iterator I = RD->field_begin(); 9454 if (I == RD->field_end()) { 9455 Result = APValue((const FieldDecl*)nullptr); 9456 return true; 9457 } 9458 9459 LValue Subobject = This; 9460 if (!HandleLValueMember(Info, E, Subobject, *I)) 9461 return false; 9462 Result = APValue(*I); 9463 ImplicitValueInitExpr VIE(I->getType()); 9464 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9465 } 9466 9467 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9468 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9469 return false; 9470 } 9471 9472 return HandleClassZeroInitialization(Info, E, RD, This, Result); 9473 } 9474 9475 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9476 switch (E->getCastKind()) { 9477 default: 9478 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9479 9480 case CK_ConstructorConversion: 9481 return Visit(E->getSubExpr()); 9482 9483 case CK_DerivedToBase: 9484 case CK_UncheckedDerivedToBase: { 9485 APValue DerivedObject; 9486 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9487 return false; 9488 if (!DerivedObject.isStruct()) 9489 return Error(E->getSubExpr()); 9490 9491 // Derived-to-base rvalue conversion: just slice off the derived part. 9492 APValue *Value = &DerivedObject; 9493 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9494 for (CastExpr::path_const_iterator PathI = E->path_begin(), 9495 PathE = E->path_end(); PathI != PathE; ++PathI) { 9496 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9497 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9498 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9499 RD = Base; 9500 } 9501 Result = *Value; 9502 return true; 9503 } 9504 } 9505 } 9506 9507 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9508 if (E->isTransparent()) 9509 return Visit(E->getInit(0)); 9510 9511 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9512 if (RD->isInvalidDecl()) return false; 9513 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9514 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9515 9516 EvalInfo::EvaluatingConstructorRAII EvalObj( 9517 Info, 9518 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9519 CXXRD && CXXRD->getNumBases()); 9520 9521 if (RD->isUnion()) { 9522 const FieldDecl *Field = E->getInitializedFieldInUnion(); 9523 Result = APValue(Field); 9524 if (!Field) 9525 return true; 9526 9527 // If the initializer list for a union does not contain any elements, the 9528 // first element of the union is value-initialized. 9529 // FIXME: The element should be initialized from an initializer list. 9530 // Is this difference ever observable for initializer lists which 9531 // we don't build? 9532 ImplicitValueInitExpr VIE(Field->getType()); 9533 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9534 9535 LValue Subobject = This; 9536 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9537 return false; 9538 9539 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9540 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9541 isa<CXXDefaultInitExpr>(InitExpr)); 9542 9543 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 9544 } 9545 9546 if (!Result.hasValue()) 9547 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9548 std::distance(RD->field_begin(), RD->field_end())); 9549 unsigned ElementNo = 0; 9550 bool Success = true; 9551 9552 // Initialize base classes. 9553 if (CXXRD && CXXRD->getNumBases()) { 9554 for (const auto &Base : CXXRD->bases()) { 9555 assert(ElementNo < E->getNumInits() && "missing init for base class"); 9556 const Expr *Init = E->getInit(ElementNo); 9557 9558 LValue Subobject = This; 9559 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9560 return false; 9561 9562 APValue &FieldVal = Result.getStructBase(ElementNo); 9563 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9564 if (!Info.noteFailure()) 9565 return false; 9566 Success = false; 9567 } 9568 ++ElementNo; 9569 } 9570 9571 EvalObj.finishedConstructingBases(); 9572 } 9573 9574 // Initialize members. 9575 for (const auto *Field : RD->fields()) { 9576 // Anonymous bit-fields are not considered members of the class for 9577 // purposes of aggregate initialization. 9578 if (Field->isUnnamedBitfield()) 9579 continue; 9580 9581 LValue Subobject = This; 9582 9583 bool HaveInit = ElementNo < E->getNumInits(); 9584 9585 // FIXME: Diagnostics here should point to the end of the initializer 9586 // list, not the start. 9587 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9588 Subobject, Field, &Layout)) 9589 return false; 9590 9591 // Perform an implicit value-initialization for members beyond the end of 9592 // the initializer list. 9593 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9594 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9595 9596 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9597 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9598 isa<CXXDefaultInitExpr>(Init)); 9599 9600 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9601 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9602 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9603 FieldVal, Field))) { 9604 if (!Info.noteFailure()) 9605 return false; 9606 Success = false; 9607 } 9608 } 9609 9610 EvalObj.finishedConstructingFields(); 9611 9612 return Success; 9613 } 9614 9615 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9616 QualType T) { 9617 // Note that E's type is not necessarily the type of our class here; we might 9618 // be initializing an array element instead. 9619 const CXXConstructorDecl *FD = E->getConstructor(); 9620 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9621 9622 bool ZeroInit = E->requiresZeroInitialization(); 9623 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9624 // If we've already performed zero-initialization, we're already done. 9625 if (Result.hasValue()) 9626 return true; 9627 9628 if (ZeroInit) 9629 return ZeroInitialization(E, T); 9630 9631 return getDefaultInitValue(T, Result); 9632 } 9633 9634 const FunctionDecl *Definition = nullptr; 9635 auto Body = FD->getBody(Definition); 9636 9637 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9638 return false; 9639 9640 // Avoid materializing a temporary for an elidable copy/move constructor. 9641 if (E->isElidable() && !ZeroInit) 9642 if (const MaterializeTemporaryExpr *ME 9643 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9644 return Visit(ME->getSubExpr()); 9645 9646 if (ZeroInit && !ZeroInitialization(E, T)) 9647 return false; 9648 9649 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9650 return HandleConstructorCall(E, This, Args, 9651 cast<CXXConstructorDecl>(Definition), Info, 9652 Result); 9653 } 9654 9655 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9656 const CXXInheritedCtorInitExpr *E) { 9657 if (!Info.CurrentCall) { 9658 assert(Info.checkingPotentialConstantExpression()); 9659 return false; 9660 } 9661 9662 const CXXConstructorDecl *FD = E->getConstructor(); 9663 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9664 return false; 9665 9666 const FunctionDecl *Definition = nullptr; 9667 auto Body = FD->getBody(Definition); 9668 9669 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9670 return false; 9671 9672 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9673 cast<CXXConstructorDecl>(Definition), Info, 9674 Result); 9675 } 9676 9677 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9678 const CXXStdInitializerListExpr *E) { 9679 const ConstantArrayType *ArrayType = 9680 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9681 9682 LValue Array; 9683 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9684 return false; 9685 9686 // Get a pointer to the first element of the array. 9687 Array.addArray(Info, E, ArrayType); 9688 9689 auto InvalidType = [&] { 9690 Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9691 << E->getType(); 9692 return false; 9693 }; 9694 9695 // FIXME: Perform the checks on the field types in SemaInit. 9696 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9697 RecordDecl::field_iterator Field = Record->field_begin(); 9698 if (Field == Record->field_end()) 9699 return InvalidType(); 9700 9701 // Start pointer. 9702 if (!Field->getType()->isPointerType() || 9703 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9704 ArrayType->getElementType())) 9705 return InvalidType(); 9706 9707 // FIXME: What if the initializer_list type has base classes, etc? 9708 Result = APValue(APValue::UninitStruct(), 0, 2); 9709 Array.moveInto(Result.getStructField(0)); 9710 9711 if (++Field == Record->field_end()) 9712 return InvalidType(); 9713 9714 if (Field->getType()->isPointerType() && 9715 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9716 ArrayType->getElementType())) { 9717 // End pointer. 9718 if (!HandleLValueArrayAdjustment(Info, E, Array, 9719 ArrayType->getElementType(), 9720 ArrayType->getSize().getZExtValue())) 9721 return false; 9722 Array.moveInto(Result.getStructField(1)); 9723 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9724 // Length. 9725 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9726 else 9727 return InvalidType(); 9728 9729 if (++Field != Record->field_end()) 9730 return InvalidType(); 9731 9732 return true; 9733 } 9734 9735 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 9736 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 9737 if (ClosureClass->isInvalidDecl()) 9738 return false; 9739 9740 const size_t NumFields = 9741 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 9742 9743 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 9744 E->capture_init_end()) && 9745 "The number of lambda capture initializers should equal the number of " 9746 "fields within the closure type"); 9747 9748 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 9749 // Iterate through all the lambda's closure object's fields and initialize 9750 // them. 9751 auto *CaptureInitIt = E->capture_init_begin(); 9752 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 9753 bool Success = true; 9754 for (const auto *Field : ClosureClass->fields()) { 9755 assert(CaptureInitIt != E->capture_init_end()); 9756 // Get the initializer for this field 9757 Expr *const CurFieldInit = *CaptureInitIt++; 9758 9759 // If there is no initializer, either this is a VLA or an error has 9760 // occurred. 9761 if (!CurFieldInit) 9762 return Error(E); 9763 9764 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9765 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 9766 if (!Info.keepEvaluatingAfterFailure()) 9767 return false; 9768 Success = false; 9769 } 9770 ++CaptureIt; 9771 } 9772 return Success; 9773 } 9774 9775 static bool EvaluateRecord(const Expr *E, const LValue &This, 9776 APValue &Result, EvalInfo &Info) { 9777 assert(E->isRValue() && E->getType()->isRecordType() && 9778 "can't evaluate expression as a record rvalue"); 9779 return RecordExprEvaluator(Info, This, Result).Visit(E); 9780 } 9781 9782 //===----------------------------------------------------------------------===// 9783 // Temporary Evaluation 9784 // 9785 // Temporaries are represented in the AST as rvalues, but generally behave like 9786 // lvalues. The full-object of which the temporary is a subobject is implicitly 9787 // materialized so that a reference can bind to it. 9788 //===----------------------------------------------------------------------===// 9789 namespace { 9790 class TemporaryExprEvaluator 9791 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 9792 public: 9793 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 9794 LValueExprEvaluatorBaseTy(Info, Result, false) {} 9795 9796 /// Visit an expression which constructs the value of this temporary. 9797 bool VisitConstructExpr(const Expr *E) { 9798 APValue &Value = 9799 Info.CurrentCall->createTemporary(E, E->getType(), false, Result); 9800 return EvaluateInPlace(Value, Info, Result, E); 9801 } 9802 9803 bool VisitCastExpr(const CastExpr *E) { 9804 switch (E->getCastKind()) { 9805 default: 9806 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 9807 9808 case CK_ConstructorConversion: 9809 return VisitConstructExpr(E->getSubExpr()); 9810 } 9811 } 9812 bool VisitInitListExpr(const InitListExpr *E) { 9813 return VisitConstructExpr(E); 9814 } 9815 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9816 return VisitConstructExpr(E); 9817 } 9818 bool VisitCallExpr(const CallExpr *E) { 9819 return VisitConstructExpr(E); 9820 } 9821 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 9822 return VisitConstructExpr(E); 9823 } 9824 bool VisitLambdaExpr(const LambdaExpr *E) { 9825 return VisitConstructExpr(E); 9826 } 9827 }; 9828 } // end anonymous namespace 9829 9830 /// Evaluate an expression of record type as a temporary. 9831 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 9832 assert(E->isRValue() && E->getType()->isRecordType()); 9833 return TemporaryExprEvaluator(Info, Result).Visit(E); 9834 } 9835 9836 //===----------------------------------------------------------------------===// 9837 // Vector Evaluation 9838 //===----------------------------------------------------------------------===// 9839 9840 namespace { 9841 class VectorExprEvaluator 9842 : public ExprEvaluatorBase<VectorExprEvaluator> { 9843 APValue &Result; 9844 public: 9845 9846 VectorExprEvaluator(EvalInfo &info, APValue &Result) 9847 : ExprEvaluatorBaseTy(info), Result(Result) {} 9848 9849 bool Success(ArrayRef<APValue> V, const Expr *E) { 9850 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 9851 // FIXME: remove this APValue copy. 9852 Result = APValue(V.data(), V.size()); 9853 return true; 9854 } 9855 bool Success(const APValue &V, const Expr *E) { 9856 assert(V.isVector()); 9857 Result = V; 9858 return true; 9859 } 9860 bool ZeroInitialization(const Expr *E); 9861 9862 bool VisitUnaryReal(const UnaryOperator *E) 9863 { return Visit(E->getSubExpr()); } 9864 bool VisitCastExpr(const CastExpr* E); 9865 bool VisitInitListExpr(const InitListExpr *E); 9866 bool VisitUnaryImag(const UnaryOperator *E); 9867 bool VisitBinaryOperator(const BinaryOperator *E); 9868 // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 9869 // conditional select), shufflevector, ExtVectorElementExpr 9870 }; 9871 } // end anonymous namespace 9872 9873 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 9874 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 9875 return VectorExprEvaluator(Info, Result).Visit(E); 9876 } 9877 9878 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 9879 const VectorType *VTy = E->getType()->castAs<VectorType>(); 9880 unsigned NElts = VTy->getNumElements(); 9881 9882 const Expr *SE = E->getSubExpr(); 9883 QualType SETy = SE->getType(); 9884 9885 switch (E->getCastKind()) { 9886 case CK_VectorSplat: { 9887 APValue Val = APValue(); 9888 if (SETy->isIntegerType()) { 9889 APSInt IntResult; 9890 if (!EvaluateInteger(SE, IntResult, Info)) 9891 return false; 9892 Val = APValue(std::move(IntResult)); 9893 } else if (SETy->isRealFloatingType()) { 9894 APFloat FloatResult(0.0); 9895 if (!EvaluateFloat(SE, FloatResult, Info)) 9896 return false; 9897 Val = APValue(std::move(FloatResult)); 9898 } else { 9899 return Error(E); 9900 } 9901 9902 // Splat and create vector APValue. 9903 SmallVector<APValue, 4> Elts(NElts, Val); 9904 return Success(Elts, E); 9905 } 9906 case CK_BitCast: { 9907 // Evaluate the operand into an APInt we can extract from. 9908 llvm::APInt SValInt; 9909 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 9910 return false; 9911 // Extract the elements 9912 QualType EltTy = VTy->getElementType(); 9913 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 9914 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 9915 SmallVector<APValue, 4> Elts; 9916 if (EltTy->isRealFloatingType()) { 9917 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 9918 unsigned FloatEltSize = EltSize; 9919 if (&Sem == &APFloat::x87DoubleExtended()) 9920 FloatEltSize = 80; 9921 for (unsigned i = 0; i < NElts; i++) { 9922 llvm::APInt Elt; 9923 if (BigEndian) 9924 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 9925 else 9926 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 9927 Elts.push_back(APValue(APFloat(Sem, Elt))); 9928 } 9929 } else if (EltTy->isIntegerType()) { 9930 for (unsigned i = 0; i < NElts; i++) { 9931 llvm::APInt Elt; 9932 if (BigEndian) 9933 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 9934 else 9935 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 9936 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 9937 } 9938 } else { 9939 return Error(E); 9940 } 9941 return Success(Elts, E); 9942 } 9943 default: 9944 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9945 } 9946 } 9947 9948 bool 9949 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9950 const VectorType *VT = E->getType()->castAs<VectorType>(); 9951 unsigned NumInits = E->getNumInits(); 9952 unsigned NumElements = VT->getNumElements(); 9953 9954 QualType EltTy = VT->getElementType(); 9955 SmallVector<APValue, 4> Elements; 9956 9957 // The number of initializers can be less than the number of 9958 // vector elements. For OpenCL, this can be due to nested vector 9959 // initialization. For GCC compatibility, missing trailing elements 9960 // should be initialized with zeroes. 9961 unsigned CountInits = 0, CountElts = 0; 9962 while (CountElts < NumElements) { 9963 // Handle nested vector initialization. 9964 if (CountInits < NumInits 9965 && E->getInit(CountInits)->getType()->isVectorType()) { 9966 APValue v; 9967 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 9968 return Error(E); 9969 unsigned vlen = v.getVectorLength(); 9970 for (unsigned j = 0; j < vlen; j++) 9971 Elements.push_back(v.getVectorElt(j)); 9972 CountElts += vlen; 9973 } else if (EltTy->isIntegerType()) { 9974 llvm::APSInt sInt(32); 9975 if (CountInits < NumInits) { 9976 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 9977 return false; 9978 } else // trailing integer zero. 9979 sInt = Info.Ctx.MakeIntValue(0, EltTy); 9980 Elements.push_back(APValue(sInt)); 9981 CountElts++; 9982 } else { 9983 llvm::APFloat f(0.0); 9984 if (CountInits < NumInits) { 9985 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 9986 return false; 9987 } else // trailing float zero. 9988 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 9989 Elements.push_back(APValue(f)); 9990 CountElts++; 9991 } 9992 CountInits++; 9993 } 9994 return Success(Elements, E); 9995 } 9996 9997 bool 9998 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 9999 const auto *VT = E->getType()->castAs<VectorType>(); 10000 QualType EltTy = VT->getElementType(); 10001 APValue ZeroElement; 10002 if (EltTy->isIntegerType()) 10003 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10004 else 10005 ZeroElement = 10006 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10007 10008 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10009 return Success(Elements, E); 10010 } 10011 10012 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10013 VisitIgnoredValue(E->getSubExpr()); 10014 return ZeroInitialization(E); 10015 } 10016 10017 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10018 BinaryOperatorKind Op = E->getOpcode(); 10019 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10020 "Operation not supported on vector types"); 10021 10022 if (Op == BO_Comma) 10023 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10024 10025 Expr *LHS = E->getLHS(); 10026 Expr *RHS = E->getRHS(); 10027 10028 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10029 "Must both be vector types"); 10030 // Checking JUST the types are the same would be fine, except shifts don't 10031 // need to have their types be the same (since you always shift by an int). 10032 assert(LHS->getType()->getAs<VectorType>()->getNumElements() == 10033 E->getType()->getAs<VectorType>()->getNumElements() && 10034 RHS->getType()->getAs<VectorType>()->getNumElements() == 10035 E->getType()->getAs<VectorType>()->getNumElements() && 10036 "All operands must be the same size."); 10037 10038 APValue LHSValue; 10039 APValue RHSValue; 10040 bool LHSOK = Evaluate(LHSValue, Info, LHS); 10041 if (!LHSOK && !Info.noteFailure()) 10042 return false; 10043 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10044 return false; 10045 10046 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10047 return false; 10048 10049 return Success(LHSValue, E); 10050 } 10051 10052 //===----------------------------------------------------------------------===// 10053 // Array Evaluation 10054 //===----------------------------------------------------------------------===// 10055 10056 namespace { 10057 class ArrayExprEvaluator 10058 : public ExprEvaluatorBase<ArrayExprEvaluator> { 10059 const LValue &This; 10060 APValue &Result; 10061 public: 10062 10063 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10064 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10065 10066 bool Success(const APValue &V, const Expr *E) { 10067 assert(V.isArray() && "expected array"); 10068 Result = V; 10069 return true; 10070 } 10071 10072 bool ZeroInitialization(const Expr *E) { 10073 const ConstantArrayType *CAT = 10074 Info.Ctx.getAsConstantArrayType(E->getType()); 10075 if (!CAT) { 10076 if (E->getType()->isIncompleteArrayType()) { 10077 // We can be asked to zero-initialize a flexible array member; this 10078 // is represented as an ImplicitValueInitExpr of incomplete array 10079 // type. In this case, the array has zero elements. 10080 Result = APValue(APValue::UninitArray(), 0, 0); 10081 return true; 10082 } 10083 // FIXME: We could handle VLAs here. 10084 return Error(E); 10085 } 10086 10087 Result = APValue(APValue::UninitArray(), 0, 10088 CAT->getSize().getZExtValue()); 10089 if (!Result.hasArrayFiller()) return true; 10090 10091 // Zero-initialize all elements. 10092 LValue Subobject = This; 10093 Subobject.addArray(Info, E, CAT); 10094 ImplicitValueInitExpr VIE(CAT->getElementType()); 10095 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10096 } 10097 10098 bool VisitCallExpr(const CallExpr *E) { 10099 return handleCallExpr(E, Result, &This); 10100 } 10101 bool VisitInitListExpr(const InitListExpr *E, 10102 QualType AllocType = QualType()); 10103 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10104 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10105 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10106 const LValue &Subobject, 10107 APValue *Value, QualType Type); 10108 bool VisitStringLiteral(const StringLiteral *E, 10109 QualType AllocType = QualType()) { 10110 expandStringLiteral(Info, E, Result, AllocType); 10111 return true; 10112 } 10113 }; 10114 } // end anonymous namespace 10115 10116 static bool EvaluateArray(const Expr *E, const LValue &This, 10117 APValue &Result, EvalInfo &Info) { 10118 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 10119 return ArrayExprEvaluator(Info, This, Result).Visit(E); 10120 } 10121 10122 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10123 APValue &Result, const InitListExpr *ILE, 10124 QualType AllocType) { 10125 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 10126 "not an array rvalue"); 10127 return ArrayExprEvaluator(Info, This, Result) 10128 .VisitInitListExpr(ILE, AllocType); 10129 } 10130 10131 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10132 APValue &Result, 10133 const CXXConstructExpr *CCE, 10134 QualType AllocType) { 10135 assert(CCE->isRValue() && CCE->getType()->isArrayType() && 10136 "not an array rvalue"); 10137 return ArrayExprEvaluator(Info, This, Result) 10138 .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10139 } 10140 10141 // Return true iff the given array filler may depend on the element index. 10142 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10143 // For now, just allow non-class value-initialization and initialization 10144 // lists comprised of them. 10145 if (isa<ImplicitValueInitExpr>(FillerExpr)) 10146 return false; 10147 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10148 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10149 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10150 return true; 10151 } 10152 return false; 10153 } 10154 return true; 10155 } 10156 10157 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10158 QualType AllocType) { 10159 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10160 AllocType.isNull() ? E->getType() : AllocType); 10161 if (!CAT) 10162 return Error(E); 10163 10164 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10165 // an appropriately-typed string literal enclosed in braces. 10166 if (E->isStringLiteralInit()) { 10167 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 10168 // FIXME: Support ObjCEncodeExpr here once we support it in 10169 // ArrayExprEvaluator generally. 10170 if (!SL) 10171 return Error(E); 10172 return VisitStringLiteral(SL, AllocType); 10173 } 10174 10175 bool Success = true; 10176 10177 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10178 "zero-initialized array shouldn't have any initialized elts"); 10179 APValue Filler; 10180 if (Result.isArray() && Result.hasArrayFiller()) 10181 Filler = Result.getArrayFiller(); 10182 10183 unsigned NumEltsToInit = E->getNumInits(); 10184 unsigned NumElts = CAT->getSize().getZExtValue(); 10185 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10186 10187 // If the initializer might depend on the array index, run it for each 10188 // array element. 10189 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10190 NumEltsToInit = NumElts; 10191 10192 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10193 << NumEltsToInit << ".\n"); 10194 10195 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10196 10197 // If the array was previously zero-initialized, preserve the 10198 // zero-initialized values. 10199 if (Filler.hasValue()) { 10200 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10201 Result.getArrayInitializedElt(I) = Filler; 10202 if (Result.hasArrayFiller()) 10203 Result.getArrayFiller() = Filler; 10204 } 10205 10206 LValue Subobject = This; 10207 Subobject.addArray(Info, E, CAT); 10208 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10209 const Expr *Init = 10210 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10211 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10212 Info, Subobject, Init) || 10213 !HandleLValueArrayAdjustment(Info, Init, Subobject, 10214 CAT->getElementType(), 1)) { 10215 if (!Info.noteFailure()) 10216 return false; 10217 Success = false; 10218 } 10219 } 10220 10221 if (!Result.hasArrayFiller()) 10222 return Success; 10223 10224 // If we get here, we have a trivial filler, which we can just evaluate 10225 // once and splat over the rest of the array elements. 10226 assert(FillerExpr && "no array filler for incomplete init list"); 10227 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10228 FillerExpr) && Success; 10229 } 10230 10231 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10232 LValue CommonLV; 10233 if (E->getCommonExpr() && 10234 !Evaluate(Info.CurrentCall->createTemporary( 10235 E->getCommonExpr(), 10236 getStorageType(Info.Ctx, E->getCommonExpr()), false, 10237 CommonLV), 10238 Info, E->getCommonExpr()->getSourceExpr())) 10239 return false; 10240 10241 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10242 10243 uint64_t Elements = CAT->getSize().getZExtValue(); 10244 Result = APValue(APValue::UninitArray(), Elements, Elements); 10245 10246 LValue Subobject = This; 10247 Subobject.addArray(Info, E, CAT); 10248 10249 bool Success = true; 10250 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10251 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10252 Info, Subobject, E->getSubExpr()) || 10253 !HandleLValueArrayAdjustment(Info, E, Subobject, 10254 CAT->getElementType(), 1)) { 10255 if (!Info.noteFailure()) 10256 return false; 10257 Success = false; 10258 } 10259 } 10260 10261 return Success; 10262 } 10263 10264 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10265 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10266 } 10267 10268 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10269 const LValue &Subobject, 10270 APValue *Value, 10271 QualType Type) { 10272 bool HadZeroInit = Value->hasValue(); 10273 10274 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10275 unsigned N = CAT->getSize().getZExtValue(); 10276 10277 // Preserve the array filler if we had prior zero-initialization. 10278 APValue Filler = 10279 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10280 : APValue(); 10281 10282 *Value = APValue(APValue::UninitArray(), N, N); 10283 10284 if (HadZeroInit) 10285 for (unsigned I = 0; I != N; ++I) 10286 Value->getArrayInitializedElt(I) = Filler; 10287 10288 // Initialize the elements. 10289 LValue ArrayElt = Subobject; 10290 ArrayElt.addArray(Info, E, CAT); 10291 for (unsigned I = 0; I != N; ++I) 10292 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10293 CAT->getElementType()) || 10294 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10295 CAT->getElementType(), 1)) 10296 return false; 10297 10298 return true; 10299 } 10300 10301 if (!Type->isRecordType()) 10302 return Error(E); 10303 10304 return RecordExprEvaluator(Info, Subobject, *Value) 10305 .VisitCXXConstructExpr(E, Type); 10306 } 10307 10308 //===----------------------------------------------------------------------===// 10309 // Integer Evaluation 10310 // 10311 // As a GNU extension, we support casting pointers to sufficiently-wide integer 10312 // types and back in constant folding. Integer values are thus represented 10313 // either as an integer-valued APValue, or as an lvalue-valued APValue. 10314 //===----------------------------------------------------------------------===// 10315 10316 namespace { 10317 class IntExprEvaluator 10318 : public ExprEvaluatorBase<IntExprEvaluator> { 10319 APValue &Result; 10320 public: 10321 IntExprEvaluator(EvalInfo &info, APValue &result) 10322 : ExprEvaluatorBaseTy(info), Result(result) {} 10323 10324 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10325 assert(E->getType()->isIntegralOrEnumerationType() && 10326 "Invalid evaluation result."); 10327 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10328 "Invalid evaluation result."); 10329 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10330 "Invalid evaluation result."); 10331 Result = APValue(SI); 10332 return true; 10333 } 10334 bool Success(const llvm::APSInt &SI, const Expr *E) { 10335 return Success(SI, E, Result); 10336 } 10337 10338 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10339 assert(E->getType()->isIntegralOrEnumerationType() && 10340 "Invalid evaluation result."); 10341 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10342 "Invalid evaluation result."); 10343 Result = APValue(APSInt(I)); 10344 Result.getInt().setIsUnsigned( 10345 E->getType()->isUnsignedIntegerOrEnumerationType()); 10346 return true; 10347 } 10348 bool Success(const llvm::APInt &I, const Expr *E) { 10349 return Success(I, E, Result); 10350 } 10351 10352 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10353 assert(E->getType()->isIntegralOrEnumerationType() && 10354 "Invalid evaluation result."); 10355 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10356 return true; 10357 } 10358 bool Success(uint64_t Value, const Expr *E) { 10359 return Success(Value, E, Result); 10360 } 10361 10362 bool Success(CharUnits Size, const Expr *E) { 10363 return Success(Size.getQuantity(), E); 10364 } 10365 10366 bool Success(const APValue &V, const Expr *E) { 10367 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10368 Result = V; 10369 return true; 10370 } 10371 return Success(V.getInt(), E); 10372 } 10373 10374 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10375 10376 //===--------------------------------------------------------------------===// 10377 // Visitor Methods 10378 //===--------------------------------------------------------------------===// 10379 10380 bool VisitIntegerLiteral(const IntegerLiteral *E) { 10381 return Success(E->getValue(), E); 10382 } 10383 bool VisitCharacterLiteral(const CharacterLiteral *E) { 10384 return Success(E->getValue(), E); 10385 } 10386 10387 bool CheckReferencedDecl(const Expr *E, const Decl *D); 10388 bool VisitDeclRefExpr(const DeclRefExpr *E) { 10389 if (CheckReferencedDecl(E, E->getDecl())) 10390 return true; 10391 10392 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10393 } 10394 bool VisitMemberExpr(const MemberExpr *E) { 10395 if (CheckReferencedDecl(E, E->getMemberDecl())) { 10396 VisitIgnoredBaseExpression(E->getBase()); 10397 return true; 10398 } 10399 10400 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10401 } 10402 10403 bool VisitCallExpr(const CallExpr *E); 10404 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10405 bool VisitBinaryOperator(const BinaryOperator *E); 10406 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10407 bool VisitUnaryOperator(const UnaryOperator *E); 10408 10409 bool VisitCastExpr(const CastExpr* E); 10410 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10411 10412 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10413 return Success(E->getValue(), E); 10414 } 10415 10416 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10417 return Success(E->getValue(), E); 10418 } 10419 10420 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10421 if (Info.ArrayInitIndex == uint64_t(-1)) { 10422 // We were asked to evaluate this subexpression independent of the 10423 // enclosing ArrayInitLoopExpr. We can't do that. 10424 Info.FFDiag(E); 10425 return false; 10426 } 10427 return Success(Info.ArrayInitIndex, E); 10428 } 10429 10430 // Note, GNU defines __null as an integer, not a pointer. 10431 bool VisitGNUNullExpr(const GNUNullExpr *E) { 10432 return ZeroInitialization(E); 10433 } 10434 10435 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10436 return Success(E->getValue(), E); 10437 } 10438 10439 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10440 return Success(E->getValue(), E); 10441 } 10442 10443 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10444 return Success(E->getValue(), E); 10445 } 10446 10447 bool VisitUnaryReal(const UnaryOperator *E); 10448 bool VisitUnaryImag(const UnaryOperator *E); 10449 10450 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10451 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10452 bool VisitSourceLocExpr(const SourceLocExpr *E); 10453 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10454 bool VisitRequiresExpr(const RequiresExpr *E); 10455 // FIXME: Missing: array subscript of vector, member of vector 10456 }; 10457 10458 class FixedPointExprEvaluator 10459 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10460 APValue &Result; 10461 10462 public: 10463 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10464 : ExprEvaluatorBaseTy(info), Result(result) {} 10465 10466 bool Success(const llvm::APInt &I, const Expr *E) { 10467 return Success( 10468 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10469 } 10470 10471 bool Success(uint64_t Value, const Expr *E) { 10472 return Success( 10473 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10474 } 10475 10476 bool Success(const APValue &V, const Expr *E) { 10477 return Success(V.getFixedPoint(), E); 10478 } 10479 10480 bool Success(const APFixedPoint &V, const Expr *E) { 10481 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10482 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10483 "Invalid evaluation result."); 10484 Result = APValue(V); 10485 return true; 10486 } 10487 10488 //===--------------------------------------------------------------------===// 10489 // Visitor Methods 10490 //===--------------------------------------------------------------------===// 10491 10492 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10493 return Success(E->getValue(), E); 10494 } 10495 10496 bool VisitCastExpr(const CastExpr *E); 10497 bool VisitUnaryOperator(const UnaryOperator *E); 10498 bool VisitBinaryOperator(const BinaryOperator *E); 10499 }; 10500 } // end anonymous namespace 10501 10502 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10503 /// produce either the integer value or a pointer. 10504 /// 10505 /// GCC has a heinous extension which folds casts between pointer types and 10506 /// pointer-sized integral types. We support this by allowing the evaluation of 10507 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10508 /// Some simple arithmetic on such values is supported (they are treated much 10509 /// like char*). 10510 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10511 EvalInfo &Info) { 10512 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10513 return IntExprEvaluator(Info, Result).Visit(E); 10514 } 10515 10516 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10517 APValue Val; 10518 if (!EvaluateIntegerOrLValue(E, Val, Info)) 10519 return false; 10520 if (!Val.isInt()) { 10521 // FIXME: It would be better to produce the diagnostic for casting 10522 // a pointer to an integer. 10523 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10524 return false; 10525 } 10526 Result = Val.getInt(); 10527 return true; 10528 } 10529 10530 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10531 APValue Evaluated = E->EvaluateInContext( 10532 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10533 return Success(Evaluated, E); 10534 } 10535 10536 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10537 EvalInfo &Info) { 10538 if (E->getType()->isFixedPointType()) { 10539 APValue Val; 10540 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10541 return false; 10542 if (!Val.isFixedPoint()) 10543 return false; 10544 10545 Result = Val.getFixedPoint(); 10546 return true; 10547 } 10548 return false; 10549 } 10550 10551 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10552 EvalInfo &Info) { 10553 if (E->getType()->isIntegerType()) { 10554 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10555 APSInt Val; 10556 if (!EvaluateInteger(E, Val, Info)) 10557 return false; 10558 Result = APFixedPoint(Val, FXSema); 10559 return true; 10560 } else if (E->getType()->isFixedPointType()) { 10561 return EvaluateFixedPoint(E, Result, Info); 10562 } 10563 return false; 10564 } 10565 10566 /// Check whether the given declaration can be directly converted to an integral 10567 /// rvalue. If not, no diagnostic is produced; there are other things we can 10568 /// try. 10569 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10570 // Enums are integer constant exprs. 10571 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10572 // Check for signedness/width mismatches between E type and ECD value. 10573 bool SameSign = (ECD->getInitVal().isSigned() 10574 == E->getType()->isSignedIntegerOrEnumerationType()); 10575 bool SameWidth = (ECD->getInitVal().getBitWidth() 10576 == Info.Ctx.getIntWidth(E->getType())); 10577 if (SameSign && SameWidth) 10578 return Success(ECD->getInitVal(), E); 10579 else { 10580 // Get rid of mismatch (otherwise Success assertions will fail) 10581 // by computing a new value matching the type of E. 10582 llvm::APSInt Val = ECD->getInitVal(); 10583 if (!SameSign) 10584 Val.setIsSigned(!ECD->getInitVal().isSigned()); 10585 if (!SameWidth) 10586 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10587 return Success(Val, E); 10588 } 10589 } 10590 return false; 10591 } 10592 10593 /// Values returned by __builtin_classify_type, chosen to match the values 10594 /// produced by GCC's builtin. 10595 enum class GCCTypeClass { 10596 None = -1, 10597 Void = 0, 10598 Integer = 1, 10599 // GCC reserves 2 for character types, but instead classifies them as 10600 // integers. 10601 Enum = 3, 10602 Bool = 4, 10603 Pointer = 5, 10604 // GCC reserves 6 for references, but appears to never use it (because 10605 // expressions never have reference type, presumably). 10606 PointerToDataMember = 7, 10607 RealFloat = 8, 10608 Complex = 9, 10609 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10610 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10611 // GCC claims to reserve 11 for pointers to member functions, but *actually* 10612 // uses 12 for that purpose, same as for a class or struct. Maybe it 10613 // internally implements a pointer to member as a struct? Who knows. 10614 PointerToMemberFunction = 12, // Not a bug, see above. 10615 ClassOrStruct = 12, 10616 Union = 13, 10617 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10618 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10619 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10620 // literals. 10621 }; 10622 10623 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10624 /// as GCC. 10625 static GCCTypeClass 10626 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10627 assert(!T->isDependentType() && "unexpected dependent type"); 10628 10629 QualType CanTy = T.getCanonicalType(); 10630 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10631 10632 switch (CanTy->getTypeClass()) { 10633 #define TYPE(ID, BASE) 10634 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10635 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10636 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10637 #include "clang/AST/TypeNodes.inc" 10638 case Type::Auto: 10639 case Type::DeducedTemplateSpecialization: 10640 llvm_unreachable("unexpected non-canonical or dependent type"); 10641 10642 case Type::Builtin: 10643 switch (BT->getKind()) { 10644 #define BUILTIN_TYPE(ID, SINGLETON_ID) 10645 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10646 case BuiltinType::ID: return GCCTypeClass::Integer; 10647 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10648 case BuiltinType::ID: return GCCTypeClass::RealFloat; 10649 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10650 case BuiltinType::ID: break; 10651 #include "clang/AST/BuiltinTypes.def" 10652 case BuiltinType::Void: 10653 return GCCTypeClass::Void; 10654 10655 case BuiltinType::Bool: 10656 return GCCTypeClass::Bool; 10657 10658 case BuiltinType::Char_U: 10659 case BuiltinType::UChar: 10660 case BuiltinType::WChar_U: 10661 case BuiltinType::Char8: 10662 case BuiltinType::Char16: 10663 case BuiltinType::Char32: 10664 case BuiltinType::UShort: 10665 case BuiltinType::UInt: 10666 case BuiltinType::ULong: 10667 case BuiltinType::ULongLong: 10668 case BuiltinType::UInt128: 10669 return GCCTypeClass::Integer; 10670 10671 case BuiltinType::UShortAccum: 10672 case BuiltinType::UAccum: 10673 case BuiltinType::ULongAccum: 10674 case BuiltinType::UShortFract: 10675 case BuiltinType::UFract: 10676 case BuiltinType::ULongFract: 10677 case BuiltinType::SatUShortAccum: 10678 case BuiltinType::SatUAccum: 10679 case BuiltinType::SatULongAccum: 10680 case BuiltinType::SatUShortFract: 10681 case BuiltinType::SatUFract: 10682 case BuiltinType::SatULongFract: 10683 return GCCTypeClass::None; 10684 10685 case BuiltinType::NullPtr: 10686 10687 case BuiltinType::ObjCId: 10688 case BuiltinType::ObjCClass: 10689 case BuiltinType::ObjCSel: 10690 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10691 case BuiltinType::Id: 10692 #include "clang/Basic/OpenCLImageTypes.def" 10693 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10694 case BuiltinType::Id: 10695 #include "clang/Basic/OpenCLExtensionTypes.def" 10696 case BuiltinType::OCLSampler: 10697 case BuiltinType::OCLEvent: 10698 case BuiltinType::OCLClkEvent: 10699 case BuiltinType::OCLQueue: 10700 case BuiltinType::OCLReserveID: 10701 #define SVE_TYPE(Name, Id, SingletonId) \ 10702 case BuiltinType::Id: 10703 #include "clang/Basic/AArch64SVEACLETypes.def" 10704 return GCCTypeClass::None; 10705 10706 case BuiltinType::Dependent: 10707 llvm_unreachable("unexpected dependent type"); 10708 }; 10709 llvm_unreachable("unexpected placeholder type"); 10710 10711 case Type::Enum: 10712 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 10713 10714 case Type::Pointer: 10715 case Type::ConstantArray: 10716 case Type::VariableArray: 10717 case Type::IncompleteArray: 10718 case Type::FunctionNoProto: 10719 case Type::FunctionProto: 10720 return GCCTypeClass::Pointer; 10721 10722 case Type::MemberPointer: 10723 return CanTy->isMemberDataPointerType() 10724 ? GCCTypeClass::PointerToDataMember 10725 : GCCTypeClass::PointerToMemberFunction; 10726 10727 case Type::Complex: 10728 return GCCTypeClass::Complex; 10729 10730 case Type::Record: 10731 return CanTy->isUnionType() ? GCCTypeClass::Union 10732 : GCCTypeClass::ClassOrStruct; 10733 10734 case Type::Atomic: 10735 // GCC classifies _Atomic T the same as T. 10736 return EvaluateBuiltinClassifyType( 10737 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 10738 10739 case Type::BlockPointer: 10740 case Type::Vector: 10741 case Type::ExtVector: 10742 case Type::ConstantMatrix: 10743 case Type::ObjCObject: 10744 case Type::ObjCInterface: 10745 case Type::ObjCObjectPointer: 10746 case Type::Pipe: 10747 case Type::ExtInt: 10748 // GCC classifies vectors as None. We follow its lead and classify all 10749 // other types that don't fit into the regular classification the same way. 10750 return GCCTypeClass::None; 10751 10752 case Type::LValueReference: 10753 case Type::RValueReference: 10754 llvm_unreachable("invalid type for expression"); 10755 } 10756 10757 llvm_unreachable("unexpected type class"); 10758 } 10759 10760 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10761 /// as GCC. 10762 static GCCTypeClass 10763 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 10764 // If no argument was supplied, default to None. This isn't 10765 // ideal, however it is what gcc does. 10766 if (E->getNumArgs() == 0) 10767 return GCCTypeClass::None; 10768 10769 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 10770 // being an ICE, but still folds it to a constant using the type of the first 10771 // argument. 10772 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 10773 } 10774 10775 /// EvaluateBuiltinConstantPForLValue - Determine the result of 10776 /// __builtin_constant_p when applied to the given pointer. 10777 /// 10778 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 10779 /// or it points to the first character of a string literal. 10780 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 10781 APValue::LValueBase Base = LV.getLValueBase(); 10782 if (Base.isNull()) { 10783 // A null base is acceptable. 10784 return true; 10785 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 10786 if (!isa<StringLiteral>(E)) 10787 return false; 10788 return LV.getLValueOffset().isZero(); 10789 } else if (Base.is<TypeInfoLValue>()) { 10790 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 10791 // evaluate to true. 10792 return true; 10793 } else { 10794 // Any other base is not constant enough for GCC. 10795 return false; 10796 } 10797 } 10798 10799 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 10800 /// GCC as we can manage. 10801 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 10802 // This evaluation is not permitted to have side-effects, so evaluate it in 10803 // a speculative evaluation context. 10804 SpeculativeEvaluationRAII SpeculativeEval(Info); 10805 10806 // Constant-folding is always enabled for the operand of __builtin_constant_p 10807 // (even when the enclosing evaluation context otherwise requires a strict 10808 // language-specific constant expression). 10809 FoldConstant Fold(Info, true); 10810 10811 QualType ArgType = Arg->getType(); 10812 10813 // __builtin_constant_p always has one operand. The rules which gcc follows 10814 // are not precisely documented, but are as follows: 10815 // 10816 // - If the operand is of integral, floating, complex or enumeration type, 10817 // and can be folded to a known value of that type, it returns 1. 10818 // - If the operand can be folded to a pointer to the first character 10819 // of a string literal (or such a pointer cast to an integral type) 10820 // or to a null pointer or an integer cast to a pointer, it returns 1. 10821 // 10822 // Otherwise, it returns 0. 10823 // 10824 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 10825 // its support for this did not work prior to GCC 9 and is not yet well 10826 // understood. 10827 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 10828 ArgType->isAnyComplexType() || ArgType->isPointerType() || 10829 ArgType->isNullPtrType()) { 10830 APValue V; 10831 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 10832 Fold.keepDiagnostics(); 10833 return false; 10834 } 10835 10836 // For a pointer (possibly cast to integer), there are special rules. 10837 if (V.getKind() == APValue::LValue) 10838 return EvaluateBuiltinConstantPForLValue(V); 10839 10840 // Otherwise, any constant value is good enough. 10841 return V.hasValue(); 10842 } 10843 10844 // Anything else isn't considered to be sufficiently constant. 10845 return false; 10846 } 10847 10848 /// Retrieves the "underlying object type" of the given expression, 10849 /// as used by __builtin_object_size. 10850 static QualType getObjectType(APValue::LValueBase B) { 10851 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 10852 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 10853 return VD->getType(); 10854 } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 10855 if (isa<CompoundLiteralExpr>(E)) 10856 return E->getType(); 10857 } else if (B.is<TypeInfoLValue>()) { 10858 return B.getTypeInfoType(); 10859 } else if (B.is<DynamicAllocLValue>()) { 10860 return B.getDynamicAllocType(); 10861 } 10862 10863 return QualType(); 10864 } 10865 10866 /// A more selective version of E->IgnoreParenCasts for 10867 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 10868 /// to change the type of E. 10869 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 10870 /// 10871 /// Always returns an RValue with a pointer representation. 10872 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 10873 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 10874 10875 auto *NoParens = E->IgnoreParens(); 10876 auto *Cast = dyn_cast<CastExpr>(NoParens); 10877 if (Cast == nullptr) 10878 return NoParens; 10879 10880 // We only conservatively allow a few kinds of casts, because this code is 10881 // inherently a simple solution that seeks to support the common case. 10882 auto CastKind = Cast->getCastKind(); 10883 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 10884 CastKind != CK_AddressSpaceConversion) 10885 return NoParens; 10886 10887 auto *SubExpr = Cast->getSubExpr(); 10888 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 10889 return NoParens; 10890 return ignorePointerCastsAndParens(SubExpr); 10891 } 10892 10893 /// Checks to see if the given LValue's Designator is at the end of the LValue's 10894 /// record layout. e.g. 10895 /// struct { struct { int a, b; } fst, snd; } obj; 10896 /// obj.fst // no 10897 /// obj.snd // yes 10898 /// obj.fst.a // no 10899 /// obj.fst.b // no 10900 /// obj.snd.a // no 10901 /// obj.snd.b // yes 10902 /// 10903 /// Please note: this function is specialized for how __builtin_object_size 10904 /// views "objects". 10905 /// 10906 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 10907 /// correct result, it will always return true. 10908 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 10909 assert(!LVal.Designator.Invalid); 10910 10911 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 10912 const RecordDecl *Parent = FD->getParent(); 10913 Invalid = Parent->isInvalidDecl(); 10914 if (Invalid || Parent->isUnion()) 10915 return true; 10916 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 10917 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 10918 }; 10919 10920 auto &Base = LVal.getLValueBase(); 10921 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 10922 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 10923 bool Invalid; 10924 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10925 return Invalid; 10926 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 10927 for (auto *FD : IFD->chain()) { 10928 bool Invalid; 10929 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 10930 return Invalid; 10931 } 10932 } 10933 } 10934 10935 unsigned I = 0; 10936 QualType BaseType = getType(Base); 10937 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 10938 // If we don't know the array bound, conservatively assume we're looking at 10939 // the final array element. 10940 ++I; 10941 if (BaseType->isIncompleteArrayType()) 10942 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 10943 else 10944 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 10945 } 10946 10947 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 10948 const auto &Entry = LVal.Designator.Entries[I]; 10949 if (BaseType->isArrayType()) { 10950 // Because __builtin_object_size treats arrays as objects, we can ignore 10951 // the index iff this is the last array in the Designator. 10952 if (I + 1 == E) 10953 return true; 10954 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 10955 uint64_t Index = Entry.getAsArrayIndex(); 10956 if (Index + 1 != CAT->getSize()) 10957 return false; 10958 BaseType = CAT->getElementType(); 10959 } else if (BaseType->isAnyComplexType()) { 10960 const auto *CT = BaseType->castAs<ComplexType>(); 10961 uint64_t Index = Entry.getAsArrayIndex(); 10962 if (Index != 1) 10963 return false; 10964 BaseType = CT->getElementType(); 10965 } else if (auto *FD = getAsField(Entry)) { 10966 bool Invalid; 10967 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 10968 return Invalid; 10969 BaseType = FD->getType(); 10970 } else { 10971 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 10972 return false; 10973 } 10974 } 10975 return true; 10976 } 10977 10978 /// Tests to see if the LValue has a user-specified designator (that isn't 10979 /// necessarily valid). Note that this always returns 'true' if the LValue has 10980 /// an unsized array as its first designator entry, because there's currently no 10981 /// way to tell if the user typed *foo or foo[0]. 10982 static bool refersToCompleteObject(const LValue &LVal) { 10983 if (LVal.Designator.Invalid) 10984 return false; 10985 10986 if (!LVal.Designator.Entries.empty()) 10987 return LVal.Designator.isMostDerivedAnUnsizedArray(); 10988 10989 if (!LVal.InvalidBase) 10990 return true; 10991 10992 // If `E` is a MemberExpr, then the first part of the designator is hiding in 10993 // the LValueBase. 10994 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 10995 return !E || !isa<MemberExpr>(E); 10996 } 10997 10998 /// Attempts to detect a user writing into a piece of memory that's impossible 10999 /// to figure out the size of by just using types. 11000 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11001 const SubobjectDesignator &Designator = LVal.Designator; 11002 // Notes: 11003 // - Users can only write off of the end when we have an invalid base. Invalid 11004 // bases imply we don't know where the memory came from. 11005 // - We used to be a bit more aggressive here; we'd only be conservative if 11006 // the array at the end was flexible, or if it had 0 or 1 elements. This 11007 // broke some common standard library extensions (PR30346), but was 11008 // otherwise seemingly fine. It may be useful to reintroduce this behavior 11009 // with some sort of list. OTOH, it seems that GCC is always 11010 // conservative with the last element in structs (if it's an array), so our 11011 // current behavior is more compatible than an explicit list approach would 11012 // be. 11013 return LVal.InvalidBase && 11014 Designator.Entries.size() == Designator.MostDerivedPathLength && 11015 Designator.MostDerivedIsArrayElement && 11016 isDesignatorAtObjectEnd(Ctx, LVal); 11017 } 11018 11019 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11020 /// Fails if the conversion would cause loss of precision. 11021 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11022 CharUnits &Result) { 11023 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11024 if (Int.ugt(CharUnitsMax)) 11025 return false; 11026 Result = CharUnits::fromQuantity(Int.getZExtValue()); 11027 return true; 11028 } 11029 11030 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11031 /// determine how many bytes exist from the beginning of the object to either 11032 /// the end of the current subobject, or the end of the object itself, depending 11033 /// on what the LValue looks like + the value of Type. 11034 /// 11035 /// If this returns false, the value of Result is undefined. 11036 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11037 unsigned Type, const LValue &LVal, 11038 CharUnits &EndOffset) { 11039 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11040 11041 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11042 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11043 return false; 11044 return HandleSizeof(Info, ExprLoc, Ty, Result); 11045 }; 11046 11047 // We want to evaluate the size of the entire object. This is a valid fallback 11048 // for when Type=1 and the designator is invalid, because we're asked for an 11049 // upper-bound. 11050 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11051 // Type=3 wants a lower bound, so we can't fall back to this. 11052 if (Type == 3 && !DetermineForCompleteObject) 11053 return false; 11054 11055 llvm::APInt APEndOffset; 11056 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11057 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11058 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11059 11060 if (LVal.InvalidBase) 11061 return false; 11062 11063 QualType BaseTy = getObjectType(LVal.getLValueBase()); 11064 return CheckedHandleSizeof(BaseTy, EndOffset); 11065 } 11066 11067 // We want to evaluate the size of a subobject. 11068 const SubobjectDesignator &Designator = LVal.Designator; 11069 11070 // The following is a moderately common idiom in C: 11071 // 11072 // struct Foo { int a; char c[1]; }; 11073 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11074 // strcpy(&F->c[0], Bar); 11075 // 11076 // In order to not break too much legacy code, we need to support it. 11077 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11078 // If we can resolve this to an alloc_size call, we can hand that back, 11079 // because we know for certain how many bytes there are to write to. 11080 llvm::APInt APEndOffset; 11081 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11082 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11083 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11084 11085 // If we cannot determine the size of the initial allocation, then we can't 11086 // given an accurate upper-bound. However, we are still able to give 11087 // conservative lower-bounds for Type=3. 11088 if (Type == 1) 11089 return false; 11090 } 11091 11092 CharUnits BytesPerElem; 11093 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11094 return false; 11095 11096 // According to the GCC documentation, we want the size of the subobject 11097 // denoted by the pointer. But that's not quite right -- what we actually 11098 // want is the size of the immediately-enclosing array, if there is one. 11099 int64_t ElemsRemaining; 11100 if (Designator.MostDerivedIsArrayElement && 11101 Designator.Entries.size() == Designator.MostDerivedPathLength) { 11102 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11103 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11104 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11105 } else { 11106 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11107 } 11108 11109 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11110 return true; 11111 } 11112 11113 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11114 /// returns true and stores the result in @p Size. 11115 /// 11116 /// If @p WasError is non-null, this will report whether the failure to evaluate 11117 /// is to be treated as an Error in IntExprEvaluator. 11118 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11119 EvalInfo &Info, uint64_t &Size) { 11120 // Determine the denoted object. 11121 LValue LVal; 11122 { 11123 // The operand of __builtin_object_size is never evaluated for side-effects. 11124 // If there are any, but we can determine the pointed-to object anyway, then 11125 // ignore the side-effects. 11126 SpeculativeEvaluationRAII SpeculativeEval(Info); 11127 IgnoreSideEffectsRAII Fold(Info); 11128 11129 if (E->isGLValue()) { 11130 // It's possible for us to be given GLValues if we're called via 11131 // Expr::tryEvaluateObjectSize. 11132 APValue RVal; 11133 if (!EvaluateAsRValue(Info, E, RVal)) 11134 return false; 11135 LVal.setFrom(Info.Ctx, RVal); 11136 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11137 /*InvalidBaseOK=*/true)) 11138 return false; 11139 } 11140 11141 // If we point to before the start of the object, there are no accessible 11142 // bytes. 11143 if (LVal.getLValueOffset().isNegative()) { 11144 Size = 0; 11145 return true; 11146 } 11147 11148 CharUnits EndOffset; 11149 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11150 return false; 11151 11152 // If we've fallen outside of the end offset, just pretend there's nothing to 11153 // write to/read from. 11154 if (EndOffset <= LVal.getLValueOffset()) 11155 Size = 0; 11156 else 11157 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11158 return true; 11159 } 11160 11161 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11162 if (unsigned BuiltinOp = E->getBuiltinCallee()) 11163 return VisitBuiltinCallExpr(E, BuiltinOp); 11164 11165 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11166 } 11167 11168 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11169 APValue &Val, APSInt &Alignment) { 11170 QualType SrcTy = E->getArg(0)->getType(); 11171 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11172 return false; 11173 // Even though we are evaluating integer expressions we could get a pointer 11174 // argument for the __builtin_is_aligned() case. 11175 if (SrcTy->isPointerType()) { 11176 LValue Ptr; 11177 if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11178 return false; 11179 Ptr.moveInto(Val); 11180 } else if (!SrcTy->isIntegralOrEnumerationType()) { 11181 Info.FFDiag(E->getArg(0)); 11182 return false; 11183 } else { 11184 APSInt SrcInt; 11185 if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11186 return false; 11187 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11188 "Bit widths must be the same"); 11189 Val = APValue(SrcInt); 11190 } 11191 assert(Val.hasValue()); 11192 return true; 11193 } 11194 11195 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11196 unsigned BuiltinOp) { 11197 switch (BuiltinOp) { 11198 default: 11199 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11200 11201 case Builtin::BI__builtin_dynamic_object_size: 11202 case Builtin::BI__builtin_object_size: { 11203 // The type was checked when we built the expression. 11204 unsigned Type = 11205 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11206 assert(Type <= 3 && "unexpected type"); 11207 11208 uint64_t Size; 11209 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11210 return Success(Size, E); 11211 11212 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11213 return Success((Type & 2) ? 0 : -1, E); 11214 11215 // Expression had no side effects, but we couldn't statically determine the 11216 // size of the referenced object. 11217 switch (Info.EvalMode) { 11218 case EvalInfo::EM_ConstantExpression: 11219 case EvalInfo::EM_ConstantFold: 11220 case EvalInfo::EM_IgnoreSideEffects: 11221 // Leave it to IR generation. 11222 return Error(E); 11223 case EvalInfo::EM_ConstantExpressionUnevaluated: 11224 // Reduce it to a constant now. 11225 return Success((Type & 2) ? 0 : -1, E); 11226 } 11227 11228 llvm_unreachable("unexpected EvalMode"); 11229 } 11230 11231 case Builtin::BI__builtin_os_log_format_buffer_size: { 11232 analyze_os_log::OSLogBufferLayout Layout; 11233 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11234 return Success(Layout.size().getQuantity(), E); 11235 } 11236 11237 case Builtin::BI__builtin_is_aligned: { 11238 APValue Src; 11239 APSInt Alignment; 11240 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11241 return false; 11242 if (Src.isLValue()) { 11243 // If we evaluated a pointer, check the minimum known alignment. 11244 LValue Ptr; 11245 Ptr.setFrom(Info.Ctx, Src); 11246 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11247 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11248 // We can return true if the known alignment at the computed offset is 11249 // greater than the requested alignment. 11250 assert(PtrAlign.isPowerOfTwo()); 11251 assert(Alignment.isPowerOf2()); 11252 if (PtrAlign.getQuantity() >= Alignment) 11253 return Success(1, E); 11254 // If the alignment is not known to be sufficient, some cases could still 11255 // be aligned at run time. However, if the requested alignment is less or 11256 // equal to the base alignment and the offset is not aligned, we know that 11257 // the run-time value can never be aligned. 11258 if (BaseAlignment.getQuantity() >= Alignment && 11259 PtrAlign.getQuantity() < Alignment) 11260 return Success(0, E); 11261 // Otherwise we can't infer whether the value is sufficiently aligned. 11262 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11263 // in cases where we can't fully evaluate the pointer. 11264 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11265 << Alignment; 11266 return false; 11267 } 11268 assert(Src.isInt()); 11269 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11270 } 11271 case Builtin::BI__builtin_align_up: { 11272 APValue Src; 11273 APSInt Alignment; 11274 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11275 return false; 11276 if (!Src.isInt()) 11277 return Error(E); 11278 APSInt AlignedVal = 11279 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11280 Src.getInt().isUnsigned()); 11281 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11282 return Success(AlignedVal, E); 11283 } 11284 case Builtin::BI__builtin_align_down: { 11285 APValue Src; 11286 APSInt Alignment; 11287 if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11288 return false; 11289 if (!Src.isInt()) 11290 return Error(E); 11291 APSInt AlignedVal = 11292 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11293 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11294 return Success(AlignedVal, E); 11295 } 11296 11297 case Builtin::BI__builtin_bitreverse8: 11298 case Builtin::BI__builtin_bitreverse16: 11299 case Builtin::BI__builtin_bitreverse32: 11300 case Builtin::BI__builtin_bitreverse64: { 11301 APSInt Val; 11302 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11303 return false; 11304 11305 return Success(Val.reverseBits(), E); 11306 } 11307 11308 case Builtin::BI__builtin_bswap16: 11309 case Builtin::BI__builtin_bswap32: 11310 case Builtin::BI__builtin_bswap64: { 11311 APSInt Val; 11312 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11313 return false; 11314 11315 return Success(Val.byteSwap(), E); 11316 } 11317 11318 case Builtin::BI__builtin_classify_type: 11319 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11320 11321 case Builtin::BI__builtin_clrsb: 11322 case Builtin::BI__builtin_clrsbl: 11323 case Builtin::BI__builtin_clrsbll: { 11324 APSInt Val; 11325 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11326 return false; 11327 11328 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11329 } 11330 11331 case Builtin::BI__builtin_clz: 11332 case Builtin::BI__builtin_clzl: 11333 case Builtin::BI__builtin_clzll: 11334 case Builtin::BI__builtin_clzs: { 11335 APSInt Val; 11336 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11337 return false; 11338 if (!Val) 11339 return Error(E); 11340 11341 return Success(Val.countLeadingZeros(), E); 11342 } 11343 11344 case Builtin::BI__builtin_constant_p: { 11345 const Expr *Arg = E->getArg(0); 11346 if (EvaluateBuiltinConstantP(Info, Arg)) 11347 return Success(true, E); 11348 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11349 // Outside a constant context, eagerly evaluate to false in the presence 11350 // of side-effects in order to avoid -Wunsequenced false-positives in 11351 // a branch on __builtin_constant_p(expr). 11352 return Success(false, E); 11353 } 11354 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11355 return false; 11356 } 11357 11358 case Builtin::BI__builtin_is_constant_evaluated: { 11359 const auto *Callee = Info.CurrentCall->getCallee(); 11360 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11361 (Info.CallStackDepth == 1 || 11362 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11363 Callee->getIdentifier() && 11364 Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11365 // FIXME: Find a better way to avoid duplicated diagnostics. 11366 if (Info.EvalStatus.Diag) 11367 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11368 : Info.CurrentCall->CallLoc, 11369 diag::warn_is_constant_evaluated_always_true_constexpr) 11370 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11371 : "std::is_constant_evaluated"); 11372 } 11373 11374 return Success(Info.InConstantContext, E); 11375 } 11376 11377 case Builtin::BI__builtin_ctz: 11378 case Builtin::BI__builtin_ctzl: 11379 case Builtin::BI__builtin_ctzll: 11380 case Builtin::BI__builtin_ctzs: { 11381 APSInt Val; 11382 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11383 return false; 11384 if (!Val) 11385 return Error(E); 11386 11387 return Success(Val.countTrailingZeros(), E); 11388 } 11389 11390 case Builtin::BI__builtin_eh_return_data_regno: { 11391 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11392 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11393 return Success(Operand, E); 11394 } 11395 11396 case Builtin::BI__builtin_expect: 11397 case Builtin::BI__builtin_expect_with_probability: 11398 return Visit(E->getArg(0)); 11399 11400 case Builtin::BI__builtin_ffs: 11401 case Builtin::BI__builtin_ffsl: 11402 case Builtin::BI__builtin_ffsll: { 11403 APSInt Val; 11404 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11405 return false; 11406 11407 unsigned N = Val.countTrailingZeros(); 11408 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11409 } 11410 11411 case Builtin::BI__builtin_fpclassify: { 11412 APFloat Val(0.0); 11413 if (!EvaluateFloat(E->getArg(5), Val, Info)) 11414 return false; 11415 unsigned Arg; 11416 switch (Val.getCategory()) { 11417 case APFloat::fcNaN: Arg = 0; break; 11418 case APFloat::fcInfinity: Arg = 1; break; 11419 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11420 case APFloat::fcZero: Arg = 4; break; 11421 } 11422 return Visit(E->getArg(Arg)); 11423 } 11424 11425 case Builtin::BI__builtin_isinf_sign: { 11426 APFloat Val(0.0); 11427 return EvaluateFloat(E->getArg(0), Val, Info) && 11428 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11429 } 11430 11431 case Builtin::BI__builtin_isinf: { 11432 APFloat Val(0.0); 11433 return EvaluateFloat(E->getArg(0), Val, Info) && 11434 Success(Val.isInfinity() ? 1 : 0, E); 11435 } 11436 11437 case Builtin::BI__builtin_isfinite: { 11438 APFloat Val(0.0); 11439 return EvaluateFloat(E->getArg(0), Val, Info) && 11440 Success(Val.isFinite() ? 1 : 0, E); 11441 } 11442 11443 case Builtin::BI__builtin_isnan: { 11444 APFloat Val(0.0); 11445 return EvaluateFloat(E->getArg(0), Val, Info) && 11446 Success(Val.isNaN() ? 1 : 0, E); 11447 } 11448 11449 case Builtin::BI__builtin_isnormal: { 11450 APFloat Val(0.0); 11451 return EvaluateFloat(E->getArg(0), Val, Info) && 11452 Success(Val.isNormal() ? 1 : 0, E); 11453 } 11454 11455 case Builtin::BI__builtin_parity: 11456 case Builtin::BI__builtin_parityl: 11457 case Builtin::BI__builtin_parityll: { 11458 APSInt Val; 11459 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11460 return false; 11461 11462 return Success(Val.countPopulation() % 2, E); 11463 } 11464 11465 case Builtin::BI__builtin_popcount: 11466 case Builtin::BI__builtin_popcountl: 11467 case Builtin::BI__builtin_popcountll: { 11468 APSInt Val; 11469 if (!EvaluateInteger(E->getArg(0), Val, Info)) 11470 return false; 11471 11472 return Success(Val.countPopulation(), E); 11473 } 11474 11475 case Builtin::BI__builtin_rotateleft8: 11476 case Builtin::BI__builtin_rotateleft16: 11477 case Builtin::BI__builtin_rotateleft32: 11478 case Builtin::BI__builtin_rotateleft64: 11479 case Builtin::BI_rotl8: // Microsoft variants of rotate right 11480 case Builtin::BI_rotl16: 11481 case Builtin::BI_rotl: 11482 case Builtin::BI_lrotl: 11483 case Builtin::BI_rotl64: { 11484 APSInt Val, Amt; 11485 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11486 !EvaluateInteger(E->getArg(1), Amt, Info)) 11487 return false; 11488 11489 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11490 } 11491 11492 case Builtin::BI__builtin_rotateright8: 11493 case Builtin::BI__builtin_rotateright16: 11494 case Builtin::BI__builtin_rotateright32: 11495 case Builtin::BI__builtin_rotateright64: 11496 case Builtin::BI_rotr8: // Microsoft variants of rotate right 11497 case Builtin::BI_rotr16: 11498 case Builtin::BI_rotr: 11499 case Builtin::BI_lrotr: 11500 case Builtin::BI_rotr64: { 11501 APSInt Val, Amt; 11502 if (!EvaluateInteger(E->getArg(0), Val, Info) || 11503 !EvaluateInteger(E->getArg(1), Amt, Info)) 11504 return false; 11505 11506 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11507 } 11508 11509 case Builtin::BIstrlen: 11510 case Builtin::BIwcslen: 11511 // A call to strlen is not a constant expression. 11512 if (Info.getLangOpts().CPlusPlus11) 11513 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11514 << /*isConstexpr*/0 << /*isConstructor*/0 11515 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11516 else 11517 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11518 LLVM_FALLTHROUGH; 11519 case Builtin::BI__builtin_strlen: 11520 case Builtin::BI__builtin_wcslen: { 11521 // As an extension, we support __builtin_strlen() as a constant expression, 11522 // and support folding strlen() to a constant. 11523 LValue String; 11524 if (!EvaluatePointer(E->getArg(0), String, Info)) 11525 return false; 11526 11527 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11528 11529 // Fast path: if it's a string literal, search the string value. 11530 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11531 String.getLValueBase().dyn_cast<const Expr *>())) { 11532 // The string literal may have embedded null characters. Find the first 11533 // one and truncate there. 11534 StringRef Str = S->getBytes(); 11535 int64_t Off = String.Offset.getQuantity(); 11536 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11537 S->getCharByteWidth() == 1 && 11538 // FIXME: Add fast-path for wchar_t too. 11539 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11540 Str = Str.substr(Off); 11541 11542 StringRef::size_type Pos = Str.find(0); 11543 if (Pos != StringRef::npos) 11544 Str = Str.substr(0, Pos); 11545 11546 return Success(Str.size(), E); 11547 } 11548 11549 // Fall through to slow path to issue appropriate diagnostic. 11550 } 11551 11552 // Slow path: scan the bytes of the string looking for the terminating 0. 11553 for (uint64_t Strlen = 0; /**/; ++Strlen) { 11554 APValue Char; 11555 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11556 !Char.isInt()) 11557 return false; 11558 if (!Char.getInt()) 11559 return Success(Strlen, E); 11560 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11561 return false; 11562 } 11563 } 11564 11565 case Builtin::BIstrcmp: 11566 case Builtin::BIwcscmp: 11567 case Builtin::BIstrncmp: 11568 case Builtin::BIwcsncmp: 11569 case Builtin::BImemcmp: 11570 case Builtin::BIbcmp: 11571 case Builtin::BIwmemcmp: 11572 // A call to strlen is not a constant expression. 11573 if (Info.getLangOpts().CPlusPlus11) 11574 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11575 << /*isConstexpr*/0 << /*isConstructor*/0 11576 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11577 else 11578 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11579 LLVM_FALLTHROUGH; 11580 case Builtin::BI__builtin_strcmp: 11581 case Builtin::BI__builtin_wcscmp: 11582 case Builtin::BI__builtin_strncmp: 11583 case Builtin::BI__builtin_wcsncmp: 11584 case Builtin::BI__builtin_memcmp: 11585 case Builtin::BI__builtin_bcmp: 11586 case Builtin::BI__builtin_wmemcmp: { 11587 LValue String1, String2; 11588 if (!EvaluatePointer(E->getArg(0), String1, Info) || 11589 !EvaluatePointer(E->getArg(1), String2, Info)) 11590 return false; 11591 11592 uint64_t MaxLength = uint64_t(-1); 11593 if (BuiltinOp != Builtin::BIstrcmp && 11594 BuiltinOp != Builtin::BIwcscmp && 11595 BuiltinOp != Builtin::BI__builtin_strcmp && 11596 BuiltinOp != Builtin::BI__builtin_wcscmp) { 11597 APSInt N; 11598 if (!EvaluateInteger(E->getArg(2), N, Info)) 11599 return false; 11600 MaxLength = N.getExtValue(); 11601 } 11602 11603 // Empty substrings compare equal by definition. 11604 if (MaxLength == 0u) 11605 return Success(0, E); 11606 11607 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11608 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11609 String1.Designator.Invalid || String2.Designator.Invalid) 11610 return false; 11611 11612 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11613 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11614 11615 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11616 BuiltinOp == Builtin::BIbcmp || 11617 BuiltinOp == Builtin::BI__builtin_memcmp || 11618 BuiltinOp == Builtin::BI__builtin_bcmp; 11619 11620 assert(IsRawByte || 11621 (Info.Ctx.hasSameUnqualifiedType( 11622 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11623 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11624 11625 // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11626 // 'char8_t', but no other types. 11627 if (IsRawByte && 11628 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11629 // FIXME: Consider using our bit_cast implementation to support this. 11630 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11631 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11632 << CharTy1 << CharTy2; 11633 return false; 11634 } 11635 11636 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11637 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11638 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11639 Char1.isInt() && Char2.isInt(); 11640 }; 11641 const auto &AdvanceElems = [&] { 11642 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11643 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11644 }; 11645 11646 bool StopAtNull = 11647 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11648 BuiltinOp != Builtin::BIwmemcmp && 11649 BuiltinOp != Builtin::BI__builtin_memcmp && 11650 BuiltinOp != Builtin::BI__builtin_bcmp && 11651 BuiltinOp != Builtin::BI__builtin_wmemcmp); 11652 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11653 BuiltinOp == Builtin::BIwcsncmp || 11654 BuiltinOp == Builtin::BIwmemcmp || 11655 BuiltinOp == Builtin::BI__builtin_wcscmp || 11656 BuiltinOp == Builtin::BI__builtin_wcsncmp || 11657 BuiltinOp == Builtin::BI__builtin_wmemcmp; 11658 11659 for (; MaxLength; --MaxLength) { 11660 APValue Char1, Char2; 11661 if (!ReadCurElems(Char1, Char2)) 11662 return false; 11663 if (Char1.getInt().ne(Char2.getInt())) { 11664 if (IsWide) // wmemcmp compares with wchar_t signedness. 11665 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11666 // memcmp always compares unsigned chars. 11667 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11668 } 11669 if (StopAtNull && !Char1.getInt()) 11670 return Success(0, E); 11671 assert(!(StopAtNull && !Char2.getInt())); 11672 if (!AdvanceElems()) 11673 return false; 11674 } 11675 // We hit the strncmp / memcmp limit. 11676 return Success(0, E); 11677 } 11678 11679 case Builtin::BI__atomic_always_lock_free: 11680 case Builtin::BI__atomic_is_lock_free: 11681 case Builtin::BI__c11_atomic_is_lock_free: { 11682 APSInt SizeVal; 11683 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11684 return false; 11685 11686 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11687 // of two less than or equal to the maximum inline atomic width, we know it 11688 // is lock-free. If the size isn't a power of two, or greater than the 11689 // maximum alignment where we promote atomics, we know it is not lock-free 11690 // (at least not in the sense of atomic_is_lock_free). Otherwise, 11691 // the answer can only be determined at runtime; for example, 16-byte 11692 // atomics have lock-free implementations on some, but not all, 11693 // x86-64 processors. 11694 11695 // Check power-of-two. 11696 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11697 if (Size.isPowerOfTwo()) { 11698 // Check against inlining width. 11699 unsigned InlineWidthBits = 11700 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11701 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11702 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11703 Size == CharUnits::One() || 11704 E->getArg(1)->isNullPointerConstant(Info.Ctx, 11705 Expr::NPC_NeverValueDependent)) 11706 // OK, we will inline appropriately-aligned operations of this size, 11707 // and _Atomic(T) is appropriately-aligned. 11708 return Success(1, E); 11709 11710 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 11711 castAs<PointerType>()->getPointeeType(); 11712 if (!PointeeType->isIncompleteType() && 11713 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 11714 // OK, we will inline operations on this object. 11715 return Success(1, E); 11716 } 11717 } 11718 } 11719 11720 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 11721 Success(0, E) : Error(E); 11722 } 11723 case Builtin::BIomp_is_initial_device: 11724 // We can decide statically which value the runtime would return if called. 11725 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 11726 case Builtin::BI__builtin_add_overflow: 11727 case Builtin::BI__builtin_sub_overflow: 11728 case Builtin::BI__builtin_mul_overflow: 11729 case Builtin::BI__builtin_sadd_overflow: 11730 case Builtin::BI__builtin_uadd_overflow: 11731 case Builtin::BI__builtin_uaddl_overflow: 11732 case Builtin::BI__builtin_uaddll_overflow: 11733 case Builtin::BI__builtin_usub_overflow: 11734 case Builtin::BI__builtin_usubl_overflow: 11735 case Builtin::BI__builtin_usubll_overflow: 11736 case Builtin::BI__builtin_umul_overflow: 11737 case Builtin::BI__builtin_umull_overflow: 11738 case Builtin::BI__builtin_umulll_overflow: 11739 case Builtin::BI__builtin_saddl_overflow: 11740 case Builtin::BI__builtin_saddll_overflow: 11741 case Builtin::BI__builtin_ssub_overflow: 11742 case Builtin::BI__builtin_ssubl_overflow: 11743 case Builtin::BI__builtin_ssubll_overflow: 11744 case Builtin::BI__builtin_smul_overflow: 11745 case Builtin::BI__builtin_smull_overflow: 11746 case Builtin::BI__builtin_smulll_overflow: { 11747 LValue ResultLValue; 11748 APSInt LHS, RHS; 11749 11750 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 11751 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 11752 !EvaluateInteger(E->getArg(1), RHS, Info) || 11753 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 11754 return false; 11755 11756 APSInt Result; 11757 bool DidOverflow = false; 11758 11759 // If the types don't have to match, enlarge all 3 to the largest of them. 11760 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11761 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11762 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11763 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 11764 ResultType->isSignedIntegerOrEnumerationType(); 11765 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 11766 ResultType->isSignedIntegerOrEnumerationType(); 11767 uint64_t LHSSize = LHS.getBitWidth(); 11768 uint64_t RHSSize = RHS.getBitWidth(); 11769 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 11770 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 11771 11772 // Add an additional bit if the signedness isn't uniformly agreed to. We 11773 // could do this ONLY if there is a signed and an unsigned that both have 11774 // MaxBits, but the code to check that is pretty nasty. The issue will be 11775 // caught in the shrink-to-result later anyway. 11776 if (IsSigned && !AllSigned) 11777 ++MaxBits; 11778 11779 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 11780 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 11781 Result = APSInt(MaxBits, !IsSigned); 11782 } 11783 11784 // Find largest int. 11785 switch (BuiltinOp) { 11786 default: 11787 llvm_unreachable("Invalid value for BuiltinOp"); 11788 case Builtin::BI__builtin_add_overflow: 11789 case Builtin::BI__builtin_sadd_overflow: 11790 case Builtin::BI__builtin_saddl_overflow: 11791 case Builtin::BI__builtin_saddll_overflow: 11792 case Builtin::BI__builtin_uadd_overflow: 11793 case Builtin::BI__builtin_uaddl_overflow: 11794 case Builtin::BI__builtin_uaddll_overflow: 11795 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 11796 : LHS.uadd_ov(RHS, DidOverflow); 11797 break; 11798 case Builtin::BI__builtin_sub_overflow: 11799 case Builtin::BI__builtin_ssub_overflow: 11800 case Builtin::BI__builtin_ssubl_overflow: 11801 case Builtin::BI__builtin_ssubll_overflow: 11802 case Builtin::BI__builtin_usub_overflow: 11803 case Builtin::BI__builtin_usubl_overflow: 11804 case Builtin::BI__builtin_usubll_overflow: 11805 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 11806 : LHS.usub_ov(RHS, DidOverflow); 11807 break; 11808 case Builtin::BI__builtin_mul_overflow: 11809 case Builtin::BI__builtin_smul_overflow: 11810 case Builtin::BI__builtin_smull_overflow: 11811 case Builtin::BI__builtin_smulll_overflow: 11812 case Builtin::BI__builtin_umul_overflow: 11813 case Builtin::BI__builtin_umull_overflow: 11814 case Builtin::BI__builtin_umulll_overflow: 11815 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 11816 : LHS.umul_ov(RHS, DidOverflow); 11817 break; 11818 } 11819 11820 // In the case where multiple sizes are allowed, truncate and see if 11821 // the values are the same. 11822 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 11823 BuiltinOp == Builtin::BI__builtin_sub_overflow || 11824 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 11825 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 11826 // since it will give us the behavior of a TruncOrSelf in the case where 11827 // its parameter <= its size. We previously set Result to be at least the 11828 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 11829 // will work exactly like TruncOrSelf. 11830 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 11831 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 11832 11833 if (!APSInt::isSameValue(Temp, Result)) 11834 DidOverflow = true; 11835 Result = Temp; 11836 } 11837 11838 APValue APV{Result}; 11839 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 11840 return false; 11841 return Success(DidOverflow, E); 11842 } 11843 } 11844 } 11845 11846 /// Determine whether this is a pointer past the end of the complete 11847 /// object referred to by the lvalue. 11848 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 11849 const LValue &LV) { 11850 // A null pointer can be viewed as being "past the end" but we don't 11851 // choose to look at it that way here. 11852 if (!LV.getLValueBase()) 11853 return false; 11854 11855 // If the designator is valid and refers to a subobject, we're not pointing 11856 // past the end. 11857 if (!LV.getLValueDesignator().Invalid && 11858 !LV.getLValueDesignator().isOnePastTheEnd()) 11859 return false; 11860 11861 // A pointer to an incomplete type might be past-the-end if the type's size is 11862 // zero. We cannot tell because the type is incomplete. 11863 QualType Ty = getType(LV.getLValueBase()); 11864 if (Ty->isIncompleteType()) 11865 return true; 11866 11867 // We're a past-the-end pointer if we point to the byte after the object, 11868 // no matter what our type or path is. 11869 auto Size = Ctx.getTypeSizeInChars(Ty); 11870 return LV.getLValueOffset() == Size; 11871 } 11872 11873 namespace { 11874 11875 /// Data recursive integer evaluator of certain binary operators. 11876 /// 11877 /// We use a data recursive algorithm for binary operators so that we are able 11878 /// to handle extreme cases of chained binary operators without causing stack 11879 /// overflow. 11880 class DataRecursiveIntBinOpEvaluator { 11881 struct EvalResult { 11882 APValue Val; 11883 bool Failed; 11884 11885 EvalResult() : Failed(false) { } 11886 11887 void swap(EvalResult &RHS) { 11888 Val.swap(RHS.Val); 11889 Failed = RHS.Failed; 11890 RHS.Failed = false; 11891 } 11892 }; 11893 11894 struct Job { 11895 const Expr *E; 11896 EvalResult LHSResult; // meaningful only for binary operator expression. 11897 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 11898 11899 Job() = default; 11900 Job(Job &&) = default; 11901 11902 void startSpeculativeEval(EvalInfo &Info) { 11903 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 11904 } 11905 11906 private: 11907 SpeculativeEvaluationRAII SpecEvalRAII; 11908 }; 11909 11910 SmallVector<Job, 16> Queue; 11911 11912 IntExprEvaluator &IntEval; 11913 EvalInfo &Info; 11914 APValue &FinalResult; 11915 11916 public: 11917 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 11918 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 11919 11920 /// True if \param E is a binary operator that we are going to handle 11921 /// data recursively. 11922 /// We handle binary operators that are comma, logical, or that have operands 11923 /// with integral or enumeration type. 11924 static bool shouldEnqueue(const BinaryOperator *E) { 11925 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 11926 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 11927 E->getLHS()->getType()->isIntegralOrEnumerationType() && 11928 E->getRHS()->getType()->isIntegralOrEnumerationType()); 11929 } 11930 11931 bool Traverse(const BinaryOperator *E) { 11932 enqueue(E); 11933 EvalResult PrevResult; 11934 while (!Queue.empty()) 11935 process(PrevResult); 11936 11937 if (PrevResult.Failed) return false; 11938 11939 FinalResult.swap(PrevResult.Val); 11940 return true; 11941 } 11942 11943 private: 11944 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 11945 return IntEval.Success(Value, E, Result); 11946 } 11947 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 11948 return IntEval.Success(Value, E, Result); 11949 } 11950 bool Error(const Expr *E) { 11951 return IntEval.Error(E); 11952 } 11953 bool Error(const Expr *E, diag::kind D) { 11954 return IntEval.Error(E, D); 11955 } 11956 11957 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 11958 return Info.CCEDiag(E, D); 11959 } 11960 11961 // Returns true if visiting the RHS is necessary, false otherwise. 11962 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11963 bool &SuppressRHSDiags); 11964 11965 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 11966 const BinaryOperator *E, APValue &Result); 11967 11968 void EvaluateExpr(const Expr *E, EvalResult &Result) { 11969 Result.Failed = !Evaluate(Result.Val, Info, E); 11970 if (Result.Failed) 11971 Result.Val = APValue(); 11972 } 11973 11974 void process(EvalResult &Result); 11975 11976 void enqueue(const Expr *E) { 11977 E = E->IgnoreParens(); 11978 Queue.resize(Queue.size()+1); 11979 Queue.back().E = E; 11980 Queue.back().Kind = Job::AnyExprKind; 11981 } 11982 }; 11983 11984 } 11985 11986 bool DataRecursiveIntBinOpEvaluator:: 11987 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 11988 bool &SuppressRHSDiags) { 11989 if (E->getOpcode() == BO_Comma) { 11990 // Ignore LHS but note if we could not evaluate it. 11991 if (LHSResult.Failed) 11992 return Info.noteSideEffect(); 11993 return true; 11994 } 11995 11996 if (E->isLogicalOp()) { 11997 bool LHSAsBool; 11998 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 11999 // We were able to evaluate the LHS, see if we can get away with not 12000 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12001 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12002 Success(LHSAsBool, E, LHSResult.Val); 12003 return false; // Ignore RHS 12004 } 12005 } else { 12006 LHSResult.Failed = true; 12007 12008 // Since we weren't able to evaluate the left hand side, it 12009 // might have had side effects. 12010 if (!Info.noteSideEffect()) 12011 return false; 12012 12013 // We can't evaluate the LHS; however, sometimes the result 12014 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12015 // Don't ignore RHS and suppress diagnostics from this arm. 12016 SuppressRHSDiags = true; 12017 } 12018 12019 return true; 12020 } 12021 12022 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12023 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12024 12025 if (LHSResult.Failed && !Info.noteFailure()) 12026 return false; // Ignore RHS; 12027 12028 return true; 12029 } 12030 12031 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12032 bool IsSub) { 12033 // Compute the new offset in the appropriate width, wrapping at 64 bits. 12034 // FIXME: When compiling for a 32-bit target, we should use 32-bit 12035 // offsets. 12036 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12037 CharUnits &Offset = LVal.getLValueOffset(); 12038 uint64_t Offset64 = Offset.getQuantity(); 12039 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12040 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12041 : Offset64 + Index64); 12042 } 12043 12044 bool DataRecursiveIntBinOpEvaluator:: 12045 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12046 const BinaryOperator *E, APValue &Result) { 12047 if (E->getOpcode() == BO_Comma) { 12048 if (RHSResult.Failed) 12049 return false; 12050 Result = RHSResult.Val; 12051 return true; 12052 } 12053 12054 if (E->isLogicalOp()) { 12055 bool lhsResult, rhsResult; 12056 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12057 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12058 12059 if (LHSIsOK) { 12060 if (RHSIsOK) { 12061 if (E->getOpcode() == BO_LOr) 12062 return Success(lhsResult || rhsResult, E, Result); 12063 else 12064 return Success(lhsResult && rhsResult, E, Result); 12065 } 12066 } else { 12067 if (RHSIsOK) { 12068 // We can't evaluate the LHS; however, sometimes the result 12069 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12070 if (rhsResult == (E->getOpcode() == BO_LOr)) 12071 return Success(rhsResult, E, Result); 12072 } 12073 } 12074 12075 return false; 12076 } 12077 12078 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12079 E->getRHS()->getType()->isIntegralOrEnumerationType()); 12080 12081 if (LHSResult.Failed || RHSResult.Failed) 12082 return false; 12083 12084 const APValue &LHSVal = LHSResult.Val; 12085 const APValue &RHSVal = RHSResult.Val; 12086 12087 // Handle cases like (unsigned long)&a + 4. 12088 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12089 Result = LHSVal; 12090 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12091 return true; 12092 } 12093 12094 // Handle cases like 4 + (unsigned long)&a 12095 if (E->getOpcode() == BO_Add && 12096 RHSVal.isLValue() && LHSVal.isInt()) { 12097 Result = RHSVal; 12098 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12099 return true; 12100 } 12101 12102 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12103 // Handle (intptr_t)&&A - (intptr_t)&&B. 12104 if (!LHSVal.getLValueOffset().isZero() || 12105 !RHSVal.getLValueOffset().isZero()) 12106 return false; 12107 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12108 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12109 if (!LHSExpr || !RHSExpr) 12110 return false; 12111 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12112 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12113 if (!LHSAddrExpr || !RHSAddrExpr) 12114 return false; 12115 // Make sure both labels come from the same function. 12116 if (LHSAddrExpr->getLabel()->getDeclContext() != 12117 RHSAddrExpr->getLabel()->getDeclContext()) 12118 return false; 12119 Result = APValue(LHSAddrExpr, RHSAddrExpr); 12120 return true; 12121 } 12122 12123 // All the remaining cases expect both operands to be an integer 12124 if (!LHSVal.isInt() || !RHSVal.isInt()) 12125 return Error(E); 12126 12127 // Set up the width and signedness manually, in case it can't be deduced 12128 // from the operation we're performing. 12129 // FIXME: Don't do this in the cases where we can deduce it. 12130 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12131 E->getType()->isUnsignedIntegerOrEnumerationType()); 12132 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12133 RHSVal.getInt(), Value)) 12134 return false; 12135 return Success(Value, E, Result); 12136 } 12137 12138 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12139 Job &job = Queue.back(); 12140 12141 switch (job.Kind) { 12142 case Job::AnyExprKind: { 12143 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12144 if (shouldEnqueue(Bop)) { 12145 job.Kind = Job::BinOpKind; 12146 enqueue(Bop->getLHS()); 12147 return; 12148 } 12149 } 12150 12151 EvaluateExpr(job.E, Result); 12152 Queue.pop_back(); 12153 return; 12154 } 12155 12156 case Job::BinOpKind: { 12157 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12158 bool SuppressRHSDiags = false; 12159 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12160 Queue.pop_back(); 12161 return; 12162 } 12163 if (SuppressRHSDiags) 12164 job.startSpeculativeEval(Info); 12165 job.LHSResult.swap(Result); 12166 job.Kind = Job::BinOpVisitedLHSKind; 12167 enqueue(Bop->getRHS()); 12168 return; 12169 } 12170 12171 case Job::BinOpVisitedLHSKind: { 12172 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12173 EvalResult RHS; 12174 RHS.swap(Result); 12175 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12176 Queue.pop_back(); 12177 return; 12178 } 12179 } 12180 12181 llvm_unreachable("Invalid Job::Kind!"); 12182 } 12183 12184 namespace { 12185 /// Used when we determine that we should fail, but can keep evaluating prior to 12186 /// noting that we had a failure. 12187 class DelayedNoteFailureRAII { 12188 EvalInfo &Info; 12189 bool NoteFailure; 12190 12191 public: 12192 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 12193 : Info(Info), NoteFailure(NoteFailure) {} 12194 ~DelayedNoteFailureRAII() { 12195 if (NoteFailure) { 12196 bool ContinueAfterFailure = Info.noteFailure(); 12197 (void)ContinueAfterFailure; 12198 assert(ContinueAfterFailure && 12199 "Shouldn't have kept evaluating on failure."); 12200 } 12201 } 12202 }; 12203 12204 enum class CmpResult { 12205 Unequal, 12206 Less, 12207 Equal, 12208 Greater, 12209 Unordered, 12210 }; 12211 } 12212 12213 template <class SuccessCB, class AfterCB> 12214 static bool 12215 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12216 SuccessCB &&Success, AfterCB &&DoAfter) { 12217 assert(E->isComparisonOp() && "expected comparison operator"); 12218 assert((E->getOpcode() == BO_Cmp || 12219 E->getType()->isIntegralOrEnumerationType()) && 12220 "unsupported binary expression evaluation"); 12221 auto Error = [&](const Expr *E) { 12222 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12223 return false; 12224 }; 12225 12226 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12227 bool IsEquality = E->isEqualityOp(); 12228 12229 QualType LHSTy = E->getLHS()->getType(); 12230 QualType RHSTy = E->getRHS()->getType(); 12231 12232 if (LHSTy->isIntegralOrEnumerationType() && 12233 RHSTy->isIntegralOrEnumerationType()) { 12234 APSInt LHS, RHS; 12235 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12236 if (!LHSOK && !Info.noteFailure()) 12237 return false; 12238 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12239 return false; 12240 if (LHS < RHS) 12241 return Success(CmpResult::Less, E); 12242 if (LHS > RHS) 12243 return Success(CmpResult::Greater, E); 12244 return Success(CmpResult::Equal, E); 12245 } 12246 12247 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12248 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12249 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12250 12251 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12252 if (!LHSOK && !Info.noteFailure()) 12253 return false; 12254 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12255 return false; 12256 if (LHSFX < RHSFX) 12257 return Success(CmpResult::Less, E); 12258 if (LHSFX > RHSFX) 12259 return Success(CmpResult::Greater, E); 12260 return Success(CmpResult::Equal, E); 12261 } 12262 12263 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12264 ComplexValue LHS, RHS; 12265 bool LHSOK; 12266 if (E->isAssignmentOp()) { 12267 LValue LV; 12268 EvaluateLValue(E->getLHS(), LV, Info); 12269 LHSOK = false; 12270 } else if (LHSTy->isRealFloatingType()) { 12271 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12272 if (LHSOK) { 12273 LHS.makeComplexFloat(); 12274 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12275 } 12276 } else { 12277 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12278 } 12279 if (!LHSOK && !Info.noteFailure()) 12280 return false; 12281 12282 if (E->getRHS()->getType()->isRealFloatingType()) { 12283 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12284 return false; 12285 RHS.makeComplexFloat(); 12286 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12287 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12288 return false; 12289 12290 if (LHS.isComplexFloat()) { 12291 APFloat::cmpResult CR_r = 12292 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12293 APFloat::cmpResult CR_i = 12294 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12295 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12296 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12297 } else { 12298 assert(IsEquality && "invalid complex comparison"); 12299 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12300 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12301 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12302 } 12303 } 12304 12305 if (LHSTy->isRealFloatingType() && 12306 RHSTy->isRealFloatingType()) { 12307 APFloat RHS(0.0), LHS(0.0); 12308 12309 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12310 if (!LHSOK && !Info.noteFailure()) 12311 return false; 12312 12313 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12314 return false; 12315 12316 assert(E->isComparisonOp() && "Invalid binary operator!"); 12317 auto GetCmpRes = [&]() { 12318 switch (LHS.compare(RHS)) { 12319 case APFloat::cmpEqual: 12320 return CmpResult::Equal; 12321 case APFloat::cmpLessThan: 12322 return CmpResult::Less; 12323 case APFloat::cmpGreaterThan: 12324 return CmpResult::Greater; 12325 case APFloat::cmpUnordered: 12326 return CmpResult::Unordered; 12327 } 12328 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12329 }; 12330 return Success(GetCmpRes(), E); 12331 } 12332 12333 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12334 LValue LHSValue, RHSValue; 12335 12336 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12337 if (!LHSOK && !Info.noteFailure()) 12338 return false; 12339 12340 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12341 return false; 12342 12343 // Reject differing bases from the normal codepath; we special-case 12344 // comparisons to null. 12345 if (!HasSameBase(LHSValue, RHSValue)) { 12346 // Inequalities and subtractions between unrelated pointers have 12347 // unspecified or undefined behavior. 12348 if (!IsEquality) { 12349 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12350 return false; 12351 } 12352 // A constant address may compare equal to the address of a symbol. 12353 // The one exception is that address of an object cannot compare equal 12354 // to a null pointer constant. 12355 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12356 (!RHSValue.Base && !RHSValue.Offset.isZero())) 12357 return Error(E); 12358 // It's implementation-defined whether distinct literals will have 12359 // distinct addresses. In clang, the result of such a comparison is 12360 // unspecified, so it is not a constant expression. However, we do know 12361 // that the address of a literal will be non-null. 12362 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12363 LHSValue.Base && RHSValue.Base) 12364 return Error(E); 12365 // We can't tell whether weak symbols will end up pointing to the same 12366 // object. 12367 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12368 return Error(E); 12369 // We can't compare the address of the start of one object with the 12370 // past-the-end address of another object, per C++ DR1652. 12371 if ((LHSValue.Base && LHSValue.Offset.isZero() && 12372 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12373 (RHSValue.Base && RHSValue.Offset.isZero() && 12374 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12375 return Error(E); 12376 // We can't tell whether an object is at the same address as another 12377 // zero sized object. 12378 if ((RHSValue.Base && isZeroSized(LHSValue)) || 12379 (LHSValue.Base && isZeroSized(RHSValue))) 12380 return Error(E); 12381 return Success(CmpResult::Unequal, E); 12382 } 12383 12384 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12385 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12386 12387 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12388 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12389 12390 // C++11 [expr.rel]p3: 12391 // Pointers to void (after pointer conversions) can be compared, with a 12392 // result defined as follows: If both pointers represent the same 12393 // address or are both the null pointer value, the result is true if the 12394 // operator is <= or >= and false otherwise; otherwise the result is 12395 // unspecified. 12396 // We interpret this as applying to pointers to *cv* void. 12397 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12398 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12399 12400 // C++11 [expr.rel]p2: 12401 // - If two pointers point to non-static data members of the same object, 12402 // or to subobjects or array elements fo such members, recursively, the 12403 // pointer to the later declared member compares greater provided the 12404 // two members have the same access control and provided their class is 12405 // not a union. 12406 // [...] 12407 // - Otherwise pointer comparisons are unspecified. 12408 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12409 bool WasArrayIndex; 12410 unsigned Mismatch = FindDesignatorMismatch( 12411 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12412 // At the point where the designators diverge, the comparison has a 12413 // specified value if: 12414 // - we are comparing array indices 12415 // - we are comparing fields of a union, or fields with the same access 12416 // Otherwise, the result is unspecified and thus the comparison is not a 12417 // constant expression. 12418 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12419 Mismatch < RHSDesignator.Entries.size()) { 12420 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12421 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12422 if (!LF && !RF) 12423 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12424 else if (!LF) 12425 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12426 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12427 << RF->getParent() << RF; 12428 else if (!RF) 12429 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12430 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12431 << LF->getParent() << LF; 12432 else if (!LF->getParent()->isUnion() && 12433 LF->getAccess() != RF->getAccess()) 12434 Info.CCEDiag(E, 12435 diag::note_constexpr_pointer_comparison_differing_access) 12436 << LF << LF->getAccess() << RF << RF->getAccess() 12437 << LF->getParent(); 12438 } 12439 } 12440 12441 // The comparison here must be unsigned, and performed with the same 12442 // width as the pointer. 12443 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12444 uint64_t CompareLHS = LHSOffset.getQuantity(); 12445 uint64_t CompareRHS = RHSOffset.getQuantity(); 12446 assert(PtrSize <= 64 && "Unexpected pointer width"); 12447 uint64_t Mask = ~0ULL >> (64 - PtrSize); 12448 CompareLHS &= Mask; 12449 CompareRHS &= Mask; 12450 12451 // If there is a base and this is a relational operator, we can only 12452 // compare pointers within the object in question; otherwise, the result 12453 // depends on where the object is located in memory. 12454 if (!LHSValue.Base.isNull() && IsRelational) { 12455 QualType BaseTy = getType(LHSValue.Base); 12456 if (BaseTy->isIncompleteType()) 12457 return Error(E); 12458 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12459 uint64_t OffsetLimit = Size.getQuantity(); 12460 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12461 return Error(E); 12462 } 12463 12464 if (CompareLHS < CompareRHS) 12465 return Success(CmpResult::Less, E); 12466 if (CompareLHS > CompareRHS) 12467 return Success(CmpResult::Greater, E); 12468 return Success(CmpResult::Equal, E); 12469 } 12470 12471 if (LHSTy->isMemberPointerType()) { 12472 assert(IsEquality && "unexpected member pointer operation"); 12473 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12474 12475 MemberPtr LHSValue, RHSValue; 12476 12477 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12478 if (!LHSOK && !Info.noteFailure()) 12479 return false; 12480 12481 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12482 return false; 12483 12484 // C++11 [expr.eq]p2: 12485 // If both operands are null, they compare equal. Otherwise if only one is 12486 // null, they compare unequal. 12487 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12488 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12489 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12490 } 12491 12492 // Otherwise if either is a pointer to a virtual member function, the 12493 // result is unspecified. 12494 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12495 if (MD->isVirtual()) 12496 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12497 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12498 if (MD->isVirtual()) 12499 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12500 12501 // Otherwise they compare equal if and only if they would refer to the 12502 // same member of the same most derived object or the same subobject if 12503 // they were dereferenced with a hypothetical object of the associated 12504 // class type. 12505 bool Equal = LHSValue == RHSValue; 12506 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12507 } 12508 12509 if (LHSTy->isNullPtrType()) { 12510 assert(E->isComparisonOp() && "unexpected nullptr operation"); 12511 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12512 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12513 // are compared, the result is true of the operator is <=, >= or ==, and 12514 // false otherwise. 12515 return Success(CmpResult::Equal, E); 12516 } 12517 12518 return DoAfter(); 12519 } 12520 12521 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12522 if (!CheckLiteralType(Info, E)) 12523 return false; 12524 12525 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12526 ComparisonCategoryResult CCR; 12527 switch (CR) { 12528 case CmpResult::Unequal: 12529 llvm_unreachable("should never produce Unequal for three-way comparison"); 12530 case CmpResult::Less: 12531 CCR = ComparisonCategoryResult::Less; 12532 break; 12533 case CmpResult::Equal: 12534 CCR = ComparisonCategoryResult::Equal; 12535 break; 12536 case CmpResult::Greater: 12537 CCR = ComparisonCategoryResult::Greater; 12538 break; 12539 case CmpResult::Unordered: 12540 CCR = ComparisonCategoryResult::Unordered; 12541 break; 12542 } 12543 // Evaluation succeeded. Lookup the information for the comparison category 12544 // type and fetch the VarDecl for the result. 12545 const ComparisonCategoryInfo &CmpInfo = 12546 Info.Ctx.CompCategories.getInfoForType(E->getType()); 12547 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12548 // Check and evaluate the result as a constant expression. 12549 LValue LV; 12550 LV.set(VD); 12551 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12552 return false; 12553 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 12554 }; 12555 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12556 return ExprEvaluatorBaseTy::VisitBinCmp(E); 12557 }); 12558 } 12559 12560 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12561 // We don't call noteFailure immediately because the assignment happens after 12562 // we evaluate LHS and RHS. 12563 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 12564 return Error(E); 12565 12566 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 12567 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12568 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12569 12570 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12571 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12572 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12573 12574 if (E->isComparisonOp()) { 12575 // Evaluate builtin binary comparisons by evaluating them as three-way 12576 // comparisons and then translating the result. 12577 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12578 assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12579 "should only produce Unequal for equality comparisons"); 12580 bool IsEqual = CR == CmpResult::Equal, 12581 IsLess = CR == CmpResult::Less, 12582 IsGreater = CR == CmpResult::Greater; 12583 auto Op = E->getOpcode(); 12584 switch (Op) { 12585 default: 12586 llvm_unreachable("unsupported binary operator"); 12587 case BO_EQ: 12588 case BO_NE: 12589 return Success(IsEqual == (Op == BO_EQ), E); 12590 case BO_LT: 12591 return Success(IsLess, E); 12592 case BO_GT: 12593 return Success(IsGreater, E); 12594 case BO_LE: 12595 return Success(IsEqual || IsLess, E); 12596 case BO_GE: 12597 return Success(IsEqual || IsGreater, E); 12598 } 12599 }; 12600 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12601 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12602 }); 12603 } 12604 12605 QualType LHSTy = E->getLHS()->getType(); 12606 QualType RHSTy = E->getRHS()->getType(); 12607 12608 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12609 E->getOpcode() == BO_Sub) { 12610 LValue LHSValue, RHSValue; 12611 12612 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12613 if (!LHSOK && !Info.noteFailure()) 12614 return false; 12615 12616 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12617 return false; 12618 12619 // Reject differing bases from the normal codepath; we special-case 12620 // comparisons to null. 12621 if (!HasSameBase(LHSValue, RHSValue)) { 12622 // Handle &&A - &&B. 12623 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12624 return Error(E); 12625 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12626 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12627 if (!LHSExpr || !RHSExpr) 12628 return Error(E); 12629 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12630 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12631 if (!LHSAddrExpr || !RHSAddrExpr) 12632 return Error(E); 12633 // Make sure both labels come from the same function. 12634 if (LHSAddrExpr->getLabel()->getDeclContext() != 12635 RHSAddrExpr->getLabel()->getDeclContext()) 12636 return Error(E); 12637 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12638 } 12639 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12640 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12641 12642 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12643 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12644 12645 // C++11 [expr.add]p6: 12646 // Unless both pointers point to elements of the same array object, or 12647 // one past the last element of the array object, the behavior is 12648 // undefined. 12649 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12650 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12651 RHSDesignator)) 12652 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12653 12654 QualType Type = E->getLHS()->getType(); 12655 QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12656 12657 CharUnits ElementSize; 12658 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12659 return false; 12660 12661 // As an extension, a type may have zero size (empty struct or union in 12662 // C, array of zero length). Pointer subtraction in such cases has 12663 // undefined behavior, so is not constant. 12664 if (ElementSize.isZero()) { 12665 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12666 << ElementType; 12667 return false; 12668 } 12669 12670 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12671 // and produce incorrect results when it overflows. Such behavior 12672 // appears to be non-conforming, but is common, so perhaps we should 12673 // assume the standard intended for such cases to be undefined behavior 12674 // and check for them. 12675 12676 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12677 // overflow in the final conversion to ptrdiff_t. 12678 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12679 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12680 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12681 false); 12682 APSInt TrueResult = (LHS - RHS) / ElemSize; 12683 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12684 12685 if (Result.extend(65) != TrueResult && 12686 !HandleOverflow(Info, E, TrueResult, E->getType())) 12687 return false; 12688 return Success(Result, E); 12689 } 12690 12691 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12692 } 12693 12694 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12695 /// a result as the expression's type. 12696 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12697 const UnaryExprOrTypeTraitExpr *E) { 12698 switch(E->getKind()) { 12699 case UETT_PreferredAlignOf: 12700 case UETT_AlignOf: { 12701 if (E->isArgumentType()) 12702 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 12703 E); 12704 else 12705 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 12706 E); 12707 } 12708 12709 case UETT_VecStep: { 12710 QualType Ty = E->getTypeOfArgument(); 12711 12712 if (Ty->isVectorType()) { 12713 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 12714 12715 // The vec_step built-in functions that take a 3-component 12716 // vector return 4. (OpenCL 1.1 spec 6.11.12) 12717 if (n == 3) 12718 n = 4; 12719 12720 return Success(n, E); 12721 } else 12722 return Success(1, E); 12723 } 12724 12725 case UETT_SizeOf: { 12726 QualType SrcTy = E->getTypeOfArgument(); 12727 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 12728 // the result is the size of the referenced type." 12729 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 12730 SrcTy = Ref->getPointeeType(); 12731 12732 CharUnits Sizeof; 12733 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 12734 return false; 12735 return Success(Sizeof, E); 12736 } 12737 case UETT_OpenMPRequiredSimdAlign: 12738 assert(E->isArgumentType()); 12739 return Success( 12740 Info.Ctx.toCharUnitsFromBits( 12741 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 12742 .getQuantity(), 12743 E); 12744 } 12745 12746 llvm_unreachable("unknown expr/type trait"); 12747 } 12748 12749 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 12750 CharUnits Result; 12751 unsigned n = OOE->getNumComponents(); 12752 if (n == 0) 12753 return Error(OOE); 12754 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 12755 for (unsigned i = 0; i != n; ++i) { 12756 OffsetOfNode ON = OOE->getComponent(i); 12757 switch (ON.getKind()) { 12758 case OffsetOfNode::Array: { 12759 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 12760 APSInt IdxResult; 12761 if (!EvaluateInteger(Idx, IdxResult, Info)) 12762 return false; 12763 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 12764 if (!AT) 12765 return Error(OOE); 12766 CurrentType = AT->getElementType(); 12767 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 12768 Result += IdxResult.getSExtValue() * ElementSize; 12769 break; 12770 } 12771 12772 case OffsetOfNode::Field: { 12773 FieldDecl *MemberDecl = ON.getField(); 12774 const RecordType *RT = CurrentType->getAs<RecordType>(); 12775 if (!RT) 12776 return Error(OOE); 12777 RecordDecl *RD = RT->getDecl(); 12778 if (RD->isInvalidDecl()) return false; 12779 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12780 unsigned i = MemberDecl->getFieldIndex(); 12781 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 12782 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 12783 CurrentType = MemberDecl->getType().getNonReferenceType(); 12784 break; 12785 } 12786 12787 case OffsetOfNode::Identifier: 12788 llvm_unreachable("dependent __builtin_offsetof"); 12789 12790 case OffsetOfNode::Base: { 12791 CXXBaseSpecifier *BaseSpec = ON.getBase(); 12792 if (BaseSpec->isVirtual()) 12793 return Error(OOE); 12794 12795 // Find the layout of the class whose base we are looking into. 12796 const RecordType *RT = CurrentType->getAs<RecordType>(); 12797 if (!RT) 12798 return Error(OOE); 12799 RecordDecl *RD = RT->getDecl(); 12800 if (RD->isInvalidDecl()) return false; 12801 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 12802 12803 // Find the base class itself. 12804 CurrentType = BaseSpec->getType(); 12805 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 12806 if (!BaseRT) 12807 return Error(OOE); 12808 12809 // Add the offset to the base. 12810 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 12811 break; 12812 } 12813 } 12814 } 12815 return Success(Result, OOE); 12816 } 12817 12818 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12819 switch (E->getOpcode()) { 12820 default: 12821 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 12822 // See C99 6.6p3. 12823 return Error(E); 12824 case UO_Extension: 12825 // FIXME: Should extension allow i-c-e extension expressions in its scope? 12826 // If so, we could clear the diagnostic ID. 12827 return Visit(E->getSubExpr()); 12828 case UO_Plus: 12829 // The result is just the value. 12830 return Visit(E->getSubExpr()); 12831 case UO_Minus: { 12832 if (!Visit(E->getSubExpr())) 12833 return false; 12834 if (!Result.isInt()) return Error(E); 12835 const APSInt &Value = Result.getInt(); 12836 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 12837 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 12838 E->getType())) 12839 return false; 12840 return Success(-Value, E); 12841 } 12842 case UO_Not: { 12843 if (!Visit(E->getSubExpr())) 12844 return false; 12845 if (!Result.isInt()) return Error(E); 12846 return Success(~Result.getInt(), E); 12847 } 12848 case UO_LNot: { 12849 bool bres; 12850 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 12851 return false; 12852 return Success(!bres, E); 12853 } 12854 } 12855 } 12856 12857 /// HandleCast - This is used to evaluate implicit or explicit casts where the 12858 /// result type is integer. 12859 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 12860 const Expr *SubExpr = E->getSubExpr(); 12861 QualType DestType = E->getType(); 12862 QualType SrcType = SubExpr->getType(); 12863 12864 switch (E->getCastKind()) { 12865 case CK_BaseToDerived: 12866 case CK_DerivedToBase: 12867 case CK_UncheckedDerivedToBase: 12868 case CK_Dynamic: 12869 case CK_ToUnion: 12870 case CK_ArrayToPointerDecay: 12871 case CK_FunctionToPointerDecay: 12872 case CK_NullToPointer: 12873 case CK_NullToMemberPointer: 12874 case CK_BaseToDerivedMemberPointer: 12875 case CK_DerivedToBaseMemberPointer: 12876 case CK_ReinterpretMemberPointer: 12877 case CK_ConstructorConversion: 12878 case CK_IntegralToPointer: 12879 case CK_ToVoid: 12880 case CK_VectorSplat: 12881 case CK_IntegralToFloating: 12882 case CK_FloatingCast: 12883 case CK_CPointerToObjCPointerCast: 12884 case CK_BlockPointerToObjCPointerCast: 12885 case CK_AnyPointerToBlockPointerCast: 12886 case CK_ObjCObjectLValueCast: 12887 case CK_FloatingRealToComplex: 12888 case CK_FloatingComplexToReal: 12889 case CK_FloatingComplexCast: 12890 case CK_FloatingComplexToIntegralComplex: 12891 case CK_IntegralRealToComplex: 12892 case CK_IntegralComplexCast: 12893 case CK_IntegralComplexToFloatingComplex: 12894 case CK_BuiltinFnToFnPtr: 12895 case CK_ZeroToOCLOpaqueType: 12896 case CK_NonAtomicToAtomic: 12897 case CK_AddressSpaceConversion: 12898 case CK_IntToOCLSampler: 12899 case CK_FloatingToFixedPoint: 12900 case CK_FixedPointToFloating: 12901 case CK_FixedPointCast: 12902 case CK_IntegralToFixedPoint: 12903 llvm_unreachable("invalid cast kind for integral value"); 12904 12905 case CK_BitCast: 12906 case CK_Dependent: 12907 case CK_LValueBitCast: 12908 case CK_ARCProduceObject: 12909 case CK_ARCConsumeObject: 12910 case CK_ARCReclaimReturnedObject: 12911 case CK_ARCExtendBlockObject: 12912 case CK_CopyAndAutoreleaseBlockObject: 12913 return Error(E); 12914 12915 case CK_UserDefinedConversion: 12916 case CK_LValueToRValue: 12917 case CK_AtomicToNonAtomic: 12918 case CK_NoOp: 12919 case CK_LValueToRValueBitCast: 12920 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12921 12922 case CK_MemberPointerToBoolean: 12923 case CK_PointerToBoolean: 12924 case CK_IntegralToBoolean: 12925 case CK_FloatingToBoolean: 12926 case CK_BooleanToSignedIntegral: 12927 case CK_FloatingComplexToBoolean: 12928 case CK_IntegralComplexToBoolean: { 12929 bool BoolResult; 12930 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 12931 return false; 12932 uint64_t IntResult = BoolResult; 12933 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 12934 IntResult = (uint64_t)-1; 12935 return Success(IntResult, E); 12936 } 12937 12938 case CK_FixedPointToIntegral: { 12939 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 12940 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 12941 return false; 12942 bool Overflowed; 12943 llvm::APSInt Result = Src.convertToInt( 12944 Info.Ctx.getIntWidth(DestType), 12945 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 12946 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 12947 return false; 12948 return Success(Result, E); 12949 } 12950 12951 case CK_FixedPointToBoolean: { 12952 // Unsigned padding does not affect this. 12953 APValue Val; 12954 if (!Evaluate(Val, Info, SubExpr)) 12955 return false; 12956 return Success(Val.getFixedPoint().getBoolValue(), E); 12957 } 12958 12959 case CK_IntegralCast: { 12960 if (!Visit(SubExpr)) 12961 return false; 12962 12963 if (!Result.isInt()) { 12964 // Allow casts of address-of-label differences if they are no-ops 12965 // or narrowing. (The narrowing case isn't actually guaranteed to 12966 // be constant-evaluatable except in some narrow cases which are hard 12967 // to detect here. We let it through on the assumption the user knows 12968 // what they are doing.) 12969 if (Result.isAddrLabelDiff()) 12970 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 12971 // Only allow casts of lvalues if they are lossless. 12972 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 12973 } 12974 12975 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 12976 Result.getInt()), E); 12977 } 12978 12979 case CK_PointerToIntegral: { 12980 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 12981 12982 LValue LV; 12983 if (!EvaluatePointer(SubExpr, LV, Info)) 12984 return false; 12985 12986 if (LV.getLValueBase()) { 12987 // Only allow based lvalue casts if they are lossless. 12988 // FIXME: Allow a larger integer size than the pointer size, and allow 12989 // narrowing back down to pointer width in subsequent integral casts. 12990 // FIXME: Check integer type's active bits, not its type size. 12991 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 12992 return Error(E); 12993 12994 LV.Designator.setInvalid(); 12995 LV.moveInto(Result); 12996 return true; 12997 } 12998 12999 APSInt AsInt; 13000 APValue V; 13001 LV.moveInto(V); 13002 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13003 llvm_unreachable("Can't cast this!"); 13004 13005 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13006 } 13007 13008 case CK_IntegralComplexToReal: { 13009 ComplexValue C; 13010 if (!EvaluateComplex(SubExpr, C, Info)) 13011 return false; 13012 return Success(C.getComplexIntReal(), E); 13013 } 13014 13015 case CK_FloatingToIntegral: { 13016 APFloat F(0.0); 13017 if (!EvaluateFloat(SubExpr, F, Info)) 13018 return false; 13019 13020 APSInt Value; 13021 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13022 return false; 13023 return Success(Value, E); 13024 } 13025 } 13026 13027 llvm_unreachable("unknown cast resulting in integral value"); 13028 } 13029 13030 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13031 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13032 ComplexValue LV; 13033 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13034 return false; 13035 if (!LV.isComplexInt()) 13036 return Error(E); 13037 return Success(LV.getComplexIntReal(), E); 13038 } 13039 13040 return Visit(E->getSubExpr()); 13041 } 13042 13043 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13044 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13045 ComplexValue LV; 13046 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13047 return false; 13048 if (!LV.isComplexInt()) 13049 return Error(E); 13050 return Success(LV.getComplexIntImag(), E); 13051 } 13052 13053 VisitIgnoredValue(E->getSubExpr()); 13054 return Success(0, E); 13055 } 13056 13057 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13058 return Success(E->getPackLength(), E); 13059 } 13060 13061 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13062 return Success(E->getValue(), E); 13063 } 13064 13065 bool IntExprEvaluator::VisitConceptSpecializationExpr( 13066 const ConceptSpecializationExpr *E) { 13067 return Success(E->isSatisfied(), E); 13068 } 13069 13070 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13071 return Success(E->isSatisfied(), E); 13072 } 13073 13074 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13075 switch (E->getOpcode()) { 13076 default: 13077 // Invalid unary operators 13078 return Error(E); 13079 case UO_Plus: 13080 // The result is just the value. 13081 return Visit(E->getSubExpr()); 13082 case UO_Minus: { 13083 if (!Visit(E->getSubExpr())) return false; 13084 if (!Result.isFixedPoint()) 13085 return Error(E); 13086 bool Overflowed; 13087 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13088 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13089 return false; 13090 return Success(Negated, E); 13091 } 13092 case UO_LNot: { 13093 bool bres; 13094 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13095 return false; 13096 return Success(!bres, E); 13097 } 13098 } 13099 } 13100 13101 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13102 const Expr *SubExpr = E->getSubExpr(); 13103 QualType DestType = E->getType(); 13104 assert(DestType->isFixedPointType() && 13105 "Expected destination type to be a fixed point type"); 13106 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13107 13108 switch (E->getCastKind()) { 13109 case CK_FixedPointCast: { 13110 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13111 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13112 return false; 13113 bool Overflowed; 13114 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13115 if (Overflowed) { 13116 if (Info.checkingForUndefinedBehavior()) 13117 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13118 diag::warn_fixedpoint_constant_overflow) 13119 << Result.toString() << E->getType(); 13120 else if (!HandleOverflow(Info, E, Result, E->getType())) 13121 return false; 13122 } 13123 return Success(Result, E); 13124 } 13125 case CK_IntegralToFixedPoint: { 13126 APSInt Src; 13127 if (!EvaluateInteger(SubExpr, Src, Info)) 13128 return false; 13129 13130 bool Overflowed; 13131 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13132 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13133 13134 if (Overflowed) { 13135 if (Info.checkingForUndefinedBehavior()) 13136 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13137 diag::warn_fixedpoint_constant_overflow) 13138 << IntResult.toString() << E->getType(); 13139 else if (!HandleOverflow(Info, E, IntResult, E->getType())) 13140 return false; 13141 } 13142 13143 return Success(IntResult, E); 13144 } 13145 case CK_FloatingToFixedPoint: { 13146 APFloat Src(0.0); 13147 if (!EvaluateFloat(SubExpr, Src, Info)) 13148 return false; 13149 13150 bool Overflowed; 13151 APFixedPoint Result = APFixedPoint::getFromFloatValue( 13152 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13153 13154 if (Overflowed) { 13155 if (Info.checkingForUndefinedBehavior()) 13156 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13157 diag::warn_fixedpoint_constant_overflow) 13158 << Result.toString() << E->getType(); 13159 else if (!HandleOverflow(Info, E, Result, E->getType())) 13160 return false; 13161 } 13162 13163 return Success(Result, E); 13164 } 13165 case CK_NoOp: 13166 case CK_LValueToRValue: 13167 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13168 default: 13169 return Error(E); 13170 } 13171 } 13172 13173 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13174 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13175 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13176 13177 const Expr *LHS = E->getLHS(); 13178 const Expr *RHS = E->getRHS(); 13179 FixedPointSemantics ResultFXSema = 13180 Info.Ctx.getFixedPointSemantics(E->getType()); 13181 13182 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13183 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13184 return false; 13185 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13186 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13187 return false; 13188 13189 bool OpOverflow = false, ConversionOverflow = false; 13190 APFixedPoint Result(LHSFX.getSemantics()); 13191 switch (E->getOpcode()) { 13192 case BO_Add: { 13193 Result = LHSFX.add(RHSFX, &OpOverflow) 13194 .convert(ResultFXSema, &ConversionOverflow); 13195 break; 13196 } 13197 case BO_Sub: { 13198 Result = LHSFX.sub(RHSFX, &OpOverflow) 13199 .convert(ResultFXSema, &ConversionOverflow); 13200 break; 13201 } 13202 case BO_Mul: { 13203 Result = LHSFX.mul(RHSFX, &OpOverflow) 13204 .convert(ResultFXSema, &ConversionOverflow); 13205 break; 13206 } 13207 case BO_Div: { 13208 if (RHSFX.getValue() == 0) { 13209 Info.FFDiag(E, diag::note_expr_divide_by_zero); 13210 return false; 13211 } 13212 Result = LHSFX.div(RHSFX, &OpOverflow) 13213 .convert(ResultFXSema, &ConversionOverflow); 13214 break; 13215 } 13216 case BO_Shl: 13217 case BO_Shr: { 13218 FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13219 llvm::APSInt RHSVal = RHSFX.getValue(); 13220 13221 unsigned ShiftBW = 13222 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13223 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13224 // Embedded-C 4.1.6.2.2: 13225 // The right operand must be nonnegative and less than the total number 13226 // of (nonpadding) bits of the fixed-point operand ... 13227 if (RHSVal.isNegative()) 13228 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13229 else if (Amt != RHSVal) 13230 Info.CCEDiag(E, diag::note_constexpr_large_shift) 13231 << RHSVal << E->getType() << ShiftBW; 13232 13233 if (E->getOpcode() == BO_Shl) 13234 Result = LHSFX.shl(Amt, &OpOverflow); 13235 else 13236 Result = LHSFX.shr(Amt, &OpOverflow); 13237 break; 13238 } 13239 default: 13240 return false; 13241 } 13242 if (OpOverflow || ConversionOverflow) { 13243 if (Info.checkingForUndefinedBehavior()) 13244 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13245 diag::warn_fixedpoint_constant_overflow) 13246 << Result.toString() << E->getType(); 13247 else if (!HandleOverflow(Info, E, Result, E->getType())) 13248 return false; 13249 } 13250 return Success(Result, E); 13251 } 13252 13253 //===----------------------------------------------------------------------===// 13254 // Float Evaluation 13255 //===----------------------------------------------------------------------===// 13256 13257 namespace { 13258 class FloatExprEvaluator 13259 : public ExprEvaluatorBase<FloatExprEvaluator> { 13260 APFloat &Result; 13261 public: 13262 FloatExprEvaluator(EvalInfo &info, APFloat &result) 13263 : ExprEvaluatorBaseTy(info), Result(result) {} 13264 13265 bool Success(const APValue &V, const Expr *e) { 13266 Result = V.getFloat(); 13267 return true; 13268 } 13269 13270 bool ZeroInitialization(const Expr *E) { 13271 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13272 return true; 13273 } 13274 13275 bool VisitCallExpr(const CallExpr *E); 13276 13277 bool VisitUnaryOperator(const UnaryOperator *E); 13278 bool VisitBinaryOperator(const BinaryOperator *E); 13279 bool VisitFloatingLiteral(const FloatingLiteral *E); 13280 bool VisitCastExpr(const CastExpr *E); 13281 13282 bool VisitUnaryReal(const UnaryOperator *E); 13283 bool VisitUnaryImag(const UnaryOperator *E); 13284 13285 // FIXME: Missing: array subscript of vector, member of vector 13286 }; 13287 } // end anonymous namespace 13288 13289 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13290 assert(E->isRValue() && E->getType()->isRealFloatingType()); 13291 return FloatExprEvaluator(Info, Result).Visit(E); 13292 } 13293 13294 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13295 QualType ResultTy, 13296 const Expr *Arg, 13297 bool SNaN, 13298 llvm::APFloat &Result) { 13299 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13300 if (!S) return false; 13301 13302 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13303 13304 llvm::APInt fill; 13305 13306 // Treat empty strings as if they were zero. 13307 if (S->getString().empty()) 13308 fill = llvm::APInt(32, 0); 13309 else if (S->getString().getAsInteger(0, fill)) 13310 return false; 13311 13312 if (Context.getTargetInfo().isNan2008()) { 13313 if (SNaN) 13314 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13315 else 13316 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13317 } else { 13318 // Prior to IEEE 754-2008, architectures were allowed to choose whether 13319 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13320 // a different encoding to what became a standard in 2008, and for pre- 13321 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13322 // sNaN. This is now known as "legacy NaN" encoding. 13323 if (SNaN) 13324 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13325 else 13326 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13327 } 13328 13329 return true; 13330 } 13331 13332 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13333 switch (E->getBuiltinCallee()) { 13334 default: 13335 return ExprEvaluatorBaseTy::VisitCallExpr(E); 13336 13337 case Builtin::BI__builtin_huge_val: 13338 case Builtin::BI__builtin_huge_valf: 13339 case Builtin::BI__builtin_huge_vall: 13340 case Builtin::BI__builtin_huge_valf128: 13341 case Builtin::BI__builtin_inf: 13342 case Builtin::BI__builtin_inff: 13343 case Builtin::BI__builtin_infl: 13344 case Builtin::BI__builtin_inff128: { 13345 const llvm::fltSemantics &Sem = 13346 Info.Ctx.getFloatTypeSemantics(E->getType()); 13347 Result = llvm::APFloat::getInf(Sem); 13348 return true; 13349 } 13350 13351 case Builtin::BI__builtin_nans: 13352 case Builtin::BI__builtin_nansf: 13353 case Builtin::BI__builtin_nansl: 13354 case Builtin::BI__builtin_nansf128: 13355 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13356 true, Result)) 13357 return Error(E); 13358 return true; 13359 13360 case Builtin::BI__builtin_nan: 13361 case Builtin::BI__builtin_nanf: 13362 case Builtin::BI__builtin_nanl: 13363 case Builtin::BI__builtin_nanf128: 13364 // If this is __builtin_nan() turn this into a nan, otherwise we 13365 // can't constant fold it. 13366 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13367 false, Result)) 13368 return Error(E); 13369 return true; 13370 13371 case Builtin::BI__builtin_fabs: 13372 case Builtin::BI__builtin_fabsf: 13373 case Builtin::BI__builtin_fabsl: 13374 case Builtin::BI__builtin_fabsf128: 13375 if (!EvaluateFloat(E->getArg(0), Result, Info)) 13376 return false; 13377 13378 if (Result.isNegative()) 13379 Result.changeSign(); 13380 return true; 13381 13382 // FIXME: Builtin::BI__builtin_powi 13383 // FIXME: Builtin::BI__builtin_powif 13384 // FIXME: Builtin::BI__builtin_powil 13385 13386 case Builtin::BI__builtin_copysign: 13387 case Builtin::BI__builtin_copysignf: 13388 case Builtin::BI__builtin_copysignl: 13389 case Builtin::BI__builtin_copysignf128: { 13390 APFloat RHS(0.); 13391 if (!EvaluateFloat(E->getArg(0), Result, Info) || 13392 !EvaluateFloat(E->getArg(1), RHS, Info)) 13393 return false; 13394 Result.copySign(RHS); 13395 return true; 13396 } 13397 } 13398 } 13399 13400 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13401 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13402 ComplexValue CV; 13403 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13404 return false; 13405 Result = CV.FloatReal; 13406 return true; 13407 } 13408 13409 return Visit(E->getSubExpr()); 13410 } 13411 13412 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13413 if (E->getSubExpr()->getType()->isAnyComplexType()) { 13414 ComplexValue CV; 13415 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13416 return false; 13417 Result = CV.FloatImag; 13418 return true; 13419 } 13420 13421 VisitIgnoredValue(E->getSubExpr()); 13422 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13423 Result = llvm::APFloat::getZero(Sem); 13424 return true; 13425 } 13426 13427 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13428 switch (E->getOpcode()) { 13429 default: return Error(E); 13430 case UO_Plus: 13431 return EvaluateFloat(E->getSubExpr(), Result, Info); 13432 case UO_Minus: 13433 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13434 return false; 13435 Result.changeSign(); 13436 return true; 13437 } 13438 } 13439 13440 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13441 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13442 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13443 13444 APFloat RHS(0.0); 13445 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13446 if (!LHSOK && !Info.noteFailure()) 13447 return false; 13448 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13449 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13450 } 13451 13452 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13453 Result = E->getValue(); 13454 return true; 13455 } 13456 13457 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13458 const Expr* SubExpr = E->getSubExpr(); 13459 13460 switch (E->getCastKind()) { 13461 default: 13462 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13463 13464 case CK_IntegralToFloating: { 13465 APSInt IntResult; 13466 return EvaluateInteger(SubExpr, IntResult, Info) && 13467 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 13468 E->getType(), Result); 13469 } 13470 13471 case CK_FixedPointToFloating: { 13472 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13473 if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13474 return false; 13475 Result = 13476 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13477 return true; 13478 } 13479 13480 case CK_FloatingCast: { 13481 if (!Visit(SubExpr)) 13482 return false; 13483 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13484 Result); 13485 } 13486 13487 case CK_FloatingComplexToReal: { 13488 ComplexValue V; 13489 if (!EvaluateComplex(SubExpr, V, Info)) 13490 return false; 13491 Result = V.getComplexFloatReal(); 13492 return true; 13493 } 13494 } 13495 } 13496 13497 //===----------------------------------------------------------------------===// 13498 // Complex Evaluation (for float and integer) 13499 //===----------------------------------------------------------------------===// 13500 13501 namespace { 13502 class ComplexExprEvaluator 13503 : public ExprEvaluatorBase<ComplexExprEvaluator> { 13504 ComplexValue &Result; 13505 13506 public: 13507 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13508 : ExprEvaluatorBaseTy(info), Result(Result) {} 13509 13510 bool Success(const APValue &V, const Expr *e) { 13511 Result.setFrom(V); 13512 return true; 13513 } 13514 13515 bool ZeroInitialization(const Expr *E); 13516 13517 //===--------------------------------------------------------------------===// 13518 // Visitor Methods 13519 //===--------------------------------------------------------------------===// 13520 13521 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13522 bool VisitCastExpr(const CastExpr *E); 13523 bool VisitBinaryOperator(const BinaryOperator *E); 13524 bool VisitUnaryOperator(const UnaryOperator *E); 13525 bool VisitInitListExpr(const InitListExpr *E); 13526 bool VisitCallExpr(const CallExpr *E); 13527 }; 13528 } // end anonymous namespace 13529 13530 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13531 EvalInfo &Info) { 13532 assert(E->isRValue() && E->getType()->isAnyComplexType()); 13533 return ComplexExprEvaluator(Info, Result).Visit(E); 13534 } 13535 13536 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13537 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13538 if (ElemTy->isRealFloatingType()) { 13539 Result.makeComplexFloat(); 13540 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13541 Result.FloatReal = Zero; 13542 Result.FloatImag = Zero; 13543 } else { 13544 Result.makeComplexInt(); 13545 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13546 Result.IntReal = Zero; 13547 Result.IntImag = Zero; 13548 } 13549 return true; 13550 } 13551 13552 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13553 const Expr* SubExpr = E->getSubExpr(); 13554 13555 if (SubExpr->getType()->isRealFloatingType()) { 13556 Result.makeComplexFloat(); 13557 APFloat &Imag = Result.FloatImag; 13558 if (!EvaluateFloat(SubExpr, Imag, Info)) 13559 return false; 13560 13561 Result.FloatReal = APFloat(Imag.getSemantics()); 13562 return true; 13563 } else { 13564 assert(SubExpr->getType()->isIntegerType() && 13565 "Unexpected imaginary literal."); 13566 13567 Result.makeComplexInt(); 13568 APSInt &Imag = Result.IntImag; 13569 if (!EvaluateInteger(SubExpr, Imag, Info)) 13570 return false; 13571 13572 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13573 return true; 13574 } 13575 } 13576 13577 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13578 13579 switch (E->getCastKind()) { 13580 case CK_BitCast: 13581 case CK_BaseToDerived: 13582 case CK_DerivedToBase: 13583 case CK_UncheckedDerivedToBase: 13584 case CK_Dynamic: 13585 case CK_ToUnion: 13586 case CK_ArrayToPointerDecay: 13587 case CK_FunctionToPointerDecay: 13588 case CK_NullToPointer: 13589 case CK_NullToMemberPointer: 13590 case CK_BaseToDerivedMemberPointer: 13591 case CK_DerivedToBaseMemberPointer: 13592 case CK_MemberPointerToBoolean: 13593 case CK_ReinterpretMemberPointer: 13594 case CK_ConstructorConversion: 13595 case CK_IntegralToPointer: 13596 case CK_PointerToIntegral: 13597 case CK_PointerToBoolean: 13598 case CK_ToVoid: 13599 case CK_VectorSplat: 13600 case CK_IntegralCast: 13601 case CK_BooleanToSignedIntegral: 13602 case CK_IntegralToBoolean: 13603 case CK_IntegralToFloating: 13604 case CK_FloatingToIntegral: 13605 case CK_FloatingToBoolean: 13606 case CK_FloatingCast: 13607 case CK_CPointerToObjCPointerCast: 13608 case CK_BlockPointerToObjCPointerCast: 13609 case CK_AnyPointerToBlockPointerCast: 13610 case CK_ObjCObjectLValueCast: 13611 case CK_FloatingComplexToReal: 13612 case CK_FloatingComplexToBoolean: 13613 case CK_IntegralComplexToReal: 13614 case CK_IntegralComplexToBoolean: 13615 case CK_ARCProduceObject: 13616 case CK_ARCConsumeObject: 13617 case CK_ARCReclaimReturnedObject: 13618 case CK_ARCExtendBlockObject: 13619 case CK_CopyAndAutoreleaseBlockObject: 13620 case CK_BuiltinFnToFnPtr: 13621 case CK_ZeroToOCLOpaqueType: 13622 case CK_NonAtomicToAtomic: 13623 case CK_AddressSpaceConversion: 13624 case CK_IntToOCLSampler: 13625 case CK_FloatingToFixedPoint: 13626 case CK_FixedPointToFloating: 13627 case CK_FixedPointCast: 13628 case CK_FixedPointToBoolean: 13629 case CK_FixedPointToIntegral: 13630 case CK_IntegralToFixedPoint: 13631 llvm_unreachable("invalid cast kind for complex value"); 13632 13633 case CK_LValueToRValue: 13634 case CK_AtomicToNonAtomic: 13635 case CK_NoOp: 13636 case CK_LValueToRValueBitCast: 13637 return ExprEvaluatorBaseTy::VisitCastExpr(E); 13638 13639 case CK_Dependent: 13640 case CK_LValueBitCast: 13641 case CK_UserDefinedConversion: 13642 return Error(E); 13643 13644 case CK_FloatingRealToComplex: { 13645 APFloat &Real = Result.FloatReal; 13646 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13647 return false; 13648 13649 Result.makeComplexFloat(); 13650 Result.FloatImag = APFloat(Real.getSemantics()); 13651 return true; 13652 } 13653 13654 case CK_FloatingComplexCast: { 13655 if (!Visit(E->getSubExpr())) 13656 return false; 13657 13658 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13659 QualType From 13660 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13661 13662 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13663 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13664 } 13665 13666 case CK_FloatingComplexToIntegralComplex: { 13667 if (!Visit(E->getSubExpr())) 13668 return false; 13669 13670 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13671 QualType From 13672 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13673 Result.makeComplexInt(); 13674 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13675 To, Result.IntReal) && 13676 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13677 To, Result.IntImag); 13678 } 13679 13680 case CK_IntegralRealToComplex: { 13681 APSInt &Real = Result.IntReal; 13682 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13683 return false; 13684 13685 Result.makeComplexInt(); 13686 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13687 return true; 13688 } 13689 13690 case CK_IntegralComplexCast: { 13691 if (!Visit(E->getSubExpr())) 13692 return false; 13693 13694 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13695 QualType From 13696 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13697 13698 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 13699 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 13700 return true; 13701 } 13702 13703 case CK_IntegralComplexToFloatingComplex: { 13704 if (!Visit(E->getSubExpr())) 13705 return false; 13706 13707 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13708 QualType From 13709 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13710 Result.makeComplexFloat(); 13711 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 13712 To, Result.FloatReal) && 13713 HandleIntToFloatCast(Info, E, From, Result.IntImag, 13714 To, Result.FloatImag); 13715 } 13716 } 13717 13718 llvm_unreachable("unknown cast resulting in complex value"); 13719 } 13720 13721 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13722 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13723 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13724 13725 // Track whether the LHS or RHS is real at the type system level. When this is 13726 // the case we can simplify our evaluation strategy. 13727 bool LHSReal = false, RHSReal = false; 13728 13729 bool LHSOK; 13730 if (E->getLHS()->getType()->isRealFloatingType()) { 13731 LHSReal = true; 13732 APFloat &Real = Result.FloatReal; 13733 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 13734 if (LHSOK) { 13735 Result.makeComplexFloat(); 13736 Result.FloatImag = APFloat(Real.getSemantics()); 13737 } 13738 } else { 13739 LHSOK = Visit(E->getLHS()); 13740 } 13741 if (!LHSOK && !Info.noteFailure()) 13742 return false; 13743 13744 ComplexValue RHS; 13745 if (E->getRHS()->getType()->isRealFloatingType()) { 13746 RHSReal = true; 13747 APFloat &Real = RHS.FloatReal; 13748 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 13749 return false; 13750 RHS.makeComplexFloat(); 13751 RHS.FloatImag = APFloat(Real.getSemantics()); 13752 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 13753 return false; 13754 13755 assert(!(LHSReal && RHSReal) && 13756 "Cannot have both operands of a complex operation be real."); 13757 switch (E->getOpcode()) { 13758 default: return Error(E); 13759 case BO_Add: 13760 if (Result.isComplexFloat()) { 13761 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 13762 APFloat::rmNearestTiesToEven); 13763 if (LHSReal) 13764 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13765 else if (!RHSReal) 13766 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 13767 APFloat::rmNearestTiesToEven); 13768 } else { 13769 Result.getComplexIntReal() += RHS.getComplexIntReal(); 13770 Result.getComplexIntImag() += RHS.getComplexIntImag(); 13771 } 13772 break; 13773 case BO_Sub: 13774 if (Result.isComplexFloat()) { 13775 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 13776 APFloat::rmNearestTiesToEven); 13777 if (LHSReal) { 13778 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 13779 Result.getComplexFloatImag().changeSign(); 13780 } else if (!RHSReal) { 13781 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 13782 APFloat::rmNearestTiesToEven); 13783 } 13784 } else { 13785 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 13786 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 13787 } 13788 break; 13789 case BO_Mul: 13790 if (Result.isComplexFloat()) { 13791 // This is an implementation of complex multiplication according to the 13792 // constraints laid out in C11 Annex G. The implementation uses the 13793 // following naming scheme: 13794 // (a + ib) * (c + id) 13795 ComplexValue LHS = Result; 13796 APFloat &A = LHS.getComplexFloatReal(); 13797 APFloat &B = LHS.getComplexFloatImag(); 13798 APFloat &C = RHS.getComplexFloatReal(); 13799 APFloat &D = RHS.getComplexFloatImag(); 13800 APFloat &ResR = Result.getComplexFloatReal(); 13801 APFloat &ResI = Result.getComplexFloatImag(); 13802 if (LHSReal) { 13803 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 13804 ResR = A * C; 13805 ResI = A * D; 13806 } else if (RHSReal) { 13807 ResR = C * A; 13808 ResI = C * B; 13809 } else { 13810 // In the fully general case, we need to handle NaNs and infinities 13811 // robustly. 13812 APFloat AC = A * C; 13813 APFloat BD = B * D; 13814 APFloat AD = A * D; 13815 APFloat BC = B * C; 13816 ResR = AC - BD; 13817 ResI = AD + BC; 13818 if (ResR.isNaN() && ResI.isNaN()) { 13819 bool Recalc = false; 13820 if (A.isInfinity() || B.isInfinity()) { 13821 A = APFloat::copySign( 13822 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13823 B = APFloat::copySign( 13824 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13825 if (C.isNaN()) 13826 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13827 if (D.isNaN()) 13828 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13829 Recalc = true; 13830 } 13831 if (C.isInfinity() || D.isInfinity()) { 13832 C = APFloat::copySign( 13833 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13834 D = APFloat::copySign( 13835 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13836 if (A.isNaN()) 13837 A = APFloat::copySign(APFloat(A.getSemantics()), A); 13838 if (B.isNaN()) 13839 B = APFloat::copySign(APFloat(B.getSemantics()), B); 13840 Recalc = true; 13841 } 13842 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 13843 AD.isInfinity() || BC.isInfinity())) { 13844 if (A.isNaN()) 13845 A = APFloat::copySign(APFloat(A.getSemantics()), A); 13846 if (B.isNaN()) 13847 B = APFloat::copySign(APFloat(B.getSemantics()), B); 13848 if (C.isNaN()) 13849 C = APFloat::copySign(APFloat(C.getSemantics()), C); 13850 if (D.isNaN()) 13851 D = APFloat::copySign(APFloat(D.getSemantics()), D); 13852 Recalc = true; 13853 } 13854 if (Recalc) { 13855 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 13856 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 13857 } 13858 } 13859 } 13860 } else { 13861 ComplexValue LHS = Result; 13862 Result.getComplexIntReal() = 13863 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 13864 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 13865 Result.getComplexIntImag() = 13866 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 13867 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 13868 } 13869 break; 13870 case BO_Div: 13871 if (Result.isComplexFloat()) { 13872 // This is an implementation of complex division according to the 13873 // constraints laid out in C11 Annex G. The implementation uses the 13874 // following naming scheme: 13875 // (a + ib) / (c + id) 13876 ComplexValue LHS = Result; 13877 APFloat &A = LHS.getComplexFloatReal(); 13878 APFloat &B = LHS.getComplexFloatImag(); 13879 APFloat &C = RHS.getComplexFloatReal(); 13880 APFloat &D = RHS.getComplexFloatImag(); 13881 APFloat &ResR = Result.getComplexFloatReal(); 13882 APFloat &ResI = Result.getComplexFloatImag(); 13883 if (RHSReal) { 13884 ResR = A / C; 13885 ResI = B / C; 13886 } else { 13887 if (LHSReal) { 13888 // No real optimizations we can do here, stub out with zero. 13889 B = APFloat::getZero(A.getSemantics()); 13890 } 13891 int DenomLogB = 0; 13892 APFloat MaxCD = maxnum(abs(C), abs(D)); 13893 if (MaxCD.isFinite()) { 13894 DenomLogB = ilogb(MaxCD); 13895 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 13896 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 13897 } 13898 APFloat Denom = C * C + D * D; 13899 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 13900 APFloat::rmNearestTiesToEven); 13901 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 13902 APFloat::rmNearestTiesToEven); 13903 if (ResR.isNaN() && ResI.isNaN()) { 13904 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 13905 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 13906 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 13907 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 13908 D.isFinite()) { 13909 A = APFloat::copySign( 13910 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 13911 B = APFloat::copySign( 13912 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 13913 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 13914 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 13915 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 13916 C = APFloat::copySign( 13917 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 13918 D = APFloat::copySign( 13919 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 13920 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 13921 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 13922 } 13923 } 13924 } 13925 } else { 13926 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 13927 return Error(E, diag::note_expr_divide_by_zero); 13928 13929 ComplexValue LHS = Result; 13930 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 13931 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 13932 Result.getComplexIntReal() = 13933 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 13934 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 13935 Result.getComplexIntImag() = 13936 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 13937 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 13938 } 13939 break; 13940 } 13941 13942 return true; 13943 } 13944 13945 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13946 // Get the operand value into 'Result'. 13947 if (!Visit(E->getSubExpr())) 13948 return false; 13949 13950 switch (E->getOpcode()) { 13951 default: 13952 return Error(E); 13953 case UO_Extension: 13954 return true; 13955 case UO_Plus: 13956 // The result is always just the subexpr. 13957 return true; 13958 case UO_Minus: 13959 if (Result.isComplexFloat()) { 13960 Result.getComplexFloatReal().changeSign(); 13961 Result.getComplexFloatImag().changeSign(); 13962 } 13963 else { 13964 Result.getComplexIntReal() = -Result.getComplexIntReal(); 13965 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13966 } 13967 return true; 13968 case UO_Not: 13969 if (Result.isComplexFloat()) 13970 Result.getComplexFloatImag().changeSign(); 13971 else 13972 Result.getComplexIntImag() = -Result.getComplexIntImag(); 13973 return true; 13974 } 13975 } 13976 13977 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 13978 if (E->getNumInits() == 2) { 13979 if (E->getType()->isComplexType()) { 13980 Result.makeComplexFloat(); 13981 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 13982 return false; 13983 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 13984 return false; 13985 } else { 13986 Result.makeComplexInt(); 13987 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 13988 return false; 13989 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 13990 return false; 13991 } 13992 return true; 13993 } 13994 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 13995 } 13996 13997 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 13998 switch (E->getBuiltinCallee()) { 13999 case Builtin::BI__builtin_complex: 14000 Result.makeComplexFloat(); 14001 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14002 return false; 14003 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14004 return false; 14005 return true; 14006 14007 default: 14008 break; 14009 } 14010 14011 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14012 } 14013 14014 //===----------------------------------------------------------------------===// 14015 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14016 // implicit conversion. 14017 //===----------------------------------------------------------------------===// 14018 14019 namespace { 14020 class AtomicExprEvaluator : 14021 public ExprEvaluatorBase<AtomicExprEvaluator> { 14022 const LValue *This; 14023 APValue &Result; 14024 public: 14025 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14026 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14027 14028 bool Success(const APValue &V, const Expr *E) { 14029 Result = V; 14030 return true; 14031 } 14032 14033 bool ZeroInitialization(const Expr *E) { 14034 ImplicitValueInitExpr VIE( 14035 E->getType()->castAs<AtomicType>()->getValueType()); 14036 // For atomic-qualified class (and array) types in C++, initialize the 14037 // _Atomic-wrapped subobject directly, in-place. 14038 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14039 : Evaluate(Result, Info, &VIE); 14040 } 14041 14042 bool VisitCastExpr(const CastExpr *E) { 14043 switch (E->getCastKind()) { 14044 default: 14045 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14046 case CK_NonAtomicToAtomic: 14047 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14048 : Evaluate(Result, Info, E->getSubExpr()); 14049 } 14050 } 14051 }; 14052 } // end anonymous namespace 14053 14054 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14055 EvalInfo &Info) { 14056 assert(E->isRValue() && E->getType()->isAtomicType()); 14057 return AtomicExprEvaluator(Info, This, Result).Visit(E); 14058 } 14059 14060 //===----------------------------------------------------------------------===// 14061 // Void expression evaluation, primarily for a cast to void on the LHS of a 14062 // comma operator 14063 //===----------------------------------------------------------------------===// 14064 14065 namespace { 14066 class VoidExprEvaluator 14067 : public ExprEvaluatorBase<VoidExprEvaluator> { 14068 public: 14069 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14070 14071 bool Success(const APValue &V, const Expr *e) { return true; } 14072 14073 bool ZeroInitialization(const Expr *E) { return true; } 14074 14075 bool VisitCastExpr(const CastExpr *E) { 14076 switch (E->getCastKind()) { 14077 default: 14078 return ExprEvaluatorBaseTy::VisitCastExpr(E); 14079 case CK_ToVoid: 14080 VisitIgnoredValue(E->getSubExpr()); 14081 return true; 14082 } 14083 } 14084 14085 bool VisitCallExpr(const CallExpr *E) { 14086 switch (E->getBuiltinCallee()) { 14087 case Builtin::BI__assume: 14088 case Builtin::BI__builtin_assume: 14089 // The argument is not evaluated! 14090 return true; 14091 14092 case Builtin::BI__builtin_operator_delete: 14093 return HandleOperatorDeleteCall(Info, E); 14094 14095 default: 14096 break; 14097 } 14098 14099 return ExprEvaluatorBaseTy::VisitCallExpr(E); 14100 } 14101 14102 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14103 }; 14104 } // end anonymous namespace 14105 14106 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14107 // We cannot speculatively evaluate a delete expression. 14108 if (Info.SpeculativeEvaluationDepth) 14109 return false; 14110 14111 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14112 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14113 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14114 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14115 return false; 14116 } 14117 14118 const Expr *Arg = E->getArgument(); 14119 14120 LValue Pointer; 14121 if (!EvaluatePointer(Arg, Pointer, Info)) 14122 return false; 14123 if (Pointer.Designator.Invalid) 14124 return false; 14125 14126 // Deleting a null pointer has no effect. 14127 if (Pointer.isNullPointer()) { 14128 // This is the only case where we need to produce an extension warning: 14129 // the only other way we can succeed is if we find a dynamic allocation, 14130 // and we will have warned when we allocated it in that case. 14131 if (!Info.getLangOpts().CPlusPlus20) 14132 Info.CCEDiag(E, diag::note_constexpr_new); 14133 return true; 14134 } 14135 14136 Optional<DynAlloc *> Alloc = CheckDeleteKind( 14137 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14138 if (!Alloc) 14139 return false; 14140 QualType AllocType = Pointer.Base.getDynamicAllocType(); 14141 14142 // For the non-array case, the designator must be empty if the static type 14143 // does not have a virtual destructor. 14144 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14145 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14146 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14147 << Arg->getType()->getPointeeType() << AllocType; 14148 return false; 14149 } 14150 14151 // For a class type with a virtual destructor, the selected operator delete 14152 // is the one looked up when building the destructor. 14153 if (!E->isArrayForm() && !E->isGlobalDelete()) { 14154 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14155 if (VirtualDelete && 14156 !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14157 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14158 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14159 return false; 14160 } 14161 } 14162 14163 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14164 (*Alloc)->Value, AllocType)) 14165 return false; 14166 14167 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14168 // The element was already erased. This means the destructor call also 14169 // deleted the object. 14170 // FIXME: This probably results in undefined behavior before we get this 14171 // far, and should be diagnosed elsewhere first. 14172 Info.FFDiag(E, diag::note_constexpr_double_delete); 14173 return false; 14174 } 14175 14176 return true; 14177 } 14178 14179 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14180 assert(E->isRValue() && E->getType()->isVoidType()); 14181 return VoidExprEvaluator(Info).Visit(E); 14182 } 14183 14184 //===----------------------------------------------------------------------===// 14185 // Top level Expr::EvaluateAsRValue method. 14186 //===----------------------------------------------------------------------===// 14187 14188 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14189 // In C, function designators are not lvalues, but we evaluate them as if they 14190 // are. 14191 QualType T = E->getType(); 14192 if (E->isGLValue() || T->isFunctionType()) { 14193 LValue LV; 14194 if (!EvaluateLValue(E, LV, Info)) 14195 return false; 14196 LV.moveInto(Result); 14197 } else if (T->isVectorType()) { 14198 if (!EvaluateVector(E, Result, Info)) 14199 return false; 14200 } else if (T->isIntegralOrEnumerationType()) { 14201 if (!IntExprEvaluator(Info, Result).Visit(E)) 14202 return false; 14203 } else if (T->hasPointerRepresentation()) { 14204 LValue LV; 14205 if (!EvaluatePointer(E, LV, Info)) 14206 return false; 14207 LV.moveInto(Result); 14208 } else if (T->isRealFloatingType()) { 14209 llvm::APFloat F(0.0); 14210 if (!EvaluateFloat(E, F, Info)) 14211 return false; 14212 Result = APValue(F); 14213 } else if (T->isAnyComplexType()) { 14214 ComplexValue C; 14215 if (!EvaluateComplex(E, C, Info)) 14216 return false; 14217 C.moveInto(Result); 14218 } else if (T->isFixedPointType()) { 14219 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14220 } else if (T->isMemberPointerType()) { 14221 MemberPtr P; 14222 if (!EvaluateMemberPointer(E, P, Info)) 14223 return false; 14224 P.moveInto(Result); 14225 return true; 14226 } else if (T->isArrayType()) { 14227 LValue LV; 14228 APValue &Value = 14229 Info.CurrentCall->createTemporary(E, T, false, LV); 14230 if (!EvaluateArray(E, LV, Value, Info)) 14231 return false; 14232 Result = Value; 14233 } else if (T->isRecordType()) { 14234 LValue LV; 14235 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV); 14236 if (!EvaluateRecord(E, LV, Value, Info)) 14237 return false; 14238 Result = Value; 14239 } else if (T->isVoidType()) { 14240 if (!Info.getLangOpts().CPlusPlus11) 14241 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14242 << E->getType(); 14243 if (!EvaluateVoid(E, Info)) 14244 return false; 14245 } else if (T->isAtomicType()) { 14246 QualType Unqual = T.getAtomicUnqualifiedType(); 14247 if (Unqual->isArrayType() || Unqual->isRecordType()) { 14248 LValue LV; 14249 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV); 14250 if (!EvaluateAtomic(E, &LV, Value, Info)) 14251 return false; 14252 } else { 14253 if (!EvaluateAtomic(E, nullptr, Result, Info)) 14254 return false; 14255 } 14256 } else if (Info.getLangOpts().CPlusPlus11) { 14257 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14258 return false; 14259 } else { 14260 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14261 return false; 14262 } 14263 14264 return true; 14265 } 14266 14267 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14268 /// cases, the in-place evaluation is essential, since later initializers for 14269 /// an object can indirectly refer to subobjects which were initialized earlier. 14270 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14271 const Expr *E, bool AllowNonLiteralTypes) { 14272 assert(!E->isValueDependent()); 14273 14274 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14275 return false; 14276 14277 if (E->isRValue()) { 14278 // Evaluate arrays and record types in-place, so that later initializers can 14279 // refer to earlier-initialized members of the object. 14280 QualType T = E->getType(); 14281 if (T->isArrayType()) 14282 return EvaluateArray(E, This, Result, Info); 14283 else if (T->isRecordType()) 14284 return EvaluateRecord(E, This, Result, Info); 14285 else if (T->isAtomicType()) { 14286 QualType Unqual = T.getAtomicUnqualifiedType(); 14287 if (Unqual->isArrayType() || Unqual->isRecordType()) 14288 return EvaluateAtomic(E, &This, Result, Info); 14289 } 14290 } 14291 14292 // For any other type, in-place evaluation is unimportant. 14293 return Evaluate(Result, Info, E); 14294 } 14295 14296 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14297 /// lvalue-to-rvalue cast if it is an lvalue. 14298 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14299 if (Info.EnableNewConstInterp) { 14300 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14301 return false; 14302 } else { 14303 if (E->getType().isNull()) 14304 return false; 14305 14306 if (!CheckLiteralType(Info, E)) 14307 return false; 14308 14309 if (!::Evaluate(Result, Info, E)) 14310 return false; 14311 14312 if (E->isGLValue()) { 14313 LValue LV; 14314 LV.setFrom(Info.Ctx, Result); 14315 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14316 return false; 14317 } 14318 } 14319 14320 // Check this core constant expression is a constant expression. 14321 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) && 14322 CheckMemoryLeaks(Info); 14323 } 14324 14325 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14326 const ASTContext &Ctx, bool &IsConst) { 14327 // Fast-path evaluations of integer literals, since we sometimes see files 14328 // containing vast quantities of these. 14329 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14330 Result.Val = APValue(APSInt(L->getValue(), 14331 L->getType()->isUnsignedIntegerType())); 14332 IsConst = true; 14333 return true; 14334 } 14335 14336 // This case should be rare, but we need to check it before we check on 14337 // the type below. 14338 if (Exp->getType().isNull()) { 14339 IsConst = false; 14340 return true; 14341 } 14342 14343 // FIXME: Evaluating values of large array and record types can cause 14344 // performance problems. Only do so in C++11 for now. 14345 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 14346 Exp->getType()->isRecordType()) && 14347 !Ctx.getLangOpts().CPlusPlus11) { 14348 IsConst = false; 14349 return true; 14350 } 14351 return false; 14352 } 14353 14354 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14355 Expr::SideEffectsKind SEK) { 14356 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14357 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14358 } 14359 14360 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14361 const ASTContext &Ctx, EvalInfo &Info) { 14362 bool IsConst; 14363 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14364 return IsConst; 14365 14366 return EvaluateAsRValue(Info, E, Result.Val); 14367 } 14368 14369 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14370 const ASTContext &Ctx, 14371 Expr::SideEffectsKind AllowSideEffects, 14372 EvalInfo &Info) { 14373 if (!E->getType()->isIntegralOrEnumerationType()) 14374 return false; 14375 14376 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14377 !ExprResult.Val.isInt() || 14378 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14379 return false; 14380 14381 return true; 14382 } 14383 14384 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14385 const ASTContext &Ctx, 14386 Expr::SideEffectsKind AllowSideEffects, 14387 EvalInfo &Info) { 14388 if (!E->getType()->isFixedPointType()) 14389 return false; 14390 14391 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14392 return false; 14393 14394 if (!ExprResult.Val.isFixedPoint() || 14395 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14396 return false; 14397 14398 return true; 14399 } 14400 14401 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14402 /// any crazy technique (that has nothing to do with language standards) that 14403 /// we want to. If this function returns true, it returns the folded constant 14404 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14405 /// will be applied to the result. 14406 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14407 bool InConstantContext) const { 14408 assert(!isValueDependent() && 14409 "Expression evaluator can't be called on a dependent expression."); 14410 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14411 Info.InConstantContext = InConstantContext; 14412 return ::EvaluateAsRValue(this, Result, Ctx, Info); 14413 } 14414 14415 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14416 bool InConstantContext) const { 14417 assert(!isValueDependent() && 14418 "Expression evaluator can't be called on a dependent expression."); 14419 EvalResult Scratch; 14420 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14421 HandleConversionToBool(Scratch.Val, Result); 14422 } 14423 14424 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14425 SideEffectsKind AllowSideEffects, 14426 bool InConstantContext) const { 14427 assert(!isValueDependent() && 14428 "Expression evaluator can't be called on a dependent expression."); 14429 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14430 Info.InConstantContext = InConstantContext; 14431 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14432 } 14433 14434 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14435 SideEffectsKind AllowSideEffects, 14436 bool InConstantContext) const { 14437 assert(!isValueDependent() && 14438 "Expression evaluator can't be called on a dependent expression."); 14439 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14440 Info.InConstantContext = InConstantContext; 14441 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14442 } 14443 14444 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14445 SideEffectsKind AllowSideEffects, 14446 bool InConstantContext) const { 14447 assert(!isValueDependent() && 14448 "Expression evaluator can't be called on a dependent expression."); 14449 14450 if (!getType()->isRealFloatingType()) 14451 return false; 14452 14453 EvalResult ExprResult; 14454 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14455 !ExprResult.Val.isFloat() || 14456 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14457 return false; 14458 14459 Result = ExprResult.Val.getFloat(); 14460 return true; 14461 } 14462 14463 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14464 bool InConstantContext) const { 14465 assert(!isValueDependent() && 14466 "Expression evaluator can't be called on a dependent expression."); 14467 14468 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14469 Info.InConstantContext = InConstantContext; 14470 LValue LV; 14471 CheckedTemporaries CheckedTemps; 14472 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14473 Result.HasSideEffects || 14474 !CheckLValueConstantExpression(Info, getExprLoc(), 14475 Ctx.getLValueReferenceType(getType()), LV, 14476 Expr::EvaluateForCodeGen, CheckedTemps)) 14477 return false; 14478 14479 LV.moveInto(Result.Val); 14480 return true; 14481 } 14482 14483 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 14484 const ASTContext &Ctx, bool InPlace) const { 14485 assert(!isValueDependent() && 14486 "Expression evaluator can't be called on a dependent expression."); 14487 14488 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14489 EvalInfo Info(Ctx, Result, EM); 14490 Info.InConstantContext = true; 14491 14492 if (InPlace) { 14493 Info.setEvaluatingDecl(this, Result.Val); 14494 LValue LVal; 14495 LVal.set(this); 14496 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || 14497 Result.HasSideEffects) 14498 return false; 14499 } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects) 14500 return false; 14501 14502 if (!Info.discardCleanups()) 14503 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14504 14505 return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14506 Result.Val, Usage) && 14507 CheckMemoryLeaks(Info); 14508 } 14509 14510 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14511 const VarDecl *VD, 14512 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14513 assert(!isValueDependent() && 14514 "Expression evaluator can't be called on a dependent expression."); 14515 14516 // FIXME: Evaluating initializers for large array and record types can cause 14517 // performance problems. Only do so in C++11 for now. 14518 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14519 !Ctx.getLangOpts().CPlusPlus11) 14520 return false; 14521 14522 Expr::EvalStatus EStatus; 14523 EStatus.Diag = &Notes; 14524 14525 EvalInfo Info(Ctx, EStatus, VD->isConstexpr() 14526 ? EvalInfo::EM_ConstantExpression 14527 : EvalInfo::EM_ConstantFold); 14528 Info.setEvaluatingDecl(VD, Value); 14529 Info.InConstantContext = true; 14530 14531 SourceLocation DeclLoc = VD->getLocation(); 14532 QualType DeclTy = VD->getType(); 14533 14534 if (Info.EnableNewConstInterp) { 14535 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14536 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14537 return false; 14538 } else { 14539 LValue LVal; 14540 LVal.set(VD); 14541 14542 if (!EvaluateInPlace(Value, Info, LVal, this, 14543 /*AllowNonLiteralTypes=*/true) || 14544 EStatus.HasSideEffects) 14545 return false; 14546 14547 // At this point, any lifetime-extended temporaries are completely 14548 // initialized. 14549 Info.performLifetimeExtension(); 14550 14551 if (!Info.discardCleanups()) 14552 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14553 } 14554 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) && 14555 CheckMemoryLeaks(Info); 14556 } 14557 14558 bool VarDecl::evaluateDestruction( 14559 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14560 Expr::EvalStatus EStatus; 14561 EStatus.Diag = &Notes; 14562 14563 // Make a copy of the value for the destructor to mutate, if we know it. 14564 // Otherwise, treat the value as default-initialized; if the destructor works 14565 // anyway, then the destruction is constant (and must be essentially empty). 14566 APValue DestroyedValue; 14567 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14568 DestroyedValue = *getEvaluatedValue(); 14569 else if (!getDefaultInitValue(getType(), DestroyedValue)) 14570 return false; 14571 14572 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression); 14573 Info.setEvaluatingDecl(this, DestroyedValue, 14574 EvalInfo::EvaluatingDeclKind::Dtor); 14575 Info.InConstantContext = true; 14576 14577 SourceLocation DeclLoc = getLocation(); 14578 QualType DeclTy = getType(); 14579 14580 LValue LVal; 14581 LVal.set(this); 14582 14583 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) || 14584 EStatus.HasSideEffects) 14585 return false; 14586 14587 if (!Info.discardCleanups()) 14588 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14589 14590 ensureEvaluatedStmt()->HasConstantDestruction = true; 14591 return true; 14592 } 14593 14594 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14595 /// constant folded, but discard the result. 14596 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14597 assert(!isValueDependent() && 14598 "Expression evaluator can't be called on a dependent expression."); 14599 14600 EvalResult Result; 14601 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14602 !hasUnacceptableSideEffect(Result, SEK); 14603 } 14604 14605 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14606 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14607 assert(!isValueDependent() && 14608 "Expression evaluator can't be called on a dependent expression."); 14609 14610 EvalResult EVResult; 14611 EVResult.Diag = Diag; 14612 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14613 Info.InConstantContext = true; 14614 14615 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14616 (void)Result; 14617 assert(Result && "Could not evaluate expression"); 14618 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14619 14620 return EVResult.Val.getInt(); 14621 } 14622 14623 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14624 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14625 assert(!isValueDependent() && 14626 "Expression evaluator can't be called on a dependent expression."); 14627 14628 EvalResult EVResult; 14629 EVResult.Diag = Diag; 14630 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14631 Info.InConstantContext = true; 14632 Info.CheckingForUndefinedBehavior = true; 14633 14634 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 14635 (void)Result; 14636 assert(Result && "Could not evaluate expression"); 14637 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14638 14639 return EVResult.Val.getInt(); 14640 } 14641 14642 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 14643 assert(!isValueDependent() && 14644 "Expression evaluator can't be called on a dependent expression."); 14645 14646 bool IsConst; 14647 EvalResult EVResult; 14648 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 14649 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14650 Info.CheckingForUndefinedBehavior = true; 14651 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 14652 } 14653 } 14654 14655 bool Expr::EvalResult::isGlobalLValue() const { 14656 assert(Val.isLValue()); 14657 return IsGlobalLValue(Val.getLValueBase()); 14658 } 14659 14660 14661 /// isIntegerConstantExpr - this recursive routine will test if an expression is 14662 /// an integer constant expression. 14663 14664 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 14665 /// comma, etc 14666 14667 // CheckICE - This function does the fundamental ICE checking: the returned 14668 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 14669 // and a (possibly null) SourceLocation indicating the location of the problem. 14670 // 14671 // Note that to reduce code duplication, this helper does no evaluation 14672 // itself; the caller checks whether the expression is evaluatable, and 14673 // in the rare cases where CheckICE actually cares about the evaluated 14674 // value, it calls into Evaluate. 14675 14676 namespace { 14677 14678 enum ICEKind { 14679 /// This expression is an ICE. 14680 IK_ICE, 14681 /// This expression is not an ICE, but if it isn't evaluated, it's 14682 /// a legal subexpression for an ICE. This return value is used to handle 14683 /// the comma operator in C99 mode, and non-constant subexpressions. 14684 IK_ICEIfUnevaluated, 14685 /// This expression is not an ICE, and is not a legal subexpression for one. 14686 IK_NotICE 14687 }; 14688 14689 struct ICEDiag { 14690 ICEKind Kind; 14691 SourceLocation Loc; 14692 14693 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 14694 }; 14695 14696 } 14697 14698 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 14699 14700 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 14701 14702 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 14703 Expr::EvalResult EVResult; 14704 Expr::EvalStatus Status; 14705 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 14706 14707 Info.InConstantContext = true; 14708 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 14709 !EVResult.Val.isInt()) 14710 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14711 14712 return NoDiag(); 14713 } 14714 14715 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 14716 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 14717 if (!E->getType()->isIntegralOrEnumerationType()) 14718 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14719 14720 switch (E->getStmtClass()) { 14721 #define ABSTRACT_STMT(Node) 14722 #define STMT(Node, Base) case Expr::Node##Class: 14723 #define EXPR(Node, Base) 14724 #include "clang/AST/StmtNodes.inc" 14725 case Expr::PredefinedExprClass: 14726 case Expr::FloatingLiteralClass: 14727 case Expr::ImaginaryLiteralClass: 14728 case Expr::StringLiteralClass: 14729 case Expr::ArraySubscriptExprClass: 14730 case Expr::MatrixSubscriptExprClass: 14731 case Expr::OMPArraySectionExprClass: 14732 case Expr::OMPArrayShapingExprClass: 14733 case Expr::OMPIteratorExprClass: 14734 case Expr::MemberExprClass: 14735 case Expr::CompoundAssignOperatorClass: 14736 case Expr::CompoundLiteralExprClass: 14737 case Expr::ExtVectorElementExprClass: 14738 case Expr::DesignatedInitExprClass: 14739 case Expr::ArrayInitLoopExprClass: 14740 case Expr::ArrayInitIndexExprClass: 14741 case Expr::NoInitExprClass: 14742 case Expr::DesignatedInitUpdateExprClass: 14743 case Expr::ImplicitValueInitExprClass: 14744 case Expr::ParenListExprClass: 14745 case Expr::VAArgExprClass: 14746 case Expr::AddrLabelExprClass: 14747 case Expr::StmtExprClass: 14748 case Expr::CXXMemberCallExprClass: 14749 case Expr::CUDAKernelCallExprClass: 14750 case Expr::CXXAddrspaceCastExprClass: 14751 case Expr::CXXDynamicCastExprClass: 14752 case Expr::CXXTypeidExprClass: 14753 case Expr::CXXUuidofExprClass: 14754 case Expr::MSPropertyRefExprClass: 14755 case Expr::MSPropertySubscriptExprClass: 14756 case Expr::CXXNullPtrLiteralExprClass: 14757 case Expr::UserDefinedLiteralClass: 14758 case Expr::CXXThisExprClass: 14759 case Expr::CXXThrowExprClass: 14760 case Expr::CXXNewExprClass: 14761 case Expr::CXXDeleteExprClass: 14762 case Expr::CXXPseudoDestructorExprClass: 14763 case Expr::UnresolvedLookupExprClass: 14764 case Expr::TypoExprClass: 14765 case Expr::RecoveryExprClass: 14766 case Expr::DependentScopeDeclRefExprClass: 14767 case Expr::CXXConstructExprClass: 14768 case Expr::CXXInheritedCtorInitExprClass: 14769 case Expr::CXXStdInitializerListExprClass: 14770 case Expr::CXXBindTemporaryExprClass: 14771 case Expr::ExprWithCleanupsClass: 14772 case Expr::CXXTemporaryObjectExprClass: 14773 case Expr::CXXUnresolvedConstructExprClass: 14774 case Expr::CXXDependentScopeMemberExprClass: 14775 case Expr::UnresolvedMemberExprClass: 14776 case Expr::ObjCStringLiteralClass: 14777 case Expr::ObjCBoxedExprClass: 14778 case Expr::ObjCArrayLiteralClass: 14779 case Expr::ObjCDictionaryLiteralClass: 14780 case Expr::ObjCEncodeExprClass: 14781 case Expr::ObjCMessageExprClass: 14782 case Expr::ObjCSelectorExprClass: 14783 case Expr::ObjCProtocolExprClass: 14784 case Expr::ObjCIvarRefExprClass: 14785 case Expr::ObjCPropertyRefExprClass: 14786 case Expr::ObjCSubscriptRefExprClass: 14787 case Expr::ObjCIsaExprClass: 14788 case Expr::ObjCAvailabilityCheckExprClass: 14789 case Expr::ShuffleVectorExprClass: 14790 case Expr::ConvertVectorExprClass: 14791 case Expr::BlockExprClass: 14792 case Expr::NoStmtClass: 14793 case Expr::OpaqueValueExprClass: 14794 case Expr::PackExpansionExprClass: 14795 case Expr::SubstNonTypeTemplateParmPackExprClass: 14796 case Expr::FunctionParmPackExprClass: 14797 case Expr::AsTypeExprClass: 14798 case Expr::ObjCIndirectCopyRestoreExprClass: 14799 case Expr::MaterializeTemporaryExprClass: 14800 case Expr::PseudoObjectExprClass: 14801 case Expr::AtomicExprClass: 14802 case Expr::LambdaExprClass: 14803 case Expr::CXXFoldExprClass: 14804 case Expr::CoawaitExprClass: 14805 case Expr::DependentCoawaitExprClass: 14806 case Expr::CoyieldExprClass: 14807 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14808 14809 case Expr::InitListExprClass: { 14810 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 14811 // form "T x = { a };" is equivalent to "T x = a;". 14812 // Unless we're initializing a reference, T is a scalar as it is known to be 14813 // of integral or enumeration type. 14814 if (E->isRValue()) 14815 if (cast<InitListExpr>(E)->getNumInits() == 1) 14816 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 14817 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14818 } 14819 14820 case Expr::SizeOfPackExprClass: 14821 case Expr::GNUNullExprClass: 14822 case Expr::SourceLocExprClass: 14823 return NoDiag(); 14824 14825 case Expr::SubstNonTypeTemplateParmExprClass: 14826 return 14827 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 14828 14829 case Expr::ConstantExprClass: 14830 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 14831 14832 case Expr::ParenExprClass: 14833 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 14834 case Expr::GenericSelectionExprClass: 14835 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 14836 case Expr::IntegerLiteralClass: 14837 case Expr::FixedPointLiteralClass: 14838 case Expr::CharacterLiteralClass: 14839 case Expr::ObjCBoolLiteralExprClass: 14840 case Expr::CXXBoolLiteralExprClass: 14841 case Expr::CXXScalarValueInitExprClass: 14842 case Expr::TypeTraitExprClass: 14843 case Expr::ConceptSpecializationExprClass: 14844 case Expr::RequiresExprClass: 14845 case Expr::ArrayTypeTraitExprClass: 14846 case Expr::ExpressionTraitExprClass: 14847 case Expr::CXXNoexceptExprClass: 14848 return NoDiag(); 14849 case Expr::CallExprClass: 14850 case Expr::CXXOperatorCallExprClass: { 14851 // C99 6.6/3 allows function calls within unevaluated subexpressions of 14852 // constant expressions, but they can never be ICEs because an ICE cannot 14853 // contain an operand of (pointer to) function type. 14854 const CallExpr *CE = cast<CallExpr>(E); 14855 if (CE->getBuiltinCallee()) 14856 return CheckEvalInICE(E, Ctx); 14857 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14858 } 14859 case Expr::CXXRewrittenBinaryOperatorClass: 14860 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 14861 Ctx); 14862 case Expr::DeclRefExprClass: { 14863 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 14864 return NoDiag(); 14865 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 14866 if (Ctx.getLangOpts().CPlusPlus && 14867 D && IsConstNonVolatile(D->getType())) { 14868 // Parameter variables are never constants. Without this check, 14869 // getAnyInitializer() can find a default argument, which leads 14870 // to chaos. 14871 if (isa<ParmVarDecl>(D)) 14872 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14873 14874 // C++ 7.1.5.1p2 14875 // A variable of non-volatile const-qualified integral or enumeration 14876 // type initialized by an ICE can be used in ICEs. 14877 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 14878 if (!Dcl->getType()->isIntegralOrEnumerationType()) 14879 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14880 14881 const VarDecl *VD; 14882 // Look for a declaration of this variable that has an initializer, and 14883 // check whether it is an ICE. 14884 if (Dcl->getAnyInitializer(VD) && !VD->isWeak() && VD->checkInitIsICE()) 14885 return NoDiag(); 14886 else 14887 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 14888 } 14889 } 14890 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14891 } 14892 case Expr::UnaryOperatorClass: { 14893 const UnaryOperator *Exp = cast<UnaryOperator>(E); 14894 switch (Exp->getOpcode()) { 14895 case UO_PostInc: 14896 case UO_PostDec: 14897 case UO_PreInc: 14898 case UO_PreDec: 14899 case UO_AddrOf: 14900 case UO_Deref: 14901 case UO_Coawait: 14902 // C99 6.6/3 allows increment and decrement within unevaluated 14903 // subexpressions of constant expressions, but they can never be ICEs 14904 // because an ICE cannot contain an lvalue operand. 14905 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14906 case UO_Extension: 14907 case UO_LNot: 14908 case UO_Plus: 14909 case UO_Minus: 14910 case UO_Not: 14911 case UO_Real: 14912 case UO_Imag: 14913 return CheckICE(Exp->getSubExpr(), Ctx); 14914 } 14915 llvm_unreachable("invalid unary operator class"); 14916 } 14917 case Expr::OffsetOfExprClass: { 14918 // Note that per C99, offsetof must be an ICE. And AFAIK, using 14919 // EvaluateAsRValue matches the proposed gcc behavior for cases like 14920 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 14921 // compliance: we should warn earlier for offsetof expressions with 14922 // array subscripts that aren't ICEs, and if the array subscripts 14923 // are ICEs, the value of the offsetof must be an integer constant. 14924 return CheckEvalInICE(E, Ctx); 14925 } 14926 case Expr::UnaryExprOrTypeTraitExprClass: { 14927 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 14928 if ((Exp->getKind() == UETT_SizeOf) && 14929 Exp->getTypeOfArgument()->isVariableArrayType()) 14930 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14931 return NoDiag(); 14932 } 14933 case Expr::BinaryOperatorClass: { 14934 const BinaryOperator *Exp = cast<BinaryOperator>(E); 14935 switch (Exp->getOpcode()) { 14936 case BO_PtrMemD: 14937 case BO_PtrMemI: 14938 case BO_Assign: 14939 case BO_MulAssign: 14940 case BO_DivAssign: 14941 case BO_RemAssign: 14942 case BO_AddAssign: 14943 case BO_SubAssign: 14944 case BO_ShlAssign: 14945 case BO_ShrAssign: 14946 case BO_AndAssign: 14947 case BO_XorAssign: 14948 case BO_OrAssign: 14949 // C99 6.6/3 allows assignments within unevaluated subexpressions of 14950 // constant expressions, but they can never be ICEs because an ICE cannot 14951 // contain an lvalue operand. 14952 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14953 14954 case BO_Mul: 14955 case BO_Div: 14956 case BO_Rem: 14957 case BO_Add: 14958 case BO_Sub: 14959 case BO_Shl: 14960 case BO_Shr: 14961 case BO_LT: 14962 case BO_GT: 14963 case BO_LE: 14964 case BO_GE: 14965 case BO_EQ: 14966 case BO_NE: 14967 case BO_And: 14968 case BO_Xor: 14969 case BO_Or: 14970 case BO_Comma: 14971 case BO_Cmp: { 14972 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 14973 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 14974 if (Exp->getOpcode() == BO_Div || 14975 Exp->getOpcode() == BO_Rem) { 14976 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 14977 // we don't evaluate one. 14978 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 14979 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 14980 if (REval == 0) 14981 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14982 if (REval.isSigned() && REval.isAllOnesValue()) { 14983 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 14984 if (LEval.isMinSignedValue()) 14985 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14986 } 14987 } 14988 } 14989 if (Exp->getOpcode() == BO_Comma) { 14990 if (Ctx.getLangOpts().C99) { 14991 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 14992 // if it isn't evaluated. 14993 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 14994 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 14995 } else { 14996 // In both C89 and C++, commas in ICEs are illegal. 14997 return ICEDiag(IK_NotICE, E->getBeginLoc()); 14998 } 14999 } 15000 return Worst(LHSResult, RHSResult); 15001 } 15002 case BO_LAnd: 15003 case BO_LOr: { 15004 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15005 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15006 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15007 // Rare case where the RHS has a comma "side-effect"; we need 15008 // to actually check the condition to see whether the side 15009 // with the comma is evaluated. 15010 if ((Exp->getOpcode() == BO_LAnd) != 15011 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15012 return RHSResult; 15013 return NoDiag(); 15014 } 15015 15016 return Worst(LHSResult, RHSResult); 15017 } 15018 } 15019 llvm_unreachable("invalid binary operator kind"); 15020 } 15021 case Expr::ImplicitCastExprClass: 15022 case Expr::CStyleCastExprClass: 15023 case Expr::CXXFunctionalCastExprClass: 15024 case Expr::CXXStaticCastExprClass: 15025 case Expr::CXXReinterpretCastExprClass: 15026 case Expr::CXXConstCastExprClass: 15027 case Expr::ObjCBridgedCastExprClass: { 15028 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15029 if (isa<ExplicitCastExpr>(E)) { 15030 if (const FloatingLiteral *FL 15031 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15032 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15033 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15034 APSInt IgnoredVal(DestWidth, !DestSigned); 15035 bool Ignored; 15036 // If the value does not fit in the destination type, the behavior is 15037 // undefined, so we are not required to treat it as a constant 15038 // expression. 15039 if (FL->getValue().convertToInteger(IgnoredVal, 15040 llvm::APFloat::rmTowardZero, 15041 &Ignored) & APFloat::opInvalidOp) 15042 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15043 return NoDiag(); 15044 } 15045 } 15046 switch (cast<CastExpr>(E)->getCastKind()) { 15047 case CK_LValueToRValue: 15048 case CK_AtomicToNonAtomic: 15049 case CK_NonAtomicToAtomic: 15050 case CK_NoOp: 15051 case CK_IntegralToBoolean: 15052 case CK_IntegralCast: 15053 return CheckICE(SubExpr, Ctx); 15054 default: 15055 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15056 } 15057 } 15058 case Expr::BinaryConditionalOperatorClass: { 15059 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15060 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15061 if (CommonResult.Kind == IK_NotICE) return CommonResult; 15062 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15063 if (FalseResult.Kind == IK_NotICE) return FalseResult; 15064 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15065 if (FalseResult.Kind == IK_ICEIfUnevaluated && 15066 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15067 return FalseResult; 15068 } 15069 case Expr::ConditionalOperatorClass: { 15070 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15071 // If the condition (ignoring parens) is a __builtin_constant_p call, 15072 // then only the true side is actually considered in an integer constant 15073 // expression, and it is fully evaluated. This is an important GNU 15074 // extension. See GCC PR38377 for discussion. 15075 if (const CallExpr *CallCE 15076 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15077 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15078 return CheckEvalInICE(E, Ctx); 15079 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15080 if (CondResult.Kind == IK_NotICE) 15081 return CondResult; 15082 15083 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15084 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15085 15086 if (TrueResult.Kind == IK_NotICE) 15087 return TrueResult; 15088 if (FalseResult.Kind == IK_NotICE) 15089 return FalseResult; 15090 if (CondResult.Kind == IK_ICEIfUnevaluated) 15091 return CondResult; 15092 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15093 return NoDiag(); 15094 // Rare case where the diagnostics depend on which side is evaluated 15095 // Note that if we get here, CondResult is 0, and at least one of 15096 // TrueResult and FalseResult is non-zero. 15097 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15098 return FalseResult; 15099 return TrueResult; 15100 } 15101 case Expr::CXXDefaultArgExprClass: 15102 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15103 case Expr::CXXDefaultInitExprClass: 15104 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15105 case Expr::ChooseExprClass: { 15106 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15107 } 15108 case Expr::BuiltinBitCastExprClass: { 15109 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15110 return ICEDiag(IK_NotICE, E->getBeginLoc()); 15111 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15112 } 15113 } 15114 15115 llvm_unreachable("Invalid StmtClass!"); 15116 } 15117 15118 /// Evaluate an expression as a C++11 integral constant expression. 15119 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15120 const Expr *E, 15121 llvm::APSInt *Value, 15122 SourceLocation *Loc) { 15123 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15124 if (Loc) *Loc = E->getExprLoc(); 15125 return false; 15126 } 15127 15128 APValue Result; 15129 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15130 return false; 15131 15132 if (!Result.isInt()) { 15133 if (Loc) *Loc = E->getExprLoc(); 15134 return false; 15135 } 15136 15137 if (Value) *Value = Result.getInt(); 15138 return true; 15139 } 15140 15141 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15142 SourceLocation *Loc) const { 15143 assert(!isValueDependent() && 15144 "Expression evaluator can't be called on a dependent expression."); 15145 15146 if (Ctx.getLangOpts().CPlusPlus11) 15147 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15148 15149 ICEDiag D = CheckICE(this, Ctx); 15150 if (D.Kind != IK_ICE) { 15151 if (Loc) *Loc = D.Loc; 15152 return false; 15153 } 15154 return true; 15155 } 15156 15157 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15158 SourceLocation *Loc, 15159 bool isEvaluated) const { 15160 assert(!isValueDependent() && 15161 "Expression evaluator can't be called on a dependent expression."); 15162 15163 APSInt Value; 15164 15165 if (Ctx.getLangOpts().CPlusPlus11) { 15166 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15167 return Value; 15168 return None; 15169 } 15170 15171 if (!isIntegerConstantExpr(Ctx, Loc)) 15172 return None; 15173 15174 // The only possible side-effects here are due to UB discovered in the 15175 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15176 // required to treat the expression as an ICE, so we produce the folded 15177 // value. 15178 EvalResult ExprResult; 15179 Expr::EvalStatus Status; 15180 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15181 Info.InConstantContext = true; 15182 15183 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15184 llvm_unreachable("ICE cannot be evaluated!"); 15185 15186 return ExprResult.Val.getInt(); 15187 } 15188 15189 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15190 assert(!isValueDependent() && 15191 "Expression evaluator can't be called on a dependent expression."); 15192 15193 return CheckICE(this, Ctx).Kind == IK_ICE; 15194 } 15195 15196 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15197 SourceLocation *Loc) const { 15198 assert(!isValueDependent() && 15199 "Expression evaluator can't be called on a dependent expression."); 15200 15201 // We support this checking in C++98 mode in order to diagnose compatibility 15202 // issues. 15203 assert(Ctx.getLangOpts().CPlusPlus); 15204 15205 // Build evaluation settings. 15206 Expr::EvalStatus Status; 15207 SmallVector<PartialDiagnosticAt, 8> Diags; 15208 Status.Diag = &Diags; 15209 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15210 15211 APValue Scratch; 15212 bool IsConstExpr = 15213 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15214 // FIXME: We don't produce a diagnostic for this, but the callers that 15215 // call us on arbitrary full-expressions should generally not care. 15216 Info.discardCleanups() && !Status.HasSideEffects; 15217 15218 if (!Diags.empty()) { 15219 IsConstExpr = false; 15220 if (Loc) *Loc = Diags[0].first; 15221 } else if (!IsConstExpr) { 15222 // FIXME: This shouldn't happen. 15223 if (Loc) *Loc = getExprLoc(); 15224 } 15225 15226 return IsConstExpr; 15227 } 15228 15229 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15230 const FunctionDecl *Callee, 15231 ArrayRef<const Expr*> Args, 15232 const Expr *This) const { 15233 assert(!isValueDependent() && 15234 "Expression evaluator can't be called on a dependent expression."); 15235 15236 Expr::EvalStatus Status; 15237 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15238 Info.InConstantContext = true; 15239 15240 LValue ThisVal; 15241 const LValue *ThisPtr = nullptr; 15242 if (This) { 15243 #ifndef NDEBUG 15244 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15245 assert(MD && "Don't provide `this` for non-methods."); 15246 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15247 #endif 15248 if (!This->isValueDependent() && 15249 EvaluateObjectArgument(Info, This, ThisVal) && 15250 !Info.EvalStatus.HasSideEffects) 15251 ThisPtr = &ThisVal; 15252 15253 // Ignore any side-effects from a failed evaluation. This is safe because 15254 // they can't interfere with any other argument evaluation. 15255 Info.EvalStatus.HasSideEffects = false; 15256 } 15257 15258 ArgVector ArgValues(Args.size()); 15259 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15260 I != E; ++I) { 15261 if ((*I)->isValueDependent() || 15262 !Evaluate(ArgValues[I - Args.begin()], Info, *I) || 15263 Info.EvalStatus.HasSideEffects) 15264 // If evaluation fails, throw away the argument entirely. 15265 ArgValues[I - Args.begin()] = APValue(); 15266 15267 // Ignore any side-effects from a failed evaluation. This is safe because 15268 // they can't interfere with any other argument evaluation. 15269 Info.EvalStatus.HasSideEffects = false; 15270 } 15271 15272 // Parameter cleanups happen in the caller and are not part of this 15273 // evaluation. 15274 Info.discardCleanups(); 15275 Info.EvalStatus.HasSideEffects = false; 15276 15277 // Build fake call to Callee. 15278 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 15279 ArgValues.data()); 15280 // FIXME: Missing ExprWithCleanups in enable_if conditions? 15281 FullExpressionRAII Scope(Info); 15282 return Evaluate(Value, Info, this) && Scope.destroy() && 15283 !Info.EvalStatus.HasSideEffects; 15284 } 15285 15286 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15287 SmallVectorImpl< 15288 PartialDiagnosticAt> &Diags) { 15289 // FIXME: It would be useful to check constexpr function templates, but at the 15290 // moment the constant expression evaluator cannot cope with the non-rigorous 15291 // ASTs which we build for dependent expressions. 15292 if (FD->isDependentContext()) 15293 return true; 15294 15295 // Bail out if a constexpr constructor has an initializer that contains an 15296 // error. We deliberately don't produce a diagnostic, as we have produced a 15297 // relevant diagnostic when parsing the error initializer. 15298 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 15299 for (const auto *InitExpr : Ctor->inits()) { 15300 if (InitExpr->getInit() && InitExpr->getInit()->containsErrors()) 15301 return false; 15302 } 15303 } 15304 Expr::EvalStatus Status; 15305 Status.Diag = &Diags; 15306 15307 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15308 Info.InConstantContext = true; 15309 Info.CheckingPotentialConstantExpression = true; 15310 15311 // The constexpr VM attempts to compile all methods to bytecode here. 15312 if (Info.EnableNewConstInterp) { 15313 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15314 return Diags.empty(); 15315 } 15316 15317 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15318 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15319 15320 // Fabricate an arbitrary expression on the stack and pretend that it 15321 // is a temporary being used as the 'this' pointer. 15322 LValue This; 15323 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15324 This.set({&VIE, Info.CurrentCall->Index}); 15325 15326 ArrayRef<const Expr*> Args; 15327 15328 APValue Scratch; 15329 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15330 // Evaluate the call as a constant initializer, to allow the construction 15331 // of objects of non-literal types. 15332 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15333 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15334 } else { 15335 SourceLocation Loc = FD->getLocation(); 15336 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15337 Args, /*ArgValues*/ nullptr, FD->getBody(), Info, 15338 Scratch, nullptr); 15339 } 15340 15341 return Diags.empty(); 15342 } 15343 15344 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15345 const FunctionDecl *FD, 15346 SmallVectorImpl< 15347 PartialDiagnosticAt> &Diags) { 15348 assert(!E->isValueDependent() && 15349 "Expression evaluator can't be called on a dependent expression."); 15350 15351 Expr::EvalStatus Status; 15352 Status.Diag = &Diags; 15353 15354 EvalInfo Info(FD->getASTContext(), Status, 15355 EvalInfo::EM_ConstantExpressionUnevaluated); 15356 Info.InConstantContext = true; 15357 Info.CheckingPotentialConstantExpression = true; 15358 15359 // Fabricate a call stack frame to give the arguments a plausible cover story. 15360 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, 15361 /*ArgValues*/ nullptr); 15362 15363 APValue ResultScratch; 15364 Evaluate(ResultScratch, Info, E); 15365 return Diags.empty(); 15366 } 15367 15368 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15369 unsigned Type) const { 15370 if (!getType()->isPointerType()) 15371 return false; 15372 15373 Expr::EvalStatus Status; 15374 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15375 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15376 } 15377